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