]> git.sesse.net Git - kdenlive/blob - src/audioscopes/audiospectrum.cpp
Audio scopes: Mouse tracking can be disabled
[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
26 #ifdef DEBUG_AUDIOSPEC
27 #include <QDebug>
28 #endif
29
30 #define MIN_DB_VALUE -120
31 #define MAX_FREQ_VALUE 96000
32 #define MIN_FREQ_VALUE 1000
33
34 AudioSpectrum::AudioSpectrum(QWidget *parent) :
35         AbstractAudioScopeWidget(true, parent),
36         m_fftTools(),
37         m_lastFFT(),
38         m_lastFFTLock(1)
39 {
40     ui = new Ui::AudioSpectrum_UI;
41     ui->setupUi(this);
42
43
44     m_aResetHz = new QAction(i18n("Reset maximum frequency to sampling rate"), this);
45     m_aTrackMouse = new QAction(i18n("Track mouse"), this);
46     m_aTrackMouse->setCheckable(true);
47
48
49     m_menu->addSeparator();
50     m_menu->addAction(m_aResetHz);
51     m_menu->addAction(m_aTrackMouse);
52     m_menu->removeAction(m_aRealtime);
53
54
55     ui->windowSize->addItem("256", QVariant(256));
56     ui->windowSize->addItem("512", QVariant(512));
57     ui->windowSize->addItem("1024", QVariant(1024));
58     ui->windowSize->addItem("2048", QVariant(2048));
59
60     ui->windowFunction->addItem(i18n("Rectangular window"), FFTTools::Window_Rect);
61     ui->windowFunction->addItem(i18n("Triangular window"), FFTTools::Window_Triangle);
62     ui->windowFunction->addItem(i18n("Hamming window"), FFTTools::Window_Hamming);
63
64
65     bool b = true;
66     b &= connect(m_aResetHz, SIGNAL(triggered()), this, SLOT(slotResetMaxFreq()));
67     b &= connect(ui->windowFunction, SIGNAL(currentIndexChanged(int)), this, SLOT(forceUpdate()));
68     b &= connect(this, SIGNAL(signalMousePositionChanged()), this, SLOT(forceUpdateHUD()));
69     Q_ASSERT(b);
70
71
72     // Note: These strings are used in both Spectogram and AudioSpectrum. Ideally change both (if necessary) to reduce workload on translators
73     ui->labelFFTSize->setToolTip(i18n("The maximum window size is limited by the number of samples per frame."));
74     ui->windowSize->setToolTip(i18n("A bigger window improves the accuracy at the cost of computational power."));
75     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."));
76
77     AbstractScopeWidget::init();
78 }
79 AudioSpectrum::~AudioSpectrum()
80 {
81     writeConfig();
82
83     delete m_aResetHz;
84     delete m_aTrackMouse;
85 }
86
87 void AudioSpectrum::readConfig()
88 {
89     AbstractScopeWidget::readConfig();
90
91     KSharedConfigPtr config = KGlobal::config();
92     KConfigGroup scopeConfig(config, AbstractScopeWidget::configName());
93
94     ui->windowSize->setCurrentIndex(scopeConfig.readEntry("windowSize", 0));
95     ui->windowFunction->setCurrentIndex(scopeConfig.readEntry("windowFunction", 0));
96     m_aTrackMouse->setChecked(scopeConfig.readEntry("trackMouse", true));
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("trackMouse", m_aTrackMouse->isChecked());
116     scopeConfig.writeEntry("dBmax", m_dBmax);
117     scopeConfig.writeEntry("dBmin", m_dBmin);
118     if (m_customFreq) {
119         scopeConfig.writeEntry("freqMax", m_freqMax);
120     } else {
121         scopeConfig.writeEntry("freqMax", 0);
122     }
123
124     scopeConfig.sync();
125 }
126
127 QString AudioSpectrum::widgetName() const { return QString("AudioSpectrum"); }
128 bool AudioSpectrum::isBackgroundDependingOnInput() const { return false; }
129 bool AudioSpectrum::isScopeDependingOnInput() const { return true; }
130 bool AudioSpectrum::isHUDDependingOnInput() const { return false; }
131
132 QImage AudioSpectrum::renderBackground(uint) { return QImage(); }
133
134 QImage AudioSpectrum::renderAudioScope(uint, const QVector<int16_t> audioFrame, const int freq, const int num_channels,
135                                        const int num_samples, const int)
136 {
137     if (audioFrame.size() > 63) {
138         if (!m_customFreq) {
139             m_freqMax = freq / 2;
140         }
141
142         QTime start = QTime::currentTime();
143
144
145         // Determine the window size to use. It should be
146         // * not bigger than the number of samples actually available
147         // * divisible by 2
148         int fftWindow = ui->windowSize->itemData(ui->windowSize->currentIndex()).toInt();
149         if (fftWindow > num_samples) {
150             fftWindow = num_samples;
151         }
152         if ((fftWindow & 1) == 1) {
153             fftWindow--;
154         }
155
156         // Show the window size used, for information
157         ui->labelFFTSizeNumber->setText(QVariant(fftWindow).toString());
158
159
160         // Get the spectral power distribution of the input samples,
161         // using the given window size and function
162         float freqSpectrum[fftWindow/2];
163         FFTTools::WindowType windowType = (FFTTools::WindowType) ui->windowFunction->itemData(ui->windowFunction->currentIndex()).toInt();
164         m_fftTools.fftNormalized(audioFrame, 0, num_channels, freqSpectrum, windowType, fftWindow, 0);
165
166
167         // Store the current FFT window (for the HUD) and run the interpolation
168         // for easy pixel-based dB value access
169         QVector<float> dbMap;
170         m_lastFFTLock.acquire();
171         m_lastFFT = QVector<float>(fftWindow/2);
172         memcpy(m_lastFFT.data(), &(freqSpectrum[0]), fftWindow/2 * sizeof(float));
173
174         uint right = ((float) m_freqMax)/(m_freq) * (m_lastFFT.size() - 1);
175         dbMap = interpolatePeakPreserving(m_lastFFT, m_innerScopeRect.width(), 0, right, -120);
176         m_lastFFTLock.release();
177
178
179         // Draw the spectrum
180         QImage spectrum(m_scopeRect.size(), QImage::Format_ARGB32);
181         spectrum.fill(qRgba(0,0,0,0));
182         const uint w = m_innerScopeRect.width();
183         const uint h = m_innerScopeRect.height();
184         const uint leftDist = m_innerScopeRect.left() - m_scopeRect.left();
185         const uint topDist = m_innerScopeRect.top() - m_scopeRect.top();
186         int yMax;
187
188         for (uint i = 0; i < w; i++) {
189             yMax = (dbMap[i] - m_dBmin) / (m_dBmax-m_dBmin) * (h-1);
190             if (yMax < 0) {
191                 yMax = 0;
192             } else if (yMax >= (int)h) {
193                 yMax = h-1;
194             }
195             for (int y = 0; y < yMax && y < (int)h; y++) {
196                 spectrum.setPixel(leftDist + i, topDist + h-y-1, qRgba(225, 182, 255, 255));
197             }
198         }
199
200         emit signalScopeRenderingFinished(start.elapsed(), 1);
201
202
203         return spectrum;
204     } else {
205         emit signalScopeRenderingFinished(0, 1);
206         return QImage();
207     }
208 }
209 QImage AudioSpectrum::renderHUD(uint)
210 {
211     QTime start = QTime::currentTime();
212
213     // Minimum distance between two lines
214     const uint minDistY = 30;
215     const uint minDistX = 40;
216     const uint textDistX = 10;
217     const uint textDistY = 25;
218     const uint topDist = m_innerScopeRect.top() - m_scopeRect.top();
219     const uint leftDist = m_innerScopeRect.left() - m_scopeRect.left();
220     const uint dbDiff = ceil((float)minDistY/m_innerScopeRect.height() * (m_dBmax-m_dBmin));
221     const int mouseX = m_mousePos.x() - m_innerScopeRect.left();
222     const int mouseY = m_mousePos.y() - m_innerScopeRect.top();
223
224     QImage hud(m_scopeRect.size(), QImage::Format_ARGB32);
225     hud.fill(qRgba(0,0,0,0));
226
227     QPainter davinci(&hud);
228     davinci.setPen(AbstractScopeWidget::penLight);
229
230     int y;
231     for (int db = -dbDiff; db > m_dBmin; db -= dbDiff) {
232         y = topDist + m_innerScopeRect.height() * ((float)db)/(m_dBmin - m_dBmax);
233         if (y-topDist > m_innerScopeRect.height()-minDistY+10) {
234             // Abort here, there is still a line left for min dB to paint which needs some room.
235             break;
236         }
237         davinci.drawLine(leftDist, y, leftDist + m_innerScopeRect.width()-1, y);
238         davinci.drawText(leftDist + m_innerScopeRect.width() + textDistX, y + 6, i18n("%1 dB", m_dBmax + db));
239     }
240     davinci.drawLine(leftDist, topDist, leftDist + m_innerScopeRect.width()-1, topDist);
241     davinci.drawText(leftDist + m_innerScopeRect.width() + textDistX, topDist+6, i18n("%1 dB", m_dBmax));
242     davinci.drawLine(leftDist, topDist+m_innerScopeRect.height()-1, leftDist + m_innerScopeRect.width()-1, topDist+m_innerScopeRect.height()-1);
243     davinci.drawText(leftDist + m_innerScopeRect.width() + textDistX, topDist+m_innerScopeRect.height()+6, i18n("%1 dB", m_dBmin));
244
245     const uint hzDiff = ceil( ((float)minDistX)/m_innerScopeRect.width() * m_freqMax / 1000 ) * 1000;
246     int x = 0;
247     const int rightBorder = leftDist + m_innerScopeRect.width()-1;
248     y = topDist + m_innerScopeRect.height() + textDistY;
249     for (uint hz = 0; x <= rightBorder; hz += hzDiff) {
250         davinci.setPen(AbstractScopeWidget::penLight);
251         x = leftDist + m_innerScopeRect.width() * ((float)hz)/m_freqMax;
252
253         if (x <= rightBorder) {
254             davinci.drawLine(x, topDist, x, topDist + m_innerScopeRect.height()+6);
255         }
256         if (hz < m_freqMax && x+textDistY < leftDist + m_innerScopeRect.width()) {
257             davinci.drawText(x-4, y, QVariant(hz/1000).toString());
258         } else {
259             x = leftDist + m_innerScopeRect.width();
260             davinci.drawLine(x, topDist, x, topDist + m_innerScopeRect.height()+6);
261             davinci.drawText(x-10, y, i18n("%1 kHz").arg((double)m_freqMax/1000, 0, 'f', 1));
262         }
263
264         if (hz > 0) {
265             // Draw finer lines between the main lines
266             davinci.setPen(AbstractScopeWidget::penLightDots);
267             for (uint dHz = 3; dHz > 0; dHz--) {
268                 x = leftDist + m_innerScopeRect.width() * ((float)hz - dHz * hzDiff/4.0f)/m_freqMax;
269                 if (x > rightBorder) {
270                     break;
271                 }
272                 davinci.drawLine(x, topDist, x, topDist + m_innerScopeRect.height()-1);
273             }
274         }
275     }
276
277     if (m_aTrackMouse->isChecked() && m_mouseWithinWidget && mouseX < m_innerScopeRect.width()-1) {
278         davinci.setPen(AbstractScopeWidget::penThin);
279
280         x = leftDist + mouseX;
281
282         float db = 0;
283         float freq = ((float) mouseX)/(m_innerScopeRect.width()-1) * m_freqMax;
284         bool drawDb = false;
285
286         m_lastFFTLock.acquire();
287         if (m_lastFFT.size() > 0) {
288             uint right = ((float) m_freqMax)/(m_freq) * (m_lastFFT.size() - 1);
289             QVector<float> dbMap = AudioSpectrum::interpolatePeakPreserving(m_lastFFT, m_innerScopeRect.width(), 0, right, -120);
290
291             db = dbMap[mouseX];
292             y = topDist + m_innerScopeRect.height()-1 - (dbMap[mouseX] - m_dBmin) / (m_dBmax-m_dBmin) * (m_innerScopeRect.height()-1);
293
294             if (y < (int)topDist + m_innerScopeRect.height()-1) {
295                 drawDb = true;
296                 davinci.drawLine(x, y, leftDist + m_innerScopeRect.width()-1, y);
297             }
298         } else {
299             y = topDist + mouseY;
300         }
301         m_lastFFTLock.release();
302
303         if (y > (int)topDist + mouseY) {
304             y = topDist+ mouseY;
305         }
306         davinci.drawLine(x, y, x, topDist + m_innerScopeRect.height()-1);
307
308         if (drawDb) {
309             QPoint dist(20, -20);
310             QRect rect(
311                         leftDist + mouseX + dist.x(),
312                         topDist + mouseY + dist.y(),
313                         100,
314                         40
315                         );
316             if (rect.right() > (int)leftDist + m_innerScopeRect.width()-1) {
317                 // Mirror the rectangle at the y axis to keep it inside the widget
318                 rect = QRect(
319                             rect.topLeft() - QPoint(rect.width() + 2*dist.x(), 0),
320                             rect.size());
321             }
322
323             QRect textRect(
324                         rect.topLeft() + QPoint(12, 4),
325                         rect.size()
326                         );
327
328             davinci.fillRect(rect, AbstractScopeWidget::penBackground.brush());
329             davinci.setPen(AbstractScopeWidget::penLighter);
330             davinci.drawRect(rect);
331             davinci.drawText(textRect, QString(
332                                  i18n("%1 dB", QString("%1").arg(db, 0, 'f', 2))
333                                  + "\n"
334                                  + i18n("%1 kHz", QString("%1").arg(freq/1000, 0, 'f', 2))));
335         }
336
337     }
338
339
340     emit signalHUDRenderingFinished(start.elapsed(), 1);
341     return hud;
342 }
343
344 QRect AudioSpectrum::scopeRect()
345 {
346     m_scopeRect = QRect(
347             QPoint(
348                     10,                                     // Left
349                     ui->verticalSpacer->geometry().top()+6  // Top
350             ),
351             AbstractAudioScopeWidget::rect().bottomRight()
352     );
353     m_innerScopeRect = QRect(
354             QPoint(
355                     m_scopeRect.left()+6,                   // Left
356                     m_scopeRect.top()+6                     // Top
357             ), QPoint(
358                     ui->verticalSpacer->geometry().right()-70,
359                     ui->verticalSpacer->geometry().bottom()-40
360             )
361     );
362     return m_scopeRect;
363 }
364
365 void AudioSpectrum::slotResetMaxFreq()
366 {
367     m_customFreq = false;
368     forceUpdateHUD();
369     forceUpdateScope();
370 }
371
372
373 ///// EVENTS /////
374
375 void AudioSpectrum::handleMouseDrag(const QPoint movement, const RescaleDirection rescaleDirection, const Qt::KeyboardModifiers rescaleModifiers)
376 {
377     if (rescaleDirection == North) {
378         // Nort-South direction: Adjust the dB scale
379
380         if ((rescaleModifiers & Qt::ShiftModifier) == 0) {
381
382             // By default adjust the min dB value
383             m_dBmin += movement.y();
384
385         } else {
386
387             // Adjust max dB value if Shift is pressed.
388             m_dBmax += movement.y();
389
390         }
391
392         // Ensure the dB values lie in [-100, 0] (or rather [MIN_DB_VALUE, 0])
393         // 0 is the upper bound, everything below -70 dB is most likely noise
394         if (m_dBmax > 0) {
395             m_dBmax = 0;
396         }
397         if (m_dBmin < MIN_DB_VALUE) {
398             m_dBmin = MIN_DB_VALUE;
399         }
400         // Ensure there is at least 6 dB between the minimum and the maximum value;
401         // lower values hardly make sense
402         if (m_dBmax - m_dBmin < 6) {
403             if ((rescaleModifiers & Qt::ShiftModifier) == 0) {
404                 // min was adjusted; Try to adjust the max value to maintain the
405                 // minimum dB difference of 6 dB
406                 m_dBmax = m_dBmin + 6;
407                 if (m_dBmax > 0) {
408                     m_dBmax = 0;
409                     m_dBmin = -6;
410                 }
411             } else {
412                 // max was adjusted, adjust min
413                 m_dBmin = m_dBmax - 6;
414                 if (m_dBmin < MIN_DB_VALUE) {
415                     m_dBmin = MIN_DB_VALUE;
416                     m_dBmax = MIN_DB_VALUE+6;
417                 }
418             }
419         }
420
421         forceUpdateHUD();
422         forceUpdateScope();
423
424     } else if (rescaleDirection == East) {
425         // East-West direction: Adjust the maximum frequency
426         m_freqMax -= 100*movement.x();
427         if (m_freqMax < MIN_FREQ_VALUE) {
428             m_freqMax = MIN_FREQ_VALUE;
429         }
430         if (m_freqMax > MAX_FREQ_VALUE) {
431             m_freqMax = MAX_FREQ_VALUE;
432         }
433         m_customFreq = true;
434
435         forceUpdateHUD();
436         forceUpdateScope();
437     }
438 }
439
440
441 const QVector<float> AudioSpectrum::interpolatePeakPreserving(const QVector<float> in, const uint targetSize, uint left, uint right, float fill)
442 {
443     if (right == 0) {
444         right = in.size()-1;
445     }
446     Q_ASSERT(targetSize > 0);
447     Q_ASSERT(left < right);
448
449     QVector<float> out(targetSize);
450
451
452     float x;
453     float x_prev = 0;
454     int xi;
455     uint i;
456     for (i = 0; i < targetSize; i++) {
457
458         // i:  Target index
459         // x:  Interpolated source index (float!)
460         // xi: floor(x)
461
462         // Transform [0,targetSize-1] to [left,right]
463         x = ((float) i) / (targetSize-1) * (right-left) + left;
464         xi = (int) floor(x);
465
466         if (x > in.size()-1) {
467             // This may happen if right > in.size()-1; Fill the rest of the vector
468             // with the default value now.
469             break;
470         }
471
472
473         // Use linear interpolation in order to get smoother display
474         if (i == 0 || i == targetSize-1) {
475             // ... except if we are at the left or right border of the display or the spectrum
476             out[i] = in[xi];
477         } else {
478             if (in[xi] > in[xi+1]
479                 && x_prev < xi) {
480                 // This is a hack to preserve peaks.
481                 // Consider f = {0, 100, 0}
482                 //          x = {0.5,  1.5}
483                 // Then x is 50 both times, and the 100 peak is lost.
484                 // Get it back here for the first x after the peak (which is at xi).
485                 // (x is the first after the peak if the previous x was smaller than floor(x).)
486                 out[i] = in[xi];
487             } else {
488                 out[i] =   (xi+1 - x) * in[xi]
489                       + (x - xi)   * in[xi+1];
490             }
491         }
492         x_prev = x;
493     }
494     // Fill the rest of the vector if the right border exceeds the input vector.
495     for (; i < targetSize; i++) {
496         out[i] = fill;
497     }
498
499     return out;
500 }
501
502
503 #ifdef DEBUG_AUDIOSPEC
504 #undef DEBUG_AUDIOSPEC
505 #endif
506
507 #undef MIN_DB_VALUE
508 #undef MAX_FREQ_VALUE
509 #undef MIN_FREQ_VALUE