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 ***************************************************************************/
14 #include "spectrogram.h"
16 // Defines the number of FFT samples to store.
17 // Around 4 kB for a window size of 2000. Should be at least as large as the
18 // highest vertical screen resolution available for complete reconstruction.
19 // Can be less as a pre-rendered image is kept in space.
20 #define SPECTROGRAM_HISTORY_SIZE 1000
22 // Uncomment for debugging
23 //#define DEBUG_SPECTROGRAM
25 #ifdef DEBUG_SPECTROGRAM
29 #define MIN_DB_VALUE -120
30 #define MAX_FREQ_VALUE 96000
31 #define MIN_FREQ_VALUE 1000
33 Spectrogram::Spectrogram(QWidget *parent) :
34 AbstractAudioScopeWidget(true, parent),
38 m_parameterChanged(false)
40 ui = new Ui::Spectrogram_UI;
44 m_aResetHz = new QAction(i18n("Reset maximum frequency to sampling rate"), this);
45 m_aGrid = new QAction(i18n("Draw grid"), this);
46 m_aGrid->setCheckable(true);
47 m_aTrackMouse = new QAction(i18n("Track mouse"), this);
48 m_aTrackMouse->setCheckable(true);
51 m_menu->addSeparator();
52 m_menu->addAction(m_aResetHz);
53 m_menu->addAction(m_aTrackMouse);
54 m_menu->addAction(m_aGrid);
55 m_menu->removeAction(m_aRealtime);
58 ui->windowSize->addItem("256", QVariant(256));
59 ui->windowSize->addItem("512", QVariant(512));
60 ui->windowSize->addItem("1024", QVariant(1024));
61 ui->windowSize->addItem("2048", QVariant(2048));
63 ui->windowFunction->addItem(i18n("Rectangular window"), FFTTools::Window_Rect);
64 ui->windowFunction->addItem(i18n("Triangular window"), FFTTools::Window_Triangle);
65 ui->windowFunction->addItem(i18n("Hamming window"), FFTTools::Window_Hamming);
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."));
73 b &= connect(m_aResetHz, SIGNAL(triggered()), this, SLOT(slotResetMaxFreq()));
74 b &= connect(ui->windowFunction, SIGNAL(currentIndexChanged(int)), this, SLOT(forceUpdate()));
75 b &= connect(this, SIGNAL(signalMousePositionChanged()), this, SLOT(forceUpdateHUD()));
78 AbstractScopeWidget::init();
81 Spectrogram::~Spectrogram()
90 void Spectrogram::readConfig()
92 AbstractScopeWidget::readConfig();
94 KSharedConfigPtr config = KGlobal::config();
95 KConfigGroup scopeConfig(config, AbstractScopeWidget::configName());
97 ui->windowSize->setCurrentIndex(scopeConfig.readEntry("windowSize", 0));
98 ui->windowFunction->setCurrentIndex(scopeConfig.readEntry("windowFunction", 0));
99 m_aTrackMouse->setChecked(scopeConfig.readEntry("trackMouse", true));
100 m_aGrid->setChecked(scopeConfig.readEntry("drawGrid", true));
101 m_dBmax = scopeConfig.readEntry("dBmax", 0);
102 m_dBmin = scopeConfig.readEntry("dBmin", -70);
103 m_freqMax = scopeConfig.readEntry("freqMax", 0);
105 if (m_freqMax == 0) {
106 m_customFreq = false;
112 void Spectrogram::writeConfig()
114 KSharedConfigPtr config = KGlobal::config();
115 KConfigGroup scopeConfig(config, AbstractScopeWidget::configName());
117 scopeConfig.writeEntry("windowSize", ui->windowSize->currentIndex());
118 scopeConfig.writeEntry("windowFunction", ui->windowFunction->currentIndex());
119 scopeConfig.writeEntry("trackMouse", m_aTrackMouse->isChecked());
120 scopeConfig.writeEntry("drawGrid", m_aGrid->isChecked());
121 scopeConfig.writeEntry("dBmax", m_dBmax);
122 scopeConfig.writeEntry("dBmin", m_dBmin);
125 scopeConfig.writeEntry("freqMax", m_freqMax);
127 scopeConfig.writeEntry("freqMax", 0);
133 QString Spectrogram::widgetName() const { return QString("Spectrogram"); }
135 QRect Spectrogram::scopeRect()
140 ui->verticalSpacer->geometry().top()+6 // Top
142 AbstractAudioScopeWidget::rect().bottomRight()
144 m_innerScopeRect = QRect(
146 m_scopeRect.left()+56, // Left
147 m_scopeRect.top()+6 // Top
149 ui->verticalSpacer->geometry().right()-70,
150 ui->verticalSpacer->geometry().bottom()-40
156 QImage Spectrogram::renderHUD(uint)
159 QTime start = QTime::currentTime();
162 const uint minDistY = 30; // Minimum distance between two lines
163 const uint minDistX = 40;
164 const uint textDistX = 10;
165 const uint textDistY = 25;
166 const uint topDist = m_innerScopeRect.top() - m_scopeRect.top();
167 const uint leftDist = m_innerScopeRect.left() - m_scopeRect.left();
168 const int mouseX = m_mousePos.x() - m_innerScopeRect.left();
169 const int mouseY = m_mousePos.y() - m_innerScopeRect.top();
172 QImage hud(m_scopeRect.size(), QImage::Format_ARGB32);
173 hud.fill(qRgba(0,0,0,0));
175 QPainter davinci(&hud);
176 davinci.setPen(AbstractScopeWidget::penLight);
180 if (m_aGrid->isChecked()) {
181 for (int frameNumber = 0; frameNumber < m_innerScopeRect.height(); frameNumber += minDistY) {
182 y = topDist + m_innerScopeRect.height()-1 - frameNumber;
183 hideText = m_aTrackMouse->isChecked() && m_mouseWithinWidget && abs(y - mouseY) < (int)textDistY && mouseY < m_innerScopeRect.height() && mouseX < m_innerScopeRect.width();
185 davinci.drawLine(leftDist, y, leftDist + m_innerScopeRect.width()-1, y);
187 davinci.drawText(leftDist + m_innerScopeRect.width() + textDistX, y + 6, QVariant(frameNumber).toString());
191 // Draw a line through the mouse position with the correct Frame number
192 if (m_aTrackMouse->isChecked() && m_mouseWithinWidget && mouseY < m_innerScopeRect.height() && mouseX < m_innerScopeRect.width()) {
193 davinci.setPen(AbstractScopeWidget::penLighter);
195 x = leftDist + mouseX;
196 y = topDist + mouseY - 20;
200 if (y > (int)topDist + m_innerScopeRect.height()-1 - 30) {
201 y = topDist + m_innerScopeRect.height()-1 - 30;
203 davinci.drawLine(x, topDist + mouseY, leftDist + m_innerScopeRect.width()-1, topDist + mouseY);
204 davinci.drawText(leftDist + m_innerScopeRect.width() + textDistX,
206 m_scopeRect.right()-m_innerScopeRect.right()-textDistX,
209 i18n("Frame\n%1", m_innerScopeRect.height()-1-mouseY));
213 const uint hzDiff = ceil( ((float)minDistX)/m_innerScopeRect.width() * m_freqMax / 1000 ) * 1000;
214 const int rightBorder = leftDist + m_innerScopeRect.width()-1;
216 y = topDist + m_innerScopeRect.height() + textDistY;
217 if (m_aGrid->isChecked()) {
218 for (uint hz = 0; x <= rightBorder; hz += hzDiff) {
219 davinci.setPen(AbstractScopeWidget::penLight);
220 x = leftDist + (m_innerScopeRect.width()-1) * ((float)hz)/m_freqMax;
222 // Hide text if it would overlap with the text drawn at the mouse position
223 hideText = m_aTrackMouse->isChecked() && m_mouseWithinWidget && abs(x-(leftDist + mouseX + 20)) < (int) minDistX + 16 && mouseX < m_innerScopeRect.width();
225 if (x <= rightBorder) {
226 davinci.drawLine(x, topDist, x, topDist + m_innerScopeRect.height()+6);
228 if (x+textDistY < leftDist + m_innerScopeRect.width()) {
229 // Only draw the text label if there is still enough room for the final one at the right.
231 davinci.drawText(x-4, y, QVariant(hz/1000).toString());
237 // Draw finer lines between the main lines
238 davinci.setPen(AbstractScopeWidget::penLightDots);
239 for (uint dHz = 3; dHz > 0; dHz--) {
240 x = leftDist + m_innerScopeRect.width() * ((float)hz - dHz * hzDiff/4.0f)/m_freqMax;
241 if (x > rightBorder) {
244 davinci.drawLine(x, topDist, x, topDist + m_innerScopeRect.height()-1);
248 // Draw the line at the very right (maximum frequency)
249 x = leftDist + m_innerScopeRect.width()-1;
250 hideText = m_aTrackMouse->isChecked() && m_mouseWithinWidget && abs(x-(leftDist + mouseX + 30)) < (int) minDistX && mouseX < m_innerScopeRect.width();
251 davinci.drawLine(x, topDist, x, topDist + m_innerScopeRect.height()+6);
253 davinci.drawText(x-10, y, i18n("%1 kHz").arg((double)m_freqMax/1000, 0, 'f', 1));
257 // Draw a line through the mouse position with the correct frequency label
258 if (m_aTrackMouse->isChecked() && m_mouseWithinWidget && mouseX < m_innerScopeRect.width()) {
259 davinci.setPen(AbstractScopeWidget::penThin);
260 x = leftDist + mouseX;
261 davinci.drawLine(x, topDist, x, topDist + m_innerScopeRect.height()+6);
262 davinci.drawText(x-10, y, i18n("%1 kHz")
263 .arg((double)(m_mousePos.x()-m_innerScopeRect.left())/m_innerScopeRect.width() * m_freqMax/1000, 0, 'f', 2));
266 // Draw the dB brightness scale
268 davinci.setPen(AbstractScopeWidget::penLighter);
269 for (y = topDist; y < (int)topDist + m_innerScopeRect.height(); y++) {
270 val = 1-((float)y-topDist)/(m_innerScopeRect.height()-1);
271 int col = qRgba(255, 255, 255, 255.0 * val);
272 for (x = leftDist-6; x >= (int)leftDist-13; x--) {
273 hud.setPixel(x, y, col);
276 const int rectWidth = leftDist-m_scopeRect.left()-22;
277 const int rectHeight = 50;
278 davinci.setFont(QFont(QFont().defaultFamily(), 10));
279 davinci.drawText(m_scopeRect.left(), topDist, rectWidth, rectHeight, Qt::AlignRight, i18n("%1\ndB", m_dBmax));
280 davinci.drawText(m_scopeRect.left(), topDist + m_innerScopeRect.height()-20, rectWidth, rectHeight, Qt::AlignRight, i18n("%1\ndB", m_dBmin));
283 emit signalHUDRenderingFinished(start.elapsed(), 1);
286 QImage Spectrogram::renderAudioScope(uint, const QVector<int16_t> audioFrame, const int freq,
287 const int num_channels, const int num_samples, const int newData) {
288 if (audioFrame.size() > 63) {
290 m_freqMax = freq / 2;
292 bool newDataAvailable = newData > 0;
294 #ifdef DEBUG_SPECTROGRAM
295 qDebug() << "New data for " << widgetName() << ": " << newDataAvailable << " (" << newData << " units)";
298 QTime start = QTime::currentTime();
300 int fftWindow = ui->windowSize->itemData(ui->windowSize->currentIndex()).toInt();
301 if (fftWindow > num_samples) {
302 fftWindow = num_samples;
304 if ((fftWindow & 1) == 1) {
308 // Show the window size used, for information
309 ui->labelFFTSizeNumber->setText(QVariant(fftWindow).toString());
311 if (newDataAvailable) {
313 float freqSpectrum[fftWindow/2];
315 // Get the spectral power distribution of the input samples,
316 // using the given window size and function
317 FFTTools::WindowType windowType = (FFTTools::WindowType) ui->windowFunction->itemData(ui->windowFunction->currentIndex()).toInt();
318 m_fftTools.fftNormalized(audioFrame, 0, num_channels, freqSpectrum, windowType, fftWindow, 0);
320 // This methid might be called also when a simple refresh is required.
321 // In this case there is no data to append to the history. Only append new data.
322 QVector<float> spectrumVector(fftWindow/2);
323 memcpy(spectrumVector.data(), &freqSpectrum[0], fftWindow/2 * sizeof(float));
324 m_fftHistory.prepend(spectrumVector);
326 #ifdef DEBUG_SPECTROGRAM
328 qDebug() << widgetName() << ": Has no new data to Fourier-transform";
332 // Limit the maximum history size to avoid wasting space
333 while (m_fftHistory.size() > SPECTROGRAM_HISTORY_SIZE) {
334 m_fftHistory.removeLast();
338 QImage spectrum(m_scopeRect.size(), QImage::Format_ARGB32);
339 spectrum.fill(qRgba(0,0,0,0));
340 QPainter davinci(&spectrum);
341 const uint w = m_innerScopeRect.width();
342 const uint h = m_innerScopeRect.height();
343 const uint leftDist = m_innerScopeRect.left() - m_scopeRect.left();
344 const uint topDist = m_innerScopeRect.top() - m_scopeRect.top();
352 bool completeRedraw = true;
354 if (m_fftHistoryImg.size() == m_scopeRect.size() && !m_parameterChanged) {
355 // The size of the widget and the parameters (like min/max dB) have not changed since last time,
356 // so we can re-use it, shift it by one pixel, and render the single remaining line. Usually about
357 // 10 times faster for a widget height of around 400 px.
358 if (newDataAvailable) {
359 davinci.drawImage(0, -1, m_fftHistoryImg);
361 // spectrum = m_fftHistoryImg does NOT work, leads to segfaults (anyone knows why, please tell me)
362 davinci.drawImage(0, 0, m_fftHistoryImg);
364 completeRedraw = false;
368 if (newData || m_parameterChanged) {
369 m_parameterChanged = false;
371 for (QList<QVector<float> >::iterator it = m_fftHistory.begin(); it != m_fftHistory.end(); it++) {
373 windowSize = (*it).size();
375 for (uint i = 0; i < w; i++) {
377 // i: Pixel coordinate
378 // f: Target frequency
379 // x: Frequency array index (float!) corresponding to the pixel
381 // val: dB value at position x (Range: [-inf,0])
383 f = i/((float) w-1.0) * m_freqMax;
384 x = 2*f/freq * (windowSize - 1);
387 if (x >= windowSize) {
391 // Use linear interpolation in order to get smoother display
392 if (i == 0 || xi == windowSize-1) {
393 // ... except if we are at the left or right border of the display or the spectrum
397 if ((*it)[xi] > (*it)[xi+1]
399 // This is a hack to preserve peaks.
400 // Consider f = {0, 100, 0}
402 // Then x is 50 both times, and the 100 peak is lost.
403 // Get it back here for the first x after the peak.
406 val = (xi+1 - x) * (*it)[xi]
407 + (x - xi) * (*it)[xi+1];
411 // Normalize to [0 1], 1 corresponding to 0 dB and 0 to dbMin dB
412 val = (val-m_dBmax)/(m_dBmax-m_dBmin) + 1;
415 } else if (val > 1) {
419 spectrum.setPixel(leftDist + i, topDist + h-1 - y, qRgba(255, 255, 255, val * 255));
425 if (y >= topDist + m_innerScopeRect.height()) {
428 if (!completeRedraw) {
434 #ifdef DEBUG_SPECTROGRAM
435 qDebug() << "Rendered " << y-topDist << "lines from " << m_fftHistory.size() << " available samples in " << start.elapsed() << " ms"
436 << (completeRedraw ? "" : " (re-used old image)");
437 uint storedBytes = 0;
438 for (QList< QVector<float> >::iterator it = m_fftHistory.begin(); it != m_fftHistory.end(); it++) {
439 storedBytes += (*it).size() * sizeof((*it)[0]);
441 qDebug() << QString("Total storage used: %1 kB").arg((double)storedBytes/1000, 0, 'f', 2);
444 m_fftHistoryImg = spectrum;
446 emit signalScopeRenderingFinished(start.elapsed(), 1);
449 emit signalScopeRenderingFinished(0, 1);
453 QImage Spectrogram::renderBackground(uint) { return QImage(); }
455 bool Spectrogram::isHUDDependingOnInput() const { return false; }
456 bool Spectrogram::isScopeDependingOnInput() const { return true; }
457 bool Spectrogram::isBackgroundDependingOnInput() const { return false; }
459 void Spectrogram::handleMouseDrag(const QPoint movement, const RescaleDirection rescaleDirection, const Qt::KeyboardModifiers rescaleModifiers)
461 if (rescaleDirection == North) {
462 // Nort-South direction: Adjust the dB scale
464 if ((rescaleModifiers & Qt::ShiftModifier) == 0) {
466 // By default adjust the min dB value
467 m_dBmin += movement.y();
471 // Adjust max dB value if Shift is pressed.
472 m_dBmax += movement.y();
476 // Ensure the dB values lie in [-100, 0] (or rather [MIN_DB_VALUE, 0])
477 // 0 is the upper bound, everything below -70 dB is most likely noise
481 if (m_dBmin < MIN_DB_VALUE) {
482 m_dBmin = MIN_DB_VALUE;
484 // Ensure there is at least 6 dB between the minimum and the maximum value;
485 // lower values hardly make sense
486 if (m_dBmax - m_dBmin < 6) {
487 if ((rescaleModifiers & Qt::ShiftModifier) == 0) {
488 // min was adjusted; Try to adjust the max value to maintain the
489 // minimum dB difference of 6 dB
490 m_dBmax = m_dBmin + 6;
496 // max was adjusted, adjust min
497 m_dBmin = m_dBmax - 6;
498 if (m_dBmin < MIN_DB_VALUE) {
499 m_dBmin = MIN_DB_VALUE;
500 m_dBmax = MIN_DB_VALUE+6;
505 m_parameterChanged = true;
509 } else if (rescaleDirection == East) {
510 // East-West direction: Adjust the maximum frequency
511 m_freqMax -= 100*movement.x();
512 if (m_freqMax < MIN_FREQ_VALUE) {
513 m_freqMax = MIN_FREQ_VALUE;
515 if (m_freqMax > MAX_FREQ_VALUE) {
516 m_freqMax = MAX_FREQ_VALUE;
520 m_parameterChanged = true;
528 void Spectrogram::slotResetMaxFreq()
530 m_customFreq = false;
531 m_parameterChanged = true;
536 void Spectrogram::resizeEvent(QResizeEvent *event)
538 m_parameterChanged = true;
539 AbstractAudioScopeWidget::resizeEvent(event);
542 #undef SPECTROGRAM_HISTORY_SIZE
543 #ifdef DEBUG_SPECTROGRAM
544 #undef DEBUG_SPECTROGRAM