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