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