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
35 #define ALPHA_MOVING_AVG 0.125
37 AudioSpectrum::AudioSpectrum(QWidget *parent) :
38 AbstractAudioScopeWidget(true, parent),
43 #ifdef DEBUG_AUDIOSPEC
48 ui = new Ui::AudioSpectrum_UI;
52 m_aResetHz = new QAction(i18n("Reset maximum frequency to sampling rate"), this);
53 m_aTrackMouse = new QAction(i18n("Track mouse"), this);
54 m_aTrackMouse->setCheckable(true);
55 m_aShowMax = new QAction(i18n("Show maximum"), this);
56 m_aShowMax->setCheckable(true);
59 m_menu->addSeparator();
60 m_menu->addAction(m_aResetHz);
61 m_menu->addAction(m_aTrackMouse);
62 m_menu->addAction(m_aShowMax);
63 m_menu->removeAction(m_aRealtime);
66 ui->windowSize->addItem("256", QVariant(256));
67 ui->windowSize->addItem("512", QVariant(512));
68 ui->windowSize->addItem("1024", QVariant(1024));
69 ui->windowSize->addItem("2048", QVariant(2048));
71 ui->windowFunction->addItem(i18n("Rectangular window"), FFTTools::Window_Rect);
72 ui->windowFunction->addItem(i18n("Triangular window"), FFTTools::Window_Triangle);
73 ui->windowFunction->addItem(i18n("Hamming window"), FFTTools::Window_Hamming);
77 b &= connect(m_aResetHz, SIGNAL(triggered()), this, SLOT(slotResetMaxFreq()));
78 b &= connect(ui->windowFunction, SIGNAL(currentIndexChanged(int)), this, SLOT(forceUpdate()));
79 b &= connect(this, SIGNAL(signalMousePositionChanged()), this, SLOT(forceUpdateHUD()));
83 // Note: These strings are used in both Spectogram and AudioSpectrum. Ideally change both (if necessary) to reduce workload on translators
84 ui->labelFFTSize->setToolTip(i18n("The maximum window size is limited by the number of samples per frame."));
85 ui->windowSize->setToolTip(i18n("A bigger window improves the accuracy at the cost of computational power."));
86 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."));
88 AbstractScopeWidget::init();
90 AudioSpectrum::~AudioSpectrum()
98 void AudioSpectrum::readConfig()
100 AbstractScopeWidget::readConfig();
102 KSharedConfigPtr config = KGlobal::config();
103 KConfigGroup scopeConfig(config, AbstractScopeWidget::configName());
105 ui->windowSize->setCurrentIndex(scopeConfig.readEntry("windowSize", 0));
106 ui->windowFunction->setCurrentIndex(scopeConfig.readEntry("windowFunction", 0));
107 m_aTrackMouse->setChecked(scopeConfig.readEntry("trackMouse", true));
108 m_aShowMax->setChecked(scopeConfig.readEntry("showMax", true));
109 m_dBmax = scopeConfig.readEntry("dBmax", 0);
110 m_dBmin = scopeConfig.readEntry("dBmin", -70);
111 m_freqMax = scopeConfig.readEntry("freqMax", 0);
113 if (m_freqMax == 0) {
114 m_customFreq = false;
120 void AudioSpectrum::writeConfig()
122 KSharedConfigPtr config = KGlobal::config();
123 KConfigGroup scopeConfig(config, AbstractScopeWidget::configName());
125 scopeConfig.writeEntry("windowSize", ui->windowSize->currentIndex());
126 scopeConfig.writeEntry("windowFunction", ui->windowFunction->currentIndex());
127 scopeConfig.writeEntry("trackMouse", m_aTrackMouse->isChecked());
128 scopeConfig.writeEntry("showMax", m_aShowMax->isChecked());
129 scopeConfig.writeEntry("dBmax", m_dBmax);
130 scopeConfig.writeEntry("dBmin", m_dBmin);
132 scopeConfig.writeEntry("freqMax", m_freqMax);
134 scopeConfig.writeEntry("freqMax", 0);
140 QString AudioSpectrum::widgetName() const { return QString("AudioSpectrum"); }
141 bool AudioSpectrum::isBackgroundDependingOnInput() const { return false; }
142 bool AudioSpectrum::isScopeDependingOnInput() const { return true; }
143 bool AudioSpectrum::isHUDDependingOnInput() const { return false; }
145 QImage AudioSpectrum::renderBackground(uint) { return QImage(); }
147 QImage AudioSpectrum::renderAudioScope(uint, const QVector<int16_t> audioFrame, const int freq, const int num_channels,
148 const int num_samples, const int)
150 if (audioFrame.size() > 63) {
152 m_freqMax = freq / 2;
155 QTime start = QTime::currentTime();
158 // Determine the window size to use. It should be
159 // * not bigger than the number of samples actually available
161 int fftWindow = ui->windowSize->itemData(ui->windowSize->currentIndex()).toInt();
162 if (fftWindow > num_samples) {
163 fftWindow = num_samples;
165 if ((fftWindow & 1) == 1) {
169 // Show the window size used, for information
170 ui->labelFFTSizeNumber->setText(QVariant(fftWindow).toString());
173 // Get the spectral power distribution of the input samples,
174 // using the given window size and function
175 float freqSpectrum[fftWindow/2];
176 FFTTools::WindowType windowType = (FFTTools::WindowType) ui->windowFunction->itemData(ui->windowFunction->currentIndex()).toInt();
177 m_fftTools.fftNormalized(audioFrame, 0, num_channels, freqSpectrum, windowType, fftWindow, 0);
180 // Store the current FFT window (for the HUD) and run the interpolation
181 // for easy pixel-based dB value access
182 QVector<float> dbMap;
183 m_lastFFTLock.acquire();
184 m_lastFFT = QVector<float>(fftWindow/2);
185 memcpy(m_lastFFT.data(), &(freqSpectrum[0]), fftWindow/2 * sizeof(float));
187 uint right = ((float) m_freqMax)/(m_freq/2) * (m_lastFFT.size() - 1);
188 dbMap = FFTTools::interpolatePeakPreserving(m_lastFFT, m_innerScopeRect.width(), 0, right, -180);
189 m_lastFFTLock.release();
192 #ifdef DEBUG_AUDIOSPEC
193 QTime drawTime = QTime::currentTime();
197 QImage spectrum(m_scopeRect.size(), QImage::Format_ARGB32);
198 spectrum.fill(qRgba(0,0,0,0));
199 const uint w = m_innerScopeRect.width();
200 const uint h = m_innerScopeRect.height();
201 const uint leftDist = m_innerScopeRect.left() - m_scopeRect.left();
202 const uint topDist = m_innerScopeRect.top() - m_scopeRect.top();
205 #ifdef AUDIOSPEC_LINES
206 QPainter davinci(&spectrum);
207 davinci.setPen(AbstractScopeWidget::penThin);
210 for (uint i = 0; i < w; i++) {
211 yMax = (dbMap[i] - m_dBmin) / (m_dBmax-m_dBmin) * (h-1);
214 } else if (yMax >= (int)h) {
217 #ifdef AUDIOSPEC_LINES
218 davinci.drawLine(leftDist + i, topDist + h-1, leftDist + i, topDist + h-1 - yMax);
220 for (int y = 0; y < yMax && y < (int)h; y++) {
221 spectrum.setPixel(leftDist + i, topDist + h-y-1, qRgba(225, 182, 255, 255));
226 // Calculate the peak values. Use the new value if it is bigger, otherwise adapt to lower
227 // values using the Moving Average formula
228 if (m_aShowMax->isChecked()) {
229 davinci.setPen(QPen(QBrush(AbstractScopeWidget::colHighlightLight), 2));
230 if (m_peaks.size() != fftWindow/2) {
231 m_peaks = QVector<float>(m_lastFFT);
233 for (int i = 0; i < fftWindow/2; i++) {
234 if (m_lastFFT[i] > m_peaks[i]) {
235 m_peaks[i] = m_lastFFT[i];
237 m_peaks[i] = ALPHA_MOVING_AVG * m_lastFFT[i] + (1-ALPHA_MOVING_AVG) * m_peaks[i];
242 m_peakMap = FFTTools::interpolatePeakPreserving(m_peaks, m_innerScopeRect.width(), 0, right, -180);
243 for (uint i = 0; i < w; i++) {
244 yMax = (m_peakMap[i] - m_dBmin) / (m_dBmax-m_dBmin) * (h-1);
247 } else if (yMax >= (int)h) {
251 davinci.drawLine(leftDist + i-1, topDist + h-prev-1, leftDist + i, topDist + h-yMax-1);
252 spectrum.setPixel(leftDist + i, topDist + h-yMax-1, AbstractScopeWidget::colHighlightLight.rgba());
257 #ifdef DEBUG_AUDIOSPEC
259 m_timeTotal += drawTime.elapsed();
260 qDebug() << widgetName() << " took " << drawTime.elapsed() << " ms for drawing. Average: " << ((float)m_timeTotal/m_showTotal) ;
263 emit signalScopeRenderingFinished(start.elapsed(), 1);
268 emit signalScopeRenderingFinished(0, 1);
272 QImage AudioSpectrum::renderHUD(uint)
274 QTime start = QTime::currentTime();
276 // Minimum distance between two lines
277 const uint minDistY = 30;
278 const uint minDistX = 40;
279 const uint textDistX = 10;
280 const uint textDistY = 25;
281 const uint topDist = m_innerScopeRect.top() - m_scopeRect.top();
282 const uint leftDist = m_innerScopeRect.left() - m_scopeRect.left();
283 const uint dbDiff = ceil((float)minDistY/m_innerScopeRect.height() * (m_dBmax-m_dBmin));
284 const int mouseX = m_mousePos.x() - m_innerScopeRect.left();
285 const int mouseY = m_mousePos.y() - m_innerScopeRect.top();
287 QImage hud(m_scopeRect.size(), QImage::Format_ARGB32);
288 hud.fill(qRgba(0,0,0,0));
290 QPainter davinci(&hud);
291 davinci.setPen(AbstractScopeWidget::penLight);
294 for (int db = -dbDiff; db > m_dBmin; db -= dbDiff) {
295 y = topDist + m_innerScopeRect.height() * ((float)db)/(m_dBmin - m_dBmax);
296 if (y-topDist > m_innerScopeRect.height()-minDistY+10) {
297 // Abort here, there is still a line left for min dB to paint which needs some room.
300 davinci.drawLine(leftDist, y, leftDist + m_innerScopeRect.width()-1, y);
301 davinci.drawText(leftDist + m_innerScopeRect.width() + textDistX, y + 6, i18n("%1 dB", m_dBmax + db));
303 davinci.drawLine(leftDist, topDist, leftDist + m_innerScopeRect.width()-1, topDist);
304 davinci.drawText(leftDist + m_innerScopeRect.width() + textDistX, topDist+6, i18n("%1 dB", m_dBmax));
305 davinci.drawLine(leftDist, topDist+m_innerScopeRect.height()-1, leftDist + m_innerScopeRect.width()-1, topDist+m_innerScopeRect.height()-1);
306 davinci.drawText(leftDist + m_innerScopeRect.width() + textDistX, topDist+m_innerScopeRect.height()+6, i18n("%1 dB", m_dBmin));
308 const uint hzDiff = ceil( ((float)minDistX)/m_innerScopeRect.width() * m_freqMax / 1000 ) * 1000;
310 const int rightBorder = leftDist + m_innerScopeRect.width()-1;
311 y = topDist + m_innerScopeRect.height() + textDistY;
312 for (int hz = 0; x <= rightBorder; hz += hzDiff) {
313 davinci.setPen(AbstractScopeWidget::penLighter);
314 x = leftDist + m_innerScopeRect.width() * ((float)hz)/m_freqMax;
316 if (x <= rightBorder) {
317 davinci.drawLine(x, topDist, x, topDist + m_innerScopeRect.height()+6);
319 if (hz < m_freqMax && x+textDistY < leftDist + m_innerScopeRect.width()) {
320 davinci.drawText(x-4, y, QVariant(hz/1000).toString());
322 x = leftDist + m_innerScopeRect.width();
323 davinci.drawLine(x, topDist, x, topDist + m_innerScopeRect.height()+6);
324 davinci.drawText(x-10, y, i18n("%1 kHz").arg((double)m_freqMax/1000, 0, 'f', 1));
328 // Draw finer lines between the main lines
329 davinci.setPen(AbstractScopeWidget::penLightDots);
330 for (uint dHz = 3; dHz > 0; dHz--) {
331 x = leftDist + m_innerScopeRect.width() * ((float)hz - dHz * hzDiff/4.0f)/m_freqMax;
332 if (x > rightBorder) {
335 davinci.drawLine(x, topDist, x, topDist + m_innerScopeRect.height()-1);
340 if (m_aTrackMouse->isChecked() && m_mouseWithinWidget && mouseX < m_innerScopeRect.width()-1) {
341 davinci.setPen(AbstractScopeWidget::penThin);
343 x = leftDist + mouseX;
346 float freq = ((float) mouseX)/(m_innerScopeRect.width()-1) * m_freqMax;
349 m_lastFFTLock.acquire();
350 // We need to test whether the mouse is inside the widget
351 // because the position could already have changed in the meantime (-> crash)
352 if (m_lastFFT.size() > 0 && mouseX >= 0 && mouseX < m_innerScopeRect.width()) {
353 uint right = ((float) m_freqMax)/(m_freq/2) * (m_lastFFT.size() - 1);
354 QVector<float> dbMap = FFTTools::interpolatePeakPreserving(m_lastFFT, m_innerScopeRect.width(), 0, right, -120);
357 y = topDist + m_innerScopeRect.height()-1 - (dbMap[mouseX] - m_dBmin) / (m_dBmax-m_dBmin) * (m_innerScopeRect.height()-1);
359 if (y < (int)topDist + m_innerScopeRect.height()-1) {
361 davinci.drawLine(x, y, leftDist + m_innerScopeRect.width()-1, y);
364 y = topDist + mouseY;
366 m_lastFFTLock.release();
368 if (y > (int)topDist + mouseY) {
371 davinci.drawLine(x, y, x, topDist + m_innerScopeRect.height()-1);
374 QPoint dist(20, -20);
376 leftDist + mouseX + dist.x(),
377 topDist + mouseY + dist.y(),
381 if (rect.right() > (int)leftDist + m_innerScopeRect.width()-1) {
382 // Mirror the rectangle at the y axis to keep it inside the widget
384 rect.topLeft() - QPoint(rect.width() + 2*dist.x(), 0),
389 rect.topLeft() + QPoint(12, 4),
393 davinci.fillRect(rect, AbstractScopeWidget::penBackground.brush());
394 davinci.setPen(AbstractScopeWidget::penLighter);
395 davinci.drawRect(rect);
396 davinci.drawText(textRect, QString(
397 i18n("%1 dB", QString("%1").arg(db, 0, 'f', 2))
399 + i18n("%1 kHz", QString("%1").arg(freq/1000, 0, 'f', 2))));
405 emit signalHUDRenderingFinished(start.elapsed(), 1);
409 QRect AudioSpectrum::scopeRect()
414 ui->verticalSpacer->geometry().top()+6 // Top
416 AbstractAudioScopeWidget::rect().bottomRight()
418 m_innerScopeRect = QRect(
420 m_scopeRect.left()+6, // Left
421 m_scopeRect.top()+6 // Top
423 ui->verticalSpacer->geometry().right()-70,
424 ui->verticalSpacer->geometry().bottom()-40
430 void AudioSpectrum::slotResetMaxFreq()
432 m_customFreq = false;
440 void AudioSpectrum::handleMouseDrag(const QPoint movement, const RescaleDirection rescaleDirection, const Qt::KeyboardModifiers rescaleModifiers)
442 if (rescaleDirection == North) {
443 // Nort-South direction: Adjust the dB scale
445 if ((rescaleModifiers & Qt::ShiftModifier) == 0) {
447 // By default adjust the min dB value
448 m_dBmin += movement.y();
452 // Adjust max dB value if Shift is pressed.
453 m_dBmax += movement.y();
457 // Ensure the dB values lie in [-100, 0] (or rather [MIN_DB_VALUE, 0])
458 // 0 is the upper bound, everything below -70 dB is most likely noise
462 if (m_dBmin < MIN_DB_VALUE) {
463 m_dBmin = MIN_DB_VALUE;
465 // Ensure there is at least 6 dB between the minimum and the maximum value;
466 // lower values hardly make sense
467 if (m_dBmax - m_dBmin < 6) {
468 if ((rescaleModifiers & Qt::ShiftModifier) == 0) {
469 // min was adjusted; Try to adjust the max value to maintain the
470 // minimum dB difference of 6 dB
471 m_dBmax = m_dBmin + 6;
477 // max was adjusted, adjust min
478 m_dBmin = m_dBmax - 6;
479 if (m_dBmin < MIN_DB_VALUE) {
480 m_dBmin = MIN_DB_VALUE;
481 m_dBmax = MIN_DB_VALUE+6;
489 } else if (rescaleDirection == East) {
490 // East-West direction: Adjust the maximum frequency
491 m_freqMax -= 100*movement.x();
492 if (m_freqMax < MIN_FREQ_VALUE) {
493 m_freqMax = MIN_FREQ_VALUE;
495 if (m_freqMax > MAX_FREQ_VALUE) {
496 m_freqMax = MAX_FREQ_VALUE;