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),
43 m_rescaleVerticalThreshold(2.0f),
44 m_rescaleActive(false),
45 m_rescalePropertiesLocked(false),
48 ui = new Ui::AudioSpectrum_UI;
52 m_aResetHz = new QAction(i18n("Reset maximum frequency to sampling rate"), this);
55 m_menu->addSeparator();
56 m_menu->addAction(m_aResetHz);
59 ui->windowSize->addItem("256", QVariant(256));
60 ui->windowSize->addItem("512", QVariant(512));
61 ui->windowSize->addItem("1024", QVariant(1024));
62 ui->windowSize->addItem("2048", QVariant(2048));
64 ui->windowFunction->addItem(i18n("Rectangular window"), FFTTools::Window_Rect);
65 ui->windowFunction->addItem(i18n("Triangular window"), FFTTools::Window_Triangle);
66 ui->windowFunction->addItem(i18n("Hamming window"), FFTTools::Window_Hamming);
69 m_cfg = kiss_fftr_alloc(ui->windowSize->itemData(ui->windowSize->currentIndex()).toInt(), 0,0,0);
73 b &= connect(ui->windowSize, SIGNAL(currentIndexChanged(int)), this, SLOT(slotUpdateCfg()));
74 b &= connect(m_aResetHz, SIGNAL(triggered()), this, SLOT(slotResetMaxFreq()));
77 AbstractScopeWidget::init();
79 AudioSpectrum::~AudioSpectrum()
87 void AudioSpectrum::readConfig()
89 AbstractScopeWidget::readConfig();
91 KSharedConfigPtr config = KGlobal::config();
92 KConfigGroup scopeConfig(config, AbstractScopeWidget::configName());
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);
100 if (m_freqMax == 0) {
101 m_customFreq = false;
107 void AudioSpectrum::writeConfig()
109 KSharedConfigPtr config = KGlobal::config();
110 KConfigGroup scopeConfig(config, AbstractScopeWidget::configName());
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);
117 scopeConfig.writeEntry("freqMax", m_freqMax);
119 scopeConfig.writeEntry("freqMax", 0);
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; }
130 QImage AudioSpectrum::renderBackground(uint) { return QImage(); }
132 QImage AudioSpectrum::renderAudioScope(uint, const QVector<int16_t> audioFrame, const int freq, const int num_channels, const int num_samples)
134 if (audioFrame.size() > 63) {
136 m_freqMax = freq / 2;
139 QTime start = QTime::currentTime();
141 bool customCfg = false;
142 kiss_fftr_cfg myCfg = m_cfg;
143 int fftWindow = ui->windowSize->itemData(ui->windowSize->currentIndex()).toInt();
144 if (fftWindow > num_samples) {
145 fftWindow = num_samples;
148 if ((fftWindow & 1) == 1) {
153 myCfg = kiss_fftr_alloc(fftWindow, 0,0,0);
156 float data[fftWindow];
157 float freqSpectrum[fftWindow/2];
160 for (int i = 0; i < fftWindow; i++) {
161 if (audioFrame.data()[i*num_channels] > maxSig) {
162 maxSig = audioFrame.data()[i*num_channels];
166 // Prepare frequency space vector. The resulting FFT vector is only half as long.
167 kiss_fft_cpx freqData[fftWindow/2];
171 // Copy the first channel's audio into a vector for the FFT display
172 // (only one channel handled at the moment)
173 if (num_samples < fftWindow) {
174 std::fill(&data[num_samples], &data[fftWindow-1], 0);
177 FFTTools::WindowType windowType = (FFTTools::WindowType) ui->windowFunction->itemData(ui->windowFunction->currentIndex()).toInt();
178 QVector<float> window;
179 float windowScaleFactor = 1;
180 if (windowType != FFTTools::Window_Rect) {
181 const QString signature = FFTTools::windowSignature(windowType, fftWindow, 0);
182 if (m_windowFunctions.contains(signature)) {
183 #ifdef DEBUG_AUDIOSPEC
184 qDebug() << "Re-using window function with signature " << signature;
186 window = m_windowFunctions.value(signature);
188 #ifdef DEBUG_AUDIOSPEC
189 qDebug() << "Building new window function with signature " << signature;
191 window = FFTTools::window(windowType, fftWindow, 0);
192 m_windowFunctions.insert(signature, window);
194 windowScaleFactor = 1.0/window[fftWindow];
197 // Normalize signals to [0,1] to get correct dB values later on
198 for (int i = 0; i < num_samples && i < fftWindow; i++) {
199 if (windowType != FFTTools::Window_Rect) {
200 data[i] = (float) audioFrame.data()[i*num_channels] / 32767.0f * window[i];
202 data[i] = (float) audioFrame.data()[i*num_channels] / 32767.0f;
206 // Calculate the Fast Fourier Transform for the input data
207 kiss_fftr(myCfg, data, freqData);
210 // Logarithmic scale: 20 * log ( 2 * magnitude / N ) with magnitude = sqrt(r² + i²)
211 // with N = FFT size (after FFT, 1/2 window size)
212 for (int i = 0; i < fftWindow/2; i++) {
213 // Logarithmic scale: 20 * log ( 2 * magnitude / N ) with magnitude = sqrt(r² + i²)
214 // with N = FFT size (after FFT, 1/2 window size)
215 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);;
221 QImage spectrum(m_scopeRect.size(), QImage::Format_ARGB32);
222 spectrum.fill(qRgba(0,0,0,0));
223 const uint w = m_innerScopeRect.width();
224 const uint h = m_innerScopeRect.height();
225 const uint leftDist = m_innerScopeRect.left() - m_scopeRect.left();
226 const uint topDist = m_innerScopeRect.top() - m_scopeRect.top();
232 for (uint i = 0; i < w; i++) {
234 // i: Pixel coordinate
235 // f: Target frequency
236 // x: Frequency array index (float!) corresponding to the pixel
239 f = i/((float) w-1.0) * m_freqMax;
240 x = 2*f/freq * (fftWindow/2 - 1);
243 if (x >= fftWindow/2) {
247 // Use linear interpolation in order to get smoother display
248 if (i == 0 || xi == fftWindow/2-1) {
249 // ... except if we are at the left or right border of the display or the spectrum
250 val = freqSpectrum[xi];
253 if (freqSpectrum[xi] > freqSpectrum[xi+1]
255 // This is a hack to preserve peaks.
256 // Consider f = {0, 100, 0}
258 // Then x is 50 both times, and the 100 peak is lost.
259 // Get it back here for the first x after the peak.
260 val = freqSpectrum[xi];
262 val = (xi+1 - x) * freqSpectrum[xi]
263 + (x - xi) * freqSpectrum[xi+1];
267 // freqSpectrum values range from 0 to -inf as they are relative dB values.
268 for (uint y = 0; y < h*(1 - (val - m_dBmax)/(m_dBmin-m_dBmax)) && y < h; y++) {
269 spectrum.setPixel(leftDist + i, topDist + h-y-1, qRgba(225, 182, 255, 255));
275 emit signalScopeRenderingFinished(start.elapsed(), 1);
277 #ifdef DEBUG_AUDIOSPEC
278 if (!fileWritten || true) {
280 mFile.open("/tmp/freq.m");
282 qDebug() << "Opening file failed.";
286 for (int sample = 0; sample < 256; sample++) {
287 mFile << data[sample] << " ";
291 mFile << "freq = [ ";
292 for (int sample = 0; sample < 256; sample++) {
293 mFile << freqData[sample].r << "+" << freqData[sample].i << "*i ";
299 qDebug() << "File written.";
302 qDebug() << "File already written.";
312 emit signalScopeRenderingFinished(0, 1);
316 QImage AudioSpectrum::renderHUD(uint)
318 QTime start = QTime::currentTime();
320 // Minimum distance between two lines
321 const uint minDistY = 30;
322 const uint minDistX = 40;
323 const uint textDistX = 10;
324 const uint textDistY = 25;
325 const uint topDist = m_innerScopeRect.top() - m_scopeRect.top();
326 const uint leftDist = m_innerScopeRect.left() - m_scopeRect.left();
327 const uint dbDiff = ceil((float)minDistY/m_innerScopeRect.height() * (m_dBmax-m_dBmin));
329 QImage hud(m_scopeRect.size(), QImage::Format_ARGB32);
330 hud.fill(qRgba(0,0,0,0));
332 QPainter davinci(&hud);
333 davinci.setPen(AbstractAudioScopeWidget::penLight);
336 for (int db = -dbDiff; db > m_dBmin; db -= dbDiff) {
337 y = topDist + m_innerScopeRect.height() * ((float)db)/(m_dBmin - m_dBmax);
338 if (y-topDist > m_innerScopeRect.height()-minDistY+10) {
339 // Abort here, there is still a line left for min dB to paint which needs some room.
342 davinci.drawLine(leftDist, y, leftDist + m_innerScopeRect.width()-1, y);
343 davinci.drawText(leftDist + m_innerScopeRect.width() + textDistX, y + 6, i18n("%1 dB", m_dBmax + db));
345 davinci.drawLine(leftDist, topDist, leftDist + m_innerScopeRect.width()-1, topDist);
346 davinci.drawText(leftDist + m_innerScopeRect.width() + textDistX, topDist+6, i18n("%1 dB", m_dBmax));
347 davinci.drawLine(leftDist, topDist+m_innerScopeRect.height()-1, leftDist + m_innerScopeRect.width()-1, topDist+m_innerScopeRect.height()-1);
348 davinci.drawText(leftDist + m_innerScopeRect.width() + textDistX, topDist+m_innerScopeRect.height()+6, i18n("%1 dB", m_dBmin));
350 const uint hzDiff = ceil( ((float)minDistX)/m_innerScopeRect.width() * m_freqMax / 1000 ) * 1000;
352 y = topDist + m_innerScopeRect.height() + textDistY;
353 for (uint hz = 0; hz <= m_freqMax; hz += hzDiff) {
354 x = leftDist + m_innerScopeRect.width() * ((float)hz)/m_freqMax;
355 davinci.drawLine(x, topDist, x, topDist + m_innerScopeRect.height()+6);
356 if (hz < m_freqMax) {
357 davinci.drawText(x-4, y, QVariant(hz/1000).toString());
359 davinci.drawText(x-10, y, i18n("%1 kHz",hz/1000));
363 for (uint dHz = 1; dHz < 4; dHz++) {
364 x = leftDist + m_innerScopeRect.width() * ((float)hz - dHz * hzDiff/4.0f)/m_freqMax;
365 davinci.drawLine(x, topDist, x, topDist + m_innerScopeRect.height()-1);
371 emit signalHUDRenderingFinished(start.elapsed(), 1);
375 QRect AudioSpectrum::scopeRect() {
379 ui->verticalSpacer->geometry().top()+6 // Top
381 AbstractAudioScopeWidget::rect().bottomRight()
383 m_innerScopeRect = QRect(
385 m_scopeRect.left()+6, // Left
386 m_scopeRect.top()+6 // Top
388 ui->verticalSpacer->geometry().right()-70,
389 ui->verticalSpacer->geometry().bottom()-40
396 void AudioSpectrum::slotUpdateCfg()
399 m_cfg = kiss_fftr_alloc(ui->windowSize->itemData(ui->windowSize->currentIndex()).toInt(), 0,0,0);
402 void AudioSpectrum::slotResetMaxFreq()
404 m_customFreq = false;
412 void AudioSpectrum::mouseMoveEvent(QMouseEvent *event)
414 QPoint movement = event->pos()-m_rescaleStartPoint;
416 if (m_rescaleActive) {
417 if (m_rescalePropertiesLocked) {
418 // Direction is known, now adjust parameters
420 // Reset the starting point to make the next moveEvent relative to the current one
421 m_rescaleStartPoint = event->pos();
424 if (!m_rescaleFirstRescaleDone) {
425 // We have just learned the desired direction; Normalize the movement to one pixel
426 // to avoid a jump by m_rescaleMinDist
428 if (movement.x() != 0) {
429 movement.setX(movement.x() / abs(movement.x()));
431 if (movement.y() != 0) {
432 movement.setY(movement.y() / abs(movement.y()));
435 m_rescaleFirstRescaleDone = true;
438 if (m_rescaleClockDirection == AudioSpectrum::North) {
439 // Nort-South direction: Adjust the dB scale
441 if ((m_rescaleModifiers & Qt::ShiftModifier) == 0) {
443 // By default adjust the min dB value
444 m_dBmin += movement.y();
448 // Adjust max dB value if Shift is pressed.
449 m_dBmax += movement.y();
453 // Ensure the dB values lie in [-100, 0] (or rather [MIN_DB_VALUE, 0])
454 // 0 is the upper bound, everything below -70 dB is most likely noise
458 if (m_dBmin < MIN_DB_VALUE) {
459 m_dBmin = MIN_DB_VALUE;
461 // Ensure there is at least 6 dB between the minimum and the maximum value;
462 // lower values hardly make sense
463 if (m_dBmax - m_dBmin < 6) {
464 if ((m_rescaleModifiers & Qt::ShiftModifier) == 0) {
465 // min was adjusted; Try to adjust the max value to maintain the
466 // minimum dB difference of 6 dB
467 m_dBmax = m_dBmin + 6;
473 // max was adjusted, adjust min
474 m_dBmin = m_dBmax - 6;
475 if (m_dBmin < MIN_DB_VALUE) {
476 m_dBmin = MIN_DB_VALUE;
477 m_dBmax = MIN_DB_VALUE+6;
485 } else if (m_rescaleClockDirection == AudioSpectrum::East) {
486 // East-West direction: Adjust the maximum frequency
487 m_freqMax -= 100*movement.x();
488 if (m_freqMax < MIN_FREQ_VALUE) {
489 m_freqMax = MIN_FREQ_VALUE;
491 if (m_freqMax > MAX_FREQ_VALUE) {
492 m_freqMax = MAX_FREQ_VALUE;
502 // Detect the movement direction here.
503 // This algorithm relies on the aspect ratio of dy/dx (size and signum).
504 if (movement.manhattanLength() > m_rescaleMinDist) {
505 float diff = ((float) movement.y())/movement.x();
507 if (abs(diff) > m_rescaleVerticalThreshold || movement.x() == 0) {
508 m_rescaleClockDirection = AudioSpectrum::North;
509 } else if (abs(diff) < 1/m_rescaleVerticalThreshold) {
510 m_rescaleClockDirection = AudioSpectrum::East;
511 } else if (diff < 0) {
512 m_rescaleClockDirection = AudioSpectrum::Northeast;
514 m_rescaleClockDirection = AudioSpectrum::Southeast;
516 #ifdef DEBUG_AUDIOSPEC
517 qDebug() << "Diff is " << diff << "; chose " << directions[m_rescaleClockDirection] << " as direction";
519 m_rescalePropertiesLocked = true;
523 AbstractAudioScopeWidget::mouseMoveEvent(event);
527 void AudioSpectrum::mousePressEvent(QMouseEvent *event)
529 if (event->button() == Qt::LeftButton) {
530 // Rescaling mode starts
531 m_rescaleActive = true;
532 m_rescalePropertiesLocked = false;
533 m_rescaleFirstRescaleDone = false;
534 m_rescaleStartPoint = event->pos();
535 m_rescaleModifiers = event->modifiers();
538 AbstractAudioScopeWidget::mousePressEvent(event);
542 void AudioSpectrum::mouseReleaseEvent(QMouseEvent *event)
544 m_rescaleActive = false;
545 m_rescalePropertiesLocked = false;
547 AbstractAudioScopeWidget::mouseReleaseEvent(event);
551 #ifdef DEBUG_AUDIOSPEC
552 #undef DEBUG_AUDIOSPEC
556 #undef MAX_FREQ_VALUE
557 #undef MIN_FREQ_VALUE