| 1 | /* |
| 2 | * Copyright (C) 2015, Mike Walters <[email protected]> |
| 3 | * |
| 4 | * This file is part of inspectrum. |
| 5 | * |
| 6 | * This program is free software: you can redistribute it and/or modify |
| 7 | * it under the terms of the GNU General Public License as published by |
| 8 | * the Free Software Foundation, either version 3 of the License, or |
| 9 | * (at your option) any later version. |
| 10 | * |
| 11 | * This program is distributed in the hope that it will be useful, |
| 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 14 | * GNU General Public License for more details. |
| 15 | * |
| 16 | * You should have received a copy of the GNU General Public License |
| 17 | * along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 18 | */ |
| 19 | |
| 20 | #include "spectrogramplot.h" |
| 21 | |
| 22 | #include <QDebug> |
| 23 | #include <QElapsedTimer> |
| 24 | #include <QPainter> |
| 25 | #include <QPaintEvent> |
| 26 | #include <QPixmapCache> |
| 27 | #include <QRect> |
| 28 | #include <liquid/liquid.h> |
| 29 | #include <algorithm> |
| 30 | #include <functional> |
| 31 | #include <cstdlib> |
| 32 | #include <limits> |
| 33 | #include "util.h" |
| 34 | |
| 35 | |
| 36 | SpectrogramPlot::SpectrogramPlot(std::shared_ptr<SampleSource<std::complex<float>>> src) : Plot(src), inputSource(src), fftSize(512), tuner(fftSize, this) |
| 37 | { |
| 38 | setFFTSize(fftSize); |
| 39 | zoomLevel = 1; |
| 40 | powerMax = 0.0f; |
| 41 | powerMin = -50.0f; |
| 42 | sampleRate = 0; |
| 43 | frequencyScaleEnabled = false; |
| 44 | sigmfAnnotationsEnabled = true; |
| 45 | |
| 46 | for (int i = 0; i < 256; i++) { |
| 47 | float p = (float)i / 256; |
| 48 | colormap[i] = QColor::fromHsvF(p * 0.83f, 1.0, 1.0 - p).rgba(); |
| 49 | } |
| 50 | |
| 51 | tunerTransform = std::make_shared<TunerTransform>(src); |
| 52 | connect(&tuner, &Tuner::tunerMoved, this, &SpectrogramPlot::tunerMoved); |
| 53 | } |
| 54 | |
| 55 | void SpectrogramPlot::invalidateEvent() |
| 56 | { |
| 57 | // HACK: this makes sure we update the height for real signals (as InputSource is passed here before the file is opened) |
| 58 | setFFTSize(fftSize); |
| 59 | |
| 60 | pixmapCache.clear(); |
| 61 | fftCache.clear(); |
| 62 | emit repaint(); |
| 63 | } |
| 64 | |
| 65 | void SpectrogramPlot::paintFront(QPainter &painter, QRect &rect, range_t<size_t> sampleRange) |
| 66 | { |
| 67 | if (tunerEnabled()) |
| 68 | tuner.paintFront(painter, rect, sampleRange); |
| 69 | |
| 70 | if (frequencyScaleEnabled) |
| 71 | paintFrequencyScale(painter, rect); |
| 72 | |
| 73 | if (sigmfAnnotationsEnabled) |
| 74 | paintAnnotations(painter, rect, sampleRange); |
| 75 | } |
| 76 | |
| 77 | void SpectrogramPlot::paintFrequencyScale(QPainter &painter, QRect &rect) |
| 78 | { |
| 79 | if (sampleRate == 0) { |
| 80 | return; |
| 81 | } |
| 82 | |
| 83 | if (sampleRate / 2 > UINT64_MAX) { |
| 84 | return; |
| 85 | } |
| 86 | |
| 87 | // At which pixel is F_+sampleRate/2 |
| 88 | int y = rect.y(); |
| 89 | |
| 90 | int plotHeight = rect.height(); |
| 91 | if (inputSource->realSignal()) |
| 92 | plotHeight *= 2; |
| 93 | |
| 94 | double bwPerPixel = (double)sampleRate / plotHeight; |
| 95 | int tickHeight = 50; |
| 96 | |
| 97 | uint64_t bwPerTick = 10 * pow(10, floor(log(bwPerPixel * tickHeight) / log(10))); |
| 98 | |
| 99 | if (bwPerTick < 1) { |
| 100 | return; |
| 101 | } |
| 102 | |
| 103 | painter.save(); |
| 104 | |
| 105 | QPen pen(Qt::white, 1, Qt::SolidLine); |
| 106 | painter.setPen(pen); |
| 107 | QFontMetrics fm(painter.font()); |
| 108 | |
| 109 | |
| 110 | uint64_t tick = 0; |
| 111 | |
| 112 | while (tick <= sampleRate / 2) { |
| 113 | |
| 114 | int tickpy = plotHeight / 2 - tick / bwPerPixel + y; |
| 115 | int tickny = plotHeight / 2 + tick / bwPerPixel + y; |
| 116 | |
| 117 | if (!inputSource->realSignal()) |
| 118 | painter.drawLine(0, tickny, 30, tickny); |
| 119 | painter.drawLine(0, tickpy, 30, tickpy); |
| 120 | |
| 121 | if (tick != 0) { |
| 122 | char buf[128]; |
| 123 | |
| 124 | if (bwPerTick % 1000000000 == 0) { |
| 125 | snprintf(buf, sizeof(buf), "-%lu GHz", tick / 1000000000); |
| 126 | } else if (bwPerTick % 1000000 == 0) { |
| 127 | snprintf(buf, sizeof(buf), "-%lu MHz", tick / 1000000); |
| 128 | } else if(bwPerTick % 1000 == 0) { |
| 129 | snprintf(buf, sizeof(buf), "-%lu kHz", tick / 1000); |
| 130 | } else { |
| 131 | snprintf(buf, sizeof(buf), "-%lu Hz", tick); |
| 132 | } |
| 133 | |
| 134 | if (!inputSource->realSignal()) |
| 135 | painter.drawText(5, tickny - 5, buf); |
| 136 | |
| 137 | buf[0] = ' '; |
| 138 | painter.drawText(5, tickpy + 15, buf); |
| 139 | } |
| 140 | |
| 141 | tick += bwPerTick; |
| 142 | } |
| 143 | |
| 144 | // Draw small ticks |
| 145 | bwPerTick /= 10; |
| 146 | |
| 147 | if (bwPerTick >= 1 ) { |
| 148 | tick = 0; |
| 149 | while (tick <= sampleRate / 2) { |
| 150 | |
| 151 | int tickpy = plotHeight / 2 - tick / bwPerPixel + y; |
| 152 | int tickny = plotHeight / 2 + tick / bwPerPixel + y; |
| 153 | |
| 154 | if (!inputSource->realSignal()) |
| 155 | painter.drawLine(0, tickny, 3, tickny); |
| 156 | painter.drawLine(0, tickpy, 3, tickpy); |
| 157 | |
| 158 | tick += bwPerTick; |
| 159 | } |
| 160 | } |
| 161 | painter.restore(); |
| 162 | } |
| 163 | |
| 164 | void SpectrogramPlot::paintAnnotations(QPainter &painter, QRect &rect, range_t<size_t> sampleRange) |
| 165 | { |
| 166 | // Pixel (from the top) at which 0 Hz sits |
| 167 | int zero = rect.y() + rect.height() / 2; |
| 168 | |
| 169 | painter.save(); |
| 170 | QPen pen(Qt::white, 1, Qt::SolidLine); |
| 171 | painter.setPen(pen); |
| 172 | QFontMetrics fm(painter.font()); |
| 173 | |
| 174 | visibleAnnotationLocations.clear(); |
| 175 | |
| 176 | for (int i = 0; i < inputSource->annotationList.size(); i++) { |
| 177 | Annotation a = inputSource->annotationList.at(i); |
| 178 | |
| 179 | size_t labelLength = fm.boundingRect(a.label).width() * getStride(); |
| 180 | |
| 181 | // Check if: |
| 182 | // (1) End of annotation (might be maximum, or end of label text) is still visible in time |
| 183 | // (2) Part of the annotation is already visible in time |
| 184 | // |
| 185 | // Currently there is no check if the annotation is visible in frequency. This is a |
| 186 | // possible performance improvement |
| 187 | // |
| 188 | size_t start = a.sampleRange.minimum; |
| 189 | size_t end = std::max(a.sampleRange.minimum + labelLength, a.sampleRange.maximum); |
| 190 | |
| 191 | if(start <= sampleRange.maximum && end >= sampleRange.minimum) { |
| 192 | |
| 193 | double frequency = a.frequencyRange.maximum - inputSource->getFrequency(); |
| 194 | int x = (a.sampleRange.minimum - sampleRange.minimum) / getStride(); |
| 195 | int y = zero - frequency / sampleRate * rect.height(); |
| 196 | int height = (a.frequencyRange.maximum - a.frequencyRange.minimum) / sampleRate * rect.height(); |
| 197 | int width = (a.sampleRange.maximum - a.sampleRange.minimum) / getStride(); |
| 198 | |
| 199 | // Draw the label 2 pixels above the box |
| 200 | painter.drawText(x, y - 2, a.label); |
| 201 | painter.drawRect(x, y, width, height); |
| 202 | |
| 203 | visibleAnnotationLocations.emplace_back(a, x, y, width, height); |
| 204 | } |
| 205 | } |
| 206 | |
| 207 | painter.restore(); |
| 208 | } |
| 209 | |
| 210 | QString *SpectrogramPlot::mouseAnnotationComment(const QMouseEvent *event) { |
| 211 | auto pos = event->pos(); |
| 212 | int mouse_x = pos.x(); |
| 213 | int mouse_y = pos.y(); |
| 214 | |
| 215 | for (auto& a : visibleAnnotationLocations) { |
| 216 | if (!a.annotation.comment.isEmpty() && a.isInside(mouse_x, mouse_y)) { |
| 217 | return &a.annotation.comment; |
| 218 | } |
| 219 | } |
| 220 | return nullptr; |
| 221 | } |
| 222 | |
| 223 | void SpectrogramPlot::paintMid(QPainter &painter, QRect &rect, range_t<size_t> sampleRange) |
| 224 | { |
| 225 | if (!inputSource || inputSource->count() == 0) |
| 226 | return; |
| 227 | |
| 228 | size_t sampleOffset = sampleRange.minimum % (getStride() * linesPerTile()); |
| 229 | size_t tileID = sampleRange.minimum - sampleOffset; |
| 230 | int xoffset = sampleOffset / getStride(); |
| 231 | |
| 232 | // Paint first (possibly partial) tile |
| 233 | painter.drawPixmap(QRect(rect.left(), rect.y(), linesPerTile() - xoffset, height()), *getPixmapTile(tileID), QRect(xoffset, 0, linesPerTile() - xoffset, height())); |
| 234 | tileID += getStride() * linesPerTile(); |
| 235 | |
| 236 | // Paint remaining tiles |
| 237 | for (int x = linesPerTile() - xoffset; x < rect.right(); x += linesPerTile()) { |
| 238 | // TODO: don't draw past rect.right() |
| 239 | // TODO: handle partial final tile |
| 240 | painter.drawPixmap(QRect(x, rect.y(), linesPerTile(), height()), *getPixmapTile(tileID), QRect(0, 0, linesPerTile(), height())); |
| 241 | tileID += getStride() * linesPerTile(); |
| 242 | } |
| 243 | } |
| 244 | |
| 245 | QPixmap* SpectrogramPlot::getPixmapTile(size_t tile) |
| 246 | { |
| 247 | QPixmap *obj = pixmapCache.object(TileCacheKey(fftSize, zoomLevel, tile)); |
| 248 | if (obj != 0) |
| 249 | return obj; |
| 250 | |
| 251 | float *fftTile = getFFTTile(tile); |
| 252 | obj = new QPixmap(linesPerTile(), fftSize); |
| 253 | QImage image(linesPerTile(), fftSize, QImage::Format_RGB32); |
| 254 | float powerRange = -1.0f / std::abs(int(powerMin - powerMax)); |
| 255 | for (int y = 0; y < fftSize; y++) { |
| 256 | auto scanLine = (QRgb*)image.scanLine(fftSize - y - 1); |
| 257 | for (int x = 0; x < linesPerTile(); x++) { |
| 258 | float *fftLine = &fftTile[x * fftSize]; |
| 259 | float normPower = (fftLine[y] - powerMax) * powerRange; |
| 260 | normPower = clamp(normPower, 0.0f, 1.0f); |
| 261 | |
| 262 | scanLine[x] = colormap[(uint8_t)(normPower * (256 - 1))]; |
| 263 | } |
| 264 | } |
| 265 | obj->convertFromImage(image); |
| 266 | pixmapCache.insert(TileCacheKey(fftSize, zoomLevel, tile), obj); |
| 267 | return obj; |
| 268 | } |
| 269 | |
| 270 | float* SpectrogramPlot::getFFTTile(size_t tile) |
| 271 | { |
| 272 | std::array<float, tileSize>* obj = fftCache.object(TileCacheKey(fftSize, zoomLevel, tile)); |
| 273 | if (obj != nullptr) |
| 274 | return obj->data(); |
| 275 | |
| 276 | std::array<float, tileSize>* destStorage = new std::array<float, tileSize>; |
| 277 | float *ptr = destStorage->data(); |
| 278 | size_t sample = tile; |
| 279 | while ((ptr - destStorage->data()) < tileSize) { |
| 280 | getLine(ptr, sample); |
| 281 | sample += getStride(); |
| 282 | ptr += fftSize; |
| 283 | } |
| 284 | fftCache.insert(TileCacheKey(fftSize, zoomLevel, tile), destStorage); |
| 285 | return destStorage->data(); |
| 286 | } |
| 287 | |
| 288 | void SpectrogramPlot::getLine(float *dest, size_t sample) |
| 289 | { |
| 290 | if (inputSource && fft) { |
| 291 | // Make sample be the midpoint of the FFT, unless this takes us |
| 292 | // past the beginning of the inputSource (if we remove the |
| 293 | // std::max(ยท, 0), then an ugly red bar appears at the beginning |
| 294 | // of the spectrogram with large zooms and FFT sizes). |
| 295 | const auto first_sample = std::max(static_cast<ssize_t>(sample) - fftSize / 2, |
| 296 | static_cast<ssize_t>(0)); |
| 297 | auto buffer = inputSource->getSamples(first_sample, fftSize); |
| 298 | if (buffer == nullptr) { |
| 299 | auto neg_infinity = -1 * std::numeric_limits<float>::infinity(); |
| 300 | for (int i = 0; i < fftSize; i++, dest++) |
| 301 | *dest = neg_infinity; |
| 302 | return; |
| 303 | } |
| 304 | |
| 305 | for (int i = 0; i < fftSize; i++) { |
| 306 | buffer[i] *= window[i]; |
| 307 | } |
| 308 | |
| 309 | fft->process(buffer.get(), buffer.get()); |
| 310 | const float invFFTSize = 1.0f / fftSize; |
| 311 | const float logMultiplier = 10.0f / log2f(10.0f); |
| 312 | for (int i = 0; i < fftSize; i++) { |
| 313 | // Start from the middle of the FFTW array and wrap |
| 314 | // to rearrange the data |
| 315 | int k = i ^ (fftSize >> 1); |
| 316 | auto s = buffer[k] * invFFTSize; |
| 317 | float power = s.real() * s.real() + s.imag() * s.imag(); |
| 318 | float logPower = log2f(power) * logMultiplier; |
| 319 | *dest = logPower; |
| 320 | dest++; |
| 321 | } |
| 322 | } |
| 323 | } |
| 324 | |
| 325 | int SpectrogramPlot::getStride() |
| 326 | { |
| 327 | return fftSize / zoomLevel; |
| 328 | } |
| 329 | |
| 330 | float SpectrogramPlot::getTunerPhaseInc() |
| 331 | { |
| 332 | auto freq = 0.5f - tuner.centre() / (float)fftSize; |
| 333 | return freq * Tau; |
| 334 | } |
| 335 | |
| 336 | std::vector<float> SpectrogramPlot::getTunerTaps() |
| 337 | { |
| 338 | float cutoff = tuner.deviation() / (float)fftSize; |
| 339 | float gain = pow(10.0f, powerMax / -10.0f); |
| 340 | auto atten = 60.0f; |
| 341 | auto len = estimate_req_filter_len(std::min(cutoff, 0.05f), atten); |
| 342 | auto taps = std::vector<float>(len); |
| 343 | liquid_firdes_kaiser(len, cutoff, atten, 0.0f, taps.data()); |
| 344 | std::transform(taps.begin(), taps.end(), taps.begin(), |
| 345 | std::bind(std::multiplies<float>(), std::placeholders::_1, gain)); |
| 346 | return taps; |
| 347 | } |
| 348 | |
| 349 | int SpectrogramPlot::linesPerTile() |
| 350 | { |
| 351 | return tileSize / fftSize; |
| 352 | } |
| 353 | |
| 354 | bool SpectrogramPlot::mouseEvent(QEvent::Type type, QMouseEvent *event) |
| 355 | { |
| 356 | if (tunerEnabled()) |
| 357 | return tuner.mouseEvent(type, event); |
| 358 | |
| 359 | return false; |
| 360 | } |
| 361 | |
| 362 | void SpectrogramPlot::leaveEvent() |
| 363 | { |
| 364 | if (tunerEnabled()) |
| 365 | tuner.leaveEvent(); |
| 366 | } |
| 367 | |
| 368 | std::shared_ptr<AbstractSampleSource> SpectrogramPlot::output() |
| 369 | { |
| 370 | return tunerTransform; |
| 371 | } |
| 372 | |
| 373 | void SpectrogramPlot::setFFTSize(int size) |
| 374 | { |
| 375 | float sizeScale = float(size) / float(fftSize); |
| 376 | fftSize = size; |
| 377 | fft.reset(new FFT(fftSize)); |
| 378 | |
| 379 | window.reset(new float[fftSize]); |
| 380 | for (int i = 0; i < fftSize; i++) { |
| 381 | window[i] = 0.5f * (1.0f - cos(Tau * i / (fftSize - 1))); |
| 382 | } |
| 383 | |
| 384 | if (inputSource->realSignal()) { |
| 385 | setHeight(fftSize/2); |
| 386 | } else { |
| 387 | setHeight(fftSize); |
| 388 | } |
| 389 | auto dev = tuner.deviation(); |
| 390 | auto centre = tuner.centre(); |
| 391 | tuner.setHeight(height()); |
| 392 | tuner.setDeviation( dev * sizeScale ); |
| 393 | tuner.setCentre( centre * sizeScale ); |
| 394 | } |
| 395 | |
| 396 | void SpectrogramPlot::setPowerMax(int power) |
| 397 | { |
| 398 | powerMax = power; |
| 399 | pixmapCache.clear(); |
| 400 | tunerMoved(); |
| 401 | } |
| 402 | |
| 403 | void SpectrogramPlot::setPowerMin(int power) |
| 404 | { |
| 405 | powerMin = power; |
| 406 | pixmapCache.clear(); |
| 407 | } |
| 408 | |
| 409 | void SpectrogramPlot::setZoomLevel(int zoom) |
| 410 | { |
| 411 | zoomLevel = zoom; |
| 412 | } |
| 413 | |
| 414 | void SpectrogramPlot::setSampleRate(double rate) |
| 415 | { |
| 416 | sampleRate = rate; |
| 417 | } |
| 418 | |
| 419 | void SpectrogramPlot::enableScales(bool enabled) |
| 420 | { |
| 421 | frequencyScaleEnabled = enabled; |
| 422 | } |
| 423 | |
| 424 | void SpectrogramPlot::enableAnnotations(bool enabled) |
| 425 | { |
| 426 | sigmfAnnotationsEnabled = enabled; |
| 427 | } |
| 428 | |
| 429 | bool SpectrogramPlot::isAnnotationsEnabled(void) |
| 430 | { |
| 431 | return sigmfAnnotationsEnabled; |
| 432 | } |
| 433 | |
| 434 | bool SpectrogramPlot::tunerEnabled() |
| 435 | { |
| 436 | return (tunerTransform->subscriberCount() > 0); |
| 437 | } |
| 438 | |
| 439 | void SpectrogramPlot::tunerMoved() |
| 440 | { |
| 441 | tunerTransform->setFrequency(getTunerPhaseInc()); |
| 442 | tunerTransform->setTaps(getTunerTaps()); |
| 443 | tunerTransform->setRelativeBandwith(tuner.deviation() * 2.0 / height()); |
| 444 | |
| 445 | // TODO: for invalidating traceplot cache, this shouldn't really go here |
| 446 | QPixmapCache::clear(); |
| 447 | |
| 448 | emit repaint(); |
| 449 | } |
| 450 | |
| 451 | uint qHash(const TileCacheKey &key, uint seed) |
| 452 | { |
| 453 | return key.fftSize ^ key.zoomLevel ^ key.sample ^ seed; |
| 454 | } |