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