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 // Enables debugging, like writing a GNU Octave .m file to /tmp
24 //#define DEBUG_AUDIOSPEC
25 #ifdef DEBUG_AUDIOSPEC
28 bool fileWritten = false;
31 #define MIN_DB_VALUE -120
32 #define MAX_FREQ_VALUE 96000
33 #define MIN_FREQ_VALUE 1000
35 AudioSpectrum::AudioSpectrum(QWidget *parent) :
36 AbstractAudioScopeWidget(false, parent),
39 ui = new Ui::AudioSpectrum_UI;
43 m_aResetHz = new QAction(i18n("Reset maximum frequency to sampling rate"), this);
46 m_menu->addSeparator();
47 m_menu->addAction(m_aResetHz);
48 m_menu->removeAction(m_aRealtime);
51 ui->windowSize->addItem("256", QVariant(256));
52 ui->windowSize->addItem("512", QVariant(512));
53 ui->windowSize->addItem("1024", QVariant(1024));
54 ui->windowSize->addItem("2048", QVariant(2048));
56 ui->windowFunction->addItem(i18n("Rectangular window"), FFTTools::Window_Rect);
57 ui->windowFunction->addItem(i18n("Triangular window"), FFTTools::Window_Triangle);
58 ui->windowFunction->addItem(i18n("Hamming window"), FFTTools::Window_Hamming);
62 b &= connect(m_aResetHz, SIGNAL(triggered()), this, SLOT(slotResetMaxFreq()));
63 b &= connect(ui->windowFunction, SIGNAL(currentIndexChanged(int)), this, SLOT(forceUpdate()));
67 // Note: These strings are used in both Spectogram and AudioSpectrum. Ideally change both (if necessary) to reduce workload on translators
68 ui->labelFFTSize->setToolTip(i18n("The maximum window size is limited by the number of samples per frame."));
69 ui->windowSize->setToolTip(i18n("A bigger window improves the accuracy at the cost of computational power."));
70 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."));
72 AbstractScopeWidget::init();
74 AudioSpectrum::~AudioSpectrum()
81 void AudioSpectrum::readConfig()
83 AbstractScopeWidget::readConfig();
85 KSharedConfigPtr config = KGlobal::config();
86 KConfigGroup scopeConfig(config, AbstractScopeWidget::configName());
88 ui->windowSize->setCurrentIndex(scopeConfig.readEntry("windowSize", 0));
89 ui->windowFunction->setCurrentIndex(scopeConfig.readEntry("windowFunction", 0));
90 m_dBmax = scopeConfig.readEntry("dBmax", 0);
91 m_dBmin = scopeConfig.readEntry("dBmin", -70);
92 m_freqMax = scopeConfig.readEntry("freqMax", 0);
101 void AudioSpectrum::writeConfig()
103 KSharedConfigPtr config = KGlobal::config();
104 KConfigGroup scopeConfig(config, AbstractScopeWidget::configName());
106 scopeConfig.writeEntry("windowSize", ui->windowSize->currentIndex());
107 scopeConfig.writeEntry("windowFunction", ui->windowFunction->currentIndex());
108 scopeConfig.writeEntry("dBmax", m_dBmax);
109 scopeConfig.writeEntry("dBmin", m_dBmin);
111 scopeConfig.writeEntry("freqMax", m_freqMax);
113 scopeConfig.writeEntry("freqMax", 0);
119 QString AudioSpectrum::widgetName() const { return QString("AudioSpectrum"); }
120 bool AudioSpectrum::isBackgroundDependingOnInput() const { return false; }
121 bool AudioSpectrum::isScopeDependingOnInput() const { return true; }
122 bool AudioSpectrum::isHUDDependingOnInput() const { return false; }
124 QImage AudioSpectrum::renderBackground(uint) { return QImage(); }
126 QImage AudioSpectrum::renderAudioScope(uint, const QVector<int16_t> audioFrame, const int freq, const int num_channels,
127 const int num_samples, const int)
129 if (audioFrame.size() > 63) {
131 m_freqMax = freq / 2;
134 QTime start = QTime::currentTime();
137 // Determine the window size to use. It should be
138 // * not bigger than the number of samples actually available
140 int fftWindow = ui->windowSize->itemData(ui->windowSize->currentIndex()).toInt();
141 if (fftWindow > num_samples) {
142 fftWindow = num_samples;
144 if ((fftWindow & 1) == 1) {
148 // Show the window size used, for information
149 ui->labelFFTSizeNumber->setText(QVariant(fftWindow).toString());
152 // Get the spectral power distribution of the input samples,
153 // using the given window size and function
154 float freqSpectrum[fftWindow/2];
155 FFTTools::WindowType windowType = (FFTTools::WindowType) ui->windowFunction->itemData(ui->windowFunction->currentIndex()).toInt();
156 m_fftTools.fftNormalized(audioFrame, 0, num_channels, freqSpectrum, windowType, fftWindow, 0);
160 QImage spectrum(m_scopeRect.size(), QImage::Format_ARGB32);
161 spectrum.fill(qRgba(0,0,0,0));
162 const uint w = m_innerScopeRect.width();
163 const uint h = m_innerScopeRect.height();
164 const uint leftDist = m_innerScopeRect.left() - m_scopeRect.left();
165 const uint topDist = m_innerScopeRect.top() - m_scopeRect.top();
171 for (uint i = 0; i < w; i++) {
173 // i: Pixel coordinate
174 // f: Target frequency
175 // x: Frequency array index (float!) corresponding to the pixel
178 f = i/((float) w-1.0) * m_freqMax;
179 x = 2*f/freq * (fftWindow/2 - 1);
182 if (x >= fftWindow/2) {
186 // Use linear interpolation in order to get smoother display
187 if (i == 0 || xi == fftWindow/2-1) {
188 // ... except if we are at the left or right border of the display or the spectrum
189 val = freqSpectrum[xi];
192 if (freqSpectrum[xi] > freqSpectrum[xi+1]
194 // This is a hack to preserve peaks.
195 // Consider f = {0, 100, 0}
197 // Then x is 50 both times, and the 100 peak is lost.
198 // Get it back here for the first x after the peak.
199 val = freqSpectrum[xi];
201 val = (xi+1 - x) * freqSpectrum[xi]
202 + (x - xi) * freqSpectrum[xi+1];
206 // freqSpectrum values range from 0 to -inf as they are relative dB values.
207 for (uint y = 0; y < h*(1 - (val - m_dBmax)/(m_dBmin-m_dBmax)) && y < h; y++) {
208 spectrum.setPixel(leftDist + i, topDist + h-y-1, qRgba(225, 182, 255, 255));
214 emit signalScopeRenderingFinished(start.elapsed(), 1);
216 #ifdef DEBUG_AUDIOSPEC
217 if (!fileWritten || true) {
219 mFile.open("/tmp/freq.m");
221 qDebug() << "Opening file failed.";
225 for (int sample = 0; sample < 256; sample++) {
226 mFile << data[sample] << " ";
230 mFile << "freq = [ ";
231 for (int sample = 0; sample < 256; sample++) {
232 mFile << freqData[sample].r << "+" << freqData[sample].i << "*i ";
238 qDebug() << "File written.";
241 qDebug() << "File already written.";
247 emit signalScopeRenderingFinished(0, 1);
251 QImage AudioSpectrum::renderHUD(uint)
253 QTime start = QTime::currentTime();
255 // Minimum distance between two lines
256 const uint minDistY = 30;
257 const uint minDistX = 40;
258 const uint textDistX = 10;
259 const uint textDistY = 25;
260 const uint topDist = m_innerScopeRect.top() - m_scopeRect.top();
261 const uint leftDist = m_innerScopeRect.left() - m_scopeRect.left();
262 const uint dbDiff = ceil((float)minDistY/m_innerScopeRect.height() * (m_dBmax-m_dBmin));
264 QImage hud(m_scopeRect.size(), QImage::Format_ARGB32);
265 hud.fill(qRgba(0,0,0,0));
267 QPainter davinci(&hud);
268 davinci.setPen(AbstractScopeWidget::penLight);
271 for (int db = -dbDiff; db > m_dBmin; db -= dbDiff) {
272 y = topDist + m_innerScopeRect.height() * ((float)db)/(m_dBmin - m_dBmax);
273 if (y-topDist > m_innerScopeRect.height()-minDistY+10) {
274 // Abort here, there is still a line left for min dB to paint which needs some room.
277 davinci.drawLine(leftDist, y, leftDist + m_innerScopeRect.width()-1, y);
278 davinci.drawText(leftDist + m_innerScopeRect.width() + textDistX, y + 6, i18n("%1 dB", m_dBmax + db));
280 davinci.drawLine(leftDist, topDist, leftDist + m_innerScopeRect.width()-1, topDist);
281 davinci.drawText(leftDist + m_innerScopeRect.width() + textDistX, topDist+6, i18n("%1 dB", m_dBmax));
282 davinci.drawLine(leftDist, topDist+m_innerScopeRect.height()-1, leftDist + m_innerScopeRect.width()-1, topDist+m_innerScopeRect.height()-1);
283 davinci.drawText(leftDist + m_innerScopeRect.width() + textDistX, topDist+m_innerScopeRect.height()+6, i18n("%1 dB", m_dBmin));
285 const uint hzDiff = ceil( ((float)minDistX)/m_innerScopeRect.width() * m_freqMax / 1000 ) * 1000;
287 const int rightBorder = leftDist + m_innerScopeRect.width()-1;
288 y = topDist + m_innerScopeRect.height() + textDistY;
289 for (uint hz = 0; x <= rightBorder; hz += hzDiff) {
290 davinci.setPen(AbstractScopeWidget::penLight);
291 x = leftDist + m_innerScopeRect.width() * ((float)hz)/m_freqMax;
293 if (x <= rightBorder) {
294 davinci.drawLine(x, topDist, x, topDist + m_innerScopeRect.height()+6);
296 if (hz < m_freqMax && x+textDistY < leftDist + m_innerScopeRect.width()) {
297 davinci.drawText(x-4, y, QVariant(hz/1000).toString());
299 x = leftDist + m_innerScopeRect.width();
300 davinci.drawLine(x, topDist, x, topDist + m_innerScopeRect.height()+6);
301 davinci.drawText(x-10, y, i18n("%1 kHz").arg((double)m_freqMax/1000, 0, 'f', 1));
305 // Draw finer lines between the main lines
306 davinci.setPen(AbstractScopeWidget::penLightDots);
307 for (uint dHz = 3; dHz > 0; dHz--) {
308 x = leftDist + m_innerScopeRect.width() * ((float)hz - dHz * hzDiff/4.0f)/m_freqMax;
309 if (x > rightBorder) {
312 davinci.drawLine(x, topDist, x, topDist + m_innerScopeRect.height()-1);
318 emit signalHUDRenderingFinished(start.elapsed(), 1);
322 QRect AudioSpectrum::scopeRect()
327 ui->verticalSpacer->geometry().top()+6 // Top
329 AbstractAudioScopeWidget::rect().bottomRight()
331 m_innerScopeRect = QRect(
333 m_scopeRect.left()+6, // Left
334 m_scopeRect.top()+6 // Top
336 ui->verticalSpacer->geometry().right()-70,
337 ui->verticalSpacer->geometry().bottom()-40
343 void AudioSpectrum::slotResetMaxFreq()
345 m_customFreq = false;
353 void AudioSpectrum::handleMouseDrag(const QPoint movement, const RescaleDirection rescaleDirection, const Qt::KeyboardModifiers rescaleModifiers)
355 if (rescaleDirection == North) {
356 // Nort-South direction: Adjust the dB scale
358 if ((rescaleModifiers & Qt::ShiftModifier) == 0) {
360 // By default adjust the min dB value
361 m_dBmin += movement.y();
365 // Adjust max dB value if Shift is pressed.
366 m_dBmax += movement.y();
370 // Ensure the dB values lie in [-100, 0] (or rather [MIN_DB_VALUE, 0])
371 // 0 is the upper bound, everything below -70 dB is most likely noise
375 if (m_dBmin < MIN_DB_VALUE) {
376 m_dBmin = MIN_DB_VALUE;
378 // Ensure there is at least 6 dB between the minimum and the maximum value;
379 // lower values hardly make sense
380 if (m_dBmax - m_dBmin < 6) {
381 if ((rescaleModifiers & Qt::ShiftModifier) == 0) {
382 // min was adjusted; Try to adjust the max value to maintain the
383 // minimum dB difference of 6 dB
384 m_dBmax = m_dBmin + 6;
390 // max was adjusted, adjust min
391 m_dBmin = m_dBmax - 6;
392 if (m_dBmin < MIN_DB_VALUE) {
393 m_dBmin = MIN_DB_VALUE;
394 m_dBmax = MIN_DB_VALUE+6;
402 } else if (rescaleDirection == East) {
403 // East-West direction: Adjust the maximum frequency
404 m_freqMax -= 100*movement.x();
405 if (m_freqMax < MIN_FREQ_VALUE) {
406 m_freqMax = MIN_FREQ_VALUE;
408 if (m_freqMax > MAX_FREQ_VALUE) {
409 m_freqMax = MAX_FREQ_VALUE;
419 #ifdef DEBUG_AUDIOSPEC
420 #undef DEBUG_AUDIOSPEC
424 #undef MAX_FREQ_VALUE
425 #undef MIN_FREQ_VALUE