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