demos/spectrum/app/spectrumanalyser.cpp
changeset 25 e24348a560a6
child 29 b72c6db6890b
equal deleted inserted replaced
23:89e065397ea6 25:e24348a560a6
       
     1 /****************************************************************************
       
     2 **
       
     3 ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
       
     4 ** All rights reserved.
       
     5 ** Contact: Nokia Corporation (qt-info@nokia.com)
       
     6 **
       
     7 ** This file is part of the examples of the Qt Toolkit.
       
     8 **
       
     9 ** $QT_BEGIN_LICENSE:LGPL$
       
    10 ** No Commercial Usage
       
    11 ** This file contains pre-release code and may not be distributed.
       
    12 ** You may use this file in accordance with the terms and conditions
       
    13 ** contained in the Technology Preview License Agreement accompanying
       
    14 ** this package.
       
    15 **
       
    16 ** GNU Lesser General Public License Usage
       
    17 ** Alternatively, this file may be used under the terms of the GNU Lesser
       
    18 ** General Public License version 2.1 as published by the Free Software
       
    19 ** Foundation and appearing in the file LICENSE.LGPL included in the
       
    20 ** packaging of this file.  Please review the following information to
       
    21 ** ensure the GNU Lesser General Public License version 2.1 requirements
       
    22 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
       
    23 **
       
    24 ** In addition, as a special exception, Nokia gives you certain additional
       
    25 ** rights.  These rights are described in the Nokia Qt LGPL Exception
       
    26 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
       
    27 **
       
    28 ** If you have questions regarding the use of this file, please contact
       
    29 ** Nokia at qt-info@nokia.com.
       
    30 **
       
    31 **
       
    32 **
       
    33 **
       
    34 **
       
    35 **
       
    36 **
       
    37 **
       
    38 ** $QT_END_LICENSE$
       
    39 **
       
    40 ****************************************************************************/
       
    41 
       
    42 #include "spectrumanalyser.h"
       
    43 #include "utils.h"
       
    44 
       
    45 #include <QtCore/qmath.h>
       
    46 #include <QtCore/qmetatype.h>
       
    47 #include <QtMultimedia/QAudioFormat>
       
    48 #include <QThread>
       
    49 
       
    50 #include "fftreal_wrapper.h"
       
    51 
       
    52 SpectrumAnalyserThread::SpectrumAnalyserThread(QObject *parent)
       
    53     :   QObject(parent)
       
    54 #ifndef DISABLE_FFT
       
    55     ,   m_fft(new FFTRealWrapper)
       
    56 #endif
       
    57     ,   m_numSamples(SpectrumLengthSamples)
       
    58     ,   m_windowFunction(DefaultWindowFunction)
       
    59     ,   m_window(SpectrumLengthSamples, 0.0)
       
    60     ,   m_input(SpectrumLengthSamples, 0.0)
       
    61     ,   m_output(SpectrumLengthSamples, 0.0)
       
    62     ,   m_spectrum(SpectrumLengthSamples)
       
    63 #ifdef SPECTRUM_ANALYSER_SEPARATE_THREAD
       
    64     ,   m_thread(new QThread(this))
       
    65 #endif
       
    66 {
       
    67 #ifdef SPECTRUM_ANALYSER_SEPARATE_THREAD
       
    68     moveToThread(m_thread);
       
    69     m_thread->start();
       
    70 #endif
       
    71     calculateWindow();
       
    72 }
       
    73 
       
    74 SpectrumAnalyserThread::~SpectrumAnalyserThread()
       
    75 {
       
    76 #ifndef DISABLE_FFT
       
    77     delete m_fft;
       
    78 #endif
       
    79 }
       
    80 
       
    81 void SpectrumAnalyserThread::setWindowFunction(WindowFunction type)
       
    82 {
       
    83     m_windowFunction = type;
       
    84     calculateWindow();
       
    85 }
       
    86 
       
    87 void SpectrumAnalyserThread::calculateWindow()
       
    88 {
       
    89     for (int i=0; i<m_numSamples; ++i) {
       
    90         DataType x = 0.0;
       
    91 
       
    92         switch (m_windowFunction) {
       
    93         case NoWindow:
       
    94             x = 1.0;
       
    95             break;
       
    96         case HannWindow:
       
    97             x = 0.5 * (1 - qCos((2 * M_PI * i) / (m_numSamples - 1)));
       
    98             break;
       
    99         default:
       
   100             Q_ASSERT(false);
       
   101         }
       
   102 
       
   103         m_window[i] = x;
       
   104     }
       
   105 }
       
   106 
       
   107 void SpectrumAnalyserThread::calculateSpectrum(const QByteArray &buffer,
       
   108                                                 int inputFrequency,
       
   109                                                 int bytesPerSample)
       
   110 {
       
   111 #ifndef DISABLE_FFT
       
   112     Q_ASSERT(buffer.size() == m_numSamples * bytesPerSample);
       
   113 
       
   114     // Initialize data array
       
   115     const char *ptr = buffer.constData();
       
   116     for (int i=0; i<m_numSamples; ++i) {
       
   117         const qint16 pcmSample = *reinterpret_cast<const qint16*>(ptr);
       
   118         // Scale down to range [-1.0, 1.0]
       
   119         const DataType realSample = pcmToReal(pcmSample);
       
   120         const DataType windowedSample = realSample * m_window[i];
       
   121         m_input[i] = windowedSample;
       
   122         ptr += bytesPerSample;
       
   123     }
       
   124 
       
   125     // Calculate the FFT
       
   126     m_fft->calculateFFT(m_output.data(), m_input.data());
       
   127 
       
   128     // Analyse output to obtain amplitude and phase for each frequency
       
   129     for (int i=2; i<=m_numSamples/2; ++i) {
       
   130         // Calculate frequency of this complex sample
       
   131         m_spectrum[i].frequency = qreal(i * inputFrequency) / (m_numSamples);
       
   132 
       
   133         const qreal real = m_output[i];
       
   134         qreal imag = 0.0;
       
   135         if (i>0 && i<m_numSamples/2)
       
   136             imag = m_output[m_numSamples/2 + i];
       
   137 
       
   138         const qreal magnitude = sqrt(real*real + imag*imag);
       
   139         qreal amplitude = SpectrumAnalyserMultiplier * log(magnitude);
       
   140 
       
   141         // Bound amplitude to [0.0, 1.0]
       
   142         m_spectrum[i].clipped = (amplitude > 1.0);
       
   143         amplitude = qMax(qreal(0.0), amplitude);
       
   144         amplitude = qMin(qreal(1.0), amplitude);
       
   145         m_spectrum[i].amplitude = amplitude;
       
   146     }
       
   147 #endif
       
   148 
       
   149     emit calculationComplete(m_spectrum);
       
   150 }
       
   151 
       
   152 
       
   153 //=============================================================================
       
   154 // SpectrumAnalyser
       
   155 //=============================================================================
       
   156 
       
   157 SpectrumAnalyser::SpectrumAnalyser(QObject *parent)
       
   158     :   QObject(parent)
       
   159     ,   m_thread(new SpectrumAnalyserThread(this))
       
   160     ,   m_state(Idle)
       
   161 #ifdef DUMP_SPECTRUMANALYSER
       
   162     ,   m_count(0)
       
   163 #endif
       
   164 {
       
   165     CHECKED_CONNECT(m_thread, SIGNAL(calculationComplete(FrequencySpectrum)),
       
   166                     this, SLOT(calculationComplete(FrequencySpectrum)));
       
   167 }
       
   168 
       
   169 SpectrumAnalyser::~SpectrumAnalyser()
       
   170 {
       
   171 
       
   172 }
       
   173 
       
   174 #ifdef DUMP_SPECTRUMANALYSER
       
   175 void SpectrumAnalyser::setOutputPath(const QString &outputDir)
       
   176 {
       
   177     m_outputDir.setPath(outputDir);
       
   178     m_textFile.setFileName(m_outputDir.filePath("spectrum.txt"));
       
   179     m_textFile.open(QIODevice::WriteOnly | QIODevice::Text);
       
   180     m_textStream.setDevice(&m_textFile);
       
   181 }
       
   182 #endif
       
   183 
       
   184 //-----------------------------------------------------------------------------
       
   185 // Public functions
       
   186 //-----------------------------------------------------------------------------
       
   187 
       
   188 void SpectrumAnalyser::setWindowFunction(WindowFunction type)
       
   189 {
       
   190     const bool b = QMetaObject::invokeMethod(m_thread, "setWindowFunction",
       
   191                               Qt::AutoConnection,
       
   192                               Q_ARG(WindowFunction, type));
       
   193     Q_ASSERT(b);
       
   194     Q_UNUSED(b) // suppress warnings in release builds
       
   195 }
       
   196 
       
   197 void SpectrumAnalyser::calculate(const QByteArray &buffer,
       
   198                          const QAudioFormat &format)
       
   199 {
       
   200     // QThread::currentThread is marked 'for internal use only', but
       
   201     // we're only using it for debug output here, so it's probably OK :)
       
   202     SPECTRUMANALYSER_DEBUG << "SpectrumAnalyser::calculate"
       
   203                            << QThread::currentThread()
       
   204                            << "state" << m_state;
       
   205 
       
   206     if (isReady()) {
       
   207         Q_ASSERT(isPCMS16LE(format));
       
   208 
       
   209         const int bytesPerSample = format.sampleSize() * format.channels() / 8;
       
   210 
       
   211 #ifdef DUMP_SPECTRUMANALYSER
       
   212         m_count++;
       
   213         const QString pcmFileName = m_outputDir.filePath(QString("spectrum_%1.pcm").arg(m_count, 4, 10, QChar('0')));
       
   214         QFile pcmFile(pcmFileName);
       
   215         pcmFile.open(QIODevice::WriteOnly);
       
   216         const int bufferLength = m_numSamples * bytesPerSample;
       
   217         pcmFile.write(buffer, bufferLength);
       
   218 
       
   219         m_textStream << "TimeDomain " << m_count << "\n";
       
   220         const qint16* input = reinterpret_cast<const qint16*>(buffer);
       
   221         for (int i=0; i<m_numSamples; ++i) {
       
   222             m_textStream << i << "\t" << *input << "\n";
       
   223             input += format.channels();
       
   224         }
       
   225 #endif
       
   226 
       
   227         m_state = Busy;
       
   228 
       
   229         // Invoke SpectrumAnalyserThread::calculateSpectrum using QMetaObject.  If
       
   230         // m_thread is in a different thread from the current thread, the
       
   231         // calculation will be done in the child thread.
       
   232         // Once the calculation is finished, a calculationChanged signal will be
       
   233         // emitted by m_thread.
       
   234         const bool b = QMetaObject::invokeMethod(m_thread, "calculateSpectrum",
       
   235                                   Qt::AutoConnection,
       
   236                                   Q_ARG(QByteArray, buffer),
       
   237                                   Q_ARG(int, format.frequency()),
       
   238                                   Q_ARG(int, bytesPerSample));
       
   239         Q_ASSERT(b);
       
   240         Q_UNUSED(b) // suppress warnings in release builds
       
   241 
       
   242 #ifdef DUMP_SPECTRUMANALYSER
       
   243         m_textStream << "FrequencySpectrum " << m_count << "\n";
       
   244         FrequencySpectrum::const_iterator x = m_spectrum.begin();
       
   245         for (int i=0; i<m_numSamples; ++i, ++x)
       
   246             m_textStream << i << "\t"
       
   247                          << x->frequency << "\t"
       
   248                          << x->amplitude<< "\t"
       
   249                          << x->phase << "\n";
       
   250 #endif
       
   251     }
       
   252 }
       
   253 
       
   254 bool SpectrumAnalyser::isReady() const
       
   255 {
       
   256     return (Idle == m_state);
       
   257 }
       
   258 
       
   259 void SpectrumAnalyser::cancelCalculation()
       
   260 {
       
   261     if (Busy == m_state)
       
   262         m_state = Cancelled;
       
   263 }
       
   264 
       
   265 
       
   266 //-----------------------------------------------------------------------------
       
   267 // Private slots
       
   268 //-----------------------------------------------------------------------------
       
   269 
       
   270 void SpectrumAnalyser::calculationComplete(const FrequencySpectrum &spectrum)
       
   271 {
       
   272     Q_ASSERT(Idle != m_state);
       
   273     if (Busy == m_state)
       
   274         emit spectrumChanged(spectrum);
       
   275     m_state = Idle;
       
   276 }
       
   277 
       
   278 
       
   279 
       
   280