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 ui->labelFFTSize->setToolTip(i18n("The maximum window size is limited by the number of samples per frame."));
68 ui->windowSize->setToolTip(i18n("A bigger window improves the accuracy at the cost of computational power."));
69 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."));
71 AbstractScopeWidget::init();
73 AudioSpectrum::~AudioSpectrum()
80 void AudioSpectrum::readConfig()
82 AbstractScopeWidget::readConfig();
84 KSharedConfigPtr config = KGlobal::config();
85 KConfigGroup scopeConfig(config, AbstractScopeWidget::configName());
87 ui->windowSize->setCurrentIndex(scopeConfig.readEntry("windowSize", 0));
88 ui->windowFunction->setCurrentIndex(scopeConfig.readEntry("windowFunction", 0));
89 m_dBmax = scopeConfig.readEntry("dBmax", 0);
90 m_dBmin = scopeConfig.readEntry("dBmin", -70);
91 m_freqMax = scopeConfig.readEntry("freqMax", 0);
100 void AudioSpectrum::writeConfig()
102 KSharedConfigPtr config = KGlobal::config();
103 KConfigGroup scopeConfig(config, AbstractScopeWidget::configName());
105 scopeConfig.writeEntry("windowSize", ui->windowSize->currentIndex());
106 scopeConfig.writeEntry("windowFunction", ui->windowFunction->currentIndex());
107 scopeConfig.writeEntry("dBmax", m_dBmax);
108 scopeConfig.writeEntry("dBmin", m_dBmin);
110 scopeConfig.writeEntry("freqMax", m_freqMax);
112 scopeConfig.writeEntry("freqMax", 0);
118 QString AudioSpectrum::widgetName() const { return QString("AudioSpectrum"); }
119 bool AudioSpectrum::isBackgroundDependingOnInput() const { return false; }
120 bool AudioSpectrum::isScopeDependingOnInput() const { return true; }
121 bool AudioSpectrum::isHUDDependingOnInput() const { return false; }
123 QImage AudioSpectrum::renderBackground(uint) { return QImage(); }
125 QImage AudioSpectrum::renderAudioScope(uint, const QVector<int16_t> audioFrame, const int freq, const int num_channels, const int num_samples)
127 if (audioFrame.size() > 63) {
129 m_freqMax = freq / 2;
132 QTime start = QTime::currentTime();
135 // Determine the window size to use. It should be
136 // * not bigger than the number of samples actually available
138 int fftWindow = ui->windowSize->itemData(ui->windowSize->currentIndex()).toInt();
139 if (fftWindow > num_samples) {
140 fftWindow = num_samples;
142 if ((fftWindow & 1) == 1) {
146 // Show the window size used, for information
147 ui->labelFFTSizeNumber->setText(QVariant(fftWindow).toString());
150 // Get the spectral power distribution of the input samples,
151 // using the given window size and function
152 float freqSpectrum[fftWindow/2];
153 FFTTools::WindowType windowType = (FFTTools::WindowType) ui->windowFunction->itemData(ui->windowFunction->currentIndex()).toInt();
154 m_fftTools.fftNormalized(audioFrame, 0, num_channels, freqSpectrum, windowType, fftWindow, 0);
158 QImage spectrum(m_scopeRect.size(), QImage::Format_ARGB32);
159 spectrum.fill(qRgba(0,0,0,0));
160 const uint w = m_innerScopeRect.width();
161 const uint h = m_innerScopeRect.height();
162 const uint leftDist = m_innerScopeRect.left() - m_scopeRect.left();
163 const uint topDist = m_innerScopeRect.top() - m_scopeRect.top();
169 for (uint i = 0; i < w; i++) {
171 // i: Pixel coordinate
172 // f: Target frequency
173 // x: Frequency array index (float!) corresponding to the pixel
176 f = i/((float) w-1.0) * m_freqMax;
177 x = 2*f/freq * (fftWindow/2 - 1);
180 if (x >= fftWindow/2) {
184 // Use linear interpolation in order to get smoother display
185 if (i == 0 || xi == fftWindow/2-1) {
186 // ... except if we are at the left or right border of the display or the spectrum
187 val = freqSpectrum[xi];
190 if (freqSpectrum[xi] > freqSpectrum[xi+1]
192 // This is a hack to preserve peaks.
193 // Consider f = {0, 100, 0}
195 // Then x is 50 both times, and the 100 peak is lost.
196 // Get it back here for the first x after the peak.
197 val = freqSpectrum[xi];
199 val = (xi+1 - x) * freqSpectrum[xi]
200 + (x - xi) * freqSpectrum[xi+1];
204 // freqSpectrum values range from 0 to -inf as they are relative dB values.
205 for (uint y = 0; y < h*(1 - (val - m_dBmax)/(m_dBmin-m_dBmax)) && y < h; y++) {
206 spectrum.setPixel(leftDist + i, topDist + h-y-1, qRgba(225, 182, 255, 255));
212 emit signalScopeRenderingFinished(start.elapsed(), 1);
214 #ifdef DEBUG_AUDIOSPEC
215 if (!fileWritten || true) {
217 mFile.open("/tmp/freq.m");
219 qDebug() << "Opening file failed.";
223 for (int sample = 0; sample < 256; sample++) {
224 mFile << data[sample] << " ";
228 mFile << "freq = [ ";
229 for (int sample = 0; sample < 256; sample++) {
230 mFile << freqData[sample].r << "+" << freqData[sample].i << "*i ";
236 qDebug() << "File written.";
239 qDebug() << "File already written.";
245 emit signalScopeRenderingFinished(0, 1);
249 QImage AudioSpectrum::renderHUD(uint)
251 QTime start = QTime::currentTime();
253 // Minimum distance between two lines
254 const uint minDistY = 30;
255 const uint minDistX = 40;
256 const uint textDistX = 10;
257 const uint textDistY = 25;
258 const uint topDist = m_innerScopeRect.top() - m_scopeRect.top();
259 const uint leftDist = m_innerScopeRect.left() - m_scopeRect.left();
260 const uint dbDiff = ceil((float)minDistY/m_innerScopeRect.height() * (m_dBmax-m_dBmin));
262 QImage hud(m_scopeRect.size(), QImage::Format_ARGB32);
263 hud.fill(qRgba(0,0,0,0));
265 QPainter davinci(&hud);
266 davinci.setPen(AbstractScopeWidget::penLight);
269 for (int db = -dbDiff; db > m_dBmin; db -= dbDiff) {
270 y = topDist + m_innerScopeRect.height() * ((float)db)/(m_dBmin - m_dBmax);
271 if (y-topDist > m_innerScopeRect.height()-minDistY+10) {
272 // Abort here, there is still a line left for min dB to paint which needs some room.
275 davinci.drawLine(leftDist, y, leftDist + m_innerScopeRect.width()-1, y);
276 davinci.drawText(leftDist + m_innerScopeRect.width() + textDistX, y + 6, i18n("%1 dB", m_dBmax + db));
278 davinci.drawLine(leftDist, topDist, leftDist + m_innerScopeRect.width()-1, topDist);
279 davinci.drawText(leftDist + m_innerScopeRect.width() + textDistX, topDist+6, i18n("%1 dB", m_dBmax));
280 davinci.drawLine(leftDist, topDist+m_innerScopeRect.height()-1, leftDist + m_innerScopeRect.width()-1, topDist+m_innerScopeRect.height()-1);
281 davinci.drawText(leftDist + m_innerScopeRect.width() + textDistX, topDist+m_innerScopeRect.height()+6, i18n("%1 dB", m_dBmin));
283 const uint hzDiff = ceil( ((float)minDistX)/m_innerScopeRect.width() * m_freqMax / 1000 ) * 1000;
285 const int rightBorder = leftDist + m_innerScopeRect.width()-1;
286 y = topDist + m_innerScopeRect.height() + textDistY;
287 for (uint hz = 0; x <= rightBorder; hz += hzDiff) {
288 davinci.setPen(AbstractScopeWidget::penLight);
289 x = leftDist + m_innerScopeRect.width() * ((float)hz)/m_freqMax;
291 if (x <= rightBorder) {
292 davinci.drawLine(x, topDist, x, topDist + m_innerScopeRect.height()+6);
294 if (hz < m_freqMax && x+textDistY < leftDist + m_innerScopeRect.width()) {
295 davinci.drawText(x-4, y, QVariant(hz/1000).toString());
297 x = leftDist + m_innerScopeRect.width();
298 davinci.drawLine(x, topDist, x, topDist + m_innerScopeRect.height()+6);
299 davinci.drawText(x-10, y, i18n("%1 kHz").arg((double)m_freqMax/1000, 0, 'f', 1));
303 // Draw finer lines between the main lines
304 davinci.setPen(AbstractScopeWidget::penLightDots);
305 for (uint dHz = 3; dHz > 0; dHz--) {
306 x = leftDist + m_innerScopeRect.width() * ((float)hz - dHz * hzDiff/4.0f)/m_freqMax;
307 if (x > rightBorder) {
310 davinci.drawLine(x, topDist, x, topDist + m_innerScopeRect.height()-1);
316 emit signalHUDRenderingFinished(start.elapsed(), 1);
320 QRect AudioSpectrum::scopeRect()
325 ui->verticalSpacer->geometry().top()+6 // Top
327 AbstractAudioScopeWidget::rect().bottomRight()
329 m_innerScopeRect = QRect(
331 m_scopeRect.left()+6, // Left
332 m_scopeRect.top()+6 // Top
334 ui->verticalSpacer->geometry().right()-70,
335 ui->verticalSpacer->geometry().bottom()-40
341 void AudioSpectrum::slotResetMaxFreq()
343 m_customFreq = false;
351 void AudioSpectrum::handleMouseDrag(const QPoint movement, const RescaleDirection rescaleDirection, const Qt::KeyboardModifiers rescaleModifiers)
353 if (rescaleDirection == AudioSpectrum::North) {
354 // Nort-South direction: Adjust the dB scale
356 if ((rescaleModifiers & Qt::ShiftModifier) == 0) {
358 // By default adjust the min dB value
359 m_dBmin += movement.y();
363 // Adjust max dB value if Shift is pressed.
364 m_dBmax += movement.y();
368 // Ensure the dB values lie in [-100, 0] (or rather [MIN_DB_VALUE, 0])
369 // 0 is the upper bound, everything below -70 dB is most likely noise
373 if (m_dBmin < MIN_DB_VALUE) {
374 m_dBmin = MIN_DB_VALUE;
376 // Ensure there is at least 6 dB between the minimum and the maximum value;
377 // lower values hardly make sense
378 if (m_dBmax - m_dBmin < 6) {
379 if ((rescaleModifiers & Qt::ShiftModifier) == 0) {
380 // min was adjusted; Try to adjust the max value to maintain the
381 // minimum dB difference of 6 dB
382 m_dBmax = m_dBmin + 6;
388 // max was adjusted, adjust min
389 m_dBmin = m_dBmax - 6;
390 if (m_dBmin < MIN_DB_VALUE) {
391 m_dBmin = MIN_DB_VALUE;
392 m_dBmax = MIN_DB_VALUE+6;
400 } else if (rescaleDirection == AudioSpectrum::East) {
401 // East-West direction: Adjust the maximum frequency
402 m_freqMax -= 100*movement.x();
403 if (m_freqMax < MIN_FREQ_VALUE) {
404 m_freqMax = MIN_FREQ_VALUE;
406 if (m_freqMax > MAX_FREQ_VALUE) {
407 m_freqMax = MAX_FREQ_VALUE;
417 #ifdef DEBUG_AUDIOSPEC
418 #undef DEBUG_AUDIOSPEC
422 #undef MAX_FREQ_VALUE
423 #undef MIN_FREQ_VALUE