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