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)
151 audioFrame.size() > 63
152 && m_innerScopeRect.width() > 0 && m_innerScopeRect.height() > 0 // <= 0 if widget is too small (resized by user)
155 m_freqMax = freq / 2;
158 QTime start = QTime::currentTime();
161 // Determine the window size to use. It should be
162 // * not bigger than the number of samples actually available
164 int fftWindow = ui->windowSize->itemData(ui->windowSize->currentIndex()).toInt();
165 if (fftWindow > num_samples) {
166 fftWindow = num_samples;
168 if ((fftWindow & 1) == 1) {
172 // Show the window size used, for information
173 ui->labelFFTSizeNumber->setText(QVariant(fftWindow).toString());
176 // Get the spectral power distribution of the input samples,
177 // using the given window size and function
178 float freqSpectrum[fftWindow/2];
179 FFTTools::WindowType windowType = (FFTTools::WindowType) ui->windowFunction->itemData(ui->windowFunction->currentIndex()).toInt();
180 m_fftTools.fftNormalized(audioFrame, 0, num_channels, freqSpectrum, windowType, fftWindow, 0);
183 // Store the current FFT window (for the HUD) and run the interpolation
184 // for easy pixel-based dB value access
185 QVector<float> dbMap;
186 m_lastFFTLock.acquire();
187 m_lastFFT = QVector<float>(fftWindow/2);
188 memcpy(m_lastFFT.data(), &(freqSpectrum[0]), fftWindow/2 * sizeof(float));
190 uint right = ((float) m_freqMax)/(m_freq/2) * (m_lastFFT.size() - 1);
191 dbMap = FFTTools::interpolatePeakPreserving(m_lastFFT, m_innerScopeRect.width(), 0, right, -180);
192 m_lastFFTLock.release();
195 #ifdef DEBUG_AUDIOSPEC
196 QTime drawTime = QTime::currentTime();
200 QImage spectrum(m_scopeRect.size(), QImage::Format_ARGB32);
201 spectrum.fill(qRgba(0,0,0,0));
202 const uint w = m_innerScopeRect.width();
203 const uint h = m_innerScopeRect.height();
204 const uint leftDist = m_innerScopeRect.left() - m_scopeRect.left();
205 const uint topDist = m_innerScopeRect.top() - m_scopeRect.top();
208 #ifdef AUDIOSPEC_LINES
209 QPainter davinci(&spectrum);
210 davinci.setPen(AbstractScopeWidget::penThin);
213 for (uint i = 0; i < w; i++) {
214 yMax = (dbMap[i] - m_dBmin) / (m_dBmax-m_dBmin) * (h-1);
217 } else if (yMax >= (int)h) {
220 #ifdef AUDIOSPEC_LINES
221 davinci.drawLine(leftDist + i, topDist + h-1, leftDist + i, topDist + h-1 - yMax);
223 for (int y = 0; y < yMax && y < (int)h; y++) {
224 spectrum.setPixel(leftDist + i, topDist + h-y-1, qRgba(225, 182, 255, 255));
229 // Calculate the peak values. Use the new value if it is bigger, otherwise adapt to lower
230 // values using the Moving Average formula
231 if (m_aShowMax->isChecked()) {
232 davinci.setPen(QPen(QBrush(AbstractScopeWidget::colHighlightLight), 2));
233 if (m_peaks.size() != fftWindow/2) {
234 m_peaks = QVector<float>(m_lastFFT);
236 for (int i = 0; i < fftWindow/2; i++) {
237 if (m_lastFFT[i] > m_peaks[i]) {
238 m_peaks[i] = m_lastFFT[i];
240 m_peaks[i] = ALPHA_MOVING_AVG * m_lastFFT[i] + (1-ALPHA_MOVING_AVG) * m_peaks[i];
245 m_peakMap = FFTTools::interpolatePeakPreserving(m_peaks, m_innerScopeRect.width(), 0, right, -180);
246 for (uint i = 0; i < w; i++) {
247 yMax = (m_peakMap[i] - m_dBmin) / (m_dBmax-m_dBmin) * (h-1);
250 } else if (yMax >= (int)h) {
254 davinci.drawLine(leftDist + i-1, topDist + h-prev-1, leftDist + i, topDist + h-yMax-1);
255 spectrum.setPixel(leftDist + i, topDist + h-yMax-1, AbstractScopeWidget::colHighlightLight.rgba());
260 #ifdef DEBUG_AUDIOSPEC
262 m_timeTotal += drawTime.elapsed();
263 qDebug() << widgetName() << " took " << drawTime.elapsed() << " ms for drawing. Average: " << ((float)m_timeTotal/m_showTotal) ;
266 emit signalScopeRenderingFinished(start.elapsed(), 1);
271 emit signalScopeRenderingFinished(0, 1);
275 QImage AudioSpectrum::renderHUD(uint)
277 QTime start = QTime::currentTime();
279 if (m_innerScopeRect.height() > 0 && m_innerScopeRect.width() > 0) { // May be below 0 if widget is too small
281 // Minimum distance between two lines
282 const uint minDistY = 30;
283 const uint minDistX = 40;
284 const uint textDistX = 10;
285 const uint textDistY = 25;
286 const uint topDist = m_innerScopeRect.top() - m_scopeRect.top();
287 const uint leftDist = m_innerScopeRect.left() - m_scopeRect.left();
288 const uint dbDiff = ceil((float)minDistY/m_innerScopeRect.height() * (m_dBmax-m_dBmin));
289 const int mouseX = m_mousePos.x() - m_innerScopeRect.left();
290 const int mouseY = m_mousePos.y() - m_innerScopeRect.top();
293 QImage hud(m_scopeRect.size(), QImage::Format_ARGB32);
294 hud.fill(qRgba(0,0,0,0));
296 QPainter davinci(&hud);
297 davinci.setPen(AbstractScopeWidget::penLight);
299 int _dw = m_innerScopeRect.width();
300 int _dh = m_innerScopeRect.height();
301 int _dld = m_innerScopeRect.width() + leftDist + textDistX;
302 int _dtd = topDist+ m_innerScopeRect.height() + 6;
303 int _fw = AbstractScopeWidget::geometry().width();
304 int _fh = AbstractScopeWidget::geometry().height();
307 for (int db = -dbDiff; db > m_dBmin; db -= dbDiff) {
308 y = topDist + m_innerScopeRect.height() * ((float)db)/(m_dBmin - m_dBmax);
309 if (y-topDist > m_innerScopeRect.height()-minDistY+10) {
310 // Abort here, there is still a line left for min dB to paint which needs some room.
313 davinci.drawLine(leftDist, y, leftDist + m_innerScopeRect.width()-1, y);
314 davinci.drawText(leftDist + m_innerScopeRect.width() + textDistX, y + 6, i18n("%1 dB", m_dBmax + db));
316 davinci.drawLine(leftDist, topDist, leftDist + m_innerScopeRect.width()-1, topDist);
317 davinci.drawText(leftDist + m_innerScopeRect.width() + textDistX, topDist+6, i18n("%1 dB", m_dBmax));
318 davinci.drawLine(leftDist, topDist+m_innerScopeRect.height()-1, leftDist + m_innerScopeRect.width()-1, topDist+m_innerScopeRect.height()-1);
319 davinci.drawText(leftDist + m_innerScopeRect.width() + textDistX, topDist+m_innerScopeRect.height()+6, i18n("%1 dB", m_dBmin));
321 const uint hzDiff = ceil( ((float)minDistX)/m_innerScopeRect.width() * m_freqMax / 1000 ) * 1000;
323 const int rightBorder = leftDist + m_innerScopeRect.width()-1;
324 y = topDist + m_innerScopeRect.height() + textDistY;
325 for (int hz = 0; x <= rightBorder; hz += hzDiff) {
326 davinci.setPen(AbstractScopeWidget::penLighter);
327 x = leftDist + m_innerScopeRect.width() * ((float)hz)/m_freqMax;
329 if (x <= rightBorder) {
330 davinci.drawLine(x, topDist, x, topDist + m_innerScopeRect.height()+6);
332 if (hz < m_freqMax && x+textDistY < leftDist + m_innerScopeRect.width()) {
333 davinci.drawText(x-4, y, QVariant(hz/1000).toString());
335 x = leftDist + m_innerScopeRect.width();
336 davinci.drawLine(x, topDist, x, topDist + m_innerScopeRect.height()+6);
337 davinci.drawText(x-10, y, i18n("%1 kHz").arg((double)m_freqMax/1000, 0, 'f', 1));
341 // Draw finer lines between the main lines
342 davinci.setPen(AbstractScopeWidget::penLightDots);
343 for (uint dHz = 3; dHz > 0; dHz--) {
344 x = leftDist + m_innerScopeRect.width() * ((float)hz - dHz * hzDiff/4.0f)/m_freqMax;
345 if (x > rightBorder) {
348 davinci.drawLine(x, topDist, x, topDist + m_innerScopeRect.height()-1);
353 if (m_aTrackMouse->isChecked() && m_mouseWithinWidget && mouseX < m_innerScopeRect.width()-1) {
354 davinci.setPen(AbstractScopeWidget::penThin);
356 x = leftDist + mouseX;
359 float freq = ((float) mouseX)/(m_innerScopeRect.width()-1) * m_freqMax;
362 m_lastFFTLock.acquire();
363 // We need to test whether the mouse is inside the widget
364 // because the position could already have changed in the meantime (-> crash)
365 if (m_lastFFT.size() > 0 && mouseX >= 0 && mouseX < m_innerScopeRect.width()) {
366 uint right = ((float) m_freqMax)/(m_freq/2) * (m_lastFFT.size() - 1);
367 QVector<float> dbMap = FFTTools::interpolatePeakPreserving(m_lastFFT, m_innerScopeRect.width(), 0, right, -120);
370 y = topDist + m_innerScopeRect.height()-1 - (dbMap[mouseX] - m_dBmin) / (m_dBmax-m_dBmin) * (m_innerScopeRect.height()-1);
372 if (y < (int)topDist + m_innerScopeRect.height()-1) {
374 davinci.drawLine(x, y, leftDist + m_innerScopeRect.width()-1, y);
377 y = topDist + mouseY;
379 m_lastFFTLock.release();
381 if (y > (int)topDist + mouseY) {
384 davinci.drawLine(x, y, x, topDist + m_innerScopeRect.height()-1);
387 QPoint dist(20, -20);
389 leftDist + mouseX + dist.x(),
390 topDist + mouseY + dist.y(),
394 if (rect.right() > (int)leftDist + m_innerScopeRect.width()-1) {
395 // Mirror the rectangle at the y axis to keep it inside the widget
397 rect.topLeft() - QPoint(rect.width() + 2*dist.x(), 0),
402 rect.topLeft() + QPoint(12, 4),
406 davinci.fillRect(rect, AbstractScopeWidget::penBackground.brush());
407 davinci.setPen(AbstractScopeWidget::penLighter);
408 davinci.drawRect(rect);
409 davinci.drawText(textRect, QString(
410 i18n("%1 dB", QString("%1").arg(db, 0, 'f', 2))
412 + i18n("%1 kHz", QString("%1").arg(freq/1000, 0, 'f', 2))));
417 emit signalHUDRenderingFinished(start.elapsed(), 1);
421 #ifdef DEBUG_AUDIOSPEC
422 qDebug() << "Widget is too small for painting inside. Size of inner scope rect is "
423 << m_innerScopeRect.width() << "x" << m_innerScopeRect.height() <<".";
425 emit signalHUDRenderingFinished(0, 1);
431 QRect AudioSpectrum::scopeRect()
436 ui->verticalSpacer->geometry().top()+6 // Top
438 AbstractAudioScopeWidget::rect().bottomRight()
440 m_innerScopeRect = QRect(
442 m_scopeRect.left()+6, // Left
443 m_scopeRect.top()+6 // Top
445 ui->verticalSpacer->geometry().right()-70,
446 ui->verticalSpacer->geometry().bottom()-40
452 void AudioSpectrum::slotResetMaxFreq()
454 m_customFreq = false;
462 void AudioSpectrum::handleMouseDrag(const QPoint movement, const RescaleDirection rescaleDirection, const Qt::KeyboardModifiers rescaleModifiers)
464 if (rescaleDirection == North) {
465 // Nort-South direction: Adjust the dB scale
467 if ((rescaleModifiers & Qt::ShiftModifier) == 0) {
469 // By default adjust the min dB value
470 m_dBmin += movement.y();
474 // Adjust max dB value if Shift is pressed.
475 m_dBmax += movement.y();
479 // Ensure the dB values lie in [-100, 0] (or rather [MIN_DB_VALUE, 0])
480 // 0 is the upper bound, everything below -70 dB is most likely noise
484 if (m_dBmin < MIN_DB_VALUE) {
485 m_dBmin = MIN_DB_VALUE;
487 // Ensure there is at least 6 dB between the minimum and the maximum value;
488 // lower values hardly make sense
489 if (m_dBmax - m_dBmin < 6) {
490 if ((rescaleModifiers & Qt::ShiftModifier) == 0) {
491 // min was adjusted; Try to adjust the max value to maintain the
492 // minimum dB difference of 6 dB
493 m_dBmax = m_dBmin + 6;
499 // max was adjusted, adjust min
500 m_dBmin = m_dBmax - 6;
501 if (m_dBmin < MIN_DB_VALUE) {
502 m_dBmin = MIN_DB_VALUE;
503 m_dBmax = MIN_DB_VALUE+6;
511 } else if (rescaleDirection == East) {
512 // East-West direction: Adjust the maximum frequency
513 m_freqMax -= 100*movement.x();
514 if (m_freqMax < MIN_FREQ_VALUE) {
515 m_freqMax = MIN_FREQ_VALUE;
517 if (m_freqMax > MAX_FREQ_VALUE) {
518 m_freqMax = MAX_FREQ_VALUE;