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