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