1 | /****************************************************************************
|
---|
2 | **
|
---|
3 | ** Copyright (C) 2011 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:BSD$
|
---|
10 | ** You may use this file under the terms of the BSD license as follows:
|
---|
11 | **
|
---|
12 | ** "Redistribution and use in source and binary forms, with or without
|
---|
13 | ** modification, are permitted provided that the following conditions are
|
---|
14 | ** met:
|
---|
15 | ** * Redistributions of source code must retain the above copyright
|
---|
16 | ** notice, this list of conditions and the following disclaimer.
|
---|
17 | ** * Redistributions in binary form must reproduce the above copyright
|
---|
18 | ** notice, this list of conditions and the following disclaimer in
|
---|
19 | ** the documentation and/or other materials provided with the
|
---|
20 | ** distribution.
|
---|
21 | ** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
|
---|
22 | ** the names of its contributors may be used to endorse or promote
|
---|
23 | ** products derived from this software without specific prior written
|
---|
24 | ** permission.
|
---|
25 | **
|
---|
26 | ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
---|
27 | ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
---|
28 | ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
---|
29 | ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
---|
30 | ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
---|
31 | ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
---|
32 | ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
---|
33 | ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
---|
34 | ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
---|
35 | ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
---|
36 | ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
|
---|
37 | ** $QT_END_LICENSE$
|
---|
38 | **
|
---|
39 | ****************************************************************************/
|
---|
40 |
|
---|
41 | #include "spectrumanalyser.h"
|
---|
42 | #include "utils.h"
|
---|
43 |
|
---|
44 | #include <QtCore/qmath.h>
|
---|
45 | #include <QtCore/qmetatype.h>
|
---|
46 | #include <QtMultimedia/QAudioFormat>
|
---|
47 | #include <QThread>
|
---|
48 |
|
---|
49 | #include "fftreal_wrapper.h"
|
---|
50 |
|
---|
51 | SpectrumAnalyserThread::SpectrumAnalyserThread(QObject *parent)
|
---|
52 | : QObject(parent)
|
---|
53 | #ifndef DISABLE_FFT
|
---|
54 | , m_fft(new FFTRealWrapper)
|
---|
55 | #endif
|
---|
56 | , m_numSamples(SpectrumLengthSamples)
|
---|
57 | , m_windowFunction(DefaultWindowFunction)
|
---|
58 | , m_window(SpectrumLengthSamples, 0.0)
|
---|
59 | , m_input(SpectrumLengthSamples, 0.0)
|
---|
60 | , m_output(SpectrumLengthSamples, 0.0)
|
---|
61 | , m_spectrum(SpectrumLengthSamples)
|
---|
62 | #ifdef SPECTRUM_ANALYSER_SEPARATE_THREAD
|
---|
63 | , m_thread(new QThread(this))
|
---|
64 | #endif
|
---|
65 | {
|
---|
66 | #ifdef SPECTRUM_ANALYSER_SEPARATE_THREAD
|
---|
67 | // moveToThread() cannot be called on a QObject with a parent
|
---|
68 | setParent(0);
|
---|
69 | moveToThread(m_thread);
|
---|
70 | m_thread->start();
|
---|
71 | #endif
|
---|
72 | calculateWindow();
|
---|
73 | }
|
---|
74 |
|
---|
75 | SpectrumAnalyserThread::~SpectrumAnalyserThread()
|
---|
76 | {
|
---|
77 | #ifndef DISABLE_FFT
|
---|
78 | delete m_fft;
|
---|
79 | #endif
|
---|
80 | }
|
---|
81 |
|
---|
82 | void SpectrumAnalyserThread::setWindowFunction(WindowFunction type)
|
---|
83 | {
|
---|
84 | m_windowFunction = type;
|
---|
85 | calculateWindow();
|
---|
86 | }
|
---|
87 |
|
---|
88 | void SpectrumAnalyserThread::calculateWindow()
|
---|
89 | {
|
---|
90 | for (int i=0; i<m_numSamples; ++i) {
|
---|
91 | DataType x = 0.0;
|
---|
92 |
|
---|
93 | switch (m_windowFunction) {
|
---|
94 | case NoWindow:
|
---|
95 | x = 1.0;
|
---|
96 | break;
|
---|
97 | case HannWindow:
|
---|
98 | x = 0.5 * (1 - qCos((2 * M_PI * i) / (m_numSamples - 1)));
|
---|
99 | break;
|
---|
100 | default:
|
---|
101 | Q_ASSERT(false);
|
---|
102 | }
|
---|
103 |
|
---|
104 | m_window[i] = x;
|
---|
105 | }
|
---|
106 | }
|
---|
107 |
|
---|
108 | void SpectrumAnalyserThread::calculateSpectrum(const QByteArray &buffer,
|
---|
109 | int inputFrequency,
|
---|
110 | int bytesPerSample)
|
---|
111 | {
|
---|
112 | #ifndef DISABLE_FFT
|
---|
113 | Q_ASSERT(buffer.size() == m_numSamples * bytesPerSample);
|
---|
114 |
|
---|
115 | // Initialize data array
|
---|
116 | const char *ptr = buffer.constData();
|
---|
117 | for (int i=0; i<m_numSamples; ++i) {
|
---|
118 | const qint16 pcmSample = *reinterpret_cast<const qint16*>(ptr);
|
---|
119 | // Scale down to range [-1.0, 1.0]
|
---|
120 | const DataType realSample = pcmToReal(pcmSample);
|
---|
121 | const DataType windowedSample = realSample * m_window[i];
|
---|
122 | m_input[i] = windowedSample;
|
---|
123 | ptr += bytesPerSample;
|
---|
124 | }
|
---|
125 |
|
---|
126 | // Calculate the FFT
|
---|
127 | m_fft->calculateFFT(m_output.data(), m_input.data());
|
---|
128 |
|
---|
129 | // Analyze output to obtain amplitude and phase for each frequency
|
---|
130 | for (int i=2; i<=m_numSamples/2; ++i) {
|
---|
131 | // Calculate frequency of this complex sample
|
---|
132 | m_spectrum[i].frequency = qreal(i * inputFrequency) / (m_numSamples);
|
---|
133 |
|
---|
134 | const qreal real = m_output[i];
|
---|
135 | qreal imag = 0.0;
|
---|
136 | if (i>0 && i<m_numSamples/2)
|
---|
137 | imag = m_output[m_numSamples/2 + i];
|
---|
138 |
|
---|
139 | const qreal magnitude = sqrt(real*real + imag*imag);
|
---|
140 | qreal amplitude = SpectrumAnalyserMultiplier * log(magnitude);
|
---|
141 |
|
---|
142 | // Bound amplitude to [0.0, 1.0]
|
---|
143 | m_spectrum[i].clipped = (amplitude > 1.0);
|
---|
144 | amplitude = qMax(qreal(0.0), amplitude);
|
---|
145 | amplitude = qMin(qreal(1.0), amplitude);
|
---|
146 | m_spectrum[i].amplitude = amplitude;
|
---|
147 | }
|
---|
148 | #endif
|
---|
149 |
|
---|
150 | emit calculationComplete(m_spectrum);
|
---|
151 | }
|
---|
152 |
|
---|
153 |
|
---|
154 | //=============================================================================
|
---|
155 | // SpectrumAnalyser
|
---|
156 | //=============================================================================
|
---|
157 |
|
---|
158 | SpectrumAnalyser::SpectrumAnalyser(QObject *parent)
|
---|
159 | : QObject(parent)
|
---|
160 | , m_thread(new SpectrumAnalyserThread(this))
|
---|
161 | , m_state(Idle)
|
---|
162 | #ifdef DUMP_SPECTRUMANALYSER
|
---|
163 | , m_count(0)
|
---|
164 | #endif
|
---|
165 | {
|
---|
166 | CHECKED_CONNECT(m_thread, SIGNAL(calculationComplete(FrequencySpectrum)),
|
---|
167 | this, SLOT(calculationComplete(FrequencySpectrum)));
|
---|
168 | }
|
---|
169 |
|
---|
170 | SpectrumAnalyser::~SpectrumAnalyser()
|
---|
171 | {
|
---|
172 |
|
---|
173 | }
|
---|
174 |
|
---|
175 | #ifdef DUMP_SPECTRUMANALYSER
|
---|
176 | void SpectrumAnalyser::setOutputPath(const QString &outputDir)
|
---|
177 | {
|
---|
178 | m_outputDir.setPath(outputDir);
|
---|
179 | m_textFile.setFileName(m_outputDir.filePath("spectrum.txt"));
|
---|
180 | m_textFile.open(QIODevice::WriteOnly | QIODevice::Text);
|
---|
181 | m_textStream.setDevice(&m_textFile);
|
---|
182 | }
|
---|
183 | #endif
|
---|
184 |
|
---|
185 | //-----------------------------------------------------------------------------
|
---|
186 | // Public functions
|
---|
187 | //-----------------------------------------------------------------------------
|
---|
188 |
|
---|
189 | void SpectrumAnalyser::setWindowFunction(WindowFunction type)
|
---|
190 | {
|
---|
191 | const bool b = QMetaObject::invokeMethod(m_thread, "setWindowFunction",
|
---|
192 | Qt::AutoConnection,
|
---|
193 | Q_ARG(WindowFunction, type));
|
---|
194 | Q_ASSERT(b);
|
---|
195 | Q_UNUSED(b) // suppress warnings in release builds
|
---|
196 | }
|
---|
197 |
|
---|
198 | void SpectrumAnalyser::calculate(const QByteArray &buffer,
|
---|
199 | const QAudioFormat &format)
|
---|
200 | {
|
---|
201 | // QThread::currentThread is marked 'for internal use only', but
|
---|
202 | // we're only using it for debug output here, so it's probably OK :)
|
---|
203 | SPECTRUMANALYSER_DEBUG << "SpectrumAnalyser::calculate"
|
---|
204 | << QThread::currentThread()
|
---|
205 | << "state" << m_state;
|
---|
206 |
|
---|
207 | if (isReady()) {
|
---|
208 | Q_ASSERT(isPCMS16LE(format));
|
---|
209 |
|
---|
210 | const int bytesPerSample = format.sampleSize() * format.channels() / 8;
|
---|
211 |
|
---|
212 | #ifdef DUMP_SPECTRUMANALYSER
|
---|
213 | m_count++;
|
---|
214 | const QString pcmFileName = m_outputDir.filePath(QString("spectrum_%1.pcm").arg(m_count, 4, 10, QChar('0')));
|
---|
215 | QFile pcmFile(pcmFileName);
|
---|
216 | pcmFile.open(QIODevice::WriteOnly);
|
---|
217 | const int bufferLength = m_numSamples * bytesPerSample;
|
---|
218 | pcmFile.write(buffer, bufferLength);
|
---|
219 |
|
---|
220 | m_textStream << "TimeDomain " << m_count << "\n";
|
---|
221 | const qint16* input = reinterpret_cast<const qint16*>(buffer);
|
---|
222 | for (int i=0; i<m_numSamples; ++i) {
|
---|
223 | m_textStream << i << "\t" << *input << "\n";
|
---|
224 | input += format.channels();
|
---|
225 | }
|
---|
226 | #endif
|
---|
227 |
|
---|
228 | m_state = Busy;
|
---|
229 |
|
---|
230 | // Invoke SpectrumAnalyserThread::calculateSpectrum using QMetaObject. If
|
---|
231 | // m_thread is in a different thread from the current thread, the
|
---|
232 | // calculation will be done in the child thread.
|
---|
233 | // Once the calculation is finished, a calculationChanged signal will be
|
---|
234 | // emitted by m_thread.
|
---|
235 | const bool b = QMetaObject::invokeMethod(m_thread, "calculateSpectrum",
|
---|
236 | Qt::AutoConnection,
|
---|
237 | Q_ARG(QByteArray, buffer),
|
---|
238 | Q_ARG(int, format.frequency()),
|
---|
239 | Q_ARG(int, bytesPerSample));
|
---|
240 | Q_ASSERT(b);
|
---|
241 | Q_UNUSED(b) // suppress warnings in release builds
|
---|
242 |
|
---|
243 | #ifdef DUMP_SPECTRUMANALYSER
|
---|
244 | m_textStream << "FrequencySpectrum " << m_count << "\n";
|
---|
245 | FrequencySpectrum::const_iterator x = m_spectrum.begin();
|
---|
246 | for (int i=0; i<m_numSamples; ++i, ++x)
|
---|
247 | m_textStream << i << "\t"
|
---|
248 | << x->frequency << "\t"
|
---|
249 | << x->amplitude<< "\t"
|
---|
250 | << x->phase << "\n";
|
---|
251 | #endif
|
---|
252 | }
|
---|
253 | }
|
---|
254 |
|
---|
255 | bool SpectrumAnalyser::isReady() const
|
---|
256 | {
|
---|
257 | return (Idle == m_state);
|
---|
258 | }
|
---|
259 |
|
---|
260 | void SpectrumAnalyser::cancelCalculation()
|
---|
261 | {
|
---|
262 | if (Busy == m_state)
|
---|
263 | m_state = Cancelled;
|
---|
264 | }
|
---|
265 |
|
---|
266 |
|
---|
267 | //-----------------------------------------------------------------------------
|
---|
268 | // Private slots
|
---|
269 | //-----------------------------------------------------------------------------
|
---|
270 |
|
---|
271 | void SpectrumAnalyser::calculationComplete(const FrequencySpectrum &spectrum)
|
---|
272 | {
|
---|
273 | Q_ASSERT(Idle != m_state);
|
---|
274 | if (Busy == m_state)
|
---|
275 | emit spectrumChanged(spectrum);
|
---|
276 | m_state = Idle;
|
---|
277 | }
|
---|
278 |
|
---|
279 |
|
---|
280 |
|
---|
281 |
|
---|