]> git.sesse.net Git - kdenlive/blob - src/scopes/audioscopes/spectrogram.cpp
Fix i18n calls
[kdenlive] / src / scopes / audioscopes / spectrogram.cpp
1 /***************************************************************************
2  *   Copyright (C) 2010 by Simon Andreas Eugster (simon.eu@gmail.com)      *
3  *   This file is part of kdenlive. See www.kdenlive.org.                  *
4  *                                                                         *
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  ***************************************************************************/
10
11 #include <QPainter>
12 #include <QMenu>
13
14 #include "spectrogram.h"
15
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
21
22 // Uncomment for debugging
23 //#define DEBUG_SPECTROGRAM
24
25 #ifdef DEBUG_SPECTROGRAM
26 #include <QDebug>
27 #endif
28
29 #define MIN_DB_VALUE -120
30 #define MAX_FREQ_VALUE 96000
31 #define MIN_FREQ_VALUE 1000
32
33 Spectrogram::Spectrogram(QWidget *parent) :
34         AbstractAudioScopeWidget(true, parent),
35         m_fftTools(),
36         m_fftHistory(),
37         m_fftHistoryImg(),
38         m_parameterChanged(false)
39 {
40     ui = new Ui::Spectrogram_UI;
41     ui->setupUi(this);
42
43
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);
49     m_aHighlightPeaks = new QAction(i18n("Highlight peaks"), this);
50     m_aHighlightPeaks->setCheckable(true);
51
52
53     m_menu->addSeparator();
54     m_menu->addAction(m_aResetHz);
55     m_menu->addAction(m_aTrackMouse);
56     m_menu->addAction(m_aGrid);
57     m_menu->addAction(m_aHighlightPeaks);
58     m_menu->removeAction(m_aRealtime);
59
60
61     ui->windowSize->addItem("256", QVariant(256));
62     ui->windowSize->addItem("512", QVariant(512));
63     ui->windowSize->addItem("1024", QVariant(1024));
64     ui->windowSize->addItem("2048", QVariant(2048));
65
66     ui->windowFunction->addItem(i18n("Rectangular window"), FFTTools::Window_Rect);
67     ui->windowFunction->addItem(i18n("Triangular window"), FFTTools::Window_Triangle);
68     ui->windowFunction->addItem(i18n("Hamming window"), FFTTools::Window_Hamming);
69
70     // Note: These strings are used in both Spectogram and AudioSpectrum. Ideally change both (if necessary) to reduce workload on translators
71     ui->labelFFTSize->setToolTip(i18n("The maximum window size is limited by the number of samples per frame."));
72     ui->windowSize->setToolTip(i18n("A bigger window improves the accuracy at the cost of computational power."));
73     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."));
74
75     bool b = true;
76     b &= connect(m_aResetHz, SIGNAL(triggered()), this, SLOT(slotResetMaxFreq()));
77     b &= connect(ui->windowFunction, SIGNAL(currentIndexChanged(int)), this, SLOT(forceUpdate()));
78     b &= connect(this, SIGNAL(signalMousePositionChanged()), this, SLOT(forceUpdateHUD()));
79     Q_ASSERT(b);
80
81     AbstractScopeWidget::init();
82 }
83
84 Spectrogram::~Spectrogram()
85 {
86     writeConfig();
87
88     delete m_aResetHz;
89     delete m_aTrackMouse;
90     delete m_aGrid;
91     delete ui;
92 }
93
94 void Spectrogram::readConfig()
95 {
96     AbstractScopeWidget::readConfig();
97
98     KSharedConfigPtr config = KGlobal::config();
99     KConfigGroup scopeConfig(config, AbstractScopeWidget::configName());
100
101     ui->windowSize->setCurrentIndex(scopeConfig.readEntry("windowSize", 0));
102     ui->windowFunction->setCurrentIndex(scopeConfig.readEntry("windowFunction", 0));
103     m_aTrackMouse->setChecked(scopeConfig.readEntry("trackMouse", true));
104     m_aGrid->setChecked(scopeConfig.readEntry("drawGrid", true));
105     m_aHighlightPeaks->setChecked(scopeConfig.readEntry("highlightPeaks", true));
106     m_dBmax = scopeConfig.readEntry("dBmax", 0);
107     m_dBmin = scopeConfig.readEntry("dBmin", -70);
108     m_freqMax = scopeConfig.readEntry("freqMax", 0);
109
110     if (m_freqMax == 0) {
111         m_customFreq = false;
112         m_freqMax = 10000;
113     } else {
114         m_customFreq = true;
115     }
116 }
117 void Spectrogram::writeConfig()
118 {
119     KSharedConfigPtr config = KGlobal::config();
120     KConfigGroup scopeConfig(config, AbstractScopeWidget::configName());
121
122     scopeConfig.writeEntry("windowSize", ui->windowSize->currentIndex());
123     scopeConfig.writeEntry("windowFunction", ui->windowFunction->currentIndex());
124     scopeConfig.writeEntry("trackMouse", m_aTrackMouse->isChecked());
125     scopeConfig.writeEntry("drawGrid", m_aGrid->isChecked());
126     scopeConfig.writeEntry("highlightPeaks", m_aHighlightPeaks->isChecked());
127     scopeConfig.writeEntry("dBmax", m_dBmax);
128     scopeConfig.writeEntry("dBmin", m_dBmin);
129
130     if (m_customFreq) {
131         scopeConfig.writeEntry("freqMax", m_freqMax);
132     } else {
133         scopeConfig.writeEntry("freqMax", 0);
134     }
135
136     scopeConfig.sync();
137 }
138
139 QString Spectrogram::widgetName() const { return QString("Spectrogram"); }
140
141 QRect Spectrogram::scopeRect()
142 {
143     m_scopeRect = QRect(
144             QPoint(
145                     10,                                     // Left
146                     ui->verticalSpacer->geometry().top()+6  // Top
147             ),
148             AbstractAudioScopeWidget::rect().bottomRight()
149     );
150     m_innerScopeRect = QRect(
151             QPoint(
152                     m_scopeRect.left()+66,                  // Left
153                     m_scopeRect.top()+6                     // Top
154             ), QPoint(
155                     ui->verticalSpacer->geometry().right()-70,
156                     ui->verticalSpacer->geometry().bottom()-40
157             )
158     );
159     return m_scopeRect;
160 }
161
162 QImage Spectrogram::renderHUD(uint)
163 {
164     if (m_innerScopeRect.width() > 0 && m_innerScopeRect.height() > 0) {
165         QTime start = QTime::currentTime();
166
167         int x, y;
168         const uint minDistY = 30; // Minimum distance between two lines
169         const uint minDistX = 40;
170         const uint textDistX = 10;
171         const uint textDistY = 25;
172         const uint topDist = m_innerScopeRect.top() - m_scopeRect.top();
173         const uint leftDist = m_innerScopeRect.left() - m_scopeRect.left();
174         const int mouseX = m_mousePos.x() - m_innerScopeRect.left();
175         const int mouseY = m_mousePos.y() - m_innerScopeRect.top();
176         bool hideText;
177
178         QImage hud(m_scopeRect.size(), QImage::Format_ARGB32);
179         hud.fill(qRgba(0,0,0,0));
180
181         QPainter davinci(&hud);
182         davinci.setPen(AbstractScopeWidget::penLight);
183
184
185         // Frame display
186         if (m_aGrid->isChecked()) {
187             for (int frameNumber = 0; frameNumber < m_innerScopeRect.height(); frameNumber += minDistY) {
188                 y = topDist + m_innerScopeRect.height()-1 - frameNumber;
189                 hideText = m_aTrackMouse->isChecked() && m_mouseWithinWidget && abs(y - mouseY) < (int)textDistY && mouseY < m_innerScopeRect.height()
190                         && mouseX < m_innerScopeRect.width() && mouseX >= 0;
191
192                 davinci.drawLine(leftDist, y, leftDist + m_innerScopeRect.width()-1, y);
193                 if (!hideText) {
194                     davinci.drawText(leftDist + m_innerScopeRect.width() + textDistX, y + 6, QVariant(frameNumber).toString());
195                 }
196             }
197         }
198         // Draw a line through the mouse position with the correct Frame number
199         if (m_aTrackMouse->isChecked() && m_mouseWithinWidget && mouseY < m_innerScopeRect.height()
200                 && mouseX < m_innerScopeRect.width() && mouseX >= 0) {
201             davinci.setPen(AbstractScopeWidget::penLighter);
202
203             x = leftDist + mouseX;
204             y = topDist + mouseY - 20;
205             if (y < 0) {
206                 y = 0;
207             }
208             if (y > (int)topDist + m_innerScopeRect.height()-1 - 30) {
209                 y = topDist + m_innerScopeRect.height()-1 - 30;
210             }
211             davinci.drawLine(x, topDist + mouseY, leftDist + m_innerScopeRect.width()-1, topDist + mouseY);
212             davinci.drawText(leftDist + m_innerScopeRect.width() + textDistX,
213                              y,
214                              m_scopeRect.right()-m_innerScopeRect.right()-textDistX,
215                              40,
216                              Qt::AlignLeft,
217                              i18n("Frame\n%1", m_innerScopeRect.height()-1-mouseY));
218         }
219
220         // Frequency grid
221         const uint hzDiff = ceil( ((float)minDistX)/m_innerScopeRect.width() * m_freqMax / 1000 ) * 1000;
222         const int rightBorder = leftDist + m_innerScopeRect.width()-1;
223         x = 0;
224         y = topDist + m_innerScopeRect.height() + textDistY;
225         if (m_aGrid->isChecked()) {
226             for (uint hz = 0; x <= rightBorder; hz += hzDiff) {
227                 davinci.setPen(AbstractScopeWidget::penLight);
228                 x = leftDist + (m_innerScopeRect.width()-1) * ((float)hz)/m_freqMax;
229
230                 // Hide text if it would overlap with the text drawn at the mouse position
231                 hideText = m_aTrackMouse->isChecked() && m_mouseWithinWidget && abs(x-(leftDist + mouseX + 20)) < (int) minDistX + 16
232                         && mouseX < m_innerScopeRect.width() && mouseX >= 0;
233
234                 if (x <= rightBorder) {
235                     davinci.drawLine(x, topDist, x, topDist + m_innerScopeRect.height()+6);
236                 }
237                 if (x+textDistY < leftDist + m_innerScopeRect.width()) {
238                     // Only draw the text label if there is still enough room for the final one at the right.
239                     if (!hideText) {
240                         davinci.drawText(x-4, y, QVariant(hz/1000).toString());
241                     }
242                 }
243
244
245                 if (hz > 0) {
246                     // Draw finer lines between the main lines
247                     davinci.setPen(AbstractScopeWidget::penLightDots);
248                     for (uint dHz = 3; dHz > 0; dHz--) {
249                         x = leftDist + m_innerScopeRect.width() * ((float)hz - dHz * hzDiff/4.0f)/m_freqMax;
250                         if (x > rightBorder) {
251                             break;
252                         }
253                         davinci.drawLine(x, topDist, x, topDist + m_innerScopeRect.height()-1);
254                     }
255                 }
256             }
257             // Draw the line at the very right (maximum frequency)
258             x = leftDist + m_innerScopeRect.width()-1;
259             hideText = m_aTrackMouse->isChecked() && m_mouseWithinWidget && abs(x-(leftDist + mouseX + 30)) < (int) minDistX
260                     && mouseX < m_innerScopeRect.width() && mouseX >= 0;
261             davinci.drawLine(x, topDist, x, topDist + m_innerScopeRect.height()+6);
262             if (!hideText) {
263                 davinci.drawText(x-10, y, i18n("%1 kHz", QString("%1").arg((double)m_freqMax/1000, 0, 'f', 1)));
264             }
265         }
266
267         // Draw a line through the mouse position with the correct frequency label
268         if (m_aTrackMouse->isChecked() && m_mouseWithinWidget && mouseX < m_innerScopeRect.width() && mouseX >= 0) {
269             davinci.setPen(AbstractScopeWidget::penThin);
270             x = leftDist + mouseX;
271             davinci.drawLine(x, topDist, x, topDist + m_innerScopeRect.height()+6);
272             davinci.drawText(x-10, y, i18n("%1 kHz", QString("%1")
273                              .arg((double)(m_mousePos.x()-m_innerScopeRect.left())/m_innerScopeRect.width() * m_freqMax/1000, 0, 'f', 2)));
274         }
275
276         // Draw the dB brightness scale
277         float val;
278         davinci.setPen(AbstractScopeWidget::penLighter);
279         for (y = topDist; y < (int)topDist + m_innerScopeRect.height(); y++) {
280             val = 1-((float)y-topDist)/(m_innerScopeRect.height()-1);
281             int col = qRgba(255, 255, 255, 255.0 * val);
282             for (x = leftDist-6; x >= (int)leftDist-13; x--) {
283                 hud.setPixel(x, y, col);
284             }
285         }
286         const int rectWidth = leftDist-m_scopeRect.left()-22;
287         const int rectHeight = 50;
288         davinci.setFont(QFont(QFont().defaultFamily(), 10));
289         davinci.drawText(m_scopeRect.left(), topDist, rectWidth, rectHeight, Qt::AlignRight, i18n("%1\ndB", m_dBmax));
290         davinci.drawText(m_scopeRect.left(), topDist + m_innerScopeRect.height()-20, rectWidth, rectHeight, Qt::AlignRight, i18n("%1\ndB", m_dBmin));
291
292
293         emit signalHUDRenderingFinished(start.elapsed(), 1);
294         return hud;
295     } else {
296         emit signalHUDRenderingFinished(0, 1);
297         return QImage();
298     }
299 }
300 QImage Spectrogram::renderAudioScope(uint, const QVector<int16_t> audioFrame, const int freq,
301                                      const int num_channels, const int num_samples, const int newData) {
302     if (
303             audioFrame.size() > 63
304             && m_innerScopeRect.width() > 0 && m_innerScopeRect.height() > 0
305     ) {
306         if (!m_customFreq) {
307             m_freqMax = freq / 2;
308         }
309         bool newDataAvailable = newData > 0;
310
311 #ifdef DEBUG_SPECTROGRAM
312         qDebug() << "New data for " << widgetName() << ": " << newDataAvailable << " (" << newData << " units)";
313 #endif
314
315         QTime start = QTime::currentTime();
316
317         int fftWindow = ui->windowSize->itemData(ui->windowSize->currentIndex()).toInt();
318         if (fftWindow > num_samples) {
319             fftWindow = num_samples;
320         }
321         if ((fftWindow & 1) == 1) {
322             fftWindow--;
323         }
324
325         // Show the window size used, for information
326         ui->labelFFTSizeNumber->setText(QVariant(fftWindow).toString());
327
328         if (newDataAvailable) {
329
330             float freqSpectrum[fftWindow/2];
331
332             // Get the spectral power distribution of the input samples,
333             // using the given window size and function
334             FFTTools::WindowType windowType = (FFTTools::WindowType) ui->windowFunction->itemData(ui->windowFunction->currentIndex()).toInt();
335             m_fftTools.fftNormalized(audioFrame, 0, num_channels, freqSpectrum, windowType, fftWindow, 0);
336
337             // This methid might be called also when a simple refresh is required.
338             // In this case there is no data to append to the history. Only append new data.
339             QVector<float> spectrumVector(fftWindow/2);
340             memcpy(spectrumVector.data(), &freqSpectrum[0], fftWindow/2 * sizeof(float));
341             m_fftHistory.prepend(spectrumVector);
342         }
343 #ifdef DEBUG_SPECTROGRAM
344         else {
345             qDebug() << widgetName() << ": Has no new data to Fourier-transform";
346         }
347 #endif
348
349         // Limit the maximum history size to avoid wasting space
350         while (m_fftHistory.size() > SPECTROGRAM_HISTORY_SIZE) {
351             m_fftHistory.removeLast();
352         }
353
354         // Draw the spectrum
355         QImage spectrum(m_scopeRect.size(), QImage::Format_ARGB32);
356         spectrum.fill(qRgba(0,0,0,0));
357         QPainter davinci(&spectrum);
358         const uint h = m_innerScopeRect.height();
359         const uint leftDist = m_innerScopeRect.left() - m_scopeRect.left();
360         const uint topDist = m_innerScopeRect.top() - m_scopeRect.top();
361         float val;
362         uint windowSize;
363         uint y;
364         bool completeRedraw = true;
365
366         if (m_fftHistoryImg.size() == m_scopeRect.size() && !m_parameterChanged) {
367             // The size of the widget and the parameters (like min/max dB) have not changed since last time,
368             // so we can re-use it, shift it by one pixel, and render the single remaining line. Usually about
369             // 10 times faster for a widget height of around 400 px.
370             if (newDataAvailable) {
371                 davinci.drawImage(0, -1, m_fftHistoryImg);
372             } else {
373                 // spectrum = m_fftHistoryImg does NOT work, leads to segfaults (anyone knows why, please tell me)
374                 davinci.drawImage(0, 0, m_fftHistoryImg);
375             }
376             completeRedraw = false;
377         }
378
379         y = 0;
380         if (newData || m_parameterChanged) {
381             m_parameterChanged = false;
382             bool peak = false;
383
384             QVector<float> dbMap;
385             uint right;
386             for (QList<QVector<float> >::iterator it = m_fftHistory.begin(); it != m_fftHistory.end(); it++) {
387
388                 windowSize = (*it).size();
389
390                 // Interpolate the frequency data to match the pixel coordinates
391                 right = ((float) m_freqMax)/(m_freq/2) * (windowSize - 1);
392                 dbMap = FFTTools::interpolatePeakPreserving((*it), m_innerScopeRect.width(), 0, right, -180);
393
394                 for (int i = 0; i < dbMap.size(); i++) {
395                     val = dbMap[i];
396                     peak = val > m_dBmax;
397
398                     // Normalize dB value to [0 1], 1 corresponding to dbMax dB and 0 to dbMin dB
399                     val = (val-m_dBmax)/(m_dBmax-m_dBmin) + 1;
400                     if (val < 0) {
401                         val = 0;
402                     } else if (val > 1) {
403                         val = 1;
404                     }
405                     if (!peak || !m_aHighlightPeaks->isChecked()) {
406                         spectrum.setPixel(leftDist + i, topDist + h-1 - y, qRgba(255, 255, 255, val * 255));
407                     } else {
408                         spectrum.setPixel(leftDist + i, topDist + h-1 - y, AbstractScopeWidget::colHighlightDark.rgba());
409                     }
410                 }
411
412                 y++;
413                 if (y >= topDist + m_innerScopeRect.height()) {
414                     break;
415                 }
416                 if (!completeRedraw) {
417                     break;
418                 }
419             }
420         }
421
422 #ifdef DEBUG_SPECTROGRAM
423         qDebug() << "Rendered " << y-topDist << "lines from " << m_fftHistory.size() << " available samples in " << start.elapsed() << " ms"
424                 << (completeRedraw ? "" : " (re-used old image)");
425         uint storedBytes = 0;
426         for (QList< QVector<float> >::iterator it = m_fftHistory.begin(); it != m_fftHistory.end(); it++) {
427             storedBytes += (*it).size() * sizeof((*it)[0]);
428         }
429         qDebug() << QString("Total storage used: %1 kB", QString("%1").arg((double)storedBytes/1000, 0, 'f', 2));
430 #endif
431
432         m_fftHistoryImg = spectrum;
433
434         emit signalScopeRenderingFinished(start.elapsed(), 1);
435         return spectrum;
436     } else {
437         emit signalScopeRenderingFinished(0, 1);
438         return QImage();
439     }
440 }
441 QImage Spectrogram::renderBackground(uint) { return QImage(); }
442
443 bool Spectrogram::isHUDDependingOnInput() const { return false; }
444 bool Spectrogram::isScopeDependingOnInput() const { return true; }
445 bool Spectrogram::isBackgroundDependingOnInput() const { return false; }
446
447 void Spectrogram::handleMouseDrag(const QPoint &movement, const RescaleDirection rescaleDirection, const Qt::KeyboardModifiers rescaleModifiers)
448 {
449     if (rescaleDirection == North) {
450         // Nort-South direction: Adjust the dB scale
451
452         if ((rescaleModifiers & Qt::ShiftModifier) == 0) {
453
454             // By default adjust the min dB value
455             m_dBmin += movement.y();
456
457         } else {
458
459             // Adjust max dB value if Shift is pressed.
460             m_dBmax += movement.y();
461
462         }
463
464         // Ensure the dB values lie in [-100, 0] (or rather [MIN_DB_VALUE, 0])
465         // 0 is the upper bound, everything below -70 dB is most likely noise
466         if (m_dBmax > 0) {
467             m_dBmax = 0;
468         }
469         if (m_dBmin < MIN_DB_VALUE) {
470             m_dBmin = MIN_DB_VALUE;
471         }
472         // Ensure there is at least 6 dB between the minimum and the maximum value;
473         // lower values hardly make sense
474         if (m_dBmax - m_dBmin < 6) {
475             if ((rescaleModifiers & Qt::ShiftModifier) == 0) {
476                 // min was adjusted; Try to adjust the max value to maintain the
477                 // minimum dB difference of 6 dB
478                 m_dBmax = m_dBmin + 6;
479                 if (m_dBmax > 0) {
480                     m_dBmax = 0;
481                     m_dBmin = -6;
482                 }
483             } else {
484                 // max was adjusted, adjust min
485                 m_dBmin = m_dBmax - 6;
486                 if (m_dBmin < MIN_DB_VALUE) {
487                     m_dBmin = MIN_DB_VALUE;
488                     m_dBmax = MIN_DB_VALUE+6;
489                 }
490             }
491         }
492
493         m_parameterChanged = true;
494         forceUpdateHUD();
495         forceUpdateScope();
496
497     } else if (rescaleDirection == East) {
498         // East-West direction: Adjust the maximum frequency
499         m_freqMax -= 100*movement.x();
500         if (m_freqMax < MIN_FREQ_VALUE) {
501             m_freqMax = MIN_FREQ_VALUE;
502         }
503         if (m_freqMax > MAX_FREQ_VALUE) {
504             m_freqMax = MAX_FREQ_VALUE;
505         }
506         m_customFreq = true;
507
508         m_parameterChanged = true;
509         forceUpdateHUD();
510         forceUpdateScope();
511     }
512 }
513
514
515
516 void Spectrogram::slotResetMaxFreq()
517 {
518     m_customFreq = false;
519     m_parameterChanged = true;
520     forceUpdateHUD();
521     forceUpdateScope();
522 }
523
524 void Spectrogram::resizeEvent(QResizeEvent *event)
525 {
526     m_parameterChanged = true;
527     AbstractAudioScopeWidget::resizeEvent(event);
528 }
529
530 #undef SPECTROGRAM_HISTORY_SIZE
531 #ifdef DEBUG_SPECTROGRAM
532 #undef DEBUG_SPECTROGRAM
533 #endif