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