1 /***************************************************************************
2 * Copyright (C) 2010 by Simon Andreas Eugster (simon.eu@gmail.com) *
3 * This file is part of kdenlive. See www.kdenlive.org. *
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 ***************************************************************************/
13 #include "audiospectrum.h"
15 #include "tools/kiss_fftr.h"
19 #include <QMouseEvent>
23 // Enables debugging, like writing a GNU Octave .m file to /tmp
24 //#define DEBUG_AUDIOSPEC
25 #ifdef DEBUG_AUDIOSPEC
28 bool fileWritten = false;
31 #define MIN_DB_VALUE -120
32 #define MAX_FREQ_VALUE 96000
33 #define MIN_FREQ_VALUE 1000
35 const QString AudioSpectrum::directions[] = {"North", "Northeast", "East", "Southeast"};
37 AudioSpectrum::AudioSpectrum(QWidget *parent) :
38 AbstractAudioScopeWidget(false, parent),
44 m_rescaleVerticalThreshold(2.0f),
45 m_rescaleActive(false),
46 m_rescalePropertiesLocked(false),
49 ui = new Ui::AudioSpectrum_UI;
53 m_aResetHz = new QAction(i18n("Reset maximum frequency to sampling rate"), this);
56 m_menu->addSeparator();
57 m_menu->addAction(m_aResetHz);
58 m_menu->removeAction(m_aRealtime);
61 ui->windowSize->addItem("256", QVariant(256));
62 ui->windowSize->addItem("512", QVariant(512));
63 ui->windowSize->addItem("1024", QVariant(1024));
64 ui->windowSize->addItem("2048", QVariant(2048));
66 ui->windowFunction->addItem(i18n("Rectangular window"), FFTTools::Window_Rect);
67 ui->windowFunction->addItem(i18n("Triangular window"), FFTTools::Window_Triangle);
68 ui->windowFunction->addItem(i18n("Hamming window"), FFTTools::Window_Hamming);
72 b &= connect(m_aResetHz, SIGNAL(triggered()), this, SLOT(slotResetMaxFreq()));
76 ui->labelFFTSize->setToolTip(i18n("The maximum window size is limited by the number of samples per frame."));
77 ui->windowSize->setToolTip(i18n("A bigger window improves the accuracy at the cost of computational power."));
78 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."));
80 AbstractScopeWidget::init();
82 AudioSpectrum::~AudioSpectrum()
86 QHash<QString, kiss_fftr_cfg>::iterator i;
87 for (i = m_fftCfgs.begin(); i != m_fftCfgs.end(); i++) {
93 void AudioSpectrum::readConfig()
95 AbstractScopeWidget::readConfig();
97 KSharedConfigPtr config = KGlobal::config();
98 KConfigGroup scopeConfig(config, AbstractScopeWidget::configName());
100 ui->windowSize->setCurrentIndex(scopeConfig.readEntry("windowSize", 0));
101 ui->windowFunction->setCurrentIndex(scopeConfig.readEntry("windowFunction", 0));
102 m_dBmax = scopeConfig.readEntry("dBmax", 0);
103 m_dBmin = scopeConfig.readEntry("dBmin", -70);
104 m_freqMax = scopeConfig.readEntry("freqMax", 0);
106 if (m_freqMax == 0) {
107 m_customFreq = false;
113 void AudioSpectrum::writeConfig()
115 KSharedConfigPtr config = KGlobal::config();
116 KConfigGroup scopeConfig(config, AbstractScopeWidget::configName());
118 scopeConfig.writeEntry("windowSize", ui->windowSize->currentIndex());
119 scopeConfig.writeEntry("windowFunction", ui->windowFunction->currentIndex());
120 scopeConfig.writeEntry("dBmax", m_dBmax);
121 scopeConfig.writeEntry("dBmin", m_dBmin);
123 scopeConfig.writeEntry("freqMax", m_freqMax);
125 scopeConfig.writeEntry("freqMax", 0);
131 QString AudioSpectrum::widgetName() const { return QString("AudioSpectrum"); }
132 bool AudioSpectrum::isBackgroundDependingOnInput() const { return false; }
133 bool AudioSpectrum::isScopeDependingOnInput() const { return true; }
134 bool AudioSpectrum::isHUDDependingOnInput() const { return false; }
136 QImage AudioSpectrum::renderBackground(uint) { return QImage(); }
138 QImage AudioSpectrum::renderAudioScope(uint, const QVector<int16_t> audioFrame, const int freq, const int num_channels, const int num_samples)
140 if (audioFrame.size() > 63) {
142 m_freqMax = freq / 2;
145 QTime start = QTime::currentTime();
148 // Determine the window size to use. It should be
149 // * not bigger than the number of samples actually available
151 int fftWindow = ui->windowSize->itemData(ui->windowSize->currentIndex()).toInt();
152 if (fftWindow > num_samples) {
153 fftWindow = num_samples;
155 if ((fftWindow & 1) == 1) {
159 // Show the window size used, for information
160 ui->labelFFTSizeNumber->setText(QVariant(fftWindow).toString());
162 // Get the kiss_fft configuration from the config cache
163 // or build a new configuration if the requested one is not available.
165 const QString signature = cfgSignature(fftWindow);
166 if (m_fftCfgs.contains(signature)) {
167 #ifdef DEBUG_AUDIOSPEC
168 qDebug() << "Re-using FFT configuration with size " << fftWindow;
170 myCfg = m_fftCfgs.value(signature);
172 #ifdef DEBUG_AUDIOSPEC
173 qDebug() << "Creating FFT configuration with size " << fftWindow;
175 myCfg = kiss_fftr_alloc(fftWindow, 0,0,0);
176 m_fftCfgs.insert(signature, myCfg);
179 float data[fftWindow];
180 float freqSpectrum[fftWindow/2];
182 // Prepare frequency space vector. The resulting FFT vector is only half as long.
183 kiss_fft_cpx freqData[fftWindow/2];
187 // Copy the first channel's audio into a vector for the FFT display
188 // (only one channel handled at the moment)
189 if (num_samples < fftWindow) {
190 std::fill(&data[num_samples], &data[fftWindow-1], 0);
193 FFTTools::WindowType windowType = (FFTTools::WindowType) ui->windowFunction->itemData(ui->windowFunction->currentIndex()).toInt();
194 QVector<float> window;
195 float windowScaleFactor = 1;
196 if (windowType != FFTTools::Window_Rect) {
197 const QString signature = FFTTools::windowSignature(windowType, fftWindow, 0);
198 if (m_windowFunctions.contains(signature)) {
199 #ifdef DEBUG_AUDIOSPEC
200 qDebug() << "Re-using window function with signature " << signature;
202 window = m_windowFunctions.value(signature);
204 #ifdef DEBUG_AUDIOSPEC
205 qDebug() << "Building new window function with signature " << signature;
207 window = FFTTools::window(windowType, fftWindow, 0);
208 m_windowFunctions.insert(signature, window);
210 windowScaleFactor = 1.0/window[fftWindow];
213 // Normalize signals to [0,1] to get correct dB values later on
214 for (int i = 0; i < num_samples && i < fftWindow; i++) {
215 if (windowType != FFTTools::Window_Rect) {
216 data[i] = (float) audioFrame.data()[i*num_channels] / 32767.0f * window[i];
218 data[i] = (float) audioFrame.data()[i*num_channels] / 32767.0f;
222 // Calculate the Fast Fourier Transform for the input data
223 kiss_fftr(myCfg, data, freqData);
226 // Logarithmic scale: 20 * log ( 2 * magnitude / N ) with magnitude = sqrt(r² + i²)
227 // with N = FFT size (after FFT, 1/2 window size)
228 for (int i = 0; i < fftWindow/2; i++) {
229 // Logarithmic scale: 20 * log ( 2 * magnitude / N ) with magnitude = sqrt(r² + i²)
230 // with N = FFT size (after FFT, 1/2 window size)
231 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);;
237 QImage spectrum(m_scopeRect.size(), QImage::Format_ARGB32);
238 spectrum.fill(qRgba(0,0,0,0));
239 const uint w = m_innerScopeRect.width();
240 const uint h = m_innerScopeRect.height();
241 const uint leftDist = m_innerScopeRect.left() - m_scopeRect.left();
242 const uint topDist = m_innerScopeRect.top() - m_scopeRect.top();
248 for (uint i = 0; i < w; i++) {
250 // i: Pixel coordinate
251 // f: Target frequency
252 // x: Frequency array index (float!) corresponding to the pixel
255 f = i/((float) w-1.0) * m_freqMax;
256 x = 2*f/freq * (fftWindow/2 - 1);
259 if (x >= fftWindow/2) {
263 // Use linear interpolation in order to get smoother display
264 if (i == 0 || xi == fftWindow/2-1) {
265 // ... except if we are at the left or right border of the display or the spectrum
266 val = freqSpectrum[xi];
269 if (freqSpectrum[xi] > freqSpectrum[xi+1]
271 // This is a hack to preserve peaks.
272 // Consider f = {0, 100, 0}
274 // Then x is 50 both times, and the 100 peak is lost.
275 // Get it back here for the first x after the peak.
276 val = freqSpectrum[xi];
278 val = (xi+1 - x) * freqSpectrum[xi]
279 + (x - xi) * freqSpectrum[xi+1];
283 // freqSpectrum values range from 0 to -inf as they are relative dB values.
284 for (uint y = 0; y < h*(1 - (val - m_dBmax)/(m_dBmin-m_dBmax)) && y < h; y++) {
285 spectrum.setPixel(leftDist + i, topDist + h-y-1, qRgba(225, 182, 255, 255));
291 emit signalScopeRenderingFinished(start.elapsed(), 1);
293 #ifdef DEBUG_AUDIOSPEC
294 if (!fileWritten || true) {
296 mFile.open("/tmp/freq.m");
298 qDebug() << "Opening file failed.";
302 for (int sample = 0; sample < 256; sample++) {
303 mFile << data[sample] << " ";
307 mFile << "freq = [ ";
308 for (int sample = 0; sample < 256; sample++) {
309 mFile << freqData[sample].r << "+" << freqData[sample].i << "*i ";
315 qDebug() << "File written.";
318 qDebug() << "File already written.";
324 emit signalScopeRenderingFinished(0, 1);
328 QImage AudioSpectrum::renderHUD(uint)
330 QTime start = QTime::currentTime();
332 // Minimum distance between two lines
333 const uint minDistY = 30;
334 const uint minDistX = 40;
335 const uint textDistX = 10;
336 const uint textDistY = 25;
337 const uint topDist = m_innerScopeRect.top() - m_scopeRect.top();
338 const uint leftDist = m_innerScopeRect.left() - m_scopeRect.left();
339 const uint dbDiff = ceil((float)minDistY/m_innerScopeRect.height() * (m_dBmax-m_dBmin));
341 QImage hud(m_scopeRect.size(), QImage::Format_ARGB32);
342 hud.fill(qRgba(0,0,0,0));
344 QPainter davinci(&hud);
345 davinci.setPen(AbstractAudioScopeWidget::penLight);
348 for (int db = -dbDiff; db > m_dBmin; db -= dbDiff) {
349 y = topDist + m_innerScopeRect.height() * ((float)db)/(m_dBmin - m_dBmax);
350 if (y-topDist > m_innerScopeRect.height()-minDistY+10) {
351 // Abort here, there is still a line left for min dB to paint which needs some room.
354 davinci.drawLine(leftDist, y, leftDist + m_innerScopeRect.width()-1, y);
355 davinci.drawText(leftDist + m_innerScopeRect.width() + textDistX, y + 6, i18n("%1 dB", m_dBmax + db));
357 davinci.drawLine(leftDist, topDist, leftDist + m_innerScopeRect.width()-1, topDist);
358 davinci.drawText(leftDist + m_innerScopeRect.width() + textDistX, topDist+6, i18n("%1 dB", m_dBmax));
359 davinci.drawLine(leftDist, topDist+m_innerScopeRect.height()-1, leftDist + m_innerScopeRect.width()-1, topDist+m_innerScopeRect.height()-1);
360 davinci.drawText(leftDist + m_innerScopeRect.width() + textDistX, topDist+m_innerScopeRect.height()+6, i18n("%1 dB", m_dBmin));
362 const uint hzDiff = ceil( ((float)minDistX)/m_innerScopeRect.width() * m_freqMax / 1000 ) * 1000;
364 y = topDist + m_innerScopeRect.height() + textDistY;
365 for (uint hz = 0; hz <= m_freqMax; hz += hzDiff) {
366 x = leftDist + m_innerScopeRect.width() * ((float)hz)/m_freqMax;
367 davinci.drawLine(x, topDist, x, topDist + m_innerScopeRect.height()+6);
368 if (hz < m_freqMax) {
369 davinci.drawText(x-4, y, QVariant(hz/1000).toString());
371 davinci.drawText(x-10, y, i18n("%1 kHz",hz/1000));
375 for (uint dHz = 1; dHz < 4; dHz++) {
376 x = leftDist + m_innerScopeRect.width() * ((float)hz - dHz * hzDiff/4.0f)/m_freqMax;
377 davinci.drawLine(x, topDist, x, topDist + m_innerScopeRect.height()-1);
383 emit signalHUDRenderingFinished(start.elapsed(), 1);
387 QRect AudioSpectrum::scopeRect() {
391 ui->verticalSpacer->geometry().top()+6 // Top
393 AbstractAudioScopeWidget::rect().bottomRight()
395 m_innerScopeRect = QRect(
397 m_scopeRect.left()+6, // Left
398 m_scopeRect.top()+6 // Top
400 ui->verticalSpacer->geometry().right()-70,
401 ui->verticalSpacer->geometry().bottom()-40
407 void AudioSpectrum::slotResetMaxFreq()
409 m_customFreq = false;
417 void AudioSpectrum::mouseMoveEvent(QMouseEvent *event)
419 QPoint movement = event->pos()-m_rescaleStartPoint;
421 if (m_rescaleActive) {
422 if (m_rescalePropertiesLocked) {
423 // Direction is known, now adjust parameters
425 // Reset the starting point to make the next moveEvent relative to the current one
426 m_rescaleStartPoint = event->pos();
429 if (!m_rescaleFirstRescaleDone) {
430 // We have just learned the desired direction; Normalize the movement to one pixel
431 // to avoid a jump by m_rescaleMinDist
433 if (movement.x() != 0) {
434 movement.setX(movement.x() / abs(movement.x()));
436 if (movement.y() != 0) {
437 movement.setY(movement.y() / abs(movement.y()));
440 m_rescaleFirstRescaleDone = true;
443 if (m_rescaleClockDirection == AudioSpectrum::North) {
444 // Nort-South direction: Adjust the dB scale
446 if ((m_rescaleModifiers & Qt::ShiftModifier) == 0) {
448 // By default adjust the min dB value
449 m_dBmin += movement.y();
453 // Adjust max dB value if Shift is pressed.
454 m_dBmax += movement.y();
458 // Ensure the dB values lie in [-100, 0] (or rather [MIN_DB_VALUE, 0])
459 // 0 is the upper bound, everything below -70 dB is most likely noise
463 if (m_dBmin < MIN_DB_VALUE) {
464 m_dBmin = MIN_DB_VALUE;
466 // Ensure there is at least 6 dB between the minimum and the maximum value;
467 // lower values hardly make sense
468 if (m_dBmax - m_dBmin < 6) {
469 if ((m_rescaleModifiers & Qt::ShiftModifier) == 0) {
470 // min was adjusted; Try to adjust the max value to maintain the
471 // minimum dB difference of 6 dB
472 m_dBmax = m_dBmin + 6;
478 // max was adjusted, adjust min
479 m_dBmin = m_dBmax - 6;
480 if (m_dBmin < MIN_DB_VALUE) {
481 m_dBmin = MIN_DB_VALUE;
482 m_dBmax = MIN_DB_VALUE+6;
490 } else if (m_rescaleClockDirection == AudioSpectrum::East) {
491 // East-West direction: Adjust the maximum frequency
492 m_freqMax -= 100*movement.x();
493 if (m_freqMax < MIN_FREQ_VALUE) {
494 m_freqMax = MIN_FREQ_VALUE;
496 if (m_freqMax > MAX_FREQ_VALUE) {
497 m_freqMax = MAX_FREQ_VALUE;
507 // Detect the movement direction here.
508 // This algorithm relies on the aspect ratio of dy/dx (size and signum).
509 if (movement.manhattanLength() > m_rescaleMinDist) {
510 float diff = ((float) movement.y())/movement.x();
512 if (abs(diff) > m_rescaleVerticalThreshold || movement.x() == 0) {
513 m_rescaleClockDirection = AudioSpectrum::North;
514 } else if (abs(diff) < 1/m_rescaleVerticalThreshold) {
515 m_rescaleClockDirection = AudioSpectrum::East;
516 } else if (diff < 0) {
517 m_rescaleClockDirection = AudioSpectrum::Northeast;
519 m_rescaleClockDirection = AudioSpectrum::Southeast;
521 #ifdef DEBUG_AUDIOSPEC
522 qDebug() << "Diff is " << diff << "; chose " << directions[m_rescaleClockDirection] << " as direction";
524 m_rescalePropertiesLocked = true;
528 AbstractAudioScopeWidget::mouseMoveEvent(event);
532 void AudioSpectrum::mousePressEvent(QMouseEvent *event)
534 if (event->button() == Qt::LeftButton) {
535 // Rescaling mode starts
536 m_rescaleActive = true;
537 m_rescalePropertiesLocked = false;
538 m_rescaleFirstRescaleDone = false;
539 m_rescaleStartPoint = event->pos();
540 m_rescaleModifiers = event->modifiers();
543 AbstractAudioScopeWidget::mousePressEvent(event);
547 void AudioSpectrum::mouseReleaseEvent(QMouseEvent *event)
549 m_rescaleActive = false;
550 m_rescalePropertiesLocked = false;
552 AbstractAudioScopeWidget::mouseReleaseEvent(event);
555 const QString AudioSpectrum::cfgSignature(const int size)
557 return QString("s%1").arg(size);
561 #ifdef DEBUG_AUDIOSPEC
562 #undef DEBUG_AUDIOSPEC
566 #undef MAX_FREQ_VALUE
567 #undef MIN_FREQ_VALUE