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 // (defined in the header file)
29 #ifdef DETECT_OVERMODULATION
34 // Draw lines instead of single pixels.
35 // This is about 25 % faster, especially when enlarging the scope to e.g. 1680x1050 px.
36 #define AUDIOSPEC_LINES
38 #define MIN_DB_VALUE -120
39 #define MAX_FREQ_VALUE 96000
40 #define MIN_FREQ_VALUE 1000
41 #define ALPHA_MOVING_AVG 0.125
42 #define MAX_OVM_COLOR 0.7
44 AudioSpectrum::AudioSpectrum(QWidget *parent) :
45 AbstractAudioScopeWidget(true, parent),
50 #ifdef DEBUG_AUDIOSPEC
56 ui = new Ui::AudioSpectrum_UI;
60 m_aResetHz = new QAction(i18n("Reset maximum frequency to sampling rate"), this);
61 m_aTrackMouse = new QAction(i18n("Track mouse"), this);
62 m_aTrackMouse->setCheckable(true);
63 m_aShowMax = new QAction(i18n("Show maximum"), this);
64 m_aShowMax->setCheckable(true);
67 m_menu->addSeparator();
68 m_menu->addAction(m_aResetHz);
69 m_menu->addAction(m_aTrackMouse);
70 m_menu->addAction(m_aShowMax);
71 m_menu->removeAction(m_aRealtime);
74 ui->windowSize->addItem("256", QVariant(256));
75 ui->windowSize->addItem("512", QVariant(512));
76 ui->windowSize->addItem("1024", QVariant(1024));
77 ui->windowSize->addItem("2048", QVariant(2048));
79 ui->windowFunction->addItem(i18n("Rectangular window"), FFTTools::Window_Rect);
80 ui->windowFunction->addItem(i18n("Triangular window"), FFTTools::Window_Triangle);
81 ui->windowFunction->addItem(i18n("Hamming window"), FFTTools::Window_Hamming);
85 b &= connect(m_aResetHz, SIGNAL(triggered()), this, SLOT(slotResetMaxFreq()));
86 b &= connect(ui->windowFunction, SIGNAL(currentIndexChanged(int)), this, SLOT(forceUpdate()));
87 b &= connect(this, SIGNAL(signalMousePositionChanged()), this, SLOT(forceUpdateHUD()));
91 // Note: These strings are used in both Spectogram and AudioSpectrum. Ideally change both (if necessary) to reduce workload on translators
92 ui->labelFFTSize->setToolTip(i18n("The maximum window size is limited by the number of samples per frame."));
93 ui->windowSize->setToolTip(i18n("A bigger window improves the accuracy at the cost of computational power."));
94 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."));
96 AbstractScopeWidget::init();
98 AudioSpectrum::~AudioSpectrum()
103 delete m_aTrackMouse;
106 void AudioSpectrum::readConfig()
108 AbstractScopeWidget::readConfig();
110 KSharedConfigPtr config = KGlobal::config();
111 KConfigGroup scopeConfig(config, AbstractScopeWidget::configName());
113 ui->windowSize->setCurrentIndex(scopeConfig.readEntry("windowSize", 0));
114 ui->windowFunction->setCurrentIndex(scopeConfig.readEntry("windowFunction", 0));
115 m_aTrackMouse->setChecked(scopeConfig.readEntry("trackMouse", true));
116 m_aShowMax->setChecked(scopeConfig.readEntry("showMax", true));
117 m_dBmax = scopeConfig.readEntry("dBmax", 0);
118 m_dBmin = scopeConfig.readEntry("dBmin", -70);
119 m_freqMax = scopeConfig.readEntry("freqMax", 0);
121 if (m_freqMax == 0) {
122 m_customFreq = false;
128 void AudioSpectrum::writeConfig()
130 KSharedConfigPtr config = KGlobal::config();
131 KConfigGroup scopeConfig(config, AbstractScopeWidget::configName());
133 scopeConfig.writeEntry("windowSize", ui->windowSize->currentIndex());
134 scopeConfig.writeEntry("windowFunction", ui->windowFunction->currentIndex());
135 scopeConfig.writeEntry("trackMouse", m_aTrackMouse->isChecked());
136 scopeConfig.writeEntry("showMax", m_aShowMax->isChecked());
137 scopeConfig.writeEntry("dBmax", m_dBmax);
138 scopeConfig.writeEntry("dBmin", m_dBmin);
140 scopeConfig.writeEntry("freqMax", m_freqMax);
142 scopeConfig.writeEntry("freqMax", 0);
148 QString AudioSpectrum::widgetName() const { return QString("AudioSpectrum"); }
149 bool AudioSpectrum::isBackgroundDependingOnInput() const { return false; }
150 bool AudioSpectrum::isScopeDependingOnInput() const { return true; }
151 bool AudioSpectrum::isHUDDependingOnInput() const { return false; }
153 QImage AudioSpectrum::renderBackground(uint) { return QImage(); }
155 QImage AudioSpectrum::renderAudioScope(uint, const QVector<int16_t> audioFrame, const int freq, const int num_channels,
156 const int num_samples, const int)
159 audioFrame.size() > 63
160 && m_innerScopeRect.width() > 0 && m_innerScopeRect.height() > 0 // <= 0 if widget is too small (resized by user)
163 m_freqMax = freq / 2;
166 QTime start = QTime::currentTime();
169 #ifdef DETECT_OVERMODULATION
170 bool overmodulated = false;
171 int overmodulateCount = 0;
173 for (int i = 0; i < audioFrame.size(); i++) {
175 audioFrame[i] == std::numeric_limits<int16_t>::max()
176 || audioFrame[i] == std::numeric_limits<int16_t>::min()) {
178 if (overmodulateCount > 3) {
179 overmodulated = true;
187 if (colorizeFactor > 0) {
188 colorizeFactor -= .08;
189 if (colorizeFactor < 0) {
197 // Determine the window size to use. It should be
198 // * not bigger than the number of samples actually available
200 int fftWindow = ui->windowSize->itemData(ui->windowSize->currentIndex()).toInt();
201 if (fftWindow > num_samples) {
202 fftWindow = num_samples;
204 if ((fftWindow & 1) == 1) {
208 // Show the window size used, for information
209 ui->labelFFTSizeNumber->setText(QVariant(fftWindow).toString());
212 // Get the spectral power distribution of the input samples,
213 // using the given window size and function
214 float freqSpectrum[fftWindow/2];
215 FFTTools::WindowType windowType = (FFTTools::WindowType) ui->windowFunction->itemData(ui->windowFunction->currentIndex()).toInt();
216 m_fftTools.fftNormalized(audioFrame, 0, num_channels, freqSpectrum, windowType, fftWindow, 0);
219 // Store the current FFT window (for the HUD) and run the interpolation
220 // for easy pixel-based dB value access
221 QVector<float> dbMap;
222 m_lastFFTLock.acquire();
223 m_lastFFT = QVector<float>(fftWindow/2);
224 memcpy(m_lastFFT.data(), &(freqSpectrum[0]), fftWindow/2 * sizeof(float));
226 uint right = ((float) m_freqMax)/(m_freq/2) * (m_lastFFT.size() - 1);
227 dbMap = FFTTools::interpolatePeakPreserving(m_lastFFT, m_innerScopeRect.width(), 0, right, -180);
228 m_lastFFTLock.release();
231 #ifdef DEBUG_AUDIOSPEC
232 QTime drawTime = QTime::currentTime();
236 QImage spectrum(m_scopeRect.size(), QImage::Format_ARGB32);
237 spectrum.fill(qRgba(0,0,0,0));
238 const uint w = m_innerScopeRect.width();
239 const uint h = m_innerScopeRect.height();
240 const uint leftDist = m_innerScopeRect.left() - m_scopeRect.left();
241 const uint topDist = m_innerScopeRect.top() - m_scopeRect.top();
242 QColor spectrumColor(AbstractScopeWidget::colDarkWhite);
245 #ifdef DETECT_OVERMODULATION
246 if (colorizeFactor > 0) {
247 QColor col = AbstractScopeWidget::colHighlightDark;
248 QColor spec = spectrumColor;
249 float f = std::sin(M_PI_2 * colorizeFactor);
250 spectrumColor = QColor(
251 (int) (f * col.red() + (1-f) * spec.red()),
252 (int) (f * col.green() + (1-f) * spec.green()),
253 (int) (f * col.blue() + (1-f) * spec.blue()),
256 // Limit the maximum colorization for non-overmodulated frames to better
257 // recognize consecutively overmodulated frames
258 if (colorizeFactor > MAX_OVM_COLOR) {
259 colorizeFactor = MAX_OVM_COLOR;
264 #ifdef AUDIOSPEC_LINES
265 QPainter davinci(&spectrum);
266 davinci.setPen(QPen(QBrush(spectrumColor.rgba()), 1, Qt::SolidLine));
269 for (uint i = 0; i < w; i++) {
270 yMax = (dbMap[i] - m_dBmin) / (m_dBmax-m_dBmin) * (h-1);
273 } else if (yMax >= (int)h) {
276 #ifdef AUDIOSPEC_LINES
277 davinci.drawLine(leftDist + i, topDist + h-1, leftDist + i, topDist + h-1 - yMax);
279 for (int y = 0; y < yMax && y < (int)h; y++) {
280 spectrum.setPixel(leftDist + i, topDist + h-y-1, spectrumColor.rgba());
285 // Calculate the peak values. Use the new value if it is bigger, otherwise adapt to lower
286 // values using the Moving Average formula
287 if (m_aShowMax->isChecked()) {
288 davinci.setPen(QPen(QBrush(AbstractScopeWidget::colHighlightLight), 2));
289 if (m_peaks.size() != fftWindow/2) {
290 m_peaks = QVector<float>(m_lastFFT);
292 for (int i = 0; i < fftWindow/2; i++) {
293 if (m_lastFFT[i] > m_peaks[i]) {
294 m_peaks[i] = m_lastFFT[i];
296 m_peaks[i] = ALPHA_MOVING_AVG * m_lastFFT[i] + (1-ALPHA_MOVING_AVG) * m_peaks[i];
301 m_peakMap = FFTTools::interpolatePeakPreserving(m_peaks, m_innerScopeRect.width(), 0, right, -180);
302 for (uint i = 0; i < w; i++) {
303 yMax = (m_peakMap[i] - m_dBmin) / (m_dBmax-m_dBmin) * (h-1);
306 } else if (yMax >= (int)h) {
310 davinci.drawLine(leftDist + i-1, topDist + h-prev-1, leftDist + i, topDist + h-yMax-1);
311 spectrum.setPixel(leftDist + i, topDist + h-yMax-1, AbstractScopeWidget::colHighlightLight.rgba());
316 #ifdef DEBUG_AUDIOSPEC
318 m_timeTotal += drawTime.elapsed();
319 qDebug() << widgetName() << " took " << drawTime.elapsed() << " ms for drawing. Average: " << ((float)m_timeTotal/m_showTotal) ;
322 emit signalScopeRenderingFinished(start.elapsed(), 1);
327 emit signalScopeRenderingFinished(0, 1);
331 QImage AudioSpectrum::renderHUD(uint)
333 QTime start = QTime::currentTime();
335 if (m_innerScopeRect.height() > 0 && m_innerScopeRect.width() > 0) { // May be below 0 if widget is too small
337 // Minimum distance between two lines
338 const uint minDistY = 30;
339 const uint minDistX = 40;
340 const uint textDistX = 10;
341 const uint textDistY = 25;
342 const uint topDist = m_innerScopeRect.top() - m_scopeRect.top();
343 const uint leftDist = m_innerScopeRect.left() - m_scopeRect.left();
344 const uint dbDiff = ceil((float)minDistY/m_innerScopeRect.height() * (m_dBmax-m_dBmin));
345 const int mouseX = m_mousePos.x() - m_innerScopeRect.left();
346 const int mouseY = m_mousePos.y() - m_innerScopeRect.top();
349 QImage hud(m_scopeRect.size(), QImage::Format_ARGB32);
350 hud.fill(qRgba(0,0,0,0));
352 QPainter davinci(&hud);
353 davinci.setPen(AbstractScopeWidget::penLight);
356 for (int db = -dbDiff; db > m_dBmin; db -= dbDiff) {
357 y = topDist + m_innerScopeRect.height() * ((float)db)/(m_dBmin - m_dBmax);
358 if (y-topDist > m_innerScopeRect.height()-minDistY+10) {
359 // Abort here, there is still a line left for min dB to paint which needs some room.
362 davinci.drawLine(leftDist, y, leftDist + m_innerScopeRect.width()-1, y);
363 davinci.drawText(leftDist + m_innerScopeRect.width() + textDistX, y + 6, i18n("%1 dB", m_dBmax + db));
365 davinci.drawLine(leftDist, topDist, leftDist + m_innerScopeRect.width()-1, topDist);
366 davinci.drawText(leftDist + m_innerScopeRect.width() + textDistX, topDist+6, i18n("%1 dB", m_dBmax));
367 davinci.drawLine(leftDist, topDist+m_innerScopeRect.height()-1, leftDist + m_innerScopeRect.width()-1, topDist+m_innerScopeRect.height()-1);
368 davinci.drawText(leftDist + m_innerScopeRect.width() + textDistX, topDist+m_innerScopeRect.height()+6, i18n("%1 dB", m_dBmin));
370 const uint hzDiff = ceil( ((float)minDistX)/m_innerScopeRect.width() * m_freqMax / 1000 ) * 1000;
372 const int rightBorder = leftDist + m_innerScopeRect.width()-1;
373 y = topDist + m_innerScopeRect.height() + textDistY;
374 for (int hz = 0; x <= rightBorder; hz += hzDiff) {
375 davinci.setPen(AbstractScopeWidget::penLighter);
376 x = leftDist + m_innerScopeRect.width() * ((float)hz)/m_freqMax;
378 if (x <= rightBorder) {
379 davinci.drawLine(x, topDist, x, topDist + m_innerScopeRect.height()+6);
381 if (hz < m_freqMax && x+textDistY < leftDist + m_innerScopeRect.width()) {
382 davinci.drawText(x-4, y, QVariant(hz/1000).toString());
384 x = leftDist + m_innerScopeRect.width();
385 davinci.drawLine(x, topDist, x, topDist + m_innerScopeRect.height()+6);
386 davinci.drawText(x-10, y, i18n("%1 kHz").arg((double)m_freqMax/1000, 0, 'f', 1));
390 // Draw finer lines between the main lines
391 davinci.setPen(AbstractScopeWidget::penLightDots);
392 for (uint dHz = 3; dHz > 0; dHz--) {
393 x = leftDist + m_innerScopeRect.width() * ((float)hz - dHz * hzDiff/4.0f)/m_freqMax;
394 if (x > rightBorder) {
397 davinci.drawLine(x, topDist, x, topDist + m_innerScopeRect.height()-1);
402 if (m_aTrackMouse->isChecked() && m_mouseWithinWidget && mouseX < m_innerScopeRect.width()-1) {
403 davinci.setPen(AbstractScopeWidget::penThin);
405 x = leftDist + mouseX;
408 float freq = ((float) mouseX)/(m_innerScopeRect.width()-1) * m_freqMax;
411 m_lastFFTLock.acquire();
412 // We need to test whether the mouse is inside the widget
413 // because the position could already have changed in the meantime (-> crash)
414 if (m_lastFFT.size() > 0 && mouseX >= 0 && mouseX < m_innerScopeRect.width()) {
415 uint right = ((float) m_freqMax)/(m_freq/2) * (m_lastFFT.size() - 1);
416 QVector<float> dbMap = FFTTools::interpolatePeakPreserving(m_lastFFT, m_innerScopeRect.width(), 0, right, -120);
419 y = topDist + m_innerScopeRect.height()-1 - (dbMap[mouseX] - m_dBmin) / (m_dBmax-m_dBmin) * (m_innerScopeRect.height()-1);
421 if (y < (int)topDist + m_innerScopeRect.height()-1) {
423 davinci.drawLine(x, y, leftDist + m_innerScopeRect.width()-1, y);
426 y = topDist + mouseY;
428 m_lastFFTLock.release();
430 if (y > (int)topDist + mouseY) {
433 davinci.drawLine(x, y, x, topDist + m_innerScopeRect.height()-1);
436 QPoint dist(20, -20);
438 leftDist + mouseX + dist.x(),
439 topDist + mouseY + dist.y(),
443 if (rect.right() > (int)leftDist + m_innerScopeRect.width()-1) {
444 // Mirror the rectangle at the y axis to keep it inside the widget
446 rect.topLeft() - QPoint(rect.width() + 2*dist.x(), 0),
451 rect.topLeft() + QPoint(12, 4),
455 davinci.fillRect(rect, AbstractScopeWidget::penBackground.brush());
456 davinci.setPen(AbstractScopeWidget::penLighter);
457 davinci.drawRect(rect);
458 davinci.drawText(textRect, QString(
459 i18n("%1 dB", QString("%1").arg(db, 0, 'f', 2))
461 + i18n("%1 kHz", QString("%1").arg(freq/1000, 0, 'f', 2))));
466 emit signalHUDRenderingFinished(start.elapsed(), 1);
470 #ifdef DEBUG_AUDIOSPEC
471 qDebug() << "Widget is too small for painting inside. Size of inner scope rect is "
472 << m_innerScopeRect.width() << "x" << m_innerScopeRect.height() <<".";
474 emit signalHUDRenderingFinished(0, 1);
480 QRect AudioSpectrum::scopeRect()
485 ui->verticalSpacer->geometry().top()+6 // Top
487 AbstractAudioScopeWidget::rect().bottomRight()
489 m_innerScopeRect = QRect(
491 m_scopeRect.left()+6, // Left
492 m_scopeRect.top()+6 // Top
494 ui->verticalSpacer->geometry().right()-70,
495 ui->verticalSpacer->geometry().bottom()-40
501 void AudioSpectrum::slotResetMaxFreq()
503 m_customFreq = false;
511 void AudioSpectrum::handleMouseDrag(const QPoint movement, const RescaleDirection rescaleDirection, const Qt::KeyboardModifiers rescaleModifiers)
513 if (rescaleDirection == North) {
514 // Nort-South direction: Adjust the dB scale
516 if ((rescaleModifiers & Qt::ShiftModifier) == 0) {
518 // By default adjust the min dB value
519 m_dBmin += movement.y();
523 // Adjust max dB value if Shift is pressed.
524 m_dBmax += movement.y();
528 // Ensure the dB values lie in [-100, 0] (or rather [MIN_DB_VALUE, 0])
529 // 0 is the upper bound, everything below -70 dB is most likely noise
533 if (m_dBmin < MIN_DB_VALUE) {
534 m_dBmin = MIN_DB_VALUE;
536 // Ensure there is at least 6 dB between the minimum and the maximum value;
537 // lower values hardly make sense
538 if (m_dBmax - m_dBmin < 6) {
539 if ((rescaleModifiers & Qt::ShiftModifier) == 0) {
540 // min was adjusted; Try to adjust the max value to maintain the
541 // minimum dB difference of 6 dB
542 m_dBmax = m_dBmin + 6;
548 // max was adjusted, adjust min
549 m_dBmin = m_dBmax - 6;
550 if (m_dBmin < MIN_DB_VALUE) {
551 m_dBmin = MIN_DB_VALUE;
552 m_dBmax = MIN_DB_VALUE+6;
560 } else if (rescaleDirection == East) {
561 // East-West direction: Adjust the maximum frequency
562 m_freqMax -= 100*movement.x();
563 if (m_freqMax < MIN_FREQ_VALUE) {
564 m_freqMax = MIN_FREQ_VALUE;
566 if (m_freqMax > MAX_FREQ_VALUE) {
567 m_freqMax = MAX_FREQ_VALUE;