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 // (defined in the header file)
24 #ifdef DEBUG_AUDIOSPEC
28 // Draw lines instead of single pixels.
29 // This is about 25 % faster, especially when enlarging the scope to e.g. 1680x1050 px.
30 #define AUDIOSPEC_LINES
32 #define MIN_DB_VALUE -120
33 #define MAX_FREQ_VALUE 96000
34 #define MIN_FREQ_VALUE 1000
36 AudioSpectrum::AudioSpectrum(QWidget *parent) :
37 AbstractAudioScopeWidget(true, parent),
41 #ifdef DEBUG_AUDIOSPEC
46 ui = new Ui::AudioSpectrum_UI;
50 m_aResetHz = new QAction(i18n("Reset maximum frequency to sampling rate"), this);
51 m_aTrackMouse = new QAction(i18n("Track mouse"), this);
52 m_aTrackMouse->setCheckable(true);
55 m_menu->addSeparator();
56 m_menu->addAction(m_aResetHz);
57 m_menu->addAction(m_aTrackMouse);
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()));
73 b &= connect(ui->windowFunction, SIGNAL(currentIndexChanged(int)), this, SLOT(forceUpdate()));
74 b &= connect(this, SIGNAL(signalMousePositionChanged()), this, SLOT(forceUpdateHUD()));
78 // Note: These strings are used in both Spectogram and AudioSpectrum. Ideally change both (if necessary) to reduce workload on translators
79 ui->labelFFTSize->setToolTip(i18n("The maximum window size is limited by the number of samples per frame."));
80 ui->windowSize->setToolTip(i18n("A bigger window improves the accuracy at the cost of computational power."));
81 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."));
83 AbstractScopeWidget::init();
85 AudioSpectrum::~AudioSpectrum()
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_aTrackMouse->setChecked(scopeConfig.readEntry("trackMouse", true));
103 m_dBmax = scopeConfig.readEntry("dBmax", 0);
104 m_dBmin = scopeConfig.readEntry("dBmin", -70);
105 m_freqMax = scopeConfig.readEntry("freqMax", 0);
107 if (m_freqMax == 0) {
108 m_customFreq = false;
114 void AudioSpectrum::writeConfig()
116 KSharedConfigPtr config = KGlobal::config();
117 KConfigGroup scopeConfig(config, AbstractScopeWidget::configName());
119 scopeConfig.writeEntry("windowSize", ui->windowSize->currentIndex());
120 scopeConfig.writeEntry("windowFunction", ui->windowFunction->currentIndex());
121 scopeConfig.writeEntry("trackMouse", m_aTrackMouse->isChecked());
122 scopeConfig.writeEntry("dBmax", m_dBmax);
123 scopeConfig.writeEntry("dBmin", m_dBmin);
125 scopeConfig.writeEntry("freqMax", m_freqMax);
127 scopeConfig.writeEntry("freqMax", 0);
133 QString AudioSpectrum::widgetName() const { return QString("AudioSpectrum"); }
134 bool AudioSpectrum::isBackgroundDependingOnInput() const { return false; }
135 bool AudioSpectrum::isScopeDependingOnInput() const { return true; }
136 bool AudioSpectrum::isHUDDependingOnInput() const { return false; }
138 QImage AudioSpectrum::renderBackground(uint) { return QImage(); }
140 QImage AudioSpectrum::renderAudioScope(uint, const QVector<int16_t> audioFrame, const int freq, const int num_channels,
141 const int num_samples, const int)
143 if (audioFrame.size() > 63) {
145 m_freqMax = freq / 2;
148 QTime start = QTime::currentTime();
151 // Determine the window size to use. It should be
152 // * not bigger than the number of samples actually available
154 int fftWindow = ui->windowSize->itemData(ui->windowSize->currentIndex()).toInt();
155 if (fftWindow > num_samples) {
156 fftWindow = num_samples;
158 if ((fftWindow & 1) == 1) {
162 // Show the window size used, for information
163 ui->labelFFTSizeNumber->setText(QVariant(fftWindow).toString());
166 // Get the spectral power distribution of the input samples,
167 // using the given window size and function
168 float freqSpectrum[fftWindow/2];
169 FFTTools::WindowType windowType = (FFTTools::WindowType) ui->windowFunction->itemData(ui->windowFunction->currentIndex()).toInt();
170 m_fftTools.fftNormalized(audioFrame, 0, num_channels, freqSpectrum, windowType, fftWindow, 0);
173 // Store the current FFT window (for the HUD) and run the interpolation
174 // for easy pixel-based dB value access
175 QVector<float> dbMap;
176 m_lastFFTLock.acquire();
177 m_lastFFT = QVector<float>(fftWindow/2);
178 memcpy(m_lastFFT.data(), &(freqSpectrum[0]), fftWindow/2 * sizeof(float));
180 uint right = ((float) m_freqMax)/(m_freq/2) * (m_lastFFT.size() - 1);
181 dbMap = FFTTools::interpolatePeakPreserving(m_lastFFT, m_innerScopeRect.width(), 0, right, -180);
182 m_lastFFTLock.release();
185 QTime drawTime = QTime::currentTime();
188 QImage spectrum(m_scopeRect.size(), QImage::Format_ARGB32);
189 spectrum.fill(qRgba(0,0,0,0));
190 const uint w = m_innerScopeRect.width();
191 const uint h = m_innerScopeRect.height();
192 const uint leftDist = m_innerScopeRect.left() - m_scopeRect.left();
193 const uint topDist = m_innerScopeRect.top() - m_scopeRect.top();
196 #ifdef AUDIOSPEC_LINES
197 QPainter davinci(&spectrum);
198 davinci.setPen(AbstractScopeWidget::penThin);
201 for (uint i = 0; i < w; i++) {
202 yMax = (dbMap[i] - m_dBmin) / (m_dBmax-m_dBmin) * (h-1);
205 } else if (yMax >= (int)h) {
208 #ifdef AUDIOSPEC_LINES
209 davinci.drawLine(leftDist + i, topDist + h-1, leftDist + i, topDist + h-1 - yMax);
211 for (int y = 0; y < yMax && y < (int)h; y++) {
212 spectrum.setPixel(leftDist + i, topDist + h-y-1, qRgba(225, 182, 255, 255));
217 #ifdef DEBUG_AUDIOSPEC
219 m_timeTotal += drawTime.elapsed();
220 qDebug() << widgetName() << " took " << drawTime.elapsed() << " ms for drawing. Average: " << ((float)m_timeTotal/m_showTotal) ;
223 emit signalScopeRenderingFinished(start.elapsed(), 1);
228 emit signalScopeRenderingFinished(0, 1);
232 QImage AudioSpectrum::renderHUD(uint)
234 QTime start = QTime::currentTime();
236 // Minimum distance between two lines
237 const uint minDistY = 30;
238 const uint minDistX = 40;
239 const uint textDistX = 10;
240 const uint textDistY = 25;
241 const uint topDist = m_innerScopeRect.top() - m_scopeRect.top();
242 const uint leftDist = m_innerScopeRect.left() - m_scopeRect.left();
243 const uint dbDiff = ceil((float)minDistY/m_innerScopeRect.height() * (m_dBmax-m_dBmin));
244 const int mouseX = m_mousePos.x() - m_innerScopeRect.left();
245 const int mouseY = m_mousePos.y() - m_innerScopeRect.top();
247 QImage hud(m_scopeRect.size(), QImage::Format_ARGB32);
248 hud.fill(qRgba(0,0,0,0));
250 QPainter davinci(&hud);
251 davinci.setPen(AbstractScopeWidget::penLight);
254 for (int db = -dbDiff; db > m_dBmin; db -= dbDiff) {
255 y = topDist + m_innerScopeRect.height() * ((float)db)/(m_dBmin - m_dBmax);
256 if (y-topDist > m_innerScopeRect.height()-minDistY+10) {
257 // Abort here, there is still a line left for min dB to paint which needs some room.
260 davinci.drawLine(leftDist, y, leftDist + m_innerScopeRect.width()-1, y);
261 davinci.drawText(leftDist + m_innerScopeRect.width() + textDistX, y + 6, i18n("%1 dB", m_dBmax + db));
263 davinci.drawLine(leftDist, topDist, leftDist + m_innerScopeRect.width()-1, topDist);
264 davinci.drawText(leftDist + m_innerScopeRect.width() + textDistX, topDist+6, i18n("%1 dB", m_dBmax));
265 davinci.drawLine(leftDist, topDist+m_innerScopeRect.height()-1, leftDist + m_innerScopeRect.width()-1, topDist+m_innerScopeRect.height()-1);
266 davinci.drawText(leftDist + m_innerScopeRect.width() + textDistX, topDist+m_innerScopeRect.height()+6, i18n("%1 dB", m_dBmin));
268 const uint hzDiff = ceil( ((float)minDistX)/m_innerScopeRect.width() * m_freqMax / 1000 ) * 1000;
270 const int rightBorder = leftDist + m_innerScopeRect.width()-1;
271 y = topDist + m_innerScopeRect.height() + textDistY;
272 for (int hz = 0; x <= rightBorder; hz += hzDiff) {
273 davinci.setPen(AbstractScopeWidget::penLighter);
274 x = leftDist + m_innerScopeRect.width() * ((float)hz)/m_freqMax;
276 if (x <= rightBorder) {
277 davinci.drawLine(x, topDist, x, topDist + m_innerScopeRect.height()+6);
279 if (hz < m_freqMax && x+textDistY < leftDist + m_innerScopeRect.width()) {
280 davinci.drawText(x-4, y, QVariant(hz/1000).toString());
282 x = leftDist + m_innerScopeRect.width();
283 davinci.drawLine(x, topDist, x, topDist + m_innerScopeRect.height()+6);
284 davinci.drawText(x-10, y, i18n("%1 kHz").arg((double)m_freqMax/1000, 0, 'f', 1));
288 // Draw finer lines between the main lines
289 davinci.setPen(AbstractScopeWidget::penLightDots);
290 for (uint dHz = 3; dHz > 0; dHz--) {
291 x = leftDist + m_innerScopeRect.width() * ((float)hz - dHz * hzDiff/4.0f)/m_freqMax;
292 if (x > rightBorder) {
295 davinci.drawLine(x, topDist, x, topDist + m_innerScopeRect.height()-1);
300 if (m_aTrackMouse->isChecked() && m_mouseWithinWidget && mouseX < m_innerScopeRect.width()-1) {
301 davinci.setPen(AbstractScopeWidget::penThin);
303 x = leftDist + mouseX;
306 float freq = ((float) mouseX)/(m_innerScopeRect.width()-1) * m_freqMax;
309 m_lastFFTLock.acquire();
310 // We need to test whether the mouse is inside the widget
311 // because the position could already have changed in the meantime (-> crash)
312 if (m_lastFFT.size() > 0 && mouseX >= 0 && mouseX < m_innerScopeRect.width()) {
313 uint right = ((float) m_freqMax)/(m_freq/2) * (m_lastFFT.size() - 1);
314 QVector<float> dbMap = FFTTools::interpolatePeakPreserving(m_lastFFT, m_innerScopeRect.width(), 0, right, -120);
317 y = topDist + m_innerScopeRect.height()-1 - (dbMap[mouseX] - m_dBmin) / (m_dBmax-m_dBmin) * (m_innerScopeRect.height()-1);
319 if (y < (int)topDist + m_innerScopeRect.height()-1) {
321 davinci.drawLine(x, y, leftDist + m_innerScopeRect.width()-1, y);
324 y = topDist + mouseY;
326 m_lastFFTLock.release();
328 if (y > (int)topDist + mouseY) {
331 davinci.drawLine(x, y, x, topDist + m_innerScopeRect.height()-1);
334 QPoint dist(20, -20);
336 leftDist + mouseX + dist.x(),
337 topDist + mouseY + dist.y(),
341 if (rect.right() > (int)leftDist + m_innerScopeRect.width()-1) {
342 // Mirror the rectangle at the y axis to keep it inside the widget
344 rect.topLeft() - QPoint(rect.width() + 2*dist.x(), 0),
349 rect.topLeft() + QPoint(12, 4),
353 davinci.fillRect(rect, AbstractScopeWidget::penBackground.brush());
354 davinci.setPen(AbstractScopeWidget::penLighter);
355 davinci.drawRect(rect);
356 davinci.drawText(textRect, QString(
357 i18n("%1 dB", QString("%1").arg(db, 0, 'f', 2))
359 + i18n("%1 kHz", QString("%1").arg(freq/1000, 0, 'f', 2))));
365 emit signalHUDRenderingFinished(start.elapsed(), 1);
369 QRect AudioSpectrum::scopeRect()
374 ui->verticalSpacer->geometry().top()+6 // Top
376 AbstractAudioScopeWidget::rect().bottomRight()
378 m_innerScopeRect = QRect(
380 m_scopeRect.left()+6, // Left
381 m_scopeRect.top()+6 // Top
383 ui->verticalSpacer->geometry().right()-70,
384 ui->verticalSpacer->geometry().bottom()-40
390 void AudioSpectrum::slotResetMaxFreq()
392 m_customFreq = false;
400 void AudioSpectrum::handleMouseDrag(const QPoint movement, const RescaleDirection rescaleDirection, const Qt::KeyboardModifiers rescaleModifiers)
402 if (rescaleDirection == North) {
403 // Nort-South direction: Adjust the dB scale
405 if ((rescaleModifiers & Qt::ShiftModifier) == 0) {
407 // By default adjust the min dB value
408 m_dBmin += movement.y();
412 // Adjust max dB value if Shift is pressed.
413 m_dBmax += movement.y();
417 // Ensure the dB values lie in [-100, 0] (or rather [MIN_DB_VALUE, 0])
418 // 0 is the upper bound, everything below -70 dB is most likely noise
422 if (m_dBmin < MIN_DB_VALUE) {
423 m_dBmin = MIN_DB_VALUE;
425 // Ensure there is at least 6 dB between the minimum and the maximum value;
426 // lower values hardly make sense
427 if (m_dBmax - m_dBmin < 6) {
428 if ((rescaleModifiers & Qt::ShiftModifier) == 0) {
429 // min was adjusted; Try to adjust the max value to maintain the
430 // minimum dB difference of 6 dB
431 m_dBmax = m_dBmin + 6;
437 // max was adjusted, adjust min
438 m_dBmin = m_dBmax - 6;
439 if (m_dBmin < MIN_DB_VALUE) {
440 m_dBmin = MIN_DB_VALUE;
441 m_dBmax = MIN_DB_VALUE+6;
449 } else if (rescaleDirection == East) {
450 // East-West direction: Adjust the maximum frequency
451 m_freqMax -= 100*movement.x();
452 if (m_freqMax < MIN_FREQ_VALUE) {
453 m_freqMax = MIN_FREQ_VALUE;
455 if (m_freqMax > MAX_FREQ_VALUE) {
456 m_freqMax = MAX_FREQ_VALUE;
466 #ifdef DEBUG_AUDIOSPEC
467 #undef DEBUG_AUDIOSPEC
471 #undef MAX_FREQ_VALUE
472 #undef MIN_FREQ_VALUE