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