]> git.sesse.net Git - kdenlive/blob - src/audioscopes/audiospectrum.cpp
Audio scopes: Caching window functions for better performance
[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 // Enables debugging, like writing a GNU Octave .m file to /tmp
24 //#define DEBUG_AUDIOSPEC
25 #ifdef DEBUG_AUDIOSPEC
26 #include <fstream>
27 #include <QDebug>
28 bool fileWritten = false;
29 #endif
30
31 #define MIN_DB_VALUE -120
32 #define MAX_FREQ_VALUE 96000
33 #define MIN_FREQ_VALUE 1000
34
35 const QString AudioSpectrum::directions[] =  {"North", "Northeast", "East", "Southeast"};
36
37 AudioSpectrum::AudioSpectrum(QWidget *parent) :
38         AbstractAudioScopeWidget(false, parent),
39         m_windowFunctions(),
40         m_freqMax(10000),
41         m_customFreq(false),
42         m_rescaleMinDist(8),
43         m_rescaleVerticalThreshold(2.0f),
44         m_rescaleActive(false),
45         m_rescalePropertiesLocked(false),
46         m_rescaleScale(1)
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
54
55     m_menu->addSeparator();
56     m_menu->addAction(m_aResetHz);
57
58
59     ui->windowSize->addItem("256", QVariant(256));
60     ui->windowSize->addItem("512", QVariant(512));
61     ui->windowSize->addItem("1024", QVariant(1024));
62     ui->windowSize->addItem("2048", QVariant(2048));
63
64     ui->windowFunction->addItem(i18n("Rectangular window"), FFTTools::Window_Rect);
65     ui->windowFunction->addItem(i18n("Triangular window"), FFTTools::Window_Triangle);
66     ui->windowFunction->addItem(i18n("Hamming window"), FFTTools::Window_Hamming);
67
68
69     m_cfg = kiss_fftr_alloc(ui->windowSize->itemData(ui->windowSize->currentIndex()).toInt(), 0,0,0);
70
71
72     bool b = true;
73     b &= connect(ui->windowSize, SIGNAL(currentIndexChanged(int)), this, SLOT(slotUpdateCfg()));
74     b &= connect(m_aResetHz, SIGNAL(triggered()), this, SLOT(slotResetMaxFreq()));
75     Q_ASSERT(b);
76
77     AbstractScopeWidget::init();
78 }
79 AudioSpectrum::~AudioSpectrum()
80 {
81     writeConfig();
82
83     free(m_cfg);
84     delete m_aResetHz;
85 }
86
87 void AudioSpectrum::readConfig()
88 {
89     AbstractScopeWidget::readConfig();
90
91     KSharedConfigPtr config = KGlobal::config();
92     KConfigGroup scopeConfig(config, AbstractScopeWidget::configName());
93
94     ui->windowSize->setCurrentIndex(scopeConfig.readEntry("windowSize", 0));
95     ui->windowFunction->setCurrentIndex(scopeConfig.readEntry("windowFunction", 0));
96     m_dBmax = scopeConfig.readEntry("dBmax", 0);
97     m_dBmin = scopeConfig.readEntry("dBmin", -70);
98     m_freqMax = scopeConfig.readEntry("freqMax", 0);
99
100     if (m_freqMax == 0) {
101         m_customFreq = false;
102         m_freqMax = 10000;
103     } else {
104         m_customFreq = true;
105     }
106 }
107 void AudioSpectrum::writeConfig()
108 {
109     KSharedConfigPtr config = KGlobal::config();
110     KConfigGroup scopeConfig(config, AbstractScopeWidget::configName());
111
112     scopeConfig.writeEntry("windowSize", ui->windowSize->currentIndex());
113     scopeConfig.writeEntry("windowFunction", ui->windowFunction->currentIndex());
114     scopeConfig.writeEntry("dBmax", m_dBmax);
115     scopeConfig.writeEntry("dBmin", m_dBmin);
116     if (m_customFreq) {
117         scopeConfig.writeEntry("freqMax", m_freqMax);
118     } else {
119         scopeConfig.writeEntry("freqMax", 0);
120     }
121
122     scopeConfig.sync();
123 }
124
125 QString AudioSpectrum::widgetName() const { return QString("AudioSpectrum"); }
126 bool AudioSpectrum::isBackgroundDependingOnInput() const { return false; }
127 bool AudioSpectrum::isScopeDependingOnInput() const { return true; }
128 bool AudioSpectrum::isHUDDependingOnInput() const { return false; }
129
130 QImage AudioSpectrum::renderBackground(uint) { return QImage(); }
131
132 QImage AudioSpectrum::renderAudioScope(uint, const QVector<int16_t> audioFrame, const int freq, const int num_channels, const int num_samples)
133 {
134     if (audioFrame.size() > 63) {
135         if (!m_customFreq) {
136             m_freqMax = freq / 2;
137         }
138
139         QTime start = QTime::currentTime();
140
141         bool customCfg = false;
142         kiss_fftr_cfg myCfg = m_cfg;
143         int fftWindow = ui->windowSize->itemData(ui->windowSize->currentIndex()).toInt();
144         if (fftWindow > num_samples) {
145             fftWindow = num_samples;
146             customCfg = true;
147         }
148         if ((fftWindow & 1) == 1) {
149             fftWindow--;
150             customCfg = true;
151         }
152         if (customCfg) {
153             myCfg = kiss_fftr_alloc(fftWindow, 0,0,0);
154         }
155
156         float data[fftWindow];
157         float freqSpectrum[fftWindow/2];
158
159         int16_t maxSig = 0;
160         for (int i = 0; i < fftWindow; i++) {
161             if (audioFrame.data()[i*num_channels] > maxSig) {
162                 maxSig = audioFrame.data()[i*num_channels];
163             }
164         }
165
166         // Prepare frequency space vector. The resulting FFT vector is only half as long.
167         kiss_fft_cpx freqData[fftWindow/2];
168
169
170
171         // Copy the first channel's audio into a vector for the FFT display
172         // (only one channel handled at the moment)
173         if (num_samples < fftWindow) {
174             std::fill(&data[num_samples], &data[fftWindow-1], 0);
175         }
176
177         FFTTools::WindowType windowType = (FFTTools::WindowType) ui->windowFunction->itemData(ui->windowFunction->currentIndex()).toInt();
178         QVector<float> window;
179         float windowScaleFactor = 1;
180         if (windowType != FFTTools::Window_Rect) {
181             const QString signature = FFTTools::windowSignature(windowType, fftWindow, 0);
182             if (m_windowFunctions.contains(signature)) {
183 #ifdef DEBUG_AUDIOSPEC
184                 qDebug() << "Re-using window function with signature " << signature;
185 #endif
186                 window = m_windowFunctions.value(signature);
187             } else {
188 #ifdef DEBUG_AUDIOSPEC
189                 qDebug() << "Building new window function with signature " << signature;
190 #endif
191                 window = FFTTools::window(windowType, fftWindow, 0);
192                 m_windowFunctions.insert(signature, window);
193             }
194             windowScaleFactor = 1.0/window[fftWindow];
195         }
196
197         // Normalize signals to [0,1] to get correct dB values later on
198         for (int i = 0; i < num_samples && i < fftWindow; i++) {
199             if (windowType != FFTTools::Window_Rect) {
200                 data[i] = (float) audioFrame.data()[i*num_channels] / 32767.0f * window[i];
201             } else {
202                 data[i] = (float) audioFrame.data()[i*num_channels] / 32767.0f;
203             }
204         }
205
206         // Calculate the Fast Fourier Transform for the input data
207         kiss_fftr(myCfg, data, freqData);
208
209
210         // Logarithmic scale: 20 * log ( 2 * magnitude / N ) with magnitude = sqrt(r² + i²)
211         // with N = FFT size (after FFT, 1/2 window size)
212         for (int i = 0; i < fftWindow/2; i++) {
213             // Logarithmic scale: 20 * log ( 2 * magnitude / N ) with magnitude = sqrt(r² + i²)
214             // with N = FFT size (after FFT, 1/2 window size)
215             freqSpectrum[i] = 20*log(pow(pow(fabs(freqData[i].r * windowScaleFactor),2) + pow(fabs(freqData[i].i * windowScaleFactor),2), .5)/((float)fftWindow/2.0f))/log(10);;
216         }
217
218
219
220         // Draw the spectrum
221         QImage spectrum(m_scopeRect.size(), QImage::Format_ARGB32);
222         spectrum.fill(qRgba(0,0,0,0));
223         const uint w = m_innerScopeRect.width();
224         const uint h = m_innerScopeRect.height();
225         const uint leftDist = m_innerScopeRect.left() - m_scopeRect.left();
226         const uint topDist = m_innerScopeRect.top() - m_scopeRect.top();
227         float f;
228         float x;
229         float x_prev = 0;
230         float val;
231         int xi;
232         for (uint i = 0; i < w; i++) {
233
234             // i:  Pixel coordinate
235             // f: Target frequency
236             // x:  Frequency array index (float!) corresponding to the pixel
237             // xi: floor(x)
238
239             f = i/((float) w-1.0) * m_freqMax;
240             x = 2*f/freq * (fftWindow/2 - 1);
241             xi = (int) floor(x);
242
243             if (x >= fftWindow/2) {
244                 break;
245             }
246
247             // Use linear interpolation in order to get smoother display
248             if (i == 0 || xi == fftWindow/2-1) {
249                 // ... except if we are at the left or right border of the display or the spectrum
250                 val = freqSpectrum[xi];
251             } else {
252
253                 if (freqSpectrum[xi] > freqSpectrum[xi+1]
254                     && x_prev < xi) {
255                     // This is a hack to preserve peaks.
256                     // Consider f = {0, 100, 0}
257                     //          x = {0.5,  1.5}
258                     // Then x is 50 both times, and the 100 peak is lost.
259                     // Get it back here for the first x after the peak.
260                     val = freqSpectrum[xi];
261                 } else {
262                     val =   (xi+1 - x) * freqSpectrum[xi]
263                           + (x - xi)   * freqSpectrum[xi+1];
264                 }
265             }
266
267             // freqSpectrum values range from 0 to -inf as they are relative dB values.
268             for (uint y = 0; y < h*(1 - (val - m_dBmax)/(m_dBmin-m_dBmax)) && y < h; y++) {
269                 spectrum.setPixel(leftDist + i, topDist + h-y-1, qRgba(225, 182, 255, 255));
270             }
271
272             x_prev = x;
273         }
274
275         emit signalScopeRenderingFinished(start.elapsed(), 1);
276
277 #ifdef DEBUG_AUDIOSPEC
278         if (!fileWritten || true) {
279             std::ofstream mFile;
280             mFile.open("/tmp/freq.m");
281             if (!mFile) {
282                 qDebug() << "Opening file failed.";
283             } else {
284                 mFile << "val = [ ";
285
286                 for (int sample = 0; sample < 256; sample++) {
287                     mFile << data[sample] << " ";
288                 }
289                 mFile << " ];\n";
290
291                 mFile << "freq = [ ";
292                 for (int sample = 0; sample < 256; sample++) {
293                     mFile << freqData[sample].r << "+" << freqData[sample].i << "*i ";
294                 }
295                 mFile << " ];\n";
296
297                 mFile.close();
298                 fileWritten = true;
299                 qDebug() << "File written.";
300             }
301         } else {
302             qDebug() << "File already written.";
303         }
304 #endif
305
306         if (customCfg) {
307             free(myCfg);
308         }
309
310         return spectrum;
311     } else {
312         emit signalScopeRenderingFinished(0, 1);
313         return QImage();
314     }
315 }
316 QImage AudioSpectrum::renderHUD(uint)
317 {
318     QTime start = QTime::currentTime();
319
320     // Minimum distance between two lines
321     const uint minDistY = 30;
322     const uint minDistX = 40;
323     const uint textDistX = 10;
324     const uint textDistY = 25;
325     const uint topDist = m_innerScopeRect.top() - m_scopeRect.top();
326     const uint leftDist = m_innerScopeRect.left() - m_scopeRect.left();
327     const uint dbDiff = ceil((float)minDistY/m_innerScopeRect.height() * (m_dBmax-m_dBmin));
328
329     QImage hud(m_scopeRect.size(), QImage::Format_ARGB32);
330     hud.fill(qRgba(0,0,0,0));
331
332     QPainter davinci(&hud);
333     davinci.setPen(AbstractAudioScopeWidget::penLight);
334
335     int y;
336     for (int db = -dbDiff; db > m_dBmin; db -= dbDiff) {
337         y = topDist + m_innerScopeRect.height() * ((float)db)/(m_dBmin - m_dBmax);
338         if (y-topDist > m_innerScopeRect.height()-minDistY+10) {
339             // Abort here, there is still a line left for min dB to paint which needs some room.
340             break;
341         }
342         davinci.drawLine(leftDist, y, leftDist + m_innerScopeRect.width()-1, y);
343         davinci.drawText(leftDist + m_innerScopeRect.width() + textDistX, y + 6, i18n("%1 dB", m_dBmax + db));
344     }
345     davinci.drawLine(leftDist, topDist, leftDist + m_innerScopeRect.width()-1, topDist);
346     davinci.drawText(leftDist + m_innerScopeRect.width() + textDistX, topDist+6, i18n("%1 dB", m_dBmax));
347     davinci.drawLine(leftDist, topDist+m_innerScopeRect.height()-1, leftDist + m_innerScopeRect.width()-1, topDist+m_innerScopeRect.height()-1);
348     davinci.drawText(leftDist + m_innerScopeRect.width() + textDistX, topDist+m_innerScopeRect.height()+6, i18n("%1 dB", m_dBmin));
349
350     const uint hzDiff = ceil( ((float)minDistX)/m_innerScopeRect.width() * m_freqMax / 1000 ) * 1000;
351     int x;
352     y = topDist + m_innerScopeRect.height() + textDistY;
353     for (uint hz = 0; hz <= m_freqMax; hz += hzDiff) {
354         x = leftDist + m_innerScopeRect.width() * ((float)hz)/m_freqMax;
355         davinci.drawLine(x, topDist, x, topDist + m_innerScopeRect.height()+6);
356         if (hz < m_freqMax) {
357             davinci.drawText(x-4, y, QVariant(hz/1000).toString());
358         } else {
359             davinci.drawText(x-10, y, i18n("%1 kHz",hz/1000));
360         }
361
362         if (hz > 0) {
363             for (uint dHz = 1; dHz < 4; dHz++) {
364                 x = leftDist + m_innerScopeRect.width() * ((float)hz - dHz * hzDiff/4.0f)/m_freqMax;
365                 davinci.drawLine(x, topDist, x, topDist + m_innerScopeRect.height()-1);
366             }
367         }
368     }
369
370
371     emit signalHUDRenderingFinished(start.elapsed(), 1);
372     return hud;
373 }
374
375 QRect AudioSpectrum::scopeRect() {
376     m_scopeRect = QRect(
377             QPoint(
378                     10,                                     // Left
379                     ui->verticalSpacer->geometry().top()+6  // Top
380             ),
381             AbstractAudioScopeWidget::rect().bottomRight()
382     );
383     m_innerScopeRect = QRect(
384             QPoint(
385                     m_scopeRect.left()+6,                   // Left
386                     m_scopeRect.top()+6                     // Top
387             ), QPoint(
388                     ui->verticalSpacer->geometry().right()-70,
389                     ui->verticalSpacer->geometry().bottom()-40
390             )
391     );
392     return m_scopeRect;
393 }
394
395
396 void AudioSpectrum::slotUpdateCfg()
397 {
398     free(m_cfg);
399     m_cfg = kiss_fftr_alloc(ui->windowSize->itemData(ui->windowSize->currentIndex()).toInt(), 0,0,0);
400 }
401
402 void AudioSpectrum::slotResetMaxFreq()
403 {
404     m_customFreq = false;
405     forceUpdateHUD();
406     forceUpdateScope();
407 }
408
409
410 ///// EVENTS /////
411
412 void AudioSpectrum::mouseMoveEvent(QMouseEvent *event)
413 {
414     QPoint movement = event->pos()-m_rescaleStartPoint;
415
416     if (m_rescaleActive) {
417         if (m_rescalePropertiesLocked) {
418             // Direction is known, now adjust parameters
419
420             // Reset the starting point to make the next moveEvent relative to the current one
421             m_rescaleStartPoint = event->pos();
422
423
424             if (!m_rescaleFirstRescaleDone) {
425                 // We have just learned the desired direction; Normalize the movement to one pixel
426                 // to avoid a jump by m_rescaleMinDist
427
428                 if (movement.x() != 0) {
429                     movement.setX(movement.x() / abs(movement.x()));
430                 }
431                 if (movement.y() != 0) {
432                     movement.setY(movement.y() / abs(movement.y()));
433                 }
434
435                 m_rescaleFirstRescaleDone = true;
436             }
437
438             if (m_rescaleClockDirection == AudioSpectrum::North) {
439                 // Nort-South direction: Adjust the dB scale
440
441                 if ((m_rescaleModifiers & Qt::ShiftModifier) == 0) {
442
443                     // By default adjust the min dB value
444                     m_dBmin += movement.y();
445
446                 } else {
447
448                     // Adjust max dB value if Shift is pressed.
449                     m_dBmax += movement.y();
450
451                 }
452
453                 // Ensure the dB values lie in [-100, 0] (or rather [MIN_DB_VALUE, 0])
454                 // 0 is the upper bound, everything below -70 dB is most likely noise
455                 if (m_dBmax > 0) {
456                     m_dBmax = 0;
457                 }
458                 if (m_dBmin < MIN_DB_VALUE) {
459                     m_dBmin = MIN_DB_VALUE;
460                 }
461                 // Ensure there is at least 6 dB between the minimum and the maximum value;
462                 // lower values hardly make sense
463                 if (m_dBmax - m_dBmin < 6) {
464                     if ((m_rescaleModifiers & Qt::ShiftModifier) == 0) {
465                         // min was adjusted; Try to adjust the max value to maintain the
466                         // minimum dB difference of 6 dB
467                         m_dBmax = m_dBmin + 6;
468                         if (m_dBmax > 0) {
469                             m_dBmax = 0;
470                             m_dBmin = -6;
471                         }
472                     } else {
473                         // max was adjusted, adjust min
474                         m_dBmin = m_dBmax - 6;
475                         if (m_dBmin < MIN_DB_VALUE) {
476                             m_dBmin = MIN_DB_VALUE;
477                             m_dBmax = MIN_DB_VALUE+6;
478                         }
479                     }
480                 }
481
482                 forceUpdateHUD();
483                 forceUpdateScope();
484
485             } else if (m_rescaleClockDirection == AudioSpectrum::East) {
486                 // East-West direction: Adjust the maximum frequency
487                 m_freqMax -= 100*movement.x();
488                 if (m_freqMax < MIN_FREQ_VALUE) {
489                     m_freqMax = MIN_FREQ_VALUE;
490                 }
491                 if (m_freqMax > MAX_FREQ_VALUE) {
492                     m_freqMax = MAX_FREQ_VALUE;
493                 }
494                 m_customFreq = true;
495
496                 forceUpdateHUD();
497                 forceUpdateScope();
498             }
499
500
501         } else {
502             // Detect the movement direction here.
503             // This algorithm relies on the aspect ratio of dy/dx (size and signum).
504             if (movement.manhattanLength() > m_rescaleMinDist) {
505                 float diff = ((float) movement.y())/movement.x();
506
507                 if (abs(diff) > m_rescaleVerticalThreshold || movement.x() == 0) {
508                     m_rescaleClockDirection = AudioSpectrum::North;
509                 } else if (abs(diff) < 1/m_rescaleVerticalThreshold) {
510                     m_rescaleClockDirection = AudioSpectrum::East;
511                 } else if (diff < 0) {
512                     m_rescaleClockDirection = AudioSpectrum::Northeast;
513                 } else {
514                     m_rescaleClockDirection = AudioSpectrum::Southeast;
515                 }
516 #ifdef DEBUG_AUDIOSPEC
517                 qDebug() << "Diff is " << diff << "; chose " << directions[m_rescaleClockDirection] << " as direction";
518 #endif
519                 m_rescalePropertiesLocked = true;
520             }
521         }
522     } else {
523         AbstractAudioScopeWidget::mouseMoveEvent(event);
524     }
525 }
526
527 void AudioSpectrum::mousePressEvent(QMouseEvent *event)
528 {
529     if (event->button() == Qt::LeftButton) {
530         // Rescaling mode starts
531         m_rescaleActive = true;
532         m_rescalePropertiesLocked = false;
533         m_rescaleFirstRescaleDone = false;
534         m_rescaleStartPoint = event->pos();
535         m_rescaleModifiers = event->modifiers();
536
537     } else {
538         AbstractAudioScopeWidget::mousePressEvent(event);
539     }
540 }
541
542 void AudioSpectrum::mouseReleaseEvent(QMouseEvent *event)
543 {
544     m_rescaleActive = false;
545     m_rescalePropertiesLocked = false;
546
547     AbstractAudioScopeWidget::mouseReleaseEvent(event);
548 }
549
550
551 #ifdef DEBUG_AUDIOSPEC
552 #undef DEBUG_AUDIOSPEC
553 #endif
554
555 #undef MIN_DB_VALUE
556 #undef MAX_FREQ_VALUE
557 #undef MIN_FREQ_VALUE