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),
41 m_rescaleVerticalThreshold(2.0f),
42 m_rescaleActive(false),
43 m_rescalePropertiesLocked(false),
46 ui = new Ui::AudioSpectrum_UI;
50 m_aResetHz = new QAction(i18n("Reset maximum frequency to sampling rate"), this);
53 m_menu->addSeparator();
54 m_menu->addAction(m_aResetHz);
55 m_menu->removeAction(m_aRealtime);
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));
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);
69 b &= connect(m_aResetHz, SIGNAL(triggered()), this, SLOT(slotResetMaxFreq()));
70 b &= connect(ui->windowFunction, SIGNAL(currentIndexChanged(int)), this, SLOT(forceUpdate()));
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."));
78 AbstractScopeWidget::init();
80 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();
142 // Determine the window size to use. It should be
143 // * not bigger than the number of samples actually available
145 int fftWindow = ui->windowSize->itemData(ui->windowSize->currentIndex()).toInt();
146 if (fftWindow > num_samples) {
147 fftWindow = num_samples;
149 if ((fftWindow & 1) == 1) {
153 // Show the window size used, for information
154 ui->labelFFTSizeNumber->setText(QVariant(fftWindow).toString());
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);
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();
176 for (uint i = 0; i < w; i++) {
178 // i: Pixel coordinate
179 // f: Target frequency
180 // x: Frequency array index (float!) corresponding to the pixel
183 f = i/((float) w-1.0) * m_freqMax;
184 x = 2*f/freq * (fftWindow/2 - 1);
187 if (x >= fftWindow/2) {
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];
197 if (freqSpectrum[xi] > freqSpectrum[xi+1]
199 // This is a hack to preserve peaks.
200 // Consider f = {0, 100, 0}
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];
206 val = (xi+1 - x) * freqSpectrum[xi]
207 + (x - xi) * freqSpectrum[xi+1];
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));
219 emit signalScopeRenderingFinished(start.elapsed(), 1);
221 #ifdef DEBUG_AUDIOSPEC
222 if (!fileWritten || true) {
224 mFile.open("/tmp/freq.m");
226 qDebug() << "Opening file failed.";
230 for (int sample = 0; sample < 256; sample++) {
231 mFile << data[sample] << " ";
235 mFile << "freq = [ ";
236 for (int sample = 0; sample < 256; sample++) {
237 mFile << freqData[sample].r << "+" << freqData[sample].i << "*i ";
243 qDebug() << "File written.";
246 qDebug() << "File already written.";
252 emit signalScopeRenderingFinished(0, 1);
256 QImage AudioSpectrum::renderHUD(uint)
258 QTime start = QTime::currentTime();
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));
269 QImage hud(m_scopeRect.size(), QImage::Format_ARGB32);
270 hud.fill(qRgba(0,0,0,0));
272 QPainter davinci(&hud);
273 davinci.setPen(AbstractScopeWidget::penLight);
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.
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));
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));
290 const uint hzDiff = ceil( ((float)minDistX)/m_innerScopeRect.width() * m_freqMax / 1000 ) * 1000;
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;
298 if (x <= rightBorder) {
299 davinci.drawLine(x, topDist, x, topDist + m_innerScopeRect.height()+6);
301 if (hz < m_freqMax && x+textDistY < leftDist + m_innerScopeRect.width()) {
302 davinci.drawText(x-4, y, QVariant(hz/1000).toString());
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));
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) {
317 davinci.drawLine(x, topDist, x, topDist + m_innerScopeRect.height()-1);
323 emit signalHUDRenderingFinished(start.elapsed(), 1);
327 QRect AudioSpectrum::scopeRect()
332 ui->verticalSpacer->geometry().top()+6 // Top
334 AbstractAudioScopeWidget::rect().bottomRight()
336 m_innerScopeRect = QRect(
338 m_scopeRect.left()+6, // Left
339 m_scopeRect.top()+6 // Top
341 ui->verticalSpacer->geometry().right()-70,
342 ui->verticalSpacer->geometry().bottom()-40
348 void AudioSpectrum::slotResetMaxFreq()
350 m_customFreq = false;
358 void AudioSpectrum::mouseMoveEvent(QMouseEvent *event)
360 QPoint movement = event->pos()-m_rescaleStartPoint;
362 if (m_rescaleActive) {
363 if (m_rescalePropertiesLocked) {
364 // Direction is known, now adjust parameters
366 // Reset the starting point to make the next moveEvent relative to the current one
367 m_rescaleStartPoint = event->pos();
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
374 if (movement.x() != 0) {
375 movement.setX(movement.x() / abs(movement.x()));
377 if (movement.y() != 0) {
378 movement.setY(movement.y() / abs(movement.y()));
381 m_rescaleFirstRescaleDone = true;
384 if (m_rescaleClockDirection == AudioSpectrum::North) {
385 // Nort-South direction: Adjust the dB scale
387 if ((m_rescaleModifiers & Qt::ShiftModifier) == 0) {
389 // By default adjust the min dB value
390 m_dBmin += movement.y();
394 // Adjust max dB value if Shift is pressed.
395 m_dBmax += movement.y();
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
404 if (m_dBmin < MIN_DB_VALUE) {
405 m_dBmin = MIN_DB_VALUE;
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;
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;
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;
437 if (m_freqMax > MAX_FREQ_VALUE) {
438 m_freqMax = MAX_FREQ_VALUE;
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();
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;
460 m_rescaleClockDirection = AudioSpectrum::Southeast;
462 #ifdef DEBUG_AUDIOSPEC
463 qDebug() << "Diff is " << diff << "; chose " << directions[m_rescaleClockDirection] << " as direction";
465 m_rescalePropertiesLocked = true;
469 AbstractAudioScopeWidget::mouseMoveEvent(event);
473 void AudioSpectrum::mousePressEvent(QMouseEvent *event)
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();
484 AbstractAudioScopeWidget::mousePressEvent(event);
488 void AudioSpectrum::mouseReleaseEvent(QMouseEvent *event)
490 m_rescaleActive = false;
491 m_rescalePropertiesLocked = false;
493 AbstractAudioScopeWidget::mouseReleaseEvent(event);
496 const QString AudioSpectrum::cfgSignature(const int size)
498 return QString("s%1").arg(size);
502 #ifdef DEBUG_AUDIOSPEC
503 #undef DEBUG_AUDIOSPEC
507 #undef MAX_FREQ_VALUE
508 #undef MIN_FREQ_VALUE