]> git.sesse.net Git - kdenlive/blob - src/audioscopes/audiospectrum.cpp
Audio spectrum: Fixed crash when the mouse cursor moved outside the widget while...
[kdenlive] / src / audioscopes / audiospectrum.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
12
13 #include "audiospectrum.h"
14 #include "ffttools.h"
15 #include "tools/kiss_fftr.h"
16
17 #include <QMenu>
18 #include <QPainter>
19 #include <QMouseEvent>
20
21 #include <iostream>
22
23 // Enables debugging
24 //#define DEBUG_AUDIOSPEC
25
26 #ifdef DEBUG_AUDIOSPEC
27 #include <QDebug>
28 #endif
29
30 #define MIN_DB_VALUE -120
31 #define MAX_FREQ_VALUE 96000
32 #define MIN_FREQ_VALUE 1000
33
34 AudioSpectrum::AudioSpectrum(QWidget *parent) :
35         AbstractAudioScopeWidget(true, parent),
36         m_fftTools(),
37         m_lastFFT(),
38         m_lastFFTLock(1)
39 {
40     ui = new Ui::AudioSpectrum_UI;
41     ui->setupUi(this);
42
43
44     m_aResetHz = new QAction(i18n("Reset maximum frequency to sampling rate"), this);
45     m_aTrackMouse = new QAction(i18n("Track mouse"), this);
46     m_aTrackMouse->setCheckable(true);
47
48
49     m_menu->addSeparator();
50     m_menu->addAction(m_aResetHz);
51     m_menu->addAction(m_aTrackMouse);
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
65     bool b = true;
66     b &= connect(m_aResetHz, SIGNAL(triggered()), this, SLOT(slotResetMaxFreq()));
67     b &= connect(ui->windowFunction, SIGNAL(currentIndexChanged(int)), this, SLOT(forceUpdate()));
68     b &= connect(this, SIGNAL(signalMousePositionChanged()), this, SLOT(forceUpdateHUD()));
69     Q_ASSERT(b);
70
71
72     // Note: These strings are used in both Spectogram and AudioSpectrum. Ideally change both (if necessary) to reduce workload on translators
73     ui->labelFFTSize->setToolTip(i18n("The maximum window size is limited by the number of samples per frame."));
74     ui->windowSize->setToolTip(i18n("A bigger window improves the accuracy at the cost of computational power."));
75     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."));
76
77     AbstractScopeWidget::init();
78 }
79 AudioSpectrum::~AudioSpectrum()
80 {
81     writeConfig();
82
83     delete m_aResetHz;
84     delete m_aTrackMouse;
85 }
86
87 void AudioSpectrum::readConfig()
88 {
89     AbstractScopeWidget::readConfig();
90
91     KSharedConfigPtr config = KGlobal::config();
92     KConfigGroup scopeConfig(config, AbstractScopeWidget::configName());
93
94     ui->windowSize->setCurrentIndex(scopeConfig.readEntry("windowSize", 0));
95     ui->windowFunction->setCurrentIndex(scopeConfig.readEntry("windowFunction", 0));
96     m_aTrackMouse->setChecked(scopeConfig.readEntry("trackMouse", true));
97     m_dBmax = scopeConfig.readEntry("dBmax", 0);
98     m_dBmin = scopeConfig.readEntry("dBmin", -70);
99     m_freqMax = scopeConfig.readEntry("freqMax", 0);
100
101     if (m_freqMax == 0) {
102         m_customFreq = false;
103         m_freqMax = 10000;
104     } else {
105         m_customFreq = true;
106     }
107 }
108 void AudioSpectrum::writeConfig()
109 {
110     KSharedConfigPtr config = KGlobal::config();
111     KConfigGroup scopeConfig(config, AbstractScopeWidget::configName());
112
113     scopeConfig.writeEntry("windowSize", ui->windowSize->currentIndex());
114     scopeConfig.writeEntry("windowFunction", ui->windowFunction->currentIndex());
115     scopeConfig.writeEntry("trackMouse", m_aTrackMouse->isChecked());
116     scopeConfig.writeEntry("dBmax", m_dBmax);
117     scopeConfig.writeEntry("dBmin", m_dBmin);
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 AudioSpectrum::widgetName() const { return QString("AudioSpectrum"); }
128 bool AudioSpectrum::isBackgroundDependingOnInput() const { return false; }
129 bool AudioSpectrum::isScopeDependingOnInput() const { return true; }
130 bool AudioSpectrum::isHUDDependingOnInput() const { return false; }
131
132 QImage AudioSpectrum::renderBackground(uint) { return QImage(); }
133
134 QImage AudioSpectrum::renderAudioScope(uint, const QVector<int16_t> audioFrame, const int freq, const int num_channels,
135                                        const int num_samples, const int)
136 {
137     if (audioFrame.size() > 63) {
138         if (!m_customFreq) {
139             m_freqMax = freq / 2;
140         }
141
142         QTime start = QTime::currentTime();
143
144
145         // Determine the window size to use. It should be
146         // * not bigger than the number of samples actually available
147         // * divisible by 2
148         int fftWindow = ui->windowSize->itemData(ui->windowSize->currentIndex()).toInt();
149         if (fftWindow > num_samples) {
150             fftWindow = num_samples;
151         }
152         if ((fftWindow & 1) == 1) {
153             fftWindow--;
154         }
155
156         // Show the window size used, for information
157         ui->labelFFTSizeNumber->setText(QVariant(fftWindow).toString());
158
159
160         // Get the spectral power distribution of the input samples,
161         // using the given window size and function
162         float freqSpectrum[fftWindow/2];
163         FFTTools::WindowType windowType = (FFTTools::WindowType) ui->windowFunction->itemData(ui->windowFunction->currentIndex()).toInt();
164         m_fftTools.fftNormalized(audioFrame, 0, num_channels, freqSpectrum, windowType, fftWindow, 0);
165
166
167         // Store the current FFT window (for the HUD) and run the interpolation
168         // for easy pixel-based dB value access
169         QVector<float> dbMap;
170         m_lastFFTLock.acquire();
171         m_lastFFT = QVector<float>(fftWindow/2);
172         memcpy(m_lastFFT.data(), &(freqSpectrum[0]), fftWindow/2 * sizeof(float));
173
174         uint right = ((float) m_freqMax)/(m_freq) * (m_lastFFT.size() - 1);
175         dbMap = interpolatePeakPreserving(m_lastFFT, m_innerScopeRect.width(), 0, right, -120);
176         m_lastFFTLock.release();
177
178
179         // Draw the spectrum
180         QImage spectrum(m_scopeRect.size(), QImage::Format_ARGB32);
181         spectrum.fill(qRgba(0,0,0,0));
182         const uint w = m_innerScopeRect.width();
183         const uint h = m_innerScopeRect.height();
184         const uint leftDist = m_innerScopeRect.left() - m_scopeRect.left();
185         const uint topDist = m_innerScopeRect.top() - m_scopeRect.top();
186         int yMax;
187
188         for (uint i = 0; i < w; i++) {
189             yMax = (dbMap[i] - m_dBmin) / (m_dBmax-m_dBmin) * (h-1);
190             if (yMax < 0) {
191                 yMax = 0;
192             } else if (yMax >= (int)h) {
193                 yMax = h-1;
194             }
195             for (int y = 0; y < yMax && y < (int)h; y++) {
196                 spectrum.setPixel(leftDist + i, topDist + h-y-1, qRgba(225, 182, 255, 255));
197             }
198         }
199
200         emit signalScopeRenderingFinished(start.elapsed(), 1);
201
202
203         return spectrum;
204     } else {
205         emit signalScopeRenderingFinished(0, 1);
206         return QImage();
207     }
208 }
209 QImage AudioSpectrum::renderHUD(uint)
210 {
211     QTime start = QTime::currentTime();
212
213     // Minimum distance between two lines
214     const uint minDistY = 30;
215     const uint minDistX = 40;
216     const uint textDistX = 10;
217     const uint textDistY = 25;
218     const uint topDist = m_innerScopeRect.top() - m_scopeRect.top();
219     const uint leftDist = m_innerScopeRect.left() - m_scopeRect.left();
220     const uint dbDiff = ceil((float)minDistY/m_innerScopeRect.height() * (m_dBmax-m_dBmin));
221     const int mouseX = m_mousePos.x() - m_innerScopeRect.left();
222     const int mouseY = m_mousePos.y() - m_innerScopeRect.top();
223
224     QImage hud(m_scopeRect.size(), QImage::Format_ARGB32);
225     hud.fill(qRgba(0,0,0,0));
226
227     QPainter davinci(&hud);
228     davinci.setPen(AbstractScopeWidget::penLight);
229
230     int y;
231     for (int db = -dbDiff; db > m_dBmin; db -= dbDiff) {
232         y = topDist + m_innerScopeRect.height() * ((float)db)/(m_dBmin - m_dBmax);
233         if (y-topDist > m_innerScopeRect.height()-minDistY+10) {
234             // Abort here, there is still a line left for min dB to paint which needs some room.
235             break;
236         }
237         davinci.drawLine(leftDist, y, leftDist + m_innerScopeRect.width()-1, y);
238         davinci.drawText(leftDist + m_innerScopeRect.width() + textDistX, y + 6, i18n("%1 dB", m_dBmax + db));
239     }
240     davinci.drawLine(leftDist, topDist, leftDist + m_innerScopeRect.width()-1, topDist);
241     davinci.drawText(leftDist + m_innerScopeRect.width() + textDistX, topDist+6, i18n("%1 dB", m_dBmax));
242     davinci.drawLine(leftDist, topDist+m_innerScopeRect.height()-1, leftDist + m_innerScopeRect.width()-1, topDist+m_innerScopeRect.height()-1);
243     davinci.drawText(leftDist + m_innerScopeRect.width() + textDistX, topDist+m_innerScopeRect.height()+6, i18n("%1 dB", m_dBmin));
244
245     const uint hzDiff = ceil( ((float)minDistX)/m_innerScopeRect.width() * m_freqMax / 1000 ) * 1000;
246     int x = 0;
247     const int rightBorder = leftDist + m_innerScopeRect.width()-1;
248     y = topDist + m_innerScopeRect.height() + textDistY;
249     for (uint hz = 0; x <= rightBorder; hz += hzDiff) {
250         davinci.setPen(AbstractScopeWidget::penLight);
251         x = leftDist + m_innerScopeRect.width() * ((float)hz)/m_freqMax;
252
253         if (x <= rightBorder) {
254             davinci.drawLine(x, topDist, x, topDist + m_innerScopeRect.height()+6);
255         }
256         if (hz < m_freqMax && x+textDistY < leftDist + m_innerScopeRect.width()) {
257             davinci.drawText(x-4, y, QVariant(hz/1000).toString());
258         } else {
259             x = leftDist + m_innerScopeRect.width();
260             davinci.drawLine(x, topDist, x, topDist + m_innerScopeRect.height()+6);
261             davinci.drawText(x-10, y, i18n("%1 kHz").arg((double)m_freqMax/1000, 0, 'f', 1));
262         }
263
264         if (hz > 0) {
265             // Draw finer lines between the main lines
266             davinci.setPen(AbstractScopeWidget::penLightDots);
267             for (uint dHz = 3; dHz > 0; dHz--) {
268                 x = leftDist + m_innerScopeRect.width() * ((float)hz - dHz * hzDiff/4.0f)/m_freqMax;
269                 if (x > rightBorder) {
270                     break;
271                 }
272                 davinci.drawLine(x, topDist, x, topDist + m_innerScopeRect.height()-1);
273             }
274         }
275     }
276
277     if (m_aTrackMouse->isChecked() && m_mouseWithinWidget && mouseX < m_innerScopeRect.width()-1) {
278         davinci.setPen(AbstractScopeWidget::penThin);
279
280         x = leftDist + mouseX;
281
282         float db = 0;
283         float freq = ((float) mouseX)/(m_innerScopeRect.width()-1) * m_freqMax;
284         bool drawDb = false;
285
286         m_lastFFTLock.acquire();
287         // We need to test whether the mouse is inside the widget
288         // because the position could already have changed in the meantime (-> crash)
289         if (m_lastFFT.size() > 0 && mouseX >= 0 && mouseX < m_innerScopeRect.width()) {
290             uint right = ((float) m_freqMax)/(m_freq) * (m_lastFFT.size() - 1);
291             QVector<float> dbMap = AudioSpectrum::interpolatePeakPreserving(m_lastFFT, m_innerScopeRect.width(), 0, right, -120);
292
293             db = dbMap[mouseX];
294             y = topDist + m_innerScopeRect.height()-1 - (dbMap[mouseX] - m_dBmin) / (m_dBmax-m_dBmin) * (m_innerScopeRect.height()-1);
295
296             if (y < (int)topDist + m_innerScopeRect.height()-1) {
297                 drawDb = true;
298                 davinci.drawLine(x, y, leftDist + m_innerScopeRect.width()-1, y);
299             }
300         } else {
301             y = topDist + mouseY;
302         }
303         m_lastFFTLock.release();
304
305         if (y > (int)topDist + mouseY) {
306             y = topDist+ mouseY;
307         }
308         davinci.drawLine(x, y, x, topDist + m_innerScopeRect.height()-1);
309
310         if (drawDb) {
311             QPoint dist(20, -20);
312             QRect rect(
313                         leftDist + mouseX + dist.x(),
314                         topDist + mouseY + dist.y(),
315                         100,
316                         40
317                         );
318             if (rect.right() > (int)leftDist + m_innerScopeRect.width()-1) {
319                 // Mirror the rectangle at the y axis to keep it inside the widget
320                 rect = QRect(
321                             rect.topLeft() - QPoint(rect.width() + 2*dist.x(), 0),
322                             rect.size());
323             }
324
325             QRect textRect(
326                         rect.topLeft() + QPoint(12, 4),
327                         rect.size()
328                         );
329
330             davinci.fillRect(rect, AbstractScopeWidget::penBackground.brush());
331             davinci.setPen(AbstractScopeWidget::penLighter);
332             davinci.drawRect(rect);
333             davinci.drawText(textRect, QString(
334                                  i18n("%1 dB", QString("%1").arg(db, 0, 'f', 2))
335                                  + "\n"
336                                  + i18n("%1 kHz", QString("%1").arg(freq/1000, 0, 'f', 2))));
337         }
338
339     }
340
341
342     emit signalHUDRenderingFinished(start.elapsed(), 1);
343     return hud;
344 }
345
346 QRect AudioSpectrum::scopeRect()
347 {
348     m_scopeRect = QRect(
349             QPoint(
350                     10,                                     // Left
351                     ui->verticalSpacer->geometry().top()+6  // Top
352             ),
353             AbstractAudioScopeWidget::rect().bottomRight()
354     );
355     m_innerScopeRect = QRect(
356             QPoint(
357                     m_scopeRect.left()+6,                   // Left
358                     m_scopeRect.top()+6                     // Top
359             ), QPoint(
360                     ui->verticalSpacer->geometry().right()-70,
361                     ui->verticalSpacer->geometry().bottom()-40
362             )
363     );
364     return m_scopeRect;
365 }
366
367 void AudioSpectrum::slotResetMaxFreq()
368 {
369     m_customFreq = false;
370     forceUpdateHUD();
371     forceUpdateScope();
372 }
373
374
375 ///// EVENTS /////
376
377 void AudioSpectrum::handleMouseDrag(const QPoint movement, const RescaleDirection rescaleDirection, const Qt::KeyboardModifiers rescaleModifiers)
378 {
379     if (rescaleDirection == North) {
380         // Nort-South direction: Adjust the dB scale
381
382         if ((rescaleModifiers & Qt::ShiftModifier) == 0) {
383
384             // By default adjust the min dB value
385             m_dBmin += movement.y();
386
387         } else {
388
389             // Adjust max dB value if Shift is pressed.
390             m_dBmax += movement.y();
391
392         }
393
394         // Ensure the dB values lie in [-100, 0] (or rather [MIN_DB_VALUE, 0])
395         // 0 is the upper bound, everything below -70 dB is most likely noise
396         if (m_dBmax > 0) {
397             m_dBmax = 0;
398         }
399         if (m_dBmin < MIN_DB_VALUE) {
400             m_dBmin = MIN_DB_VALUE;
401         }
402         // Ensure there is at least 6 dB between the minimum and the maximum value;
403         // lower values hardly make sense
404         if (m_dBmax - m_dBmin < 6) {
405             if ((rescaleModifiers & Qt::ShiftModifier) == 0) {
406                 // min was adjusted; Try to adjust the max value to maintain the
407                 // minimum dB difference of 6 dB
408                 m_dBmax = m_dBmin + 6;
409                 if (m_dBmax > 0) {
410                     m_dBmax = 0;
411                     m_dBmin = -6;
412                 }
413             } else {
414                 // max was adjusted, adjust min
415                 m_dBmin = m_dBmax - 6;
416                 if (m_dBmin < MIN_DB_VALUE) {
417                     m_dBmin = MIN_DB_VALUE;
418                     m_dBmax = MIN_DB_VALUE+6;
419                 }
420             }
421         }
422
423         forceUpdateHUD();
424         forceUpdateScope();
425
426     } else if (rescaleDirection == East) {
427         // East-West direction: Adjust the maximum frequency
428         m_freqMax -= 100*movement.x();
429         if (m_freqMax < MIN_FREQ_VALUE) {
430             m_freqMax = MIN_FREQ_VALUE;
431         }
432         if (m_freqMax > MAX_FREQ_VALUE) {
433             m_freqMax = MAX_FREQ_VALUE;
434         }
435         m_customFreq = true;
436
437         forceUpdateHUD();
438         forceUpdateScope();
439     }
440 }
441
442
443 const QVector<float> AudioSpectrum::interpolatePeakPreserving(const QVector<float> in, const uint targetSize, uint left, uint right, float fill)
444 {
445     if (right == 0) {
446         right = in.size()-1;
447     }
448     Q_ASSERT(targetSize > 0);
449     Q_ASSERT(left < right);
450
451     QVector<float> out(targetSize);
452
453
454     float x;
455     float x_prev = 0;
456     int xi;
457     uint i;
458     for (i = 0; i < targetSize; i++) {
459
460         // i:  Target index
461         // x:  Interpolated source index (float!)
462         // xi: floor(x)
463
464         // Transform [0,targetSize-1] to [left,right]
465         x = ((float) i) / (targetSize-1) * (right-left) + left;
466         xi = (int) floor(x);
467
468         if (x > in.size()-1) {
469             // This may happen if right > in.size()-1; Fill the rest of the vector
470             // with the default value now.
471             break;
472         }
473
474
475         // Use linear interpolation in order to get smoother display
476         if (i == 0 || i == targetSize-1) {
477             // ... except if we are at the left or right border of the display or the spectrum
478             out[i] = in[xi];
479         } else {
480             if (in[xi] > in[xi+1]
481                 && x_prev < xi) {
482                 // This is a hack to preserve peaks.
483                 // Consider f = {0, 100, 0}
484                 //          x = {0.5,  1.5}
485                 // Then x is 50 both times, and the 100 peak is lost.
486                 // Get it back here for the first x after the peak (which is at xi).
487                 // (x is the first after the peak if the previous x was smaller than floor(x).)
488                 out[i] = in[xi];
489             } else {
490                 out[i] =   (xi+1 - x) * in[xi]
491                       + (x - xi)   * in[xi+1];
492             }
493         }
494         x_prev = x;
495     }
496     // Fill the rest of the vector if the right border exceeds the input vector.
497     for (; i < targetSize; i++) {
498         out[i] = fill;
499     }
500
501     return out;
502 }
503
504
505 #ifdef DEBUG_AUDIOSPEC
506 #undef DEBUG_AUDIOSPEC
507 #endif
508
509 #undef MIN_DB_VALUE
510 #undef MAX_FREQ_VALUE
511 #undef MIN_FREQ_VALUE