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>
24 //#define DEBUG_AUDIOSPEC
26 #ifdef DEBUG_AUDIOSPEC
30 #define MIN_DB_VALUE -120
31 #define MAX_FREQ_VALUE 96000
32 #define MIN_FREQ_VALUE 1000
34 AudioSpectrum::AudioSpectrum(QWidget *parent) :
35 AbstractAudioScopeWidget(true, parent),
40 ui = new Ui::AudioSpectrum_UI;
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);
49 m_menu->addSeparator();
50 m_menu->addAction(m_aResetHz);
51 m_menu->addAction(m_aTrackMouse);
52 m_menu->removeAction(m_aRealtime);
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));
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);
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()));
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."));
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_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);
101 if (m_freqMax == 0) {
102 m_customFreq = false;
108 void AudioSpectrum::writeConfig()
110 KSharedConfigPtr config = KGlobal::config();
111 KConfigGroup scopeConfig(config, AbstractScopeWidget::configName());
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);
119 scopeConfig.writeEntry("freqMax", m_freqMax);
121 scopeConfig.writeEntry("freqMax", 0);
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; }
132 QImage AudioSpectrum::renderBackground(uint) { return QImage(); }
134 QImage AudioSpectrum::renderAudioScope(uint, const QVector<int16_t> audioFrame, const int freq, const int num_channels,
135 const int num_samples, const int)
137 if (audioFrame.size() > 63) {
139 m_freqMax = freq / 2;
142 QTime start = QTime::currentTime();
145 // Determine the window size to use. It should be
146 // * not bigger than the number of samples actually available
148 int fftWindow = ui->windowSize->itemData(ui->windowSize->currentIndex()).toInt();
149 if (fftWindow > num_samples) {
150 fftWindow = num_samples;
152 if ((fftWindow & 1) == 1) {
156 // Show the window size used, for information
157 ui->labelFFTSizeNumber->setText(QVariant(fftWindow).toString());
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);
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));
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();
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();
188 for (uint i = 0; i < w; i++) {
189 yMax = (dbMap[i] - m_dBmin) / (m_dBmax-m_dBmin) * (h-1);
192 } else if (yMax >= (int)h) {
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));
200 emit signalScopeRenderingFinished(start.elapsed(), 1);
205 emit signalScopeRenderingFinished(0, 1);
209 QImage AudioSpectrum::renderHUD(uint)
211 QTime start = QTime::currentTime();
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();
224 QImage hud(m_scopeRect.size(), QImage::Format_ARGB32);
225 hud.fill(qRgba(0,0,0,0));
227 QPainter davinci(&hud);
228 davinci.setPen(AbstractScopeWidget::penLight);
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.
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));
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));
245 const uint hzDiff = ceil( ((float)minDistX)/m_innerScopeRect.width() * m_freqMax / 1000 ) * 1000;
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;
253 if (x <= rightBorder) {
254 davinci.drawLine(x, topDist, x, topDist + m_innerScopeRect.height()+6);
256 if (hz < m_freqMax && x+textDistY < leftDist + m_innerScopeRect.width()) {
257 davinci.drawText(x-4, y, QVariant(hz/1000).toString());
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));
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) {
272 davinci.drawLine(x, topDist, x, topDist + m_innerScopeRect.height()-1);
277 if (m_aTrackMouse->isChecked() && m_mouseWithinWidget && mouseX < m_innerScopeRect.width()-1) {
278 davinci.setPen(AbstractScopeWidget::penThin);
280 x = leftDist + mouseX;
283 float freq = ((float) mouseX)/(m_innerScopeRect.width()-1) * m_freqMax;
286 m_lastFFTLock.acquire();
287 // We need to test whether the mouse is inside the widget
288 // because the position could already have changed in the meantime (-> crash)
289 if (m_lastFFT.size() > 0 && mouseX >= 0 && mouseX < m_innerScopeRect.width()) {
290 uint right = ((float) m_freqMax)/(m_freq) * (m_lastFFT.size() - 1);
291 QVector<float> dbMap = AudioSpectrum::interpolatePeakPreserving(m_lastFFT, m_innerScopeRect.width(), 0, right, -120);
294 y = topDist + m_innerScopeRect.height()-1 - (dbMap[mouseX] - m_dBmin) / (m_dBmax-m_dBmin) * (m_innerScopeRect.height()-1);
296 if (y < (int)topDist + m_innerScopeRect.height()-1) {
298 davinci.drawLine(x, y, leftDist + m_innerScopeRect.width()-1, y);
301 y = topDist + mouseY;
303 m_lastFFTLock.release();
305 if (y > (int)topDist + mouseY) {
308 davinci.drawLine(x, y, x, topDist + m_innerScopeRect.height()-1);
311 QPoint dist(20, -20);
313 leftDist + mouseX + dist.x(),
314 topDist + mouseY + dist.y(),
318 if (rect.right() > (int)leftDist + m_innerScopeRect.width()-1) {
319 // Mirror the rectangle at the y axis to keep it inside the widget
321 rect.topLeft() - QPoint(rect.width() + 2*dist.x(), 0),
326 rect.topLeft() + QPoint(12, 4),
330 davinci.fillRect(rect, AbstractScopeWidget::penBackground.brush());
331 davinci.setPen(AbstractScopeWidget::penLighter);
332 davinci.drawRect(rect);
333 davinci.drawText(textRect, QString(
334 i18n("%1 dB", QString("%1").arg(db, 0, 'f', 2))
336 + i18n("%1 kHz", QString("%1").arg(freq/1000, 0, 'f', 2))));
342 emit signalHUDRenderingFinished(start.elapsed(), 1);
346 QRect AudioSpectrum::scopeRect()
351 ui->verticalSpacer->geometry().top()+6 // Top
353 AbstractAudioScopeWidget::rect().bottomRight()
355 m_innerScopeRect = QRect(
357 m_scopeRect.left()+6, // Left
358 m_scopeRect.top()+6 // Top
360 ui->verticalSpacer->geometry().right()-70,
361 ui->verticalSpacer->geometry().bottom()-40
367 void AudioSpectrum::slotResetMaxFreq()
369 m_customFreq = false;
377 void AudioSpectrum::handleMouseDrag(const QPoint movement, const RescaleDirection rescaleDirection, const Qt::KeyboardModifiers rescaleModifiers)
379 if (rescaleDirection == North) {
380 // Nort-South direction: Adjust the dB scale
382 if ((rescaleModifiers & Qt::ShiftModifier) == 0) {
384 // By default adjust the min dB value
385 m_dBmin += movement.y();
389 // Adjust max dB value if Shift is pressed.
390 m_dBmax += movement.y();
394 // Ensure the dB values lie in [-100, 0] (or rather [MIN_DB_VALUE, 0])
395 // 0 is the upper bound, everything below -70 dB is most likely noise
399 if (m_dBmin < MIN_DB_VALUE) {
400 m_dBmin = MIN_DB_VALUE;
402 // Ensure there is at least 6 dB between the minimum and the maximum value;
403 // lower values hardly make sense
404 if (m_dBmax - m_dBmin < 6) {
405 if ((rescaleModifiers & Qt::ShiftModifier) == 0) {
406 // min was adjusted; Try to adjust the max value to maintain the
407 // minimum dB difference of 6 dB
408 m_dBmax = m_dBmin + 6;
414 // max was adjusted, adjust min
415 m_dBmin = m_dBmax - 6;
416 if (m_dBmin < MIN_DB_VALUE) {
417 m_dBmin = MIN_DB_VALUE;
418 m_dBmax = MIN_DB_VALUE+6;
426 } else if (rescaleDirection == East) {
427 // East-West direction: Adjust the maximum frequency
428 m_freqMax -= 100*movement.x();
429 if (m_freqMax < MIN_FREQ_VALUE) {
430 m_freqMax = MIN_FREQ_VALUE;
432 if (m_freqMax > MAX_FREQ_VALUE) {
433 m_freqMax = MAX_FREQ_VALUE;
443 const QVector<float> AudioSpectrum::interpolatePeakPreserving(const QVector<float> in, const uint targetSize, uint left, uint right, float fill)
448 Q_ASSERT(targetSize > 0);
449 Q_ASSERT(left < right);
451 QVector<float> out(targetSize);
458 for (i = 0; i < targetSize; i++) {
461 // x: Interpolated source index (float!)
464 // Transform [0,targetSize-1] to [left,right]
465 x = ((float) i) / (targetSize-1) * (right-left) + left;
468 if (x > in.size()-1) {
469 // This may happen if right > in.size()-1; Fill the rest of the vector
470 // with the default value now.
475 // Use linear interpolation in order to get smoother display
476 if (i == 0 || i == targetSize-1) {
477 // ... except if we are at the left or right border of the display or the spectrum
480 if (in[xi] > in[xi+1]
482 // This is a hack to preserve peaks.
483 // Consider f = {0, 100, 0}
485 // Then x is 50 both times, and the 100 peak is lost.
486 // Get it back here for the first x after the peak (which is at xi).
487 // (x is the first after the peak if the previous x was smaller than floor(x).)
490 out[i] = (xi+1 - x) * in[xi]
491 + (x - xi) * in[xi+1];
496 // Fill the rest of the vector if the right border exceeds the input vector.
497 for (; i < targetSize; i++) {
505 #ifdef DEBUG_AUDIOSPEC
506 #undef DEBUG_AUDIOSPEC
510 #undef MAX_FREQ_VALUE
511 #undef MIN_FREQ_VALUE