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