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