]> git.sesse.net Git - kdenlive/commitdiff
Audio Spectrum: Different Window functions added (Rectangle, Triangle, and Hamming)
authorSimon A. Eugster <simon.eu@gmail.com>
Sun, 5 Dec 2010 20:57:11 +0000 (20:57 +0000)
committerSimon A. Eugster <simon.eu@gmail.com>
Sun, 5 Dec 2010 20:57:11 +0000 (20:57 +0000)
svn path=/trunk/kdenlive/; revision=5135

src/CMakeLists.txt
src/abstractscopewidget.h
src/audioscopes/audiospectrum.cpp
src/audioscopes/audiospectrum.h
src/audioscopes/ffttools.cpp [new file with mode: 0644]
src/audioscopes/ffttools.h [new file with mode: 0644]
src/widgets/audiospectrum_ui.ui

index 82c7ef1bff30566bd3bd10c58b77c8daa27a60f0..162e5e57ada3fe9aa8965f9004cb9ea0922aec73 100644 (file)
@@ -222,6 +222,7 @@ set(kdenlive_SRCS
   abstractscopewidget.cpp
   audioscopes/abstractaudioscopewidget.cpp
   audioscopes/audiospectrum.cpp
+  audioscopes/ffttools.cpp
   rebuildgroupcommand.cpp
   colorscopes/abstractgfxscopewidget.cpp
   colorscopes/histogram.cpp
index bee68863a02725d13f078122e5fe8d163d756393..030eafbbbf1cfbf347714019c3594b06478e47ff 100644 (file)
@@ -136,7 +136,8 @@ protected:
     ///// Unimplemented Methods /////
 
     /** Where on the widget we can paint in.
-        May also update other variables that depend on the widget's size.  */
+        May also update other variables, like m_scopeRect or custom ones,
+        that have to change together with the widget's size.  */
     virtual QRect scopeRect() = 0;
 
     /** @brief HUD renderer. Must emit signalHUDRenderingFinished(). @see renderScope */
index 51893e6f4e922773834ee42517612ca2c0b5e48c..09465f92a3fcb998e10a6595b19fd0a0780a44ea 100644 (file)
@@ -8,7 +8,10 @@
  *   (at your option) any later version.                                   *
  ***************************************************************************/
 
+
+
 #include "audiospectrum.h"
+#include "ffttools.h"
 #include "tools/kiss_fftr.h"
 
 #include <QMenu>
 #include <QMouseEvent>
 
 #include <iostream>
-//#include <fstream>
 
-//bool fileWritten = false;
+// Enables debugging, like writing a GNU Octave .m file to /tmp
+//#define DEBUG_AUDIOSPEC
+#ifdef DEBUG_AUDIOSPEC
+#include <fstream>
+bool fileWritten = false;
+#endif
+
+#define MIN_DB_VALUE -120
 
 const QString AudioSpectrum::directions[] =  {"North", "Northeast", "East", "Southeast"};
 
 AudioSpectrum::AudioSpectrum(QWidget *parent) :
         AbstractAudioScopeWidget(false, parent),
+        m_windowFunctions(),
         m_rescaleMinDist(8),
         m_rescaleVerticalThreshold(2.0f),
         m_rescaleActive(false),
@@ -37,23 +47,11 @@ AudioSpectrum::AudioSpectrum(QWidget *parent) :
     m_freqMax = 10000;
 
 
-    m_aLin = new QAction(i18n("Linear scale"), this);
-    m_aLin->setCheckable(true);
-    m_aLog = new QAction(i18n("Logarithmic scale"), this);
-    m_aLog->setCheckable(true);
-
-    m_agScale = new QActionGroup(this);
-    m_agScale->addAction(m_aLin);
-    m_agScale->addAction(m_aLog);
-
     m_aLockHz = new QAction(i18n("Lock maximum frequency"), this);
     m_aLockHz->setCheckable(true);
     m_aLockHz->setEnabled(false);
 
 
-//    m_menu->addSeparator()->setText(i18n("Scale"));
-//    m_menu->addAction(m_aLin);
-//    m_menu->addAction(m_aLog);
     m_menu->addSeparator();
     m_menu->addAction(m_aLockHz);
 
@@ -63,7 +61,14 @@ AudioSpectrum::AudioSpectrum(QWidget *parent) :
     ui->windowSize->addItem("1024", QVariant(1024));
     ui->windowSize->addItem("2048", QVariant(2048));
 
+    ui->windowFunction->addItem(i18n("Rectangular window"), FFTTools::Window_Rect);
+    ui->windowFunction->addItem(i18n("Triangular window"), FFTTools::Window_Triangle);
+    ui->windowFunction->addItem(i18n("Hamming window"), FFTTools::Window_Hamming);
+
+
     m_cfg = kiss_fftr_alloc(ui->windowSize->itemData(ui->windowSize->currentIndex()).toInt(), 0,0,0);
+    //m_windowFunctions.insert("tri512", FFTTools::window(FFTTools::Window_Hamming, 8, 0));
+    // TODO Window function cache
 
 
     bool b = true;
@@ -77,9 +82,6 @@ AudioSpectrum::~AudioSpectrum()
     writeConfig();
 
     free(m_cfg);
-    delete m_agScale;
-    delete m_aLin;
-    delete m_aLog;
     delete m_aLockHz;
 }
 
@@ -89,30 +91,18 @@ void AudioSpectrum::readConfig()
 
     KSharedConfigPtr config = KGlobal::config();
     KConfigGroup scopeConfig(config, AbstractScopeWidget::configName());
-    QString scale = scopeConfig.readEntry("scale");
-    if (scale == "lin") {
-        m_aLin->setChecked(true);
-    } else {
-        m_aLog->setChecked(true);
-    }
     m_aLockHz->setChecked(scopeConfig.readEntry("lockHz", false));
     ui->windowSize->setCurrentIndex(scopeConfig.readEntry("windowSize", 0));
     m_dBmax = scopeConfig.readEntry("dBmax", 0);
     m_dBmin = scopeConfig.readEntry("dBmin", -70);
-
+    ui->windowFunction->setCurrentIndex(scopeConfig.readEntry("windowFunction", 0));
 }
 void AudioSpectrum::writeConfig()
 {
     KSharedConfigPtr config = KGlobal::config();
     KConfigGroup scopeConfig(config, AbstractScopeWidget::configName());
-    QString scale;
-    if (m_aLin->isChecked()) {
-        scale = "lin";
-    } else {
-        scale = "log";
-    }
-    scopeConfig.writeEntry("scale", scale);
     scopeConfig.writeEntry("windowSize", ui->windowSize->currentIndex());
+    scopeConfig.writeEntry("windowFunction", ui->windowFunction->currentIndex());
     scopeConfig.writeEntry("lockHz", m_aLockHz->isChecked());
     scopeConfig.writeEntry("dBmax", m_dBmax);
     scopeConfig.writeEntry("dBmin", m_dBmin);
@@ -158,46 +148,59 @@ QImage AudioSpectrum::renderAudioScope(uint, const QVector<int16_t> audioFrame,
             }
         }
 
-        // The resulting FFT vector is only half as long
+        // 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);
         }
+
+        FFTTools::WindowType windowType = (FFTTools::WindowType) ui->windowFunction->itemData(ui->windowFunction->currentIndex()).toInt();
+        QVector<float> window;
+        float windowScaleFactor = 1;
+        if (windowType != FFTTools::Window_Rect) {
+            window = FFTTools::window(windowType, fftWindow, 0);
+            windowScaleFactor = 1.0/window[fftWindow];
+            qDebug() << "Using a window scaling factor of " << windowScaleFactor;
+        }
+
+        // Normalize signals to [0,1] to get correct dB values later on
         for (int i = 0; i < num_samples && i < fftWindow; i++) {
-            // Normalize signals to [0,1] to get correct dB values later on
-            data[i] = (float) audioFrame.data()[i*num_channels] / 32767.0f;
+            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);
 
 
-        float val;
-        // Get the minimum and the maximum value of the Fourier transformed (for scaling)
+        float max = -100;
+        // 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++) {
-            if (m_aLog->isChecked()) {
-                // Logarithmic scale: 20 * log ( 2 * magnitude / N )
-                // with N = FFT size (after FFT, 1/2 window size)
-                val = 20*log(pow(pow(fabs(freqData[i].r),2) + pow(fabs(freqData[i].i),2), .5)/((float)fftWindow/2.0f))/log(10);
-            } else {
-                // sqrt(r² + i²)
-                val = pow(pow(fabs(freqData[i].r),2) + pow(fabs(freqData[i].i),2), .5);
-            }
-            freqSpectrum[i] = val;
+            // 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);;
+            if (freqSpectrum[i] > max) { max = freqSpectrum[i]; }
         }
+        qDebug() << "Maximum (dB) is " << max;
 
 
 
         // Draw the spectrum
-        QImage spectrum(scopeRect().size(), QImage::Format_ARGB32);
+        QImage spectrum(m_scopeRect.size(), QImage::Format_ARGB32);
         spectrum.fill(qRgba(0,0,0,0));
-        uint w = scopeRect().size().width();
-        uint h = scopeRect().size().height();
+        uint w = m_innerScopeRect.width();
+        uint h = m_innerScopeRect.height();
         float x;
+        float val;
         for (uint i = 0; i < w; i++) {
 
             x = i/((float) w) * fftWindow/2;
@@ -218,7 +221,7 @@ QImage AudioSpectrum::renderAudioScope(uint, const QVector<int16_t> audioFrame,
 
         emit signalScopeRenderingFinished(start.elapsed(), 1);
 
-        /*
+#ifdef DEBUG_AUDIOSPEC
         if (!fileWritten || true) {
             std::ofstream mFile;
             mFile.open("/tmp/freq.m");
@@ -245,7 +248,7 @@ QImage AudioSpectrum::renderAudioScope(uint, const QVector<int16_t> audioFrame,
         } else {
             qDebug() << "File already written.";
         }
-        //*/
+#endif
 
         if (customCfg) {
             free(myCfg);
@@ -261,12 +264,11 @@ QImage AudioSpectrum::renderHUD(uint)
 {
     QTime start = QTime::currentTime();
 
-    const QRect rect = scopeRect();
     // Minimum distance between two lines
     const uint minDistY = 30;
     const uint minDistX = 40;
     const uint textDist = 5;
-    const uint dbDiff = ceil((float)minDistY/rect.height() * (m_dBmax-m_dBmin));
+    const uint dbDiff = ceil((float)minDistY/m_innerScopeRect.height() * (m_dBmax-m_dBmin));
 
     QImage hud(AbstractAudioScopeWidget::rect().size(), QImage::Format_ARGB32);
     hud.fill(qRgba(0,0,0,0));
@@ -274,22 +276,24 @@ QImage AudioSpectrum::renderHUD(uint)
     QPainter davinci(&hud);
     davinci.setPen(AbstractAudioScopeWidget::penLight);
 
+    // TODO lower boundary
     int y;
     for (int db = -dbDiff; db > m_dBmin; db -= dbDiff) {
-        y = rect.height() * ((float)db)/(m_dBmin - m_dBmax);
-        davinci.drawLine(0, y, rect.width()-1, y);
-        davinci.drawText(rect.width() + textDist, y + 8, i18n("%1 dB", m_dBmax + db));
+        y = m_innerScopeRect.height() * ((float)db)/(m_dBmin - m_dBmax);
+        davinci.drawLine(0, y, m_innerScopeRect.width()-1, y);
+        davinci.drawText(m_innerScopeRect.width() + textDist, y + 6, i18n("%1 dB", m_dBmax + db));
     }
 
 
-    const uint hzDiff = ceil( ((float)minDistX)/rect.width() * m_freqMax / 1000 ) * 1000;
+    // TODO more vertical lines in-between
+    const uint hzDiff = ceil( ((float)minDistX)/m_innerScopeRect.width() * m_freqMax / 1000 ) * 1000;
     int x;
     for (uint hz = hzDiff; hz < m_freqMax; hz += hzDiff) {
-        x = rect.width() * ((float)hz)/m_freqMax;
-        davinci.drawLine(x, 0, x, rect.height()+4);
-        davinci.drawText(x-4, rect.height() + 20, QVariant(hz/1000).toString());
+        x = m_innerScopeRect.width() * ((float)hz)/m_freqMax;
+        davinci.drawLine(x, 0, x, m_innerScopeRect.height()+4);
+        davinci.drawText(x-4, m_innerScopeRect.height() + 20, QVariant(hz/1000).toString());
     }
-    davinci.drawText(rect.width(), rect.height() + 20, "[kHz]");
+    davinci.drawText(m_innerScopeRect.width(), m_innerScopeRect.height() + 20, "[kHz]");
 
 
     emit signalHUDRenderingFinished(start.elapsed(), 1);
@@ -297,7 +301,20 @@ QImage AudioSpectrum::renderHUD(uint)
 }
 
 QRect AudioSpectrum::scopeRect() {
-    return QRect(QPoint(0, 0), AbstractAudioScopeWidget::rect().size() - m_distance);
+    m_innerScopeRect = QRect(
+            QPoint(
+                    0,                                      // Left
+                    ui->verticalSpacer->geometry().top()    // Top
+            ), QPoint(
+                    ui->verticalSpacer->geometry().right()-70,
+                    ui->verticalSpacer->geometry().bottom()-40
+            )
+    );
+    m_scopeRect = QRect(
+            m_innerScopeRect.topLeft(),
+            AbstractAudioScopeWidget::rect().bottomRight()
+    );
+    return m_scopeRect;
 }
 
 
@@ -351,13 +368,13 @@ void AudioSpectrum::mouseMoveEvent(QMouseEvent *event)
 
                 }
 
-                // Ensure the dB values lie in [-100, 0]
+                // 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 < -100) {
-                    m_dBmin = -100;
+                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
@@ -373,9 +390,9 @@ void AudioSpectrum::mouseMoveEvent(QMouseEvent *event)
                     } else {
                         // max was adjusted, adjust min
                         m_dBmin = m_dBmax - 6;
-                        if (m_dBmin < -100) {
-                            m_dBmin = -100;
-                            m_dBmax = -100+6;
+                        if (m_dBmin < MIN_DB_VALUE) {
+                            m_dBmin = MIN_DB_VALUE;
+                            m_dBmax = MIN_DB_VALUE+6;
                         }
                     }
                 }
@@ -401,7 +418,9 @@ void AudioSpectrum::mouseMoveEvent(QMouseEvent *event)
                 } else {
                     m_rescaleClockDirection = AudioSpectrum::Southeast;
                 }
-//                qDebug() << "Diff is " << diff << "; chose " << directions[m_rescaleClockDirection] << " as direction";
+#ifdef DEBUG_AUDIOSPEC
+                qDebug() << "Diff is " << diff << "; chose " << directions[m_rescaleClockDirection] << " as direction";
+#endif
                 m_rescalePropertiesLocked = true;
             }
         }
@@ -432,3 +451,8 @@ void AudioSpectrum::mouseReleaseEvent(QMouseEvent *event)
 
     AbstractAudioScopeWidget::mouseReleaseEvent(event);
 }
+
+
+#ifdef DEBUG_AUDIOSPEC
+#undef DEBUG_AUDIOSPEC
+#endif
index 3e714895ee8cedb991b2ddee479dade1b9d0a543..61a738317901e4ff056940123a507f9617661b99 100644 (file)
 #define AUDIOSPECTRUM_H
 
 #include <QtCore>
+#include <QVector>
+#include <QHash>
 
 #include "abstractaudioscopewidget.h"
 #include "ui_audiospectrum_ui.h"
 #include "tools/kiss_fftr.h"
 
 class AudioSpectrum_UI;
-
 class AudioSpectrum : public AbstractAudioScopeWidget {
     Q_OBJECT
 
@@ -53,14 +54,15 @@ protected:
 private:
     Ui::AudioSpectrum_UI *ui;
     kiss_fftr_cfg m_cfg;
+    QHash<QString, QVector<float> > m_windowFunctions;
 
     QAction *m_aLockHz;
-    QAction *m_aLin;
-    QAction *m_aLog;
-    QActionGroup *m_agScale;
 
     QSize m_distance;
 
+    // Contains the plot only; m_scopeRect contains text and widgets as well
+    QRect m_innerScopeRect;
+
     /** Lower bound for the dB value to display */
     int m_dBmin;
     /** Upper bound (max: 0) */
diff --git a/src/audioscopes/ffttools.cpp b/src/audioscopes/ffttools.cpp
new file mode 100644 (file)
index 0000000..160dc59
--- /dev/null
@@ -0,0 +1,89 @@
+/***************************************************************************
+ *   Copyright (C) 2010 by Simon Andreas Eugster (simon.eu@gmail.com)      *
+ *   This file is part of kdenlive. See www.kdenlive.org.                  *
+ *                                                                         *
+ *   This program is free software; you can redistribute it and/or modify  *
+ *   it under the terms of the GNU General Public License as published by  *
+ *   the Free Software Foundation; either version 2 of the License, or     *
+ *   (at your option) any later version.                                   *
+ ***************************************************************************/
+
+#include <math.h>
+
+#include "ffttools.h"
+
+//#define DEBUG_FFTTOOLS
+#ifdef DEBUG_FFTTOOLS
+#include <QDebug>
+#endif
+
+FFTTools::FFTTools()
+{
+}
+
+// http://cplusplus.syntaxerrors.info/index.php?title=Cannot_declare_member_function_%E2%80%98static_int_Foo::bar%28%29%E2%80%99_to_have_static_linkage
+const QVector<float> FFTTools::window(WindowType windowType, const int size, const float param)
+{
+    // Deliberately avoid converting size to a float
+    // to keep mid an integer.
+    float mid = (size-1)/2;
+    float max = size-1;
+    QVector<float> window;
+
+    switch (windowType) {
+    case Window_Rect:
+        return QVector<float>(size+1, 1);
+        break;
+    case Window_Triangle:
+        window = QVector<float>(size+1);
+
+        for (int x = 0; x < mid; x++) {
+            window[x] = x/mid + (mid-x)/mid*param;
+        }
+        for (int x = mid; x < size; x++) {
+            window[x] = (x-mid)/(max-mid) * param + (max-x)/(max-mid);
+        }
+        window[size] = .5 + param/2;
+
+#ifdef DEBUG_FFTTOOLS
+        qDebug() << "Triangle window (factor " << window[size] << "):";
+        for (int i = 0; i < size; i++) {
+            qDebug() << window[i];
+        }
+        qDebug() << "Triangle window end.";
+#endif
+
+        return window;
+        break;
+    case Window_Hamming:
+        // Use a quick version of the Hamming window here: Instead of
+        // interpolating values between (-max/2) and (max/2)
+        // we use integer values instead, ranging from -mid to (max-mid).
+        window = QVector<float>(size+1);
+
+        for (int x = 0; x < size; x++) {
+            window[x] = .54 + .46 * cos( 2*M_PI*(x-mid) / size );
+        }
+
+        // Integrating the cosine over the window function results in
+        // an area of 0; So only the constant factor 0.54 counts.
+        window[size] = .54;
+
+#ifdef DEBUG_FFTTOOLS
+        qDebug() << "Hanning window (factor " << window[size] << "):";
+        for (int i = 0; i < size; i++) {
+            qDebug() << window[i];
+        }
+        qDebug() << "Hanning window end.";
+#endif
+
+        return window;
+        break;
+    }
+    Q_ASSERT(false);
+    return QVector<float>();
+}
+
+#ifdef DEBUG_FFTTOOLS
+#undef DEBUG_FFTTOOLS
+#endif
diff --git a/src/audioscopes/ffttools.h b/src/audioscopes/ffttools.h
new file mode 100644 (file)
index 0000000..acc8e6e
--- /dev/null
@@ -0,0 +1,40 @@
+/***************************************************************************
+ *   Copyright (C) 2010 by Simon Andreas Eugster (simon.eu@gmail.com)      *
+ *   This file is part of kdenlive. See www.kdenlive.org.                  *
+ *                                                                         *
+ *   This program is free software; you can redistribute it and/or modify  *
+ *   it under the terms of the GNU General Public License as published by  *
+ *   the Free Software Foundation; either version 2 of the License, or     *
+ *   (at your option) any later version.                                   *
+ ***************************************************************************/
+
+#ifndef FFTTOOLS_H
+#define FFTTOOLS_H
+
+#include <QVector>
+
+class FFTTools
+{
+public:
+    FFTTools();
+
+    enum WindowType { Window_Rect, Window_Triangle, Window_Hamming };
+
+    /** Creates a vector containing the factors for the selected window functions.
+        The last element in the vector (at position size+1) contains the area of
+        this window function compared to the rectangular window (e.g. for a triangular
+        window the factor will be 0.5).
+        Knowing this factor is important for the Fourier Transformation as the
+        values in the frequency domain will be scaled by this factor and need to be
+        re-scaled for proper dB display.
+        The additional parameter describes:
+        * Nothing for the Rectangular window
+        * The left and right start values for the Triangular window (i.e. ranges between param and 1;
+          default is 0)
+        * Nothing for the Hamming window
+    */
+    static const QVector<float> window(WindowType windowType, const int size, const float param);
+
+};
+
+#endif // FFTTOOLS_H
index c7f7082c830d62e53eab361de2cd059bba747919..39dcb349836811fd5d989437bc2fb420523fd2ab 100644 (file)
@@ -43,6 +43,9 @@
      </property>
     </spacer>
    </item>
+   <item row="1" column="1">
+    <widget class="QComboBox" name="windowFunction"/>
+   </item>
   </layout>
  </widget>
  <resources/>