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