]> git.sesse.net Git - kdenlive/blob - src/audioscopes/audiospectrum.cpp
Audio spectrum:
[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 (
151             audioFrame.size() > 63
152             && m_innerScopeRect.width() > 0 && m_innerScopeRect.height() > 0    // <= 0 if widget is too small (resized by user)
153     ) {
154         if (!m_customFreq) {
155             m_freqMax = freq / 2;
156         }
157
158         QTime start = QTime::currentTime();
159
160
161         // Determine the window size to use. It should be
162         // * not bigger than the number of samples actually available
163         // * divisible by 2
164         int fftWindow = ui->windowSize->itemData(ui->windowSize->currentIndex()).toInt();
165         if (fftWindow > num_samples) {
166             fftWindow = num_samples;
167         }
168         if ((fftWindow & 1) == 1) {
169             fftWindow--;
170         }
171
172         // Show the window size used, for information
173         ui->labelFFTSizeNumber->setText(QVariant(fftWindow).toString());
174
175
176         // Get the spectral power distribution of the input samples,
177         // using the given window size and function
178         float freqSpectrum[fftWindow/2];
179         FFTTools::WindowType windowType = (FFTTools::WindowType) ui->windowFunction->itemData(ui->windowFunction->currentIndex()).toInt();
180         m_fftTools.fftNormalized(audioFrame, 0, num_channels, freqSpectrum, windowType, fftWindow, 0);
181
182
183         // Store the current FFT window (for the HUD) and run the interpolation
184         // for easy pixel-based dB value access
185         QVector<float> dbMap;
186         m_lastFFTLock.acquire();
187         m_lastFFT = QVector<float>(fftWindow/2);
188         memcpy(m_lastFFT.data(), &(freqSpectrum[0]), fftWindow/2 * sizeof(float));
189
190         uint right = ((float) m_freqMax)/(m_freq/2) * (m_lastFFT.size() - 1);
191         dbMap = FFTTools::interpolatePeakPreserving(m_lastFFT, m_innerScopeRect.width(), 0, right, -180);
192         m_lastFFTLock.release();
193
194
195 #ifdef DEBUG_AUDIOSPEC
196         QTime drawTime = QTime::currentTime();
197 #endif
198
199         // Draw the spectrum
200         QImage spectrum(m_scopeRect.size(), QImage::Format_ARGB32);
201         spectrum.fill(qRgba(0,0,0,0));
202         const uint w = m_innerScopeRect.width();
203         const uint h = m_innerScopeRect.height();
204         const uint leftDist = m_innerScopeRect.left() - m_scopeRect.left();
205         const uint topDist = m_innerScopeRect.top() - m_scopeRect.top();
206         int yMax;
207
208 #ifdef AUDIOSPEC_LINES
209         QPainter davinci(&spectrum);
210         davinci.setPen(AbstractScopeWidget::penThin);
211 #endif
212
213         for (uint i = 0; i < w; i++) {
214             yMax = (dbMap[i] - m_dBmin) / (m_dBmax-m_dBmin) * (h-1);
215             if (yMax < 0) {
216                 yMax = 0;
217             } else if (yMax >= (int)h) {
218                 yMax = h-1;
219             }
220 #ifdef AUDIOSPEC_LINES
221             davinci.drawLine(leftDist + i, topDist + h-1, leftDist + i, topDist + h-1 - yMax);
222 #else
223             for (int y = 0; y < yMax && y < (int)h; y++) {
224                 spectrum.setPixel(leftDist + i, topDist + h-y-1, qRgba(225, 182, 255, 255));
225             }
226 #endif
227         }
228
229         // Calculate the peak values. Use the new value if it is bigger, otherwise adapt to lower
230         // values using the Moving Average formula
231         if (m_aShowMax->isChecked()) {
232             davinci.setPen(QPen(QBrush(AbstractScopeWidget::colHighlightLight), 2));
233             if (m_peaks.size() != fftWindow/2) {
234                 m_peaks = QVector<float>(m_lastFFT);
235             } else {
236                 for (int i = 0; i < fftWindow/2; i++) {
237                     if (m_lastFFT[i] > m_peaks[i]) {
238                         m_peaks[i] = m_lastFFT[i];
239                     } else {
240                         m_peaks[i] = ALPHA_MOVING_AVG * m_lastFFT[i] + (1-ALPHA_MOVING_AVG) * m_peaks[i];
241                     }
242                 }
243             }
244             int prev = 0;
245             m_peakMap = FFTTools::interpolatePeakPreserving(m_peaks, m_innerScopeRect.width(), 0, right, -180);
246             for (uint i = 0; i < w; i++) {
247                 yMax = (m_peakMap[i] - m_dBmin) / (m_dBmax-m_dBmin) * (h-1);
248                 if (yMax < 0) {
249                     yMax = 0;
250                 } else if (yMax >= (int)h) {
251                     yMax = h-1;
252                 }
253
254                 davinci.drawLine(leftDist + i-1, topDist + h-prev-1, leftDist + i, topDist + h-yMax-1);
255                 spectrum.setPixel(leftDist + i, topDist + h-yMax-1, AbstractScopeWidget::colHighlightLight.rgba());
256                 prev = yMax;
257             }
258         }
259
260 #ifdef DEBUG_AUDIOSPEC
261         m_showTotal++;
262         m_timeTotal += drawTime.elapsed();
263         qDebug() << widgetName() << " took " << drawTime.elapsed() << " ms for drawing. Average: " << ((float)m_timeTotal/m_showTotal) ;
264 #endif
265
266         emit signalScopeRenderingFinished(start.elapsed(), 1);
267
268
269         return spectrum;
270     } else {
271         emit signalScopeRenderingFinished(0, 1);
272         return QImage();
273     }
274 }
275 QImage AudioSpectrum::renderHUD(uint)
276 {
277     QTime start = QTime::currentTime();
278
279     if (m_innerScopeRect.height() > 0 && m_innerScopeRect.width() > 0) { // May be below 0 if widget is too small
280
281         // Minimum distance between two lines
282         const uint minDistY = 30;
283         const uint minDistX = 40;
284         const uint textDistX = 10;
285         const uint textDistY = 25;
286         const uint topDist = m_innerScopeRect.top() - m_scopeRect.top();
287         const uint leftDist = m_innerScopeRect.left() - m_scopeRect.left();
288         const uint dbDiff = ceil((float)minDistY/m_innerScopeRect.height() * (m_dBmax-m_dBmin));
289         const int mouseX = m_mousePos.x() - m_innerScopeRect.left();
290         const int mouseY = m_mousePos.y() - m_innerScopeRect.top();
291
292
293         QImage hud(m_scopeRect.size(), QImage::Format_ARGB32);
294         hud.fill(qRgba(0,0,0,0));
295
296         QPainter davinci(&hud);
297         davinci.setPen(AbstractScopeWidget::penLight);
298
299         int _dw = m_innerScopeRect.width();
300         int _dh = m_innerScopeRect.height();
301         int _dld = m_innerScopeRect.width() + leftDist + textDistX;
302         int _dtd = topDist+ m_innerScopeRect.height() + 6;
303         int _fw = AbstractScopeWidget::geometry().width();
304         int _fh = AbstractScopeWidget::geometry().height();
305
306         int y;
307         for (int db = -dbDiff; db > m_dBmin; db -= dbDiff) {
308             y = topDist + m_innerScopeRect.height() * ((float)db)/(m_dBmin - m_dBmax);
309             if (y-topDist > m_innerScopeRect.height()-minDistY+10) {
310                 // Abort here, there is still a line left for min dB to paint which needs some room.
311                 break;
312             }
313             davinci.drawLine(leftDist, y, leftDist + m_innerScopeRect.width()-1, y);
314             davinci.drawText(leftDist + m_innerScopeRect.width() + textDistX, y + 6, i18n("%1 dB", m_dBmax + db));
315         }
316         davinci.drawLine(leftDist, topDist, leftDist + m_innerScopeRect.width()-1, topDist);
317         davinci.drawText(leftDist + m_innerScopeRect.width() + textDistX, topDist+6, i18n("%1 dB", m_dBmax));
318         davinci.drawLine(leftDist, topDist+m_innerScopeRect.height()-1, leftDist + m_innerScopeRect.width()-1, topDist+m_innerScopeRect.height()-1);
319         davinci.drawText(leftDist + m_innerScopeRect.width() + textDistX, topDist+m_innerScopeRect.height()+6, i18n("%1 dB", m_dBmin));
320
321         const uint hzDiff = ceil( ((float)minDistX)/m_innerScopeRect.width() * m_freqMax / 1000 ) * 1000;
322         int x = 0;
323         const int rightBorder = leftDist + m_innerScopeRect.width()-1;
324         y = topDist + m_innerScopeRect.height() + textDistY;
325         for (int hz = 0; x <= rightBorder; hz += hzDiff) {
326             davinci.setPen(AbstractScopeWidget::penLighter);
327             x = leftDist + m_innerScopeRect.width() * ((float)hz)/m_freqMax;
328
329             if (x <= rightBorder) {
330                 davinci.drawLine(x, topDist, x, topDist + m_innerScopeRect.height()+6);
331             }
332             if (hz < m_freqMax && x+textDistY < leftDist + m_innerScopeRect.width()) {
333                 davinci.drawText(x-4, y, QVariant(hz/1000).toString());
334             } else {
335                 x = leftDist + m_innerScopeRect.width();
336                 davinci.drawLine(x, topDist, x, topDist + m_innerScopeRect.height()+6);
337                 davinci.drawText(x-10, y, i18n("%1 kHz").arg((double)m_freqMax/1000, 0, 'f', 1));
338             }
339
340             if (hz > 0) {
341                 // Draw finer lines between the main lines
342                 davinci.setPen(AbstractScopeWidget::penLightDots);
343                 for (uint dHz = 3; dHz > 0; dHz--) {
344                     x = leftDist + m_innerScopeRect.width() * ((float)hz - dHz * hzDiff/4.0f)/m_freqMax;
345                     if (x > rightBorder) {
346                         break;
347                     }
348                     davinci.drawLine(x, topDist, x, topDist + m_innerScopeRect.height()-1);
349                 }
350             }
351         }
352
353         if (m_aTrackMouse->isChecked() && m_mouseWithinWidget && mouseX < m_innerScopeRect.width()-1) {
354             davinci.setPen(AbstractScopeWidget::penThin);
355
356             x = leftDist + mouseX;
357
358             float db = 0;
359             float freq = ((float) mouseX)/(m_innerScopeRect.width()-1) * m_freqMax;
360             bool drawDb = false;
361
362             m_lastFFTLock.acquire();
363             // We need to test whether the mouse is inside the widget
364             // because the position could already have changed in the meantime (-> crash)
365             if (m_lastFFT.size() > 0 && mouseX >= 0 && mouseX < m_innerScopeRect.width()) {
366                 uint right = ((float) m_freqMax)/(m_freq/2) * (m_lastFFT.size() - 1);
367                 QVector<float> dbMap = FFTTools::interpolatePeakPreserving(m_lastFFT, m_innerScopeRect.width(), 0, right, -120);
368
369                 db = dbMap[mouseX];
370                 y = topDist + m_innerScopeRect.height()-1 - (dbMap[mouseX] - m_dBmin) / (m_dBmax-m_dBmin) * (m_innerScopeRect.height()-1);
371
372                 if (y < (int)topDist + m_innerScopeRect.height()-1) {
373                     drawDb = true;
374                     davinci.drawLine(x, y, leftDist + m_innerScopeRect.width()-1, y);
375                 }
376             } else {
377                 y = topDist + mouseY;
378             }
379             m_lastFFTLock.release();
380
381             if (y > (int)topDist + mouseY) {
382                 y = topDist+ mouseY;
383             }
384             davinci.drawLine(x, y, x, topDist + m_innerScopeRect.height()-1);
385
386             if (drawDb) {
387                 QPoint dist(20, -20);
388                 QRect rect(
389                             leftDist + mouseX + dist.x(),
390                             topDist + mouseY + dist.y(),
391                             100,
392                             40
393                             );
394                 if (rect.right() > (int)leftDist + m_innerScopeRect.width()-1) {
395                     // Mirror the rectangle at the y axis to keep it inside the widget
396                     rect = QRect(
397                                 rect.topLeft() - QPoint(rect.width() + 2*dist.x(), 0),
398                                 rect.size());
399                 }
400
401                 QRect textRect(
402                             rect.topLeft() + QPoint(12, 4),
403                             rect.size()
404                             );
405
406                 davinci.fillRect(rect, AbstractScopeWidget::penBackground.brush());
407                 davinci.setPen(AbstractScopeWidget::penLighter);
408                 davinci.drawRect(rect);
409                 davinci.drawText(textRect, QString(
410                                      i18n("%1 dB", QString("%1").arg(db, 0, 'f', 2))
411                                      + "\n"
412                                      + i18n("%1 kHz", QString("%1").arg(freq/1000, 0, 'f', 2))));
413             }
414
415         }
416
417         emit signalHUDRenderingFinished(start.elapsed(), 1);
418         return hud;
419
420     } else {
421 #ifdef DEBUG_AUDIOSPEC
422         qDebug() << "Widget is too small for painting inside. Size of inner scope rect is "
423                  << m_innerScopeRect.width() << "x" << m_innerScopeRect.height() <<".";
424 #endif
425         emit signalHUDRenderingFinished(0, 1);
426         return QImage();
427     }
428
429 }
430
431 QRect AudioSpectrum::scopeRect()
432 {
433     m_scopeRect = QRect(
434             QPoint(
435                     10,                                     // Left
436                     ui->verticalSpacer->geometry().top()+6  // Top
437             ),
438             AbstractAudioScopeWidget::rect().bottomRight()
439     );
440     m_innerScopeRect = QRect(
441             QPoint(
442                     m_scopeRect.left()+6,                   // Left
443                     m_scopeRect.top()+6                     // Top
444             ), QPoint(
445                     ui->verticalSpacer->geometry().right()-70,
446                     ui->verticalSpacer->geometry().bottom()-40
447             )
448     );
449     return m_scopeRect;
450 }
451
452 void AudioSpectrum::slotResetMaxFreq()
453 {
454     m_customFreq = false;
455     forceUpdateHUD();
456     forceUpdateScope();
457 }
458
459
460 ///// EVENTS /////
461
462 void AudioSpectrum::handleMouseDrag(const QPoint movement, const RescaleDirection rescaleDirection, const Qt::KeyboardModifiers rescaleModifiers)
463 {
464     if (rescaleDirection == North) {
465         // Nort-South direction: Adjust the dB scale
466
467         if ((rescaleModifiers & Qt::ShiftModifier) == 0) {
468
469             // By default adjust the min dB value
470             m_dBmin += movement.y();
471
472         } else {
473
474             // Adjust max dB value if Shift is pressed.
475             m_dBmax += movement.y();
476
477         }
478
479         // Ensure the dB values lie in [-100, 0] (or rather [MIN_DB_VALUE, 0])
480         // 0 is the upper bound, everything below -70 dB is most likely noise
481         if (m_dBmax > 0) {
482             m_dBmax = 0;
483         }
484         if (m_dBmin < MIN_DB_VALUE) {
485             m_dBmin = MIN_DB_VALUE;
486         }
487         // Ensure there is at least 6 dB between the minimum and the maximum value;
488         // lower values hardly make sense
489         if (m_dBmax - m_dBmin < 6) {
490             if ((rescaleModifiers & Qt::ShiftModifier) == 0) {
491                 // min was adjusted; Try to adjust the max value to maintain the
492                 // minimum dB difference of 6 dB
493                 m_dBmax = m_dBmin + 6;
494                 if (m_dBmax > 0) {
495                     m_dBmax = 0;
496                     m_dBmin = -6;
497                 }
498             } else {
499                 // max was adjusted, adjust min
500                 m_dBmin = m_dBmax - 6;
501                 if (m_dBmin < MIN_DB_VALUE) {
502                     m_dBmin = MIN_DB_VALUE;
503                     m_dBmax = MIN_DB_VALUE+6;
504                 }
505             }
506         }
507
508         forceUpdateHUD();
509         forceUpdateScope();
510
511     } else if (rescaleDirection == East) {
512         // East-West direction: Adjust the maximum frequency
513         m_freqMax -= 100*movement.x();
514         if (m_freqMax < MIN_FREQ_VALUE) {
515             m_freqMax = MIN_FREQ_VALUE;
516         }
517         if (m_freqMax > MAX_FREQ_VALUE) {
518             m_freqMax = MAX_FREQ_VALUE;
519         }
520         m_customFreq = true;
521
522         forceUpdateHUD();
523         forceUpdateScope();
524     }
525 }