]> git.sesse.net Git - kdenlive/blob - src/audioscopes/audiospectrum.cpp
* Moved movement detection to Abstract Scope widget
[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 AudioSpectrum::AudioSpectrum(QWidget *parent) :
36         AbstractAudioScopeWidget(false, parent),
37         m_fftTools()
38 {
39     ui = new Ui::AudioSpectrum_UI;
40     ui->setupUi(this);
41
42
43     m_aResetHz = new QAction(i18n("Reset maximum frequency to sampling rate"), this);
44
45
46     m_menu->addSeparator();
47     m_menu->addAction(m_aResetHz);
48     m_menu->removeAction(m_aRealtime);
49
50
51     ui->windowSize->addItem("256", QVariant(256));
52     ui->windowSize->addItem("512", QVariant(512));
53     ui->windowSize->addItem("1024", QVariant(1024));
54     ui->windowSize->addItem("2048", QVariant(2048));
55
56     ui->windowFunction->addItem(i18n("Rectangular window"), FFTTools::Window_Rect);
57     ui->windowFunction->addItem(i18n("Triangular window"), FFTTools::Window_Triangle);
58     ui->windowFunction->addItem(i18n("Hamming window"), FFTTools::Window_Hamming);
59
60
61     bool b = true;
62     b &= connect(m_aResetHz, SIGNAL(triggered()), this, SLOT(slotResetMaxFreq()));
63     b &= connect(ui->windowFunction, SIGNAL(currentIndexChanged(int)), this, SLOT(forceUpdate()));
64     Q_ASSERT(b);
65
66
67     ui->labelFFTSize->setToolTip(i18n("The maximum window size is limited by the number of samples per frame."));
68     ui->windowSize->setToolTip(i18n("A bigger window improves the accuracy at the cost of computational power."));
69     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."));
70
71     AbstractScopeWidget::init();
72 }
73 AudioSpectrum::~AudioSpectrum()
74 {
75     writeConfig();
76
77     delete m_aResetHz;
78 }
79
80 void AudioSpectrum::readConfig()
81 {
82     AbstractScopeWidget::readConfig();
83
84     KSharedConfigPtr config = KGlobal::config();
85     KConfigGroup scopeConfig(config, AbstractScopeWidget::configName());
86
87     ui->windowSize->setCurrentIndex(scopeConfig.readEntry("windowSize", 0));
88     ui->windowFunction->setCurrentIndex(scopeConfig.readEntry("windowFunction", 0));
89     m_dBmax = scopeConfig.readEntry("dBmax", 0);
90     m_dBmin = scopeConfig.readEntry("dBmin", -70);
91     m_freqMax = scopeConfig.readEntry("freqMax", 0);
92
93     if (m_freqMax == 0) {
94         m_customFreq = false;
95         m_freqMax = 10000;
96     } else {
97         m_customFreq = true;
98     }
99 }
100 void AudioSpectrum::writeConfig()
101 {
102     KSharedConfigPtr config = KGlobal::config();
103     KConfigGroup scopeConfig(config, AbstractScopeWidget::configName());
104
105     scopeConfig.writeEntry("windowSize", ui->windowSize->currentIndex());
106     scopeConfig.writeEntry("windowFunction", ui->windowFunction->currentIndex());
107     scopeConfig.writeEntry("dBmax", m_dBmax);
108     scopeConfig.writeEntry("dBmin", m_dBmin);
109     if (m_customFreq) {
110         scopeConfig.writeEntry("freqMax", m_freqMax);
111     } else {
112         scopeConfig.writeEntry("freqMax", 0);
113     }
114
115     scopeConfig.sync();
116 }
117
118 QString AudioSpectrum::widgetName() const { return QString("AudioSpectrum"); }
119 bool AudioSpectrum::isBackgroundDependingOnInput() const { return false; }
120 bool AudioSpectrum::isScopeDependingOnInput() const { return true; }
121 bool AudioSpectrum::isHUDDependingOnInput() const { return false; }
122
123 QImage AudioSpectrum::renderBackground(uint) { return QImage(); }
124
125 QImage AudioSpectrum::renderAudioScope(uint, const QVector<int16_t> audioFrame, const int freq, const int num_channels, const int num_samples)
126 {
127     if (audioFrame.size() > 63) {
128         if (!m_customFreq) {
129             m_freqMax = freq / 2;
130         }
131
132         QTime start = QTime::currentTime();
133
134
135         // Determine the window size to use. It should be
136         // * not bigger than the number of samples actually available
137         // * divisible by 2
138         int fftWindow = ui->windowSize->itemData(ui->windowSize->currentIndex()).toInt();
139         if (fftWindow > num_samples) {
140             fftWindow = num_samples;
141         }
142         if ((fftWindow & 1) == 1) {
143             fftWindow--;
144         }
145
146         // Show the window size used, for information
147         ui->labelFFTSizeNumber->setText(QVariant(fftWindow).toString());
148
149
150         // Get the spectral power distribution of the input samples,
151         // using the given window size and function
152         float freqSpectrum[fftWindow/2];
153         FFTTools::WindowType windowType = (FFTTools::WindowType) ui->windowFunction->itemData(ui->windowFunction->currentIndex()).toInt();
154         m_fftTools.fftNormalized(audioFrame, 0, num_channels, freqSpectrum, windowType, fftWindow, 0);
155
156
157         // Draw the spectrum
158         QImage spectrum(m_scopeRect.size(), QImage::Format_ARGB32);
159         spectrum.fill(qRgba(0,0,0,0));
160         const uint w = m_innerScopeRect.width();
161         const uint h = m_innerScopeRect.height();
162         const uint leftDist = m_innerScopeRect.left() - m_scopeRect.left();
163         const uint topDist = m_innerScopeRect.top() - m_scopeRect.top();
164         float f;
165         float x;
166         float x_prev = 0;
167         float val;
168         int xi;
169         for (uint i = 0; i < w; i++) {
170
171             // i:  Pixel coordinate
172             // f: Target frequency
173             // x:  Frequency array index (float!) corresponding to the pixel
174             // xi: floor(x)
175
176             f = i/((float) w-1.0) * m_freqMax;
177             x = 2*f/freq * (fftWindow/2 - 1);
178             xi = (int) floor(x);
179
180             if (x >= fftWindow/2) {
181                 break;
182             }
183
184             // Use linear interpolation in order to get smoother display
185             if (i == 0 || xi == fftWindow/2-1) {
186                 // ... except if we are at the left or right border of the display or the spectrum
187                 val = freqSpectrum[xi];
188             } else {
189
190                 if (freqSpectrum[xi] > freqSpectrum[xi+1]
191                     && x_prev < xi) {
192                     // This is a hack to preserve peaks.
193                     // Consider f = {0, 100, 0}
194                     //          x = {0.5,  1.5}
195                     // Then x is 50 both times, and the 100 peak is lost.
196                     // Get it back here for the first x after the peak.
197                     val = freqSpectrum[xi];
198                 } else {
199                     val =   (xi+1 - x) * freqSpectrum[xi]
200                           + (x - xi)   * freqSpectrum[xi+1];
201                 }
202             }
203
204             // freqSpectrum values range from 0 to -inf as they are relative dB values.
205             for (uint y = 0; y < h*(1 - (val - m_dBmax)/(m_dBmin-m_dBmax)) && y < h; y++) {
206                 spectrum.setPixel(leftDist + i, topDist + h-y-1, qRgba(225, 182, 255, 255));
207             }
208
209             x_prev = x;
210         }
211
212         emit signalScopeRenderingFinished(start.elapsed(), 1);
213
214 #ifdef DEBUG_AUDIOSPEC
215         if (!fileWritten || true) {
216             std::ofstream mFile;
217             mFile.open("/tmp/freq.m");
218             if (!mFile) {
219                 qDebug() << "Opening file failed.";
220             } else {
221                 mFile << "val = [ ";
222
223                 for (int sample = 0; sample < 256; sample++) {
224                     mFile << data[sample] << " ";
225                 }
226                 mFile << " ];\n";
227
228                 mFile << "freq = [ ";
229                 for (int sample = 0; sample < 256; sample++) {
230                     mFile << freqData[sample].r << "+" << freqData[sample].i << "*i ";
231                 }
232                 mFile << " ];\n";
233
234                 mFile.close();
235                 fileWritten = true;
236                 qDebug() << "File written.";
237             }
238         } else {
239             qDebug() << "File already written.";
240         }
241 #endif
242
243         return spectrum;
244     } else {
245         emit signalScopeRenderingFinished(0, 1);
246         return QImage();
247     }
248 }
249 QImage AudioSpectrum::renderHUD(uint)
250 {
251     QTime start = QTime::currentTime();
252
253     // Minimum distance between two lines
254     const uint minDistY = 30;
255     const uint minDistX = 40;
256     const uint textDistX = 10;
257     const uint textDistY = 25;
258     const uint topDist = m_innerScopeRect.top() - m_scopeRect.top();
259     const uint leftDist = m_innerScopeRect.left() - m_scopeRect.left();
260     const uint dbDiff = ceil((float)minDistY/m_innerScopeRect.height() * (m_dBmax-m_dBmin));
261
262     QImage hud(m_scopeRect.size(), QImage::Format_ARGB32);
263     hud.fill(qRgba(0,0,0,0));
264
265     QPainter davinci(&hud);
266     davinci.setPen(AbstractScopeWidget::penLight);
267
268     int y;
269     for (int db = -dbDiff; db > m_dBmin; db -= dbDiff) {
270         y = topDist + m_innerScopeRect.height() * ((float)db)/(m_dBmin - m_dBmax);
271         if (y-topDist > m_innerScopeRect.height()-minDistY+10) {
272             // Abort here, there is still a line left for min dB to paint which needs some room.
273             break;
274         }
275         davinci.drawLine(leftDist, y, leftDist + m_innerScopeRect.width()-1, y);
276         davinci.drawText(leftDist + m_innerScopeRect.width() + textDistX, y + 6, i18n("%1 dB", m_dBmax + db));
277     }
278     davinci.drawLine(leftDist, topDist, leftDist + m_innerScopeRect.width()-1, topDist);
279     davinci.drawText(leftDist + m_innerScopeRect.width() + textDistX, topDist+6, i18n("%1 dB", m_dBmax));
280     davinci.drawLine(leftDist, topDist+m_innerScopeRect.height()-1, leftDist + m_innerScopeRect.width()-1, topDist+m_innerScopeRect.height()-1);
281     davinci.drawText(leftDist + m_innerScopeRect.width() + textDistX, topDist+m_innerScopeRect.height()+6, i18n("%1 dB", m_dBmin));
282
283     const uint hzDiff = ceil( ((float)minDistX)/m_innerScopeRect.width() * m_freqMax / 1000 ) * 1000;
284     int x = 0;
285     const int rightBorder = leftDist + m_innerScopeRect.width()-1;
286     y = topDist + m_innerScopeRect.height() + textDistY;
287     for (uint hz = 0; x <= rightBorder; hz += hzDiff) {
288         davinci.setPen(AbstractScopeWidget::penLight);
289         x = leftDist + m_innerScopeRect.width() * ((float)hz)/m_freqMax;
290
291         if (x <= rightBorder) {
292             davinci.drawLine(x, topDist, x, topDist + m_innerScopeRect.height()+6);
293         }
294         if (hz < m_freqMax && x+textDistY < leftDist + m_innerScopeRect.width()) {
295             davinci.drawText(x-4, y, QVariant(hz/1000).toString());
296         } else {
297             x = leftDist + m_innerScopeRect.width();
298             davinci.drawLine(x, topDist, x, topDist + m_innerScopeRect.height()+6);
299             davinci.drawText(x-10, y, i18n("%1 kHz").arg((double)m_freqMax/1000, 0, 'f', 1));
300         }
301
302         if (hz > 0) {
303             // Draw finer lines between the main lines
304             davinci.setPen(AbstractScopeWidget::penLightDots);
305             for (uint dHz = 3; dHz > 0; dHz--) {
306                 x = leftDist + m_innerScopeRect.width() * ((float)hz - dHz * hzDiff/4.0f)/m_freqMax;
307                 if (x > rightBorder) {
308                     break;
309                 }
310                 davinci.drawLine(x, topDist, x, topDist + m_innerScopeRect.height()-1);
311             }
312         }
313     }
314
315
316     emit signalHUDRenderingFinished(start.elapsed(), 1);
317     return hud;
318 }
319
320 QRect AudioSpectrum::scopeRect()
321 {
322     m_scopeRect = QRect(
323             QPoint(
324                     10,                                     // Left
325                     ui->verticalSpacer->geometry().top()+6  // Top
326             ),
327             AbstractAudioScopeWidget::rect().bottomRight()
328     );
329     m_innerScopeRect = QRect(
330             QPoint(
331                     m_scopeRect.left()+6,                   // Left
332                     m_scopeRect.top()+6                     // Top
333             ), QPoint(
334                     ui->verticalSpacer->geometry().right()-70,
335                     ui->verticalSpacer->geometry().bottom()-40
336             )
337     );
338     return m_scopeRect;
339 }
340
341 void AudioSpectrum::slotResetMaxFreq()
342 {
343     m_customFreq = false;
344     forceUpdateHUD();
345     forceUpdateScope();
346 }
347
348
349 ///// EVENTS /////
350
351 void AudioSpectrum::handleMouseDrag(const QPoint movement, const RescaleDirection rescaleDirection, const Qt::KeyboardModifiers rescaleModifiers)
352 {
353     if (rescaleDirection == AudioSpectrum::North) {
354         // Nort-South direction: Adjust the dB scale
355
356         if ((rescaleModifiers & Qt::ShiftModifier) == 0) {
357
358             // By default adjust the min dB value
359             m_dBmin += movement.y();
360
361         } else {
362
363             // Adjust max dB value if Shift is pressed.
364             m_dBmax += movement.y();
365
366         }
367
368         // Ensure the dB values lie in [-100, 0] (or rather [MIN_DB_VALUE, 0])
369         // 0 is the upper bound, everything below -70 dB is most likely noise
370         if (m_dBmax > 0) {
371             m_dBmax = 0;
372         }
373         if (m_dBmin < MIN_DB_VALUE) {
374             m_dBmin = MIN_DB_VALUE;
375         }
376         // Ensure there is at least 6 dB between the minimum and the maximum value;
377         // lower values hardly make sense
378         if (m_dBmax - m_dBmin < 6) {
379             if ((rescaleModifiers & Qt::ShiftModifier) == 0) {
380                 // min was adjusted; Try to adjust the max value to maintain the
381                 // minimum dB difference of 6 dB
382                 m_dBmax = m_dBmin + 6;
383                 if (m_dBmax > 0) {
384                     m_dBmax = 0;
385                     m_dBmin = -6;
386                 }
387             } else {
388                 // max was adjusted, adjust min
389                 m_dBmin = m_dBmax - 6;
390                 if (m_dBmin < MIN_DB_VALUE) {
391                     m_dBmin = MIN_DB_VALUE;
392                     m_dBmax = MIN_DB_VALUE+6;
393                 }
394             }
395         }
396
397         forceUpdateHUD();
398         forceUpdateScope();
399
400     } else if (rescaleDirection == AudioSpectrum::East) {
401         // East-West direction: Adjust the maximum frequency
402         m_freqMax -= 100*movement.x();
403         if (m_freqMax < MIN_FREQ_VALUE) {
404             m_freqMax = MIN_FREQ_VALUE;
405         }
406         if (m_freqMax > MAX_FREQ_VALUE) {
407             m_freqMax = MAX_FREQ_VALUE;
408         }
409         m_customFreq = true;
410
411         forceUpdateHUD();
412         forceUpdateScope();
413     }
414 }
415
416
417 #ifdef DEBUG_AUDIOSPEC
418 #undef DEBUG_AUDIOSPEC
419 #endif
420
421 #undef MIN_DB_VALUE
422 #undef MAX_FREQ_VALUE
423 #undef MIN_FREQ_VALUE