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