]> git.sesse.net Git - kdenlive/blob - src/scopes/audioscopes/spectrogram.cpp
const'ref. REmove not necessary virtual keyword. Fix indent.
[kdenlive] / src / scopes / audioscopes / spectrogram.cpp
1 /***************************************************************************
2  *   Copyright (C) 2010 by Simon Andreas Eugster (simon.eu@gmail.com)      *
3  *   This file is part of kdenlive. See www.kdenlive.org.                  *
4  *                                                                         *
5  *   This program is free software; you can redistribute it and/or modify  *
6  *   it under the terms of the GNU General Public License as published by  *
7  *   the Free Software Foundation; either version 2 of the License, or     *
8  *   (at your option) any later version.                                   *
9  ***************************************************************************/
10
11 #include <QPainter>
12 #include <QMenu>
13
14 #include "spectrogram.h"
15
16 // Defines the number of FFT samples to store.
17 // Around 4 kB for a window size of 2000. Should be at least as large as the
18 // highest vertical screen resolution available for complete reconstruction.
19 // Can be less as a pre-rendered image is kept in space.
20 #define SPECTROGRAM_HISTORY_SIZE 1000
21
22 // Uncomment for debugging
23 //#define DEBUG_SPECTROGRAM
24
25 #ifdef DEBUG_SPECTROGRAM
26 #include <QDebug>
27 #endif
28
29 #define MIN_DB_VALUE -120
30 #define MAX_FREQ_VALUE 96000
31 #define MIN_FREQ_VALUE 1000
32
33 Spectrogram::Spectrogram(QWidget *parent) :
34     AbstractAudioScopeWidget(true, parent)
35   , m_fftTools()
36   , m_fftHistory()
37   , m_fftHistoryImg()
38   , m_dBmin(-70)
39   , m_dBmax(0)
40   , m_freqMax(0)
41   , m_customFreq(false)
42   , m_parameterChanged(false)
43 {
44     ui = new Ui::Spectrogram_UI;
45     ui->setupUi(this);
46
47
48     m_aResetHz = new QAction(i18n("Reset maximum frequency to sampling rate"), this);
49     m_aGrid = new QAction(i18n("Draw grid"), this);
50     m_aGrid->setCheckable(true);
51     m_aTrackMouse = new QAction(i18n("Track mouse"), this);
52     m_aTrackMouse->setCheckable(true);
53     m_aHighlightPeaks = new QAction(i18n("Highlight peaks"), this);
54     m_aHighlightPeaks->setCheckable(true);
55
56
57     m_menu->addSeparator();
58     m_menu->addAction(m_aResetHz);
59     m_menu->addAction(m_aTrackMouse);
60     m_menu->addAction(m_aGrid);
61     m_menu->addAction(m_aHighlightPeaks);
62     m_menu->removeAction(m_aRealtime);
63
64
65     ui->windowSize->addItem("256", QVariant(256));
66     ui->windowSize->addItem("512", QVariant(512));
67     ui->windowSize->addItem("1024", QVariant(1024));
68     ui->windowSize->addItem("2048", QVariant(2048));
69
70     ui->windowFunction->addItem(i18n("Rectangular window"), FFTTools::Window_Rect);
71     ui->windowFunction->addItem(i18n("Triangular window"), FFTTools::Window_Triangle);
72     ui->windowFunction->addItem(i18n("Hamming window"), FFTTools::Window_Hamming);
73
74     // Note: These strings are used in both Spectogram and AudioSpectrum. Ideally change both (if necessary) to reduce workload on translators
75     ui->labelFFTSize->setToolTip(i18n("The maximum window size is limited by the number of samples per frame."));
76     ui->windowSize->setToolTip(i18n("A bigger window improves the accuracy at the cost of computational power."));
77     ui->windowFunction->setToolTip(i18n("The rectangular window function is good for signals with equal signal strength (narrow peak), but creates more smearing. See Window function on Wikipedia."));
78
79     bool b = true;
80     b &= connect(m_aResetHz, SIGNAL(triggered()), this, SLOT(slotResetMaxFreq()));
81     b &= connect(ui->windowFunction, SIGNAL(currentIndexChanged(int)), this, SLOT(forceUpdate()));
82     b &= connect(this, SIGNAL(signalMousePositionChanged()), this, SLOT(forceUpdateHUD()));
83     Q_ASSERT(b);
84
85     AbstractScopeWidget::init();
86 }
87
88 Spectrogram::~Spectrogram()
89 {
90     writeConfig();
91
92     delete m_aResetHz;
93     delete m_aTrackMouse;
94     delete m_aGrid;
95     delete ui;
96 }
97
98 void Spectrogram::readConfig()
99 {
100     AbstractScopeWidget::readConfig();
101
102     KSharedConfigPtr config = KGlobal::config();
103     KConfigGroup scopeConfig(config, AbstractScopeWidget::configName());
104
105     ui->windowSize->setCurrentIndex(scopeConfig.readEntry("windowSize", 0));
106     ui->windowFunction->setCurrentIndex(scopeConfig.readEntry("windowFunction", 0));
107     m_aTrackMouse->setChecked(scopeConfig.readEntry("trackMouse", true));
108     m_aGrid->setChecked(scopeConfig.readEntry("drawGrid", true));
109     m_aHighlightPeaks->setChecked(scopeConfig.readEntry("highlightPeaks", true));
110     m_dBmax = scopeConfig.readEntry("dBmax", 0);
111     m_dBmin = scopeConfig.readEntry("dBmin", -70);
112     m_freqMax = scopeConfig.readEntry("freqMax", 0);
113
114     if (m_freqMax == 0) {
115         m_customFreq = false;
116         m_freqMax = 10000;
117     } else {
118         m_customFreq = true;
119     }
120 }
121 void Spectrogram::writeConfig()
122 {
123     KSharedConfigPtr config = KGlobal::config();
124     KConfigGroup scopeConfig(config, AbstractScopeWidget::configName());
125
126     scopeConfig.writeEntry("windowSize", ui->windowSize->currentIndex());
127     scopeConfig.writeEntry("windowFunction", ui->windowFunction->currentIndex());
128     scopeConfig.writeEntry("trackMouse", m_aTrackMouse->isChecked());
129     scopeConfig.writeEntry("drawGrid", m_aGrid->isChecked());
130     scopeConfig.writeEntry("highlightPeaks", m_aHighlightPeaks->isChecked());
131     scopeConfig.writeEntry("dBmax", m_dBmax);
132     scopeConfig.writeEntry("dBmin", m_dBmin);
133
134     if (m_customFreq) {
135         scopeConfig.writeEntry("freqMax", m_freqMax);
136     } else {
137         scopeConfig.writeEntry("freqMax", 0);
138     }
139
140     scopeConfig.sync();
141 }
142
143 QString Spectrogram::widgetName() const
144 {
145     return QLatin1String("Spectrogram");
146 }
147
148 QRect Spectrogram::scopeRect()
149 {
150     m_scopeRect = QRect(
151                 QPoint(
152                     10,                                     // Left
153                     ui->verticalSpacer->geometry().top()+6  // Top
154                     ),
155                 AbstractAudioScopeWidget::rect().bottomRight()
156                 );
157     m_innerScopeRect = QRect(
158                 QPoint(
159                     m_scopeRect.left()+66,                  // Left
160                     m_scopeRect.top()+6                     // Top
161                     ), QPoint(
162                     ui->verticalSpacer->geometry().right()-70,
163                     ui->verticalSpacer->geometry().bottom()-40
164                     )
165                 );
166     return m_scopeRect;
167 }
168
169 QImage Spectrogram::renderHUD(uint)
170 {
171     if (m_innerScopeRect.width() > 0 && m_innerScopeRect.height() > 0) {
172         QTime start = QTime::currentTime();
173
174         int x, y;
175         const uint minDistY = 30; // Minimum distance between two lines
176         const uint minDistX = 40;
177         const uint textDistX = 10;
178         const uint textDistY = 25;
179         const uint topDist = m_innerScopeRect.top() - m_scopeRect.top();
180         const uint leftDist = m_innerScopeRect.left() - m_scopeRect.left();
181         const int mouseX = m_mousePos.x() - m_innerScopeRect.left();
182         const int mouseY = m_mousePos.y() - m_innerScopeRect.top();
183         bool hideText;
184
185         QImage hud(m_scopeRect.size(), QImage::Format_ARGB32);
186         hud.fill(qRgba(0,0,0,0));
187
188         QPainter davinci(&hud);
189         davinci.setPen(AbstractScopeWidget::penLight);
190
191
192         // Frame display
193         if (m_aGrid->isChecked()) {
194             for (int frameNumber = 0; frameNumber < m_innerScopeRect.height(); frameNumber += minDistY) {
195                 y = topDist + m_innerScopeRect.height()-1 - frameNumber;
196                 hideText = m_aTrackMouse->isChecked() && m_mouseWithinWidget && abs(y - mouseY) < (int)textDistY && mouseY < m_innerScopeRect.height()
197                         && mouseX < m_innerScopeRect.width() && mouseX >= 0;
198
199                 davinci.drawLine(leftDist, y, leftDist + m_innerScopeRect.width()-1, y);
200                 if (!hideText) {
201                     davinci.drawText(leftDist + m_innerScopeRect.width() + textDistX, y + 6, QVariant(frameNumber).toString());
202                 }
203             }
204         }
205         // Draw a line through the mouse position with the correct Frame number
206         if (m_aTrackMouse->isChecked() && m_mouseWithinWidget && mouseY < m_innerScopeRect.height()
207                 && mouseX < m_innerScopeRect.width() && mouseX >= 0) {
208             davinci.setPen(AbstractScopeWidget::penLighter);
209
210             x = leftDist + mouseX;
211             y = topDist + mouseY - 20;
212             if (y < 0) {
213                 y = 0;
214             }
215             if (y > (int)topDist + m_innerScopeRect.height()-1 - 30) {
216                 y = topDist + m_innerScopeRect.height()-1 - 30;
217             }
218             davinci.drawLine(x, topDist + mouseY, leftDist + m_innerScopeRect.width()-1, topDist + mouseY);
219             davinci.drawText(leftDist + m_innerScopeRect.width() + textDistX,
220                              y,
221                              m_scopeRect.right()-m_innerScopeRect.right()-textDistX,
222                              40,
223                              Qt::AlignLeft,
224                              i18n("Frame\n%1", m_innerScopeRect.height()-1-mouseY));
225         }
226
227         // Frequency grid
228         const uint hzDiff = ceil( ((float)minDistX)/m_innerScopeRect.width() * m_freqMax / 1000 ) * 1000;
229         const int rightBorder = leftDist + m_innerScopeRect.width()-1;
230         x = 0;
231         y = topDist + m_innerScopeRect.height() + textDistY;
232         if (m_aGrid->isChecked()) {
233             for (uint hz = 0; x <= rightBorder; hz += hzDiff) {
234                 davinci.setPen(AbstractScopeWidget::penLight);
235                 x = leftDist + (m_innerScopeRect.width()-1) * ((float)hz)/m_freqMax;
236
237                 // Hide text if it would overlap with the text drawn at the mouse position
238                 hideText = m_aTrackMouse->isChecked() && m_mouseWithinWidget && abs(x-(leftDist + mouseX + 20)) < (int) minDistX + 16
239                         && mouseX < m_innerScopeRect.width() && mouseX >= 0;
240
241                 if (x <= rightBorder) {
242                     davinci.drawLine(x, topDist, x, topDist + m_innerScopeRect.height()+6);
243                 }
244                 if (x+textDistY < leftDist + m_innerScopeRect.width()) {
245                     // Only draw the text label if there is still enough room for the final one at the right.
246                     if (!hideText) {
247                         davinci.drawText(x-4, y, QVariant(hz/1000).toString());
248                     }
249                 }
250
251
252                 if (hz > 0) {
253                     // Draw finer lines between the main lines
254                     davinci.setPen(AbstractScopeWidget::penLightDots);
255                     for (uint dHz = 3; dHz > 0; dHz--) {
256                         x = leftDist + m_innerScopeRect.width() * ((float)hz - dHz * hzDiff/4.0f)/m_freqMax;
257                         if (x > rightBorder) {
258                             break;
259                         }
260                         davinci.drawLine(x, topDist, x, topDist + m_innerScopeRect.height()-1);
261                     }
262                 }
263             }
264             // Draw the line at the very right (maximum frequency)
265             x = leftDist + m_innerScopeRect.width()-1;
266             hideText = m_aTrackMouse->isChecked() && m_mouseWithinWidget && abs(x-(leftDist + mouseX + 30)) < (int) minDistX
267                     && mouseX < m_innerScopeRect.width() && mouseX >= 0;
268             davinci.drawLine(x, topDist, x, topDist + m_innerScopeRect.height()+6);
269             if (!hideText) {
270                 davinci.drawText(x-10, y, i18n("%1 kHz", QString("%1").arg((double)m_freqMax/1000, 0, 'f', 1)));
271             }
272         }
273
274         // Draw a line through the mouse position with the correct frequency label
275         if (m_aTrackMouse->isChecked() && m_mouseWithinWidget && mouseX < m_innerScopeRect.width() && mouseX >= 0) {
276             davinci.setPen(AbstractScopeWidget::penThin);
277             x = leftDist + mouseX;
278             davinci.drawLine(x, topDist, x, topDist + m_innerScopeRect.height()+6);
279             davinci.drawText(x-10, y, i18n("%1 kHz", QString("%1")
280                                            .arg((double)(m_mousePos.x()-m_innerScopeRect.left())/m_innerScopeRect.width() * m_freqMax/1000, 0, 'f', 2)));
281         }
282
283         // Draw the dB brightness scale
284         float val;
285         davinci.setPen(AbstractScopeWidget::penLighter);
286         for (y = topDist; y < (int)topDist + m_innerScopeRect.height(); y++) {
287             val = 1-((float)y-topDist)/(m_innerScopeRect.height()-1);
288             int col = qRgba(255, 255, 255, 255.0 * val);
289             for (x = leftDist-6; x >= (int)leftDist-13; x--) {
290                 hud.setPixel(x, y, col);
291             }
292         }
293         const int rectWidth = leftDist-m_scopeRect.left()-22;
294         const int rectHeight = 50;
295         davinci.setFont(QFont(QFont().defaultFamily(), 10));
296         davinci.drawText(m_scopeRect.left(), topDist, rectWidth, rectHeight, Qt::AlignRight, i18n("%1\ndB", m_dBmax));
297         davinci.drawText(m_scopeRect.left(), topDist + m_innerScopeRect.height()-20, rectWidth, rectHeight, Qt::AlignRight, i18n("%1\ndB", m_dBmin));
298
299
300         emit signalHUDRenderingFinished(start.elapsed(), 1);
301         return hud;
302     } else {
303         emit signalHUDRenderingFinished(0, 1);
304         return QImage();
305     }
306 }
307 QImage Spectrogram::renderAudioScope(uint, const QVector<int16_t> &audioFrame, const int freq,
308                                      const int num_channels, const int num_samples, const int newData) {
309     if (
310             audioFrame.size() > 63
311             && m_innerScopeRect.width() > 0 && m_innerScopeRect.height() > 0
312             ) {
313         if (!m_customFreq) {
314             m_freqMax = freq / 2;
315         }
316         bool newDataAvailable = newData > 0;
317
318 #ifdef DEBUG_SPECTROGRAM
319         qDebug() << "New data for " << widgetName() << ": " << newDataAvailable << " (" << newData << " units)";
320 #endif
321
322         QTime start = QTime::currentTime();
323
324         int fftWindow = ui->windowSize->itemData(ui->windowSize->currentIndex()).toInt();
325         if (fftWindow > num_samples) {
326             fftWindow = num_samples;
327         }
328         if ((fftWindow & 1) == 1) {
329             fftWindow--;
330         }
331
332         // Show the window size used, for information
333         ui->labelFFTSizeNumber->setText(QVariant(fftWindow).toString());
334
335         if (newDataAvailable) {
336
337             float freqSpectrum[fftWindow/2];
338
339             // Get the spectral power distribution of the input samples,
340             // using the given window size and function
341             FFTTools::WindowType windowType = (FFTTools::WindowType) ui->windowFunction->itemData(ui->windowFunction->currentIndex()).toInt();
342             m_fftTools.fftNormalized(audioFrame, 0, num_channels, freqSpectrum, windowType, fftWindow, 0);
343
344             // This methid might be called also when a simple refresh is required.
345             // In this case there is no data to append to the history. Only append new data.
346             QVector<float> spectrumVector(fftWindow/2);
347             memcpy(spectrumVector.data(), &freqSpectrum[0], fftWindow/2 * sizeof(float));
348             m_fftHistory.prepend(spectrumVector);
349         }
350 #ifdef DEBUG_SPECTROGRAM
351         else {
352             qDebug() << widgetName() << ": Has no new data to Fourier-transform";
353         }
354 #endif
355
356         // Limit the maximum history size to avoid wasting space
357         while (m_fftHistory.size() > SPECTROGRAM_HISTORY_SIZE) {
358             m_fftHistory.removeLast();
359         }
360
361         // Draw the spectrum
362         QImage spectrum(m_scopeRect.size(), QImage::Format_ARGB32);
363         spectrum.fill(qRgba(0,0,0,0));
364         QPainter davinci(&spectrum);
365         const uint h = m_innerScopeRect.height();
366         const uint leftDist = m_innerScopeRect.left() - m_scopeRect.left();
367         const uint topDist = m_innerScopeRect.top() - m_scopeRect.top();
368         float val;
369         uint windowSize;
370         uint y;
371         bool completeRedraw = true;
372
373         if (m_fftHistoryImg.size() == m_scopeRect.size() && !m_parameterChanged) {
374             // The size of the widget and the parameters (like min/max dB) have not changed since last time,
375             // so we can re-use it, shift it by one pixel, and render the single remaining line. Usually about
376             // 10 times faster for a widget height of around 400 px.
377             if (newDataAvailable) {
378                 davinci.drawImage(0, -1, m_fftHistoryImg);
379             } else {
380                 // spectrum = m_fftHistoryImg does NOT work, leads to segfaults (anyone knows why, please tell me)
381                 davinci.drawImage(0, 0, m_fftHistoryImg);
382             }
383             completeRedraw = false;
384         }
385
386         y = 0;
387         if (newData || m_parameterChanged) {
388             m_parameterChanged = false;
389             bool peak = false;
390
391             QVector<float> dbMap;
392             uint right;
393             for (QList<QVector<float> >::iterator it = m_fftHistory.begin(); it != m_fftHistory.end(); it++) {
394
395                 windowSize = (*it).size();
396
397                 // Interpolate the frequency data to match the pixel coordinates
398                 right = ((float) m_freqMax)/(m_freq/2) * (windowSize - 1);
399                 dbMap = FFTTools::interpolatePeakPreserving((*it), m_innerScopeRect.width(), 0, right, -180);
400
401                 for (int i = 0; i < dbMap.size(); ++i) {
402                     val = dbMap[i];
403                     peak = val > m_dBmax;
404
405                     // Normalize dB value to [0 1], 1 corresponding to dbMax dB and 0 to dbMin dB
406                     val = (val-m_dBmax)/(m_dBmax-m_dBmin) + 1;
407                     if (val < 0) {
408                         val = 0;
409                     } else if (val > 1) {
410                         val = 1;
411                     }
412                     if (!peak || !m_aHighlightPeaks->isChecked()) {
413                         spectrum.setPixel(leftDist + i, topDist + h-1 - y, qRgba(255, 255, 255, val * 255));
414                     } else {
415                         spectrum.setPixel(leftDist + i, topDist + h-1 - y, AbstractScopeWidget::colHighlightDark.rgba());
416                     }
417                 }
418
419                 y++;
420                 if (y >= topDist + m_innerScopeRect.height()) {
421                     break;
422                 }
423                 if (!completeRedraw) {
424                     break;
425                 }
426             }
427         }
428
429 #ifdef DEBUG_SPECTROGRAM
430         qDebug() << "Rendered " << y-topDist << "lines from " << m_fftHistory.size() << " available samples in " << start.elapsed() << " ms"
431                  << (completeRedraw ? "" : " (re-used old image)");
432         uint storedBytes = 0;
433         for (QList< QVector<float> >::iterator it = m_fftHistory.begin(); it != m_fftHistory.end(); it++) {
434             storedBytes += (*it).size() * sizeof((*it)[0]);
435         }
436         qDebug() << QString("Total storage used: %1 kB").arg((double)storedBytes/1000, 0, 'f', 2);
437 #endif
438
439         m_fftHistoryImg = spectrum;
440
441         emit signalScopeRenderingFinished(start.elapsed(), 1);
442         return spectrum;
443     } else {
444         emit signalScopeRenderingFinished(0, 1);
445         return QImage();
446     }
447 }
448 QImage Spectrogram::renderBackground(uint) { return QImage(); }
449
450 bool Spectrogram::isHUDDependingOnInput() const { return false; }
451 bool Spectrogram::isScopeDependingOnInput() const { return true; }
452 bool Spectrogram::isBackgroundDependingOnInput() const { return false; }
453
454 void Spectrogram::handleMouseDrag(const QPoint &movement, const RescaleDirection rescaleDirection, const Qt::KeyboardModifiers rescaleModifiers)
455 {
456     if (rescaleDirection == North) {
457         // Nort-South direction: Adjust the dB scale
458
459         if ((rescaleModifiers & Qt::ShiftModifier) == 0) {
460
461             // By default adjust the min dB value
462             m_dBmin += movement.y();
463
464         } else {
465
466             // Adjust max dB value if Shift is pressed.
467             m_dBmax += movement.y();
468
469         }
470
471         // Ensure the dB values lie in [-100, 0] (or rather [MIN_DB_VALUE, 0])
472         // 0 is the upper bound, everything below -70 dB is most likely noise
473         if (m_dBmax > 0) {
474             m_dBmax = 0;
475         }
476         if (m_dBmin < MIN_DB_VALUE) {
477             m_dBmin = MIN_DB_VALUE;
478         }
479         // Ensure there is at least 6 dB between the minimum and the maximum value;
480         // lower values hardly make sense
481         if (m_dBmax - m_dBmin < 6) {
482             if ((rescaleModifiers & Qt::ShiftModifier) == 0) {
483                 // min was adjusted; Try to adjust the max value to maintain the
484                 // minimum dB difference of 6 dB
485                 m_dBmax = m_dBmin + 6;
486                 if (m_dBmax > 0) {
487                     m_dBmax = 0;
488                     m_dBmin = -6;
489                 }
490             } else {
491                 // max was adjusted, adjust min
492                 m_dBmin = m_dBmax - 6;
493                 if (m_dBmin < MIN_DB_VALUE) {
494                     m_dBmin = MIN_DB_VALUE;
495                     m_dBmax = MIN_DB_VALUE+6;
496                 }
497             }
498         }
499
500         m_parameterChanged = true;
501         forceUpdateHUD();
502         forceUpdateScope();
503
504     } else if (rescaleDirection == East) {
505         // East-West direction: Adjust the maximum frequency
506         m_freqMax -= 100*movement.x();
507         if (m_freqMax < MIN_FREQ_VALUE) {
508             m_freqMax = MIN_FREQ_VALUE;
509         }
510         if (m_freqMax > MAX_FREQ_VALUE) {
511             m_freqMax = MAX_FREQ_VALUE;
512         }
513         m_customFreq = true;
514
515         m_parameterChanged = true;
516         forceUpdateHUD();
517         forceUpdateScope();
518     }
519 }
520
521
522
523 void Spectrogram::slotResetMaxFreq()
524 {
525     m_customFreq = false;
526     m_parameterChanged = true;
527     forceUpdateHUD();
528     forceUpdateScope();
529 }
530
531 void Spectrogram::resizeEvent(QResizeEvent *event)
532 {
533     m_parameterChanged = true;
534     AbstractAudioScopeWidget::resizeEvent(event);
535 }
536
537 #undef SPECTROGRAM_HISTORY_SIZE
538 #ifdef DEBUG_SPECTROGRAM
539 #undef DEBUG_SPECTROGRAM
540 #endif
541
542 #include "spectrogram.moc"