]> git.sesse.net Git - kdenlive/blobdiff - src/audioscopes/audiospectrum.cpp
* Moved movement detection to Abstract Scope widget
[kdenlive] / src / audioscopes / audiospectrum.cpp
index 2475094cb42facb808d018f9d767a3a58b76244d..bad169f25267a4a682ff6485dbe9a4049c9e7875 100644 (file)
@@ -32,18 +32,9 @@ bool fileWritten = false;
 #define MAX_FREQ_VALUE 96000
 #define MIN_FREQ_VALUE 1000
 
-const QString AudioSpectrum::directions[] =  {"North", "Northeast", "East", "Southeast"};
-
 AudioSpectrum::AudioSpectrum(QWidget *parent) :
         AbstractAudioScopeWidget(false, parent),
-        m_windowFunctions(),
-        m_freqMax(10000),
-        m_customFreq(false),
-        m_rescaleMinDist(8),
-        m_rescaleVerticalThreshold(2.0f),
-        m_rescaleActive(false),
-        m_rescalePropertiesLocked(false),
-        m_rescaleScale(1)
+        m_fftTools()
 {
     ui = new Ui::AudioSpectrum_UI;
     ui->setupUi(this);
@@ -54,6 +45,7 @@ AudioSpectrum::AudioSpectrum(QWidget *parent) :
 
     m_menu->addSeparator();
     m_menu->addAction(m_aResetHz);
+    m_menu->removeAction(m_aRealtime);
 
 
     ui->windowSize->addItem("256", QVariant(256));
@@ -66,21 +58,22 @@ AudioSpectrum::AudioSpectrum(QWidget *parent) :
     ui->windowFunction->addItem(i18n("Hamming window"), FFTTools::Window_Hamming);
 
 
-    m_cfg = kiss_fftr_alloc(ui->windowSize->itemData(ui->windowSize->currentIndex()).toInt(), 0,0,0);
-
-
     bool b = true;
-    b &= connect(ui->windowSize, SIGNAL(currentIndexChanged(int)), this, SLOT(slotUpdateCfg()));
     b &= connect(m_aResetHz, SIGNAL(triggered()), this, SLOT(slotResetMaxFreq()));
+    b &= connect(ui->windowFunction, SIGNAL(currentIndexChanged(int)), this, SLOT(forceUpdate()));
     Q_ASSERT(b);
 
+
+    ui->labelFFTSize->setToolTip(i18n("The maximum window size is limited by the number of samples per frame."));
+    ui->windowSize->setToolTip(i18n("A bigger window improves the accuracy at the cost of computational power."));
+    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."));
+
     AbstractScopeWidget::init();
 }
 AudioSpectrum::~AudioSpectrum()
 {
     writeConfig();
 
-    free(m_cfg);
     delete m_aResetHz;
 }
 
@@ -138,83 +131,27 @@ QImage AudioSpectrum::renderAudioScope(uint, const QVector<int16_t> audioFrame,
 
         QTime start = QTime::currentTime();
 
-        bool customCfg = false;
-        kiss_fftr_cfg myCfg = m_cfg;
+
+        // Determine the window size to use. It should be
+        // * not bigger than the number of samples actually available
+        // * divisible by 2
         int fftWindow = ui->windowSize->itemData(ui->windowSize->currentIndex()).toInt();
         if (fftWindow > num_samples) {
             fftWindow = num_samples;
-            customCfg = true;
         }
         if ((fftWindow & 1) == 1) {
             fftWindow--;
-            customCfg = true;
         }
-        if (customCfg) {
-            myCfg = kiss_fftr_alloc(fftWindow, 0,0,0);
-        }
-
-        float data[fftWindow];
-        float freqSpectrum[fftWindow/2];
 
-        int16_t maxSig = 0;
-        for (int i = 0; i < fftWindow; i++) {
-            if (audioFrame.data()[i*num_channels] > maxSig) {
-                maxSig = audioFrame.data()[i*num_channels];
-            }
-        }
+        // Show the window size used, for information
+        ui->labelFFTSizeNumber->setText(QVariant(fftWindow).toString());
 
-        // Prepare frequency space vector. The resulting FFT vector is only half as long.
-        kiss_fft_cpx freqData[fftWindow/2];
-
-
-
-        // Copy the first channel's audio into a vector for the FFT display
-        // (only one channel handled at the moment)
-        if (num_samples < fftWindow) {
-            std::fill(&data[num_samples], &data[fftWindow-1], 0);
-        }
 
+        // Get the spectral power distribution of the input samples,
+        // using the given window size and function
+        float freqSpectrum[fftWindow/2];
         FFTTools::WindowType windowType = (FFTTools::WindowType) ui->windowFunction->itemData(ui->windowFunction->currentIndex()).toInt();
-        QVector<float> window;
-        float windowScaleFactor = 1;
-        if (windowType != FFTTools::Window_Rect) {
-            const QString signature = FFTTools::windowSignature(windowType, fftWindow, 0);
-            if (m_windowFunctions.contains(signature)) {
-#ifdef DEBUG_AUDIOSPEC
-                qDebug() << "Re-using window function with signature " << signature;
-#endif
-                window = m_windowFunctions.value(signature);
-            } else {
-#ifdef DEBUG_AUDIOSPEC
-                qDebug() << "Building new window function with signature " << signature;
-#endif
-                window = FFTTools::window(windowType, fftWindow, 0);
-                m_windowFunctions.insert(signature, window);
-            }
-            windowScaleFactor = 1.0/window[fftWindow];
-        }
-
-        // Normalize signals to [0,1] to get correct dB values later on
-        for (int i = 0; i < num_samples && i < fftWindow; i++) {
-            if (windowType != FFTTools::Window_Rect) {
-                data[i] = (float) audioFrame.data()[i*num_channels] / 32767.0f * window[i];
-            } else {
-                data[i] = (float) audioFrame.data()[i*num_channels] / 32767.0f;
-            }
-        }
-
-        // Calculate the Fast Fourier Transform for the input data
-        kiss_fftr(myCfg, data, freqData);
-
-
-        // Logarithmic scale: 20 * log ( 2 * magnitude / N ) with magnitude = sqrt(r² + i²)
-        // with N = FFT size (after FFT, 1/2 window size)
-        for (int i = 0; i < fftWindow/2; i++) {
-            // Logarithmic scale: 20 * log ( 2 * magnitude / N ) with magnitude = sqrt(r² + i²)
-            // with N = FFT size (after FFT, 1/2 window size)
-            freqSpectrum[i] = 20*log(pow(pow(fabs(freqData[i].r * windowScaleFactor),2) + pow(fabs(freqData[i].i * windowScaleFactor),2), .5)/((float)fftWindow/2.0f))/log(10);;
-        }
-
+        m_fftTools.fftNormalized(audioFrame, 0, num_channels, freqSpectrum, windowType, fftWindow, 0);
 
 
         // Draw the spectrum
@@ -303,10 +240,6 @@ QImage AudioSpectrum::renderAudioScope(uint, const QVector<int16_t> audioFrame,
         }
 #endif
 
-        if (customCfg) {
-            free(myCfg);
-        }
-
         return spectrum;
     } else {
         emit signalScopeRenderingFinished(0, 1);
@@ -330,7 +263,7 @@ QImage AudioSpectrum::renderHUD(uint)
     hud.fill(qRgba(0,0,0,0));
 
     QPainter davinci(&hud);
-    davinci.setPen(AbstractAudioScopeWidget::penLight);
+    davinci.setPen(AbstractScopeWidget::penLight);
 
     int y;
     for (int db = -dbDiff; db > m_dBmin; db -= dbDiff) {
@@ -348,20 +281,32 @@ QImage AudioSpectrum::renderHUD(uint)
     davinci.drawText(leftDist + m_innerScopeRect.width() + textDistX, topDist+m_innerScopeRect.height()+6, i18n("%1 dB", m_dBmin));
 
     const uint hzDiff = ceil( ((float)minDistX)/m_innerScopeRect.width() * m_freqMax / 1000 ) * 1000;
-    int x;
+    int x = 0;
+    const int rightBorder = leftDist + m_innerScopeRect.width()-1;
     y = topDist + m_innerScopeRect.height() + textDistY;
-    for (uint hz = 0; hz <= m_freqMax; hz += hzDiff) {
+    for (uint hz = 0; x <= rightBorder; hz += hzDiff) {
+        davinci.setPen(AbstractScopeWidget::penLight);
         x = leftDist + m_innerScopeRect.width() * ((float)hz)/m_freqMax;
-        davinci.drawLine(x, topDist, x, topDist + m_innerScopeRect.height()+6);
-        if (hz < m_freqMax) {
+
+        if (x <= rightBorder) {
+            davinci.drawLine(x, topDist, x, topDist + m_innerScopeRect.height()+6);
+        }
+        if (hz < m_freqMax && x+textDistY < leftDist + m_innerScopeRect.width()) {
             davinci.drawText(x-4, y, QVariant(hz/1000).toString());
         } else {
-            davinci.drawText(x-10, y, i18n("%1 kHz",hz/1000));
+            x = leftDist + m_innerScopeRect.width();
+            davinci.drawLine(x, topDist, x, topDist + m_innerScopeRect.height()+6);
+            davinci.drawText(x-10, y, i18n("%1 kHz").arg((double)m_freqMax/1000, 0, 'f', 1));
         }
 
         if (hz > 0) {
-            for (uint dHz = 1; dHz < 4; dHz++) {
+            // Draw finer lines between the main lines
+            davinci.setPen(AbstractScopeWidget::penLightDots);
+            for (uint dHz = 3; dHz > 0; dHz--) {
                 x = leftDist + m_innerScopeRect.width() * ((float)hz - dHz * hzDiff/4.0f)/m_freqMax;
+                if (x > rightBorder) {
+                    break;
+                }
                 davinci.drawLine(x, topDist, x, topDist + m_innerScopeRect.height()-1);
             }
         }
@@ -372,7 +317,8 @@ QImage AudioSpectrum::renderHUD(uint)
     return hud;
 }
 
-QRect AudioSpectrum::scopeRect() {
+QRect AudioSpectrum::scopeRect()
+{
     m_scopeRect = QRect(
             QPoint(
                     10,                                     // Left
@@ -392,13 +338,6 @@ QRect AudioSpectrum::scopeRect() {
     return m_scopeRect;
 }
 
-
-void AudioSpectrum::slotUpdateCfg()
-{
-    free(m_cfg);
-    m_cfg = kiss_fftr_alloc(ui->windowSize->itemData(ui->windowSize->currentIndex()).toInt(), 0,0,0);
-}
-
 void AudioSpectrum::slotResetMaxFreq()
 {
     m_customFreq = false;
@@ -409,144 +348,71 @@ void AudioSpectrum::slotResetMaxFreq()
 
 ///// EVENTS /////
 
-void AudioSpectrum::mouseMoveEvent(QMouseEvent *event)
+void AudioSpectrum::handleMouseDrag(const QPoint movement, const RescaleDirection rescaleDirection, const Qt::KeyboardModifiers rescaleModifiers)
 {
-    QPoint movement = event->pos()-m_rescaleStartPoint;
+    if (rescaleDirection == AudioSpectrum::North) {
+        // Nort-South direction: Adjust the dB scale
 
-    if (m_rescaleActive) {
-        if (m_rescalePropertiesLocked) {
-            // Direction is known, now adjust parameters
+        if ((rescaleModifiers & Qt::ShiftModifier) == 0) {
 
-            // Reset the starting point to make the next moveEvent relative to the current one
-            m_rescaleStartPoint = event->pos();
+            // By default adjust the min dB value
+            m_dBmin += movement.y();
 
+        } else {
 
-            if (!m_rescaleFirstRescaleDone) {
-                // We have just learned the desired direction; Normalize the movement to one pixel
-                // to avoid a jump by m_rescaleMinDist
-
-                if (movement.x() != 0) {
-                    movement.setX(movement.x() / abs(movement.x()));
-                }
-                if (movement.y() != 0) {
-                    movement.setY(movement.y() / abs(movement.y()));
-                }
-
-                m_rescaleFirstRescaleDone = true;
-            }
-
-            if (m_rescaleClockDirection == AudioSpectrum::North) {
-                // Nort-South direction: Adjust the dB scale
-
-                if ((m_rescaleModifiers & Qt::ShiftModifier) == 0) {
-
-                    // By default adjust the min dB value
-                    m_dBmin += movement.y();
-
-                } else {
-
-                    // Adjust max dB value if Shift is pressed.
-                    m_dBmax += movement.y();
+            // Adjust max dB value if Shift is pressed.
+            m_dBmax += movement.y();
 
-                }
+        }
 
-                // Ensure the dB values lie in [-100, 0] (or rather [MIN_DB_VALUE, 0])
-                // 0 is the upper bound, everything below -70 dB is most likely noise
+        // Ensure the dB values lie in [-100, 0] (or rather [MIN_DB_VALUE, 0])
+        // 0 is the upper bound, everything below -70 dB is most likely noise
+        if (m_dBmax > 0) {
+            m_dBmax = 0;
+        }
+        if (m_dBmin < MIN_DB_VALUE) {
+            m_dBmin = MIN_DB_VALUE;
+        }
+        // Ensure there is at least 6 dB between the minimum and the maximum value;
+        // lower values hardly make sense
+        if (m_dBmax - m_dBmin < 6) {
+            if ((rescaleModifiers & Qt::ShiftModifier) == 0) {
+                // min was adjusted; Try to adjust the max value to maintain the
+                // minimum dB difference of 6 dB
+                m_dBmax = m_dBmin + 6;
                 if (m_dBmax > 0) {
                     m_dBmax = 0;
+                    m_dBmin = -6;
                 }
+            } else {
+                // max was adjusted, adjust min
+                m_dBmin = m_dBmax - 6;
                 if (m_dBmin < MIN_DB_VALUE) {
                     m_dBmin = MIN_DB_VALUE;
+                    m_dBmax = MIN_DB_VALUE+6;
                 }
-                // Ensure there is at least 6 dB between the minimum and the maximum value;
-                // lower values hardly make sense
-                if (m_dBmax - m_dBmin < 6) {
-                    if ((m_rescaleModifiers & Qt::ShiftModifier) == 0) {
-                        // min was adjusted; Try to adjust the max value to maintain the
-                        // minimum dB difference of 6 dB
-                        m_dBmax = m_dBmin + 6;
-                        if (m_dBmax > 0) {
-                            m_dBmax = 0;
-                            m_dBmin = -6;
-                        }
-                    } else {
-                        // max was adjusted, adjust min
-                        m_dBmin = m_dBmax - 6;
-                        if (m_dBmin < MIN_DB_VALUE) {
-                            m_dBmin = MIN_DB_VALUE;
-                            m_dBmax = MIN_DB_VALUE+6;
-                        }
-                    }
-                }
-
-                forceUpdateHUD();
-                forceUpdateScope();
-
-            } else if (m_rescaleClockDirection == AudioSpectrum::East) {
-                // East-West direction: Adjust the maximum frequency
-                m_freqMax -= 100*movement.x();
-                if (m_freqMax < MIN_FREQ_VALUE) {
-                    m_freqMax = MIN_FREQ_VALUE;
-                }
-                if (m_freqMax > MAX_FREQ_VALUE) {
-                    m_freqMax = MAX_FREQ_VALUE;
-                }
-                m_customFreq = true;
-
-                forceUpdateHUD();
-                forceUpdateScope();
             }
+        }
 
+        forceUpdateHUD();
+        forceUpdateScope();
 
-        } else {
-            // Detect the movement direction here.
-            // This algorithm relies on the aspect ratio of dy/dx (size and signum).
-            if (movement.manhattanLength() > m_rescaleMinDist) {
-                float diff = ((float) movement.y())/movement.x();
-
-                if (abs(diff) > m_rescaleVerticalThreshold || movement.x() == 0) {
-                    m_rescaleClockDirection = AudioSpectrum::North;
-                } else if (abs(diff) < 1/m_rescaleVerticalThreshold) {
-                    m_rescaleClockDirection = AudioSpectrum::East;
-                } else if (diff < 0) {
-                    m_rescaleClockDirection = AudioSpectrum::Northeast;
-                } else {
-                    m_rescaleClockDirection = AudioSpectrum::Southeast;
-                }
-#ifdef DEBUG_AUDIOSPEC
-                qDebug() << "Diff is " << diff << "; chose " << directions[m_rescaleClockDirection] << " as direction";
-#endif
-                m_rescalePropertiesLocked = true;
-            }
+    } else if (rescaleDirection == AudioSpectrum::East) {
+        // East-West direction: Adjust the maximum frequency
+        m_freqMax -= 100*movement.x();
+        if (m_freqMax < MIN_FREQ_VALUE) {
+            m_freqMax = MIN_FREQ_VALUE;
         }
-    } else {
-        AbstractAudioScopeWidget::mouseMoveEvent(event);
-    }
-}
-
-void AudioSpectrum::mousePressEvent(QMouseEvent *event)
-{
-    if (event->button() == Qt::LeftButton) {
-        // Rescaling mode starts
-        m_rescaleActive = true;
-        m_rescalePropertiesLocked = false;
-        m_rescaleFirstRescaleDone = false;
-        m_rescaleStartPoint = event->pos();
-        m_rescaleModifiers = event->modifiers();
+        if (m_freqMax > MAX_FREQ_VALUE) {
+            m_freqMax = MAX_FREQ_VALUE;
+        }
+        m_customFreq = true;
 
-    } else {
-        AbstractAudioScopeWidget::mousePressEvent(event);
+        forceUpdateHUD();
+        forceUpdateScope();
     }
 }
 
-void AudioSpectrum::mouseReleaseEvent(QMouseEvent *event)
-{
-    m_rescaleActive = false;
-    m_rescalePropertiesLocked = false;
-
-    AbstractAudioScopeWidget::mouseReleaseEvent(event);
-}
-
 
 #ifdef DEBUG_AUDIOSPEC
 #undef DEBUG_AUDIOSPEC