summaryrefslogtreecommitdiffstats
path: root/doc/package.n
Commit message (Expand)AuthorAgeFilesLines
* merge stable branch onto HEADdgp2007-12-131-1/+1
* Next stage of doing GOOBE improvements to documentation now that the html gen...dkf2007-10-291-34/+81
* * changes: Updated for 8.5b2 release.core_8_5_b2dgp2007-10-261-80/+34
* GOOBEdkf2007-10-251-33/+76
* Lots of improvements to look and feel of manual pagesdkf2007-10-241-2/+5
* * doc/package.n: Restored the functioning ofdgp2007-09-111-18/+11
* * doc/package.n: Restored the document parallel syntax of thedgp2007-09-101-2/+2
* nroff typohobbs2006-10-051-2/+2
* another nitdgp2006-09-251-2/+2
* * doc/package.n: Fixed nits reported by Daniel Steffen in theandreas_kupries2006-09-251-4/+4
* TIP#268 IMPLEMENTATIONandreas_kupries2006-09-221-23/+121
* correct package examplehobbs2006-09-041-3/+4
* doc changes with 1162286 fixdgp2005-11-091-8/+1
* More minor doc fixesdkf2004-10-271-3/+3
* Removed language that encouraged abuse. [package] is for packages.dgp2004-06-021-4/+2
* Added examplesdkf2004-05-301-4/+29
* * Documented global namespace context for script evaluationdgp2002-01-271-3/+5
* New or changed "SEE ALSO" section.poenitz2000-09-071-1/+4
* * doc/package.n: Corrected information about [package forget]ericm2000-06-261-4/+4
* Merged stubs changes into mainline for 8.0stanton1999-03-101-1/+6
* Replaced SCCS strings, fixed binary filescore_8_0_3stanton1998-09-141-1/+1
* Initial revisionrjohnson1998-03-261-0/+188
+ const bool changed = (m_playPosition != position); + m_playPosition = position; + if (changed || forceEmit) + emit playPositionChanged(m_playPosition); +} + +void Engine::calculateLevel(qint64 position, qint64 length) +{ +#ifdef DISABLE_LEVEL + Q_UNUSED(position) + Q_UNUSED(length) +#else + Q_ASSERT(position + length <= m_dataLength); + + qreal peakLevel = 0.0; + + qreal sum = 0.0; + const char *ptr = m_buffer.constData() + position; + const char *const end = ptr + length; + while (ptr < end) { + const qint16 value = *reinterpret_cast(ptr); + const qreal fracValue = pcmToReal(value); + peakLevel = qMax(peakLevel, fracValue); + sum += fracValue * fracValue; + ptr += 2; + } + const int numSamples = length / 2; + qreal rmsLevel = sqrt(sum / numSamples); + + rmsLevel = qMax(qreal(0.0), rmsLevel); + rmsLevel = qMin(qreal(1.0), rmsLevel); + setLevel(rmsLevel, peakLevel, numSamples); + + ENGINE_DEBUG << "Engine::calculateLevel" << "pos" << position << "len" << length + << "rms" << rmsLevel << "peak" << peakLevel; +#endif +} + +void Engine::calculateSpectrum(qint64 position) +{ +#ifdef DISABLE_SPECTRUM + Q_UNUSED(position) +#else + Q_ASSERT(position + m_spectrumLengthBytes <= m_dataLength); + Q_ASSERT(0 == m_spectrumLengthBytes % 2); // constraint of FFT algorithm + + // QThread::currentThread is marked 'for internal use only', but + // we're only using it for debug output here, so it's probably OK :) + ENGINE_DEBUG << "Engine::calculateSpectrum" << QThread::currentThread() + << "count" << m_count << "pos" << position << "len" << m_spectrumLengthBytes + << "spectrumAnalyser.isReady" << m_spectrumAnalyser.isReady(); + + if(m_spectrumAnalyser.isReady()) { + m_spectrumBuffer = QByteArray::fromRawData(m_buffer.constData() + position, + m_spectrumLengthBytes); + m_spectrumPosition = position; + m_spectrumAnalyser.calculate(m_spectrumBuffer, m_format); + } +#endif +} + +void Engine::setFormat(const QAudioFormat &format) +{ + const bool changed = (format != m_format); + m_format = format; + if (changed) + emit formatChanged(m_format); +} + +void Engine::setLevel(qreal rmsLevel, qreal peakLevel, int numSamples) +{ + m_rmsLevel = rmsLevel; + m_peakLevel = peakLevel; + emit levelChanged(m_rmsLevel, m_peakLevel, numSamples); +} + +#ifdef DUMP_DATA +void Engine::createOutputDir() +{ + m_outputDir.setPath("output"); + + // Ensure output directory exists and is empty + if (m_outputDir.exists()) { + const QStringList files = m_outputDir.entryList(QDir::Files); + QString file; + foreach (file, files) + m_outputDir.remove(file); + } else { + QDir::current().mkdir("output"); + } +} +#endif // DUMP_DATA + +#ifdef DUMP_AUDIO +void Engine::dumpData() +{ + const QString txtFileName = m_outputDir.filePath("data.txt"); + QFile txtFile(txtFileName); + txtFile.open(QFile::WriteOnly | QFile::Text); + QTextStream stream(&txtFile); + const qint16 *ptr = reinterpret_cast(m_buffer.constData()); + const int numSamples = m_dataLength / (2 * m_format.channels()); + for (int i=0; i +#include +#include +#include +#include +#include + +#ifdef DUMP_CAPTURED_AUDIO +#define DUMP_DATA +#endif + +#ifdef DUMP_SPECTRUM +#define DUMP_DATA +#endif + +#ifdef DUMP_DATA +#include +#endif + +class QAudioInput; +class QAudioOutput; +class FrequencySpectrum; +class QFile; + +/** + * This class interfaces with the QtMultimedia audio classes, and also with + * the SpectrumAnalyser class. Its role is to manage the capture and playback + * of audio data, meanwhile performing real-time analysis of the audio level + * and frequency spectrum. + */ +class Engine : public QObject { + Q_OBJECT +public: + Engine(QObject *parent = 0); + ~Engine(); + + const QList& availableAudioInputDevices() const + { return m_availableAudioInputDevices; } + + const QList& availableAudioOutputDevices() const + { return m_availableAudioOutputDevices; } + + QAudio::Mode mode() const { return m_mode; } + QAudio::State state() const { return m_state; } + + /** + * \return Reference to internal audio buffer + * \note This reference is valid for the lifetime of the Engine + */ + const QByteArray& buffer() const { return m_buffer; } + + /** + * \return Current audio format + * \note May be QAudioFormat() if engine is not initialized + */ + const QAudioFormat& format() const { return m_format; } + + /** + * Stop any ongoing recording or playback, and reset to ground state. + */ + void reset(); + + /** + * Load data from WAV file + */ + bool loadFile(const QString &fileName); + + /** + * Generate tone + */ + bool generateTone(const Tone &tone); + + /** + * Generate tone + */ + bool generateSweptTone(qreal amplitude); + + /** + * Initialize for recording + */ + bool initializeRecord(); + + /** + * Position of the audio input device. + * \return Position in microseconds. + */ + qint64 recordPosition() const { return m_recordPosition; } + + /** + * RMS level of the most recently processed set of audio samples. + * \return Level in range (0.0, 1.0) + */ + qreal rmsLevel() const { return m_rmsLevel; } + + /** + * Peak level of the most recently processed set of audio samples. + * \return Level in range (0.0, 1.0) + */ + qreal peakLevel() const { return m_peakLevel; } + + /** + * Position of the audio output device. + * \return Position in microseconds. + */ + qint64 playPosition() const { return m_playPosition; } + + /** + * Length of the internal engine buffer. + * \return Buffer length in microseconds. + */ + qint64 bufferDuration() const; + + /** + * Amount of data held in the buffer. + * \return Data duration in microseconds. + */ + qint64 dataDuration() const; + + /** + * Returns the size of the underlying audio buffer in bytes. + * This should be an approximation of the capture latency. + */ + qint64 audioBufferLength() const; + + /** + * Set window function applied to audio data before spectral analysis. + */ + void setWindowFunction(WindowFunction type); + +public slots: + void startRecording(); + void startPlayback(); + void suspend(); + void setAudioInputDevice(const QAudioDeviceInfo &device); + void setAudioOutputDevice(const QAudioDeviceInfo &device); + +signals: + void stateChanged(QAudio::Mode mode, QAudio::State state); + + /** + * Informational message for non-modal display + */ + void infoMessage(const QString &message, int durationMs); + + /** + * Error message for modal display + */ + void errorMessage(const QString &heading, const QString &detail); + + /** + * Format of audio data has changed + */ + void formatChanged(const QAudioFormat &format); + + /** + * Length of buffer has changed. + * \param duration Duration in microseconds + */ + void bufferDurationChanged(qint64 duration); + + /** + * Amount of data in buffer has changed. + * \param duration Duration of data in microseconds + */ + void dataDurationChanged(qint64 duration); + + /** + * Position of the audio input device has changed. + * \param position Position in microseconds + */ + void recordPositionChanged(qint64 position); + + /** + * Position of the audio output device has changed. + * \param position Position in microseconds + */ + void playPositionChanged(qint64 position); + + /** + * Level changed + * \param rmsLevel RMS level in range 0.0 - 1.0 + * \param peakLevel Peak level in range 0.0 - 1.0 + * \param numSamples Number of audio samples analysed + */ + void levelChanged(qreal rmsLevel, qreal peakLevel, int numSamples); + + /** + * Spectrum has changed. + * \param position Position of start of window in microseconds + * \param length Length of window in microseconds + * \param spectrum Resulting frequency spectrum + */ + void spectrumChanged(qint64 position, qint64 length, const FrequencySpectrum &spectrum); + +private slots: + void audioNotify(); + void audioStateChanged(QAudio::State state); + void audioDataReady(); + void spectrumChanged(const FrequencySpectrum &spectrum); + +private: + bool initialize(); + bool selectFormat(); + void stopRecording(); + void stopPlayback(); + void setState(QAudio::State state); + void setState(QAudio::Mode mode, QAudio::State state); + void setFormat(const QAudioFormat &format); + void setRecordPosition(qint64 position, bool forceEmit = false); + void setPlayPosition(qint64 position, bool forceEmit = false); + void calculateLevel(qint64 position, qint64 length); + void calculateSpectrum(qint64 position); + void setLevel(qreal rmsLevel, qreal peakLevel, int numSamples); + +#ifdef DUMP_DATA + void createOutputDir(); + QString outputPath() const { return m_outputDir.path(); } +#endif + +#ifdef DUMP_CAPTURED_AUDIO + void dumpData(); +#endif + +private: + QAudio::Mode m_mode; + QAudio::State m_state; + + bool m_generateTone; + SweptTone m_tone; + + QFile* m_file; + WavFile m_wavFile; + + QAudioFormat m_format; + + const QList m_availableAudioInputDevices; + QAudioDeviceInfo m_audioInputDevice; + QAudioInput* m_audioInput; + QIODevice* m_audioInputIODevice; + qint64 m_recordPosition; + + const QList m_availableAudioOutputDevices; + QAudioDeviceInfo m_audioOutputDevice; + QAudioOutput* m_audioOutput; + qint64 m_playPosition; + QBuffer m_audioOutputIODevice; + + QByteArray m_buffer; + qint64 m_dataLength; + + qreal m_rmsLevel; + qreal m_peakLevel; + + int m_spectrumLengthBytes; + QByteArray m_spectrumBuffer; + SpectrumAnalyser m_spectrumAnalyser; + qint64 m_spectrumPosition; + + int m_count; + +#ifdef DUMP_DATA + QDir m_outputDir; +#endif + +}; + +#endif // ENGINE_H diff --git a/demos/spectrum/app/frequencyspectrum.cpp b/demos/spectrum/app/frequencyspectrum.cpp new file mode 100644 index 0000000..6ab80c2 --- /dev/null +++ b/demos/spectrum/app/frequencyspectrum.cpp @@ -0,0 +1,90 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the Technology Preview License Agreement accompanying +** this package. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** If you have questions regarding the use of this file, please contact +** Nokia at qt-info@nokia.com. +** +** +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "frequencyspectrum.h" + +FrequencySpectrum::FrequencySpectrum(int numPoints) + : m_elements(numPoints) +{ + +} + +void FrequencySpectrum::reset() +{ + iterator i = begin(); + for ( ; i != end(); ++i) + *i = Element(); +} + +int FrequencySpectrum::count() const +{ + return m_elements.count(); +} + +FrequencySpectrum::Element& FrequencySpectrum::operator[](int index) +{ + return m_elements[index]; +} + +const FrequencySpectrum::Element& FrequencySpectrum::operator[](int index) const +{ + return m_elements[index]; +} + +FrequencySpectrum::iterator FrequencySpectrum::begin() +{ + return m_elements.begin(); +} + +FrequencySpectrum::iterator FrequencySpectrum::end() +{ + return m_elements.end(); +} + +FrequencySpectrum::const_iterator FrequencySpectrum::begin() const +{ + return m_elements.begin(); +} + +FrequencySpectrum::const_iterator FrequencySpectrum::end() const +{ + return m_elements.end(); +} diff --git a/demos/spectrum/app/frequencyspectrum.h b/demos/spectrum/app/frequencyspectrum.h new file mode 100644 index 0000000..610ed6e --- /dev/null +++ b/demos/spectrum/app/frequencyspectrum.h @@ -0,0 +1,93 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** You may use this file under the terms of the BSD license as follows: +** +** Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are met: +** - Redistributions of source code must retain the above copyright notice, +** this list of conditions and the following disclaimer. +** - Redistributions in binary form must reproduce the above copyright notice, +** this list of conditions and the following disclaimer in the documentation +** and/or other materials provided with the distribution. +** - Neither the name of Nokia Corporation and its Subsidiary(-ies) nor the +** names of its contributors may be used to endorse or promote products +** derived from this software without specific prior written permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +** AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +** LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +** INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +** CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +** ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +** POSSIBILITY OF SUCH DAMAGE. +** +*****************************************************************************/ + +#ifndef FREQUENCYSPECTRUM_H +#define FREQUENCYSPECTRUM_H + +#include + +/** + * Represents a frequency spectrum as a series of elements, each of which + * consists of a frequency, an amplitude and a phase. + */ +class FrequencySpectrum { +public: + FrequencySpectrum(int numPoints = 0); + + struct Element { + Element() + : frequency(0.0), amplitude(0.0), phase(0.0), clipped(false) + { } + + /** + * Frequency in Hertz + */ + qreal frequency; + + /** + * Amplitude in range [0.0, 1.0] + */ + qreal amplitude; + + /** + * Phase in range [0.0, 2*PI] + */ + qreal phase; + + /** + * Indicates whether value has been clipped during spectrum analysis + */ + bool clipped; + }; + + typedef QVector::iterator iterator; + typedef QVector::const_iterator const_iterator; + + void reset(); + + int count() const; + Element& operator[](int index); + const Element& operator[](int index) const; + iterator begin(); + iterator end(); + const_iterator begin() const; + const_iterator end() const; + +private: + QVector m_elements; + +}; + +#endif // FREQUENCYSPECTRUM_H diff --git a/demos/spectrum/app/images/record.png b/demos/spectrum/app/images/record.png new file mode 100644 index 0000000..e7493aa Binary files /dev/null and b/demos/spectrum/app/images/record.png differ diff --git a/demos/spectrum/app/images/settings.png b/demos/spectrum/app/images/settings.png new file mode 100644 index 0000000..12179dc Binary files /dev/null and b/demos/spectrum/app/images/settings.png differ diff --git a/demos/spectrum/app/levelmeter.cpp b/demos/spectrum/app/levelmeter.cpp new file mode 100644 index 0000000..eb37684 --- /dev/null +++ b/demos/spectrum/app/levelmeter.cpp @@ -0,0 +1,143 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the Technology Preview License Agreement accompanying +** this package. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** If you have questions regarding the use of this file, please contact +** Nokia at qt-info@nokia.com. +** +** +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "levelmeter.h" + +#include + +#include +#include +#include + + +// Constants +const int RedrawInterval = 100; // ms +const qreal PeakDecayRate = 0.001; +const int PeakHoldLevelDuration = 2000; // ms + + +LevelMeter::LevelMeter(QWidget *parent) + : QWidget(parent) + , m_rmsLevel(0.0) + , m_peakLevel(0.0) + , m_decayedPeakLevel(0.0) + , m_peakDecayRate(PeakDecayRate) + , m_peakHoldLevel(0.0) + , m_redrawTimer(new QTimer(this)) + , m_rmsColor(Qt::red) + , m_peakColor(255, 200, 200, 255) +{ + setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred); + setMinimumWidth(30); + + connect(m_redrawTimer, SIGNAL(timeout()), this, SLOT(redrawTimerExpired())); + m_redrawTimer->start(RedrawInterval); +} + +LevelMeter::~LevelMeter() +{ + +} + +void LevelMeter::reset() +{ + m_rmsLevel = 0.0; + m_peakLevel = 0.0; + update(); +} + +void LevelMeter::levelChanged(qreal rmsLevel, qreal peakLevel, int numSamples) +{ + // Smooth the RMS signal + const qreal smooth = pow(0.9, static_cast(numSamples) / 256); // TODO: remove this magic number + m_rmsLevel = (m_rmsLevel * smooth) + (rmsLevel * (1.0 - smooth)); + + if (peakLevel > m_decayedPeakLevel) { + m_peakLevel = peakLevel; + m_decayedPeakLevel = peakLevel; + m_peakLevelChanged.start(); + } + + if (peakLevel > m_peakHoldLevel) { + m_peakHoldLevel = peakLevel; + m_peakHoldLevelChanged.start(); + } + + update(); +} + +void LevelMeter::redrawTimerExpired() +{ + // Decay the peak signal + const int elapsedMs = m_peakLevelChanged.elapsed(); + const qreal decayAmount = m_peakDecayRate * elapsedMs; + if (decayAmount < m_peakLevel) + m_decayedPeakLevel = m_peakLevel - decayAmount; + else + m_decayedPeakLevel = 0.0; + + // Check whether to clear the peak hold level + if (m_peakHoldLevelChanged.elapsed() > PeakHoldLevelDuration) + m_peakHoldLevel = 0.0; + + update(); +} + +void LevelMeter::paintEvent(QPaintEvent *event) +{ + Q_UNUSED(event) + + QPainter painter(this); + painter.fillRect(rect(), Qt::black); + + QRect bar = rect(); + + bar.setTop(rect().top() + (1.0 - m_peakHoldLevel) * rect().height()); + bar.setBottom(bar.top() + 5); + painter.fillRect(bar, m_rmsColor); + bar.setBottom(rect().bottom()); + + bar.setTop(rect().top() + (1.0 - m_decayedPeakLevel) * rect().height()); + painter.fillRect(bar, m_peakColor); + + bar.setTop(rect().top() + (1.0 - m_rmsLevel) * rect().height()); + painter.fillRect(bar, m_rmsColor); +} diff --git a/demos/spectrum/app/levelmeter.h b/demos/spectrum/app/levelmeter.h new file mode 100644 index 0000000..7d4238d --- /dev/null +++ b/demos/spectrum/app/levelmeter.h @@ -0,0 +1,111 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** You may use this file under the terms of the BSD license as follows: +** +** Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are met: +** - Redistributions of source code must retain the above copyright notice, +** this list of conditions and the following disclaimer. +** - Redistributions in binary form must reproduce the above copyright notice, +** this list of conditions and the following disclaimer in the documentation +** and/or other materials provided with the distribution. +** - Neither the name of Nokia Corporation and its Subsidiary(-ies) nor the +** names of its contributors may be used to endorse or promote products +** derived from this software without specific prior written permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +** AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +** LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +** INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +** CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +** ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +** POSSIBILITY OF SUCH DAMAGE. +** +*****************************************************************************/ + +#ifndef LEVELMETER_H +#define LEVELMETER_H + +#include +#include + +/** + * Widget which displays a vertical audio level meter, indicating the + * RMS and peak levels of the window of audio samples most recently analysed + * by the Engine. + */ +class LevelMeter : public QWidget { + Q_OBJECT +public: + LevelMeter(QWidget *parent = 0); + ~LevelMeter(); + + void paintEvent(QPaintEvent *event); + +public slots: + void reset(); + void levelChanged(qreal rmsLevel, qreal peakLevel, int numSamples); + +private slots: + void redrawTimerExpired(); + +private: + /** + * Height of RMS level bar. + * Range 0.0 - 1.0. + */ + qreal m_rmsLevel; + + /** + * Most recent peak level. + * Range 0.0 - 1.0. + */ + qreal m_peakLevel; + + /** + * Height of peak level bar. + * This is calculated by decaying m_peakLevel depending on the + * elapsed time since m_peakLevelChanged, and the value of m_decayRate. + */ + qreal m_decayedPeakLevel; + + /** + * Time at which m_peakLevel was last changed. + */ + QTime m_peakLevelChanged; + + /** + * Rate at which peak level bar decays. + * Expressed in level units / millisecond. + */ + qreal m_peakDecayRate; + + /** + * High watermark of peak level. + * Range 0.0 - 1.0. + */ + qreal m_peakHoldLevel; + + /** + * Time at which m_peakHoldLevel was last changed. + */ + QTime m_peakHoldLevelChanged; + + QTimer *m_redrawTimer; + + QColor m_rmsColor; + QColor m_peakColor; + +}; + +#endif // LEVELMETER_H diff --git a/demos/spectrum/app/main.cpp b/demos/spectrum/app/main.cpp new file mode 100644 index 0000000..6e2b6fc --- /dev/null +++ b/demos/spectrum/app/main.cpp @@ -0,0 +1,58 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the Technology Preview License Agreement accompanying +** this package. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** If you have questions regarding the use of this file, please contact +** Nokia at qt-info@nokia.com. +** +** +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include "mainwidget.h" + +int main(int argc, char **argv) +{ + QApplication app(argc, argv); + app.setApplicationName("QtMultimedia spectrum analyser"); + MainWidget w; + +#ifdef Q_OS_SYMBIAN + w.showMaximized(); +#else + w.show(); +#endif + + return app.exec(); +} diff --git a/demos/spectrum/app/mainwidget.cpp b/demos/spectrum/app/mainwidget.cpp new file mode 100644 index 0000000..3b7c306 --- /dev/null +++ b/demos/spectrum/app/mainwidget.cpp @@ -0,0 +1,455 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the Technology Preview License Agreement accompanying +** this package. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** If you have questions regarding the use of this file, please contact +** Nokia at qt-info@nokia.com. +** +** +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "engine.h" +#include "levelmeter.h" +#include "mainwidget.h" +#include "waveform.h" +#include "progressbar.h" +#include "settingsdialog.h" +#include "spectrograph.h" +#include "tonegeneratordialog.h" +#include "utils.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +const int NullTimerId = -1; + +MainWidget::MainWidget(QWidget *parent) + : QWidget(parent) + , m_mode(NoMode) + , m_engine(new Engine(this)) +#ifndef DISABLE_WAVEFORM + , m_waveform(new Waveform(m_engine->buffer(), this)) +#endif + , m_progressBar(new ProgressBar(this)) + , m_spectrograph(new Spectrograph(this)) + , m_levelMeter(new LevelMeter(this)) + , m_modeButton(new QPushButton(this)) + , m_recordButton(new QPushButton(this)) + , m_pauseButton(new QPushButton(this)) + , m_playButton(new QPushButton(this)) + , m_settingsButton(new QPushButton(this)) + , m_infoMessage(new QLabel(tr("Select a mode to begin"), this)) + , m_infoMessageTimerId(NullTimerId) + , m_settingsDialog(new SettingsDialog( + m_engine->availableAudioInputDevices(), + m_engine->availableAudioOutputDevices(), + this)) + , m_toneGeneratorDialog(new ToneGeneratorDialog(this)) + , m_modeMenu(new QMenu(this)) + , m_loadFileAction(0) + , m_generateToneAction(0) + , m_recordAction(0) +{ + m_spectrograph->setParams(SpectrumNumBands, SpectrumLowFreq, SpectrumHighFreq); + + createUi(); + connectUi(); +} + +MainWidget::~MainWidget() +{ + +} + + +//----------------------------------------------------------------------------- +// Public slots +//----------------------------------------------------------------------------- + +void MainWidget::stateChanged(QAudio::Mode mode, QAudio::State state) +{ + Q_UNUSED(mode); + + updateButtonStates(); + + if (QAudio::ActiveState != state && QAudio::SuspendedState != state) { + m_levelMeter->reset(); + m_spectrograph->reset(); + } +} + +void MainWidget::formatChanged(const QAudioFormat &format) +{ + infoMessage(formatToString(format), NullMessageTimeout); + +#ifndef DISABLE_WAVEFORM + if (QAudioFormat() != format) { + m_waveform->initialize(format, WaveformTileLength, + WaveformWindowDuration); + } +#endif +} + +void MainWidget::spectrumChanged(qint64 position, qint64 length, + const FrequencySpectrum &spectrum) +{ + m_progressBar->windowChanged(position, length); + m_spectrograph->spectrumChanged(spectrum); +} + +void MainWidget::infoMessage(const QString &message, int timeoutMs) +{ + m_infoMessage->setText(message); + + if (NullTimerId != m_infoMessageTimerId) { + killTimer(m_infoMessageTimerId); + m_infoMessageTimerId = NullTimerId; + } + + if (NullMessageTimeout != timeoutMs) + m_infoMessageTimerId = startTimer(timeoutMs); +} + +void MainWidget::errorMessage(const QString &heading, const QString &detail) +{ +#ifdef Q_OS_SYMBIAN + const QString message = heading + "\n" + detail; + QMessageBox::warning(this, "", message, QMessageBox::Close); +#else + QMessageBox::warning(this, heading, detail, QMessageBox::Close); +#endif +} + +void MainWidget::timerEvent(QTimerEvent *event) +{ + Q_ASSERT(event->timerId() == m_infoMessageTimerId); + Q_UNUSED(event) // suppress warnings in release builds + killTimer(m_infoMessageTimerId); + m_infoMessageTimerId = NullTimerId; + m_infoMessage->setText(""); +} + +void MainWidget::positionChanged(qint64 positionUs) +{ +#ifndef DISABLE_WAVEFORM + qint64 positionBytes = audioLength(m_engine->format(), positionUs); + m_waveform->positionChanged(positionBytes); +#else + Q_UNUSED(positionUs) +#endif +} + +void MainWidget::bufferDurationChanged(qint64 durationUs) +{ + m_progressBar->bufferDurationChanged(durationUs); +} + + +//----------------------------------------------------------------------------- +// Private slots +//----------------------------------------------------------------------------- + +void MainWidget::dataDurationChanged(qint64 duration) +{ +#ifndef DISABLE_WAVEFORM + const qint64 dataLength = audioLength(m_engine->format(), duration); + m_waveform->dataLengthChanged(dataLength); +#else + Q_UNUSED(duration) +#endif + + updateButtonStates(); +} + +void MainWidget::showFileDialog() +{ + reset(); + const QString dir; + const QStringList fileNames = QFileDialog::getOpenFileNames(this, tr("Open WAV file"), dir, "*.wav"); + if (fileNames.count()) { + setMode(LoadFileMode); + m_engine->loadFile(fileNames.front()); + updateButtonStates(); + } +} + +void MainWidget::showSettingsDialog() +{ + reset(); + m_settingsDialog->exec(); + if (m_settingsDialog->result() == QDialog::Accepted) { + m_engine->setAudioInputDevice(m_settingsDialog->inputDevice()); + m_engine->setAudioOutputDevice(m_settingsDialog->outputDevice()); + m_engine->setWindowFunction(m_settingsDialog->windowFunction()); + } +} + +void MainWidget::showToneGeneratorDialog() +{ + reset(); + m_toneGeneratorDialog->exec(); + if (m_toneGeneratorDialog->result() == QDialog::Accepted) { + setMode(GenerateToneMode); + const qreal amplitude = m_toneGeneratorDialog->amplitude(); + if (m_toneGeneratorDialog->isFrequencySweepEnabled()) { + m_engine->generateSweptTone(amplitude); + } else { + const qreal frequency = m_toneGeneratorDialog->frequency(); + const Tone tone(frequency, amplitude); + m_engine->generateTone(tone); + updateButtonStates(); + } + } +} + +void MainWidget::initializeRecord() +{ + reset(); + setMode(RecordMode); + if (m_engine->initializeRecord()) + updateButtonStates(); +} + + +//----------------------------------------------------------------------------- +// Private functions +//----------------------------------------------------------------------------- + +void MainWidget::createUi() +{ + createMenus(); + + setWindowTitle(tr("Spectrum Analyser")); + + QVBoxLayout *windowLayout = new QVBoxLayout(this); + + m_infoMessage->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); + m_infoMessage->setAlignment(Qt::AlignHCenter); + windowLayout->addWidget(m_infoMessage); + +#ifdef SUPERIMPOSE_PROGRESS_ON_WAVEFORM + QScopedPointer waveformLayout(new QHBoxLayout); + waveformLayout->addWidget(m_progressBar); + m_progressBar->setMinimumHeight(m_waveform->minimumHeight()); + waveformLayout->setMargin(0); + m_waveform->setLayout(waveformLayout.data()); + waveformLayout.take(); + windowLayout->addWidget(m_waveform); +#else +#ifndef DISABLE_WAVEFORM + windowLayout->addWidget(m_waveform); +#endif // DISABLE_WAVEFORM + windowLayout->addWidget(m_progressBar); +#endif // SUPERIMPOSE_PROGRESS_ON_WAVEFORM + + // Spectrograph and level meter + + QScopedPointer analysisLayout(new QHBoxLayout); + analysisLayout->addWidget(m_spectrograph); + analysisLayout->addWidget(m_levelMeter); + windowLayout->addLayout(analysisLayout.data()); + analysisLayout.take(); + + // Button panel + + const QSize buttonSize(30, 30); + + m_modeButton->setText(tr("Mode")); + + m_recordIcon = QIcon(":/images/record.png"); + m_recordButton->setIcon(m_recordIcon); + m_recordButton->setEnabled(false); + m_recordButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); + m_recordButton->setMinimumSize(buttonSize); + + m_pauseIcon = style()->standardIcon(QStyle::SP_MediaPause); + m_pauseButton->setIcon(m_pauseIcon); + m_pauseButton->setEnabled(false); + m_pauseButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); + m_pauseButton->setMinimumSize(buttonSize); + + m_playIcon = style()->standardIcon(QStyle::SP_MediaPlay); + m_playButton->setIcon(m_playIcon); + m_playButton->setEnabled(false); + m_playButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); + m_playButton->setMinimumSize(buttonSize); + + m_settingsIcon = QIcon(":/images/settings.png"); + m_settingsButton->setIcon(m_settingsIcon); + m_settingsButton->setEnabled(true); + m_settingsButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); + m_settingsButton->setMinimumSize(buttonSize); + + QScopedPointer buttonPanelLayout(new QHBoxLayout); + buttonPanelLayout->addStretch(); + buttonPanelLayout->addWidget(m_modeButton); + buttonPanelLayout->addWidget(m_recordButton); + buttonPanelLayout->addWidget(m_pauseButton); + buttonPanelLayout->addWidget(m_playButton); + buttonPanelLayout->addWidget(m_settingsButton); + + QWidget *buttonPanel = new QWidget(this); + buttonPanel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); + buttonPanel->setLayout(buttonPanelLayout.data()); + buttonPanelLayout.take(); // ownership transferred to buttonPanel + + QScopedPointer bottomPaneLayout(new QHBoxLayout); + bottomPaneLayout->addWidget(buttonPanel); + windowLayout->addLayout(bottomPaneLayout.data()); + bottomPaneLayout.take(); // ownership transferred to windowLayout + + // Apply layout + + setLayout(windowLayout); +} + +void MainWidget::connectUi() +{ + CHECKED_CONNECT(m_recordButton, SIGNAL(clicked()), + m_engine, SLOT(startRecording())); + + CHECKED_CONNECT(m_pauseButton, SIGNAL(clicked()), + m_engine, SLOT(suspend())); + + CHECKED_CONNECT(m_playButton, SIGNAL(clicked()), + m_engine, SLOT(startPlayback())); + + CHECKED_CONNECT(m_settingsButton, SIGNAL(clicked()), + this, SLOT(showSettingsDialog())); + + CHECKED_CONNECT(m_engine, SIGNAL(stateChanged(QAudio::Mode,QAudio::State)), + this, SLOT(stateChanged(QAudio::Mode,QAudio::State))); + + CHECKED_CONNECT(m_engine, SIGNAL(formatChanged(const QAudioFormat &)), + this, SLOT(formatChanged(const QAudioFormat &))); + + m_progressBar->bufferDurationChanged(m_engine->bufferDuration()); + + CHECKED_CONNECT(m_engine, SIGNAL(bufferDurationChanged(qint64)), + this, SLOT(bufferDurationChanged(qint64))); + + CHECKED_CONNECT(m_engine, SIGNAL(dataDurationChanged(qint64)), + this, SLOT(dataDurationChanged(qint64))); + + CHECKED_CONNECT(m_engine, SIGNAL(recordPositionChanged(qint64)), + m_progressBar, SLOT(recordPositionChanged(qint64))); + + CHECKED_CONNECT(m_engine, SIGNAL(playPositionChanged(qint64)), + m_progressBar, SLOT(playPositionChanged(qint64))); + + CHECKED_CONNECT(m_engine, SIGNAL(recordPositionChanged(qint64)), + this, SLOT(positionChanged(qint64))); + + CHECKED_CONNECT(m_engine, SIGNAL(playPositionChanged(qint64)), + this, SLOT(positionChanged(qint64))); + + CHECKED_CONNECT(m_engine, SIGNAL(levelChanged(qreal, qreal, int)), + m_levelMeter, SLOT(levelChanged(qreal, qreal, int))); + + CHECKED_CONNECT(m_engine, SIGNAL(spectrumChanged(qint64, qint64, const FrequencySpectrum &)), + this, SLOT(spectrumChanged(qint64, qint64, const FrequencySpectrum &))); + + CHECKED_CONNECT(m_engine, SIGNAL(infoMessage(QString, int)), + this, SLOT(infoMessage(QString, int))); + + CHECKED_CONNECT(m_engine, SIGNAL(errorMessage(QString, QString)), + this, SLOT(errorMessage(QString, QString))); + + CHECKED_CONNECT(m_spectrograph, SIGNAL(infoMessage(QString, int)), + this, SLOT(infoMessage(QString, int))); +} + +void MainWidget::createMenus() +{ + m_modeButton->setMenu(m_modeMenu); + + m_generateToneAction = m_modeMenu->addAction(tr("Play generated tone")); + m_recordAction = m_modeMenu->addAction(tr("Record and play back")); + m_loadFileAction = m_modeMenu->addAction(tr("Play file")); + + m_loadFileAction->setCheckable(true); + m_generateToneAction->setCheckable(true); + m_recordAction->setCheckable(true); + + connect(m_loadFileAction, SIGNAL(triggered(bool)), this, SLOT(showFileDialog())); + connect(m_generateToneAction, SIGNAL(triggered(bool)), this, SLOT(showToneGeneratorDialog())); + connect(m_recordAction, SIGNAL(triggered(bool)), this, SLOT(initializeRecord())); +} + +void MainWidget::updateButtonStates() +{ + const bool recordEnabled = ((QAudio::AudioOutput == m_engine->mode() || + (QAudio::ActiveState != m_engine->state() && + QAudio::IdleState != m_engine->state())) && + RecordMode == m_mode); + m_recordButton->setEnabled(recordEnabled); + + const bool pauseEnabled = (QAudio::ActiveState == m_engine->state() || + QAudio::IdleState == m_engine->state()); + m_pauseButton->setEnabled(pauseEnabled); + + const bool playEnabled = (m_engine->dataDuration() && + (QAudio::AudioOutput != m_engine->mode() || + (QAudio::ActiveState != m_engine->state() && + QAudio::IdleState != m_engine->state()))); + m_playButton->setEnabled(playEnabled); +} + +void MainWidget::reset() +{ +#ifndef DISABLE_WAVEFORM + m_waveform->reset(); +#endif + m_engine->reset(); + m_levelMeter->reset(); + m_spectrograph->reset(); + m_progressBar->reset(); +} + +void MainWidget::setMode(Mode mode) +{ + + m_mode = mode; + m_loadFileAction->setChecked(LoadFileMode == mode); + m_generateToneAction->setChecked(GenerateToneMode == mode); + m_recordAction->setChecked(RecordMode == mode); +} + diff --git a/demos/spectrum/app/mainwidget.h b/demos/spectrum/app/mainwidget.h new file mode 100644 index 0000000..8e24f4a --- /dev/null +++ b/demos/spectrum/app/mainwidget.h @@ -0,0 +1,136 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** You may use this file under the terms of the BSD license as follows: +** +** Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are met: +** - Redistributions of source code must retain the above copyright notice, +** this list of conditions and the following disclaimer. +** - Redistributions in binary form must reproduce the above copyright notice, +** this list of conditions and the following disclaimer in the documentation +** and/or other materials provided with the distribution. +** - Neither the name of Nokia Corporation and its Subsidiary(-ies) nor the +** names of its contributors may be used to endorse or promote products +** derived from this software without specific prior written permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +** AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +** LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +** INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +** CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +** ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +** POSSIBILITY OF SUCH DAMAGE. +** +*****************************************************************************/ + +#ifndef MAINWIDGET_H +#define MAINWIDGET_H + +#include +#include +#include + +class Engine; +class FrequencySpectrum; +class ProgressBar; +class Spectrograph; +class Waveform; +class LevelMeter; +class SettingsDialog; +class ToneGeneratorDialog; +class QAudioFormat; +class QLabel; +class QPushButton; +class QMenu; +class QAction; + +/** + * Main application widget, responsible for connecting the various UI + * elements to the Engine. + */ +class MainWidget : public QWidget { + Q_OBJECT +public: + MainWidget(QWidget *parent = 0); + ~MainWidget(); + + // QObject + void timerEvent(QTimerEvent *event); + +public slots: + void stateChanged(QAudio::Mode mode, QAudio::State state); + void formatChanged(const QAudioFormat &format); + void spectrumChanged(qint64 position, qint64 length, + const FrequencySpectrum &spectrum); + void infoMessage(const QString &message, int timeoutMs); + void errorMessage(const QString &heading, const QString &detail); + void positionChanged(qint64 position); + void bufferDurationChanged(qint64 duration); + +private slots: + void showFileDialog(); + void showSettingsDialog(); + void showToneGeneratorDialog(); + void initializeRecord(); + void dataDurationChanged(qint64 duration); + +private: + void createUi(); + void createMenus(); + void connectUi(); + void updateButtonStates(); + void reset(); + + enum Mode { + NoMode, + RecordMode, + GenerateToneMode, + LoadFileMode + }; + + void setMode(Mode mode); + +private: + Mode m_mode; + + Engine* m_engine; + + Waveform* m_waveform; + ProgressBar* m_progressBar; + Spectrograph* m_spectrograph; + LevelMeter* m_levelMeter; + + QPushButton* m_modeButton; + QPushButton* m_recordButton; + QIcon m_recordIcon; + QPushButton* m_pauseButton; + QIcon m_pauseIcon; + QPushButton* m_playButton; + QIcon m_playIcon; + QPushButton* m_settingsButton; + QIcon m_settingsIcon; + + QLabel* m_infoMessage; + int m_infoMessageTimerId; + + SettingsDialog* m_settingsDialog; + ToneGeneratorDialog* m_toneGeneratorDialog; + + QMenu* m_modeMenu; + QAction* m_loadFileAction; + QAction* m_generateToneAction; + QAction* m_recordAction; + +}; + +#endif // MAINWIDGET_H diff --git a/demos/spectrum/app/progressbar.cpp b/demos/spectrum/app/progressbar.cpp new file mode 100644 index 0000000..256acf0 --- /dev/null +++ b/demos/spectrum/app/progressbar.cpp @@ -0,0 +1,141 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the Technology Preview License Agreement accompanying +** this package. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** If you have questions regarding the use of this file, please contact +** Nokia at qt-info@nokia.com. +** +** +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "progressbar.h" +#include "spectrum.h" +#include + +ProgressBar::ProgressBar(QWidget *parent) + : QWidget(parent) + , m_bufferDuration(0) + , m_recordPosition(0) + , m_playPosition(0) + , m_windowPosition(0) + , m_windowLength(0) +{ + setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); + setMinimumHeight(30); +#ifdef SUPERIMPOSE_PROGRESS_ON_WAVEFORM + setAutoFillBackground(false); +#endif +} + +ProgressBar::~ProgressBar() +{ + +} + +void ProgressBar::reset() +{ + m_bufferDuration = 0; + m_recordPosition = 0; + m_playPosition = 0; + m_windowPosition = 0; + m_windowLength = 0; + update(); +} + +void ProgressBar::paintEvent(QPaintEvent * /*event*/) +{ + QPainter painter(this); + + QColor bufferColor(0, 0, 255); + QColor windowColor(0, 255, 0); + +#ifdef SUPERIMPOSE_PROGRESS_ON_WAVEFORM + bufferColor.setAlphaF(0.5); + windowColor.setAlphaF(0.5); +#else + painter.fillRect(rect(), Qt::black); +#endif + + if (m_bufferDuration) { + QRect bar = rect(); + const qreal play = qreal(m_playPosition) / m_bufferDuration; + bar.setLeft(rect().left() + play * rect().width()); + const qreal record = qreal(m_recordPosition) / m_bufferDuration; + bar.setRight(rect().left() + record * rect().width()); + painter.fillRect(bar, bufferColor); + + QRect window = rect(); + const qreal windowLeft = qreal(m_windowPosition) / m_bufferDuration; + window.setLeft(rect().left() + windowLeft * rect().width()); + const qreal windowWidth = qreal(m_windowLength) / m_bufferDuration; + window.setWidth(windowWidth * rect().width()); + painter.fillRect(window, windowColor); + } +} + +void ProgressBar::bufferDurationChanged(qint64 bufferSize) +{ + m_bufferDuration = bufferSize; + m_recordPosition = 0; + m_playPosition = 0; + m_windowPosition = 0; + m_windowLength = 0; + repaint(); +} + +void ProgressBar::recordPositionChanged(qint64 recordPosition) +{ + Q_ASSERT(recordPosition >= 0); + Q_ASSERT(recordPosition <= m_bufferDuration); + m_recordPosition = recordPosition; + repaint(); +} + +void ProgressBar::playPositionChanged(qint64 playPosition) +{ + Q_ASSERT(playPosition >= 0); + Q_ASSERT(playPosition <= m_bufferDuration); + m_playPosition = playPosition; + repaint(); +} + +void ProgressBar::windowChanged(qint64 position, qint64 length) +{ + Q_ASSERT(position >= 0); + Q_ASSERT(position <= m_bufferDuration); + Q_ASSERT(position + length <= m_bufferDuration); + m_windowPosition = position; + m_windowLength = length; + repaint(); +} diff --git a/demos/spectrum/app/progressbar.h b/demos/spectrum/app/progressbar.h new file mode 100644 index 0000000..8dc4765 --- /dev/null +++ b/demos/spectrum/app/progressbar.h @@ -0,0 +1,69 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** You may use this file under the terms of the BSD license as follows: +** +** Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are met: +** - Redistributions of source code must retain the above copyright notice, +** this list of conditions and the following disclaimer. +** - Redistributions in binary form must reproduce the above copyright notice, +** this list of conditions and the following disclaimer in the documentation +** and/or other materials provided with the distribution. +** - Neither the name of Nokia Corporation and its Subsidiary(-ies) nor the +** names of its contributors may be used to endorse or promote products +** derived from this software without specific prior written permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +** AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +** LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +** INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +** CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +** ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +** POSSIBILITY OF SUCH DAMAGE. +** +*****************************************************************************/ + +#ifndef PROGRESSBAR_H +#define PROGRESSBAR_H + +#include + +/** + * Widget which displays a the current fill state of the Engine's internal + * buffer, and the current play/record position within that buffer. + */ +class ProgressBar : public QWidget { + Q_OBJECT +public: + ProgressBar(QWidget *parent = 0); + ~ProgressBar(); + + void reset(); + void paintEvent(QPaintEvent *event); + +public slots: + void bufferDurationChanged(qint64 bufferSize); + void recordPositionChanged(qint64 recordPosition); + void playPositionChanged(qint64 playPosition); + void windowChanged(qint64 position, qint64 length); + +private: + qint64 m_bufferDuration; + qint64 m_recordPosition; + qint64 m_playPosition; + qint64 m_windowPosition; + qint64 m_windowLength; + +}; + +#endif // PROGRESSBAR_H diff --git a/demos/spectrum/app/settingsdialog.cpp b/demos/spectrum/app/settingsdialog.cpp new file mode 100644 index 0000000..204b43f --- /dev/null +++ b/demos/spectrum/app/settingsdialog.cpp @@ -0,0 +1,149 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the Technology Preview License Agreement accompanying +** this package. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** If you have questions regarding the use of this file, please contact +** Nokia at qt-info@nokia.com. +** +** +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "settingsdialog.h" +#include +#include +#include +#include +#include +#include +#include +#include + +SettingsDialog::SettingsDialog( + const QList &availableInputDevices, + const QList &availableOutputDevices, + QWidget *parent) + : QDialog(parent) + , m_windowFunction(DefaultWindowFunction) + , m_inputDeviceComboBox(new QComboBox(this)) + , m_outputDeviceComboBox(new QComboBox(this)) + , m_windowFunctionComboBox(new QComboBox(this)) +{ + QVBoxLayout *dialogLayout = new QVBoxLayout(this); + + // Populate combo boxes + + QAudioDeviceInfo device; + foreach (device, availableInputDevices) + m_inputDeviceComboBox->addItem(device.deviceName(), + qVariantFromValue(device)); + foreach (device, availableOutputDevices) + m_outputDeviceComboBox->addItem(device.deviceName(), + qVariantFromValue(device)); + + m_windowFunctionComboBox->addItem(tr("None"), qVariantFromValue(int(NoWindow))); + m_windowFunctionComboBox->addItem("Hann", qVariantFromValue(int(HannWindow))); + m_windowFunctionComboBox->setCurrentIndex(m_windowFunction); + + // Initialize default devices + if (!availableInputDevices.empty()) + m_inputDevice = availableInputDevices.front(); + if (!availableOutputDevices.empty()) + m_outputDevice = availableOutputDevices.front(); + + // Add widgets to layout + + QScopedPointer inputDeviceLayout(new QHBoxLayout); + QLabel *inputDeviceLabel = new QLabel(tr("Input device"), this); + inputDeviceLayout->addWidget(inputDeviceLabel); + inputDeviceLayout->addWidget(m_inputDeviceComboBox); + dialogLayout->addLayout(inputDeviceLayout.data()); + inputDeviceLayout.take(); // ownership transferred to dialogLayout + + QScopedPointer outputDeviceLayout(new QHBoxLayout); + QLabel *outputDeviceLabel = new QLabel(tr("Output device"), this); + outputDeviceLayout->addWidget(outputDeviceLabel); + outputDeviceLayout->addWidget(m_outputDeviceComboBox); + dialogLayout->addLayout(outputDeviceLayout.data()); + outputDeviceLayout.take(); // ownership transferred to dialogLayout + + QScopedPointer windowFunctionLayout(new QHBoxLayout); + QLabel *windowFunctionLabel = new QLabel(tr("Window function"), this); + windowFunctionLayout->addWidget(windowFunctionLabel); + windowFunctionLayout->addWidget(m_windowFunctionComboBox); + dialogLayout->addLayout(windowFunctionLayout.data()); + windowFunctionLayout.take(); // ownership transferred to dialogLayout + + // Connect + CHECKED_CONNECT(m_inputDeviceComboBox, SIGNAL(activated(int)), + this, SLOT(inputDeviceChanged(int))); + CHECKED_CONNECT(m_outputDeviceComboBox, SIGNAL(activated(int)), + this, SLOT(outputDeviceChanged(int))); + CHECKED_CONNECT(m_windowFunctionComboBox, SIGNAL(activated(int)), + this, SLOT(windowFunctionChanged(int))); + + // Add standard buttons to layout + QDialogButtonBox *buttonBox = new QDialogButtonBox(this); + buttonBox->setStandardButtons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); + dialogLayout->addWidget(buttonBox); + + // Connect standard buttons + CHECKED_CONNECT(buttonBox->button(QDialogButtonBox::Ok), SIGNAL(clicked()), + this, SLOT(accept())); + CHECKED_CONNECT(buttonBox->button(QDialogButtonBox::Cancel), SIGNAL(clicked()), + this, SLOT(reject())); + + setLayout(dialogLayout); +} + +SettingsDialog::~SettingsDialog() +{ + +} + +void SettingsDialog::windowFunctionChanged(int index) +{ + m_windowFunction = static_cast( + m_windowFunctionComboBox->itemData(index).value()); +} + +void SettingsDialog::inputDeviceChanged(int index) +{ + m_inputDevice = m_inputDeviceComboBox->itemData(index).value(); +} + +void SettingsDialog::outputDeviceChanged(int index) +{ + m_outputDevice = m_outputDeviceComboBox->itemData(index).value(); +} + diff --git a/demos/spectrum/app/settingsdialog.h b/demos/spectrum/app/settingsdialog.h new file mode 100644 index 0000000..5f613c0 --- /dev/null +++ b/demos/spectrum/app/settingsdialog.h @@ -0,0 +1,82 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** You may use this file under the terms of the BSD license as follows: +** +** Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are met: +** - Redistributions of source code must retain the above copyright notice, +** this list of conditions and the following disclaimer. +** - Redistributions in binary form must reproduce the above copyright notice, +** this list of conditions and the following disclaimer in the documentation +** and/or other materials provided with the distribution. +** - Neither the name of Nokia Corporation and its Subsidiary(-ies) nor the +** names of its contributors may be used to endorse or promote products +** derived from this software without specific prior written permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +** AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +** LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +** INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +** CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +** ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +** POSSIBILITY OF SUCH DAMAGE. +** +*****************************************************************************/ + +#ifndef SETTINGSDIALOG_H +#define SETTINGSDIALOG_H + +#include "spectrum.h" +#include +#include + +class QComboBox; +class QCheckBox; +class QSlider; +class QSpinBox; +class QGridLayout; + +/** + * Dialog used to control settings such as the audio input / output device + * and the windowing function. + */ +class SettingsDialog : public QDialog { + Q_OBJECT +public: + SettingsDialog(const QList &availableInputDevices, + const QList &availableOutputDevices, + QWidget *parent = 0); + ~SettingsDialog(); + + WindowFunction windowFunction() const { return m_windowFunction; } + const QAudioDeviceInfo& inputDevice() const { return m_inputDevice; } + const QAudioDeviceInfo& outputDevice() const { return m_outputDevice; } + +private slots: + void windowFunctionChanged(int index); + void inputDeviceChanged(int index); + void outputDeviceChanged(int index); + +private: + WindowFunction m_windowFunction; + QAudioDeviceInfo m_inputDevice; + QAudioDeviceInfo m_outputDevice; + + QComboBox* m_inputDeviceComboBox; + QComboBox* m_outputDeviceComboBox; + + QComboBox* m_windowFunctionComboBox; + +}; + +#endif // SETTINGSDIALOG_H diff --git a/demos/spectrum/app/spectrograph.cpp b/demos/spectrum/app/spectrograph.cpp new file mode 100644 index 0000000..1fcf434 --- /dev/null +++ b/demos/spectrum/app/spectrograph.cpp @@ -0,0 +1,242 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the Technology Preview License Agreement accompanying +** this package. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** If you have questions regarding the use of this file, please contact +** Nokia at qt-info@nokia.com. +** +** +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "spectrograph.h" +#include +#include +#include +#include + +const int NullTimerId = -1; +const int NullIndex = -1; +const int BarSelectionInterval = 2000; + +Spectrograph::Spectrograph(QWidget *parent) + : QWidget(parent) + , m_barSelected(NullIndex) + , m_timerId(NullTimerId) + , m_lowFreq(0.0) + , m_highFreq(0.0) +{ + setMinimumHeight(100); +} + +Spectrograph::~Spectrograph() +{ + +} + +void Spectrograph::setParams(int numBars, qreal lowFreq, qreal highFreq) +{ + Q_ASSERT(numBars > 0); + Q_ASSERT(highFreq > lowFreq); + m_bars.resize(numBars); + m_lowFreq = lowFreq; + m_highFreq = highFreq; + updateBars(); +} + +void Spectrograph::timerEvent(QTimerEvent *event) +{ + Q_ASSERT(event->timerId() == m_timerId); + Q_UNUSED(event) // suppress warnings in release builds + killTimer(m_timerId); + m_timerId = NullTimerId; + m_barSelected = NullIndex; + update(); +} + +void Spectrograph::paintEvent(QPaintEvent *event) +{ + Q_UNUSED(event) + + QPainter painter(this); + painter.fillRect(rect(), Qt::black); + + const int numBars = m_bars.count(); + + // Highlight region of selected bar + if (m_barSelected != NullIndex && numBars) { + QRect regionRect = rect(); + regionRect.setLeft(m_barSelected * rect().width() / numBars); + regionRect.setWidth(rect().width() / numBars); + QColor regionColor(202, 202, 64); + painter.setBrush(Qt::DiagCrossPattern); + painter.fillRect(regionRect, regionColor); + painter.setBrush(Qt::NoBrush); + } + + QColor barColor(51, 204, 102); + QColor clipColor(255, 255, 0); + + // Draw the outline + const QColor gridColor = barColor.darker(); + QPen gridPen(gridColor); + painter.setPen(gridPen); + painter.drawLine(rect().topLeft(), rect().topRight()); + painter.drawLine(rect().topRight(), rect().bottomRight()); + painter.drawLine(rect().bottomRight(), rect().bottomLeft()); + painter.drawLine(rect().bottomLeft(), rect().topLeft()); + + QVector dashes; + dashes << 2 << 2; + gridPen.setDashPattern(dashes); + painter.setPen(gridPen); + + // Draw vertical lines between bars + if (numBars) { + const int numHorizontalSections = numBars; + QLine line(rect().topLeft(), rect().bottomLeft()); + for (int i=1; i= 0.0 && value <= 1.0); + QRect bar = rect(); + bar.setLeft(rect().left() + leftPaddingWidth + (i * (gapWidth + barWidth))); + bar.setWidth(barWidth); + bar.setTop(rect().top() + gapWidth + (1.0 - value) * barHeight); + bar.setBottom(rect().bottom() - gapWidth); + + QColor color = barColor; + if (m_bars[i].clipped) + color = clipColor; + + painter.fillRect(bar, color); + } + } +} + +void Spectrograph::mousePressEvent(QMouseEvent *event) +{ + const QPoint pos = event->pos(); + const int index = m_bars.count() * (pos.x() - rect().left()) / rect().width(); + selectBar(index); +} + +void Spectrograph::reset() +{ + m_spectrum.reset(); + spectrumChanged(m_spectrum); +} + +void Spectrograph::spectrumChanged(const FrequencySpectrum &spectrum) +{ + m_spectrum = spectrum; + updateBars(); +} + +int Spectrograph::barIndex(qreal frequency) const +{ + Q_ASSERT(frequency >= m_lowFreq && frequency < m_highFreq); + const qreal bandWidth = (m_highFreq - m_lowFreq) / m_bars.count(); + const int index = (frequency - m_lowFreq) / bandWidth; + if(index <0 || index >= m_bars.count()) + Q_ASSERT(false); + return index; +} + +QPair Spectrograph::barRange(int index) const +{ + Q_ASSERT(index >= 0 && index < m_bars.count()); + const qreal bandWidth = (m_highFreq - m_lowFreq) / m_bars.count(); + return QPair(index * bandWidth, (index+1) * bandWidth); +} + +void Spectrograph::updateBars() +{ + m_bars.fill(Bar()); + FrequencySpectrum::const_iterator i = m_spectrum.begin(); + const FrequencySpectrum::const_iterator end = m_spectrum.end(); + for ( ; i != end; ++i) { + const FrequencySpectrum::Element e = *i; + if (e.frequency >= m_lowFreq && e.frequency < m_highFreq) { + Bar &bar = m_bars[barIndex(e.frequency)]; + bar.value = qMax(bar.value, e.amplitude); + bar.clipped |= e.clipped; + } + } + update(); +} + +void Spectrograph::selectBar(int index) { + const QPair frequencyRange = barRange(index); + const QString message = QString("%1 - %2 Hz") + .arg(frequencyRange.first) + .arg(frequencyRange.second); + emit infoMessage(message, BarSelectionInterval); + + if (NullTimerId != m_timerId) + killTimer(m_timerId); + m_timerId = startTimer(BarSelectionInterval); + + m_barSelected = index; + update(); +} + + diff --git a/demos/spectrum/app/spectrograph.h b/demos/spectrum/app/spectrograph.h new file mode 100644 index 0000000..837a1a5 --- /dev/null +++ b/demos/spectrum/app/spectrograph.h @@ -0,0 +1,94 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** You may use this file under the terms of the BSD license as follows: +** +** Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are met: +** - Redistributions of source code must retain the above copyright notice, +** this list of conditions and the following disclaimer. +** - Redistributions in binary form must reproduce the above copyright notice, +** this list of conditions and the following disclaimer in the documentation +** and/or other materials provided with the distribution. +** - Neither the name of Nokia Corporation and its Subsidiary(-ies) nor the +** names of its contributors may be used to endorse or promote products +** derived from this software without specific prior written permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +** AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +** LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +** INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +** CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +** ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +** POSSIBILITY OF SUCH DAMAGE. +** +*****************************************************************************/ + +#ifndef SPECTROGRAPH_H +#define SPECTROGRAPH_H + +#include +#include "frequencyspectrum.h" + +class QMouseEvent; + +/** + * Widget which displays a spectrograph showing the frequency spectrum + * of the window of audio samples most recently analysed by the Engine. + */ +class Spectrograph : public QWidget { + Q_OBJECT +public: + Spectrograph(QWidget *parent = 0); + ~Spectrograph(); + + void setParams(int numBars, qreal lowFreq, qreal highFreq); + + // QObject + void timerEvent(QTimerEvent *event); + + // QWidget + void paintEvent(QPaintEvent *event); + void mousePressEvent(QMouseEvent *event); + +signals: + void infoMessage(const QString &message, int intervalMs); + +public slots: + void reset(); + void spectrumChanged(const FrequencySpectrum &spectrum); + +private: + int barIndex(qreal frequency) const; + QPair barRange(int barIndex) const; + void updateBars(); + + void selectBar(int index); + +private: + struct Bar { + Bar() : value(0.0), clipped(false) { } + qreal value; + bool clipped; + }; + + QVector m_bars; + int m_barSelected; + int m_timerId; + qreal m_lowFreq; + qreal m_highFreq; + FrequencySpectrum m_spectrum; + + +}; + +#endif // SPECTROGRAPH_H diff --git a/demos/spectrum/app/spectrum.h b/demos/spectrum/app/spectrum.h new file mode 100644 index 0000000..47b88ae --- /dev/null +++ b/demos/spectrum/app/spectrum.h @@ -0,0 +1,139 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** You may use this file under the terms of the BSD license as follows: +** +** Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are met: +** - Redistributions of source code must retain the above copyright notice, +** this list of conditions and the following disclaimer. +** - Redistributions in binary form must reproduce the above copyright notice, +** this list of conditions and the following disclaimer in the documentation +** and/or other materials provided with the distribution. +** - Neither the name of Nokia Corporation and its Subsidiary(-ies) nor the +** names of its contributors may be used to endorse or promote products +** derived from this software without specific prior written permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +** AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +** LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +** INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +** CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +** ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +** POSSIBILITY OF SUCH DAMAGE. +** +*****************************************************************************/ + +#ifndef SPECTRUM_H +#define SPECTRUM_H + +#include +#include "utils.h" +#include "fftreal_wrapper.h" // For FFTLengthPowerOfTwo + +//----------------------------------------------------------------------------- +// Constants +//----------------------------------------------------------------------------- + +// Number of audio samples used to calculate the frequency spectrum +const int SpectrumLengthSamples = PowerOfTwo::Result; + +// Number of bands in the frequency spectrum +const int SpectrumNumBands = 10; + +// Lower bound of first band in the spectrum +const qreal SpectrumLowFreq = 0.0; // Hz + +// Upper band of last band in the spectrum +const qreal SpectrumHighFreq = 1000.0; // Hz + +// Waveform window size in microseconds +const qint64 WaveformWindowDuration = 500 * 1000; + +// Length of waveform tiles in bytes +// Ideally, these would match the QAudio*::bufferSize(), but that isn't +// available until some time after QAudio*::start() has been called, and we +// need this value in order to initialize the waveform display. +// We therefore just choose a sensible value. +const int WaveformTileLength = 4096; + +// Fudge factor used to calculate the spectrum bar heights +const qreal SpectrumAnalyserMultiplier = 0.15; + +// Disable message timeout +const int NullMessageTimeout = -1; + + +//----------------------------------------------------------------------------- +// Types and data structures +//----------------------------------------------------------------------------- + +enum WindowFunction { + NoWindow, + HannWindow +}; + +const WindowFunction DefaultWindowFunction = HannWindow; + +struct Tone { + Tone(qreal freq = 0.0, qreal amp = 0.0) + : frequency(freq), amplitude(amp) + { } + + // Start and end frequencies for swept tone generation + qreal frequency; + + // Amplitude in range [0.0, 1.0] + qreal amplitude; +}; + +struct SweptTone { + SweptTone(qreal start = 0.0, qreal end = 0.0, qreal amp = 0.0) + : startFreq(start), endFreq(end), amplitude(amp) + { Q_ASSERT(end >= start); } + + SweptTone(const Tone &tone) + : startFreq(tone.frequency), endFreq(tone.frequency), amplitude(tone.amplitude) + { } + + // Start and end frequencies for swept tone generation + qreal startFreq; + qreal endFreq; + + // Amplitude in range [0.0, 1.0] + qreal amplitude; +}; + + +//----------------------------------------------------------------------------- +// Macros +//----------------------------------------------------------------------------- + +// Macro which connects a signal to a slot, and which causes application to +// abort if the connection fails. This is intended to catch programming errors +// such as mis-typing a signal or slot name. It is necessary to write our own +// macro to do this - the following idiom +// Q_ASSERT(connect(source, signal, receiver, slot)); +// will not work because Q_ASSERT compiles to a no-op in release builds. + +#define CHECKED_CONNECT(source, signal, receiver, slot) \ + if(!connect(source, signal, receiver, slot)) \ + qt_assert_x(Q_FUNC_INFO, "CHECKED_CONNECT failed", __FILE__, __LINE__); + +// Handle some dependencies between macros defined in the .pro file + +#ifdef DISABLE_WAVEFORM +#undef SUPERIMPOSE_PROGRESS_ON_WAVEFORM +#endif + +#endif // SPECTRUM_H + diff --git a/demos/spectrum/app/spectrum.qrc b/demos/spectrum/app/spectrum.qrc new file mode 100644 index 0000000..6100479 --- /dev/null +++ b/demos/spectrum/app/spectrum.qrc @@ -0,0 +1,7 @@ + + + images/record.png + images/settings.png + + + diff --git a/demos/spectrum/app/spectrum.sh b/demos/spectrum/app/spectrum.sh new file mode 100644 index 0000000..75ad6c2 --- /dev/null +++ b/demos/spectrum/app/spectrum.sh @@ -0,0 +1,9 @@ +#!/bin/sh + +# Shell script for launching spectrum application on Unix systems other than Mac OSX + +bindir=`dirname "$0"` +LD_LIBRARY_PATH="${bindir}:${LD_LIBRARY_PATH}" +export LD_LIBRARY_PATH +exec "${bindir}/spectrum.bin" ${1+"$@"} + diff --git a/demos/spectrum/app/spectrumanalyser.cpp b/demos/spectrum/app/spectrumanalyser.cpp new file mode 100644 index 0000000..54d3f5e --- /dev/null +++ b/demos/spectrum/app/spectrumanalyser.cpp @@ -0,0 +1,280 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the Technology Preview License Agreement accompanying +** this package. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** If you have questions regarding the use of this file, please contact +** Nokia at qt-info@nokia.com. +** +** +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "spectrumanalyser.h" +#include "utils.h" + +#include +#include +#include +#include + +#include "fftreal_wrapper.h" + +SpectrumAnalyserThread::SpectrumAnalyserThread(QObject *parent) + : QObject(parent) +#ifndef DISABLE_FFT + , m_fft(new FFTRealWrapper) +#endif + , m_numSamples(SpectrumLengthSamples) + , m_windowFunction(DefaultWindowFunction) + , m_window(SpectrumLengthSamples, 0.0) + , m_input(SpectrumLengthSamples, 0.0) + , m_output(SpectrumLengthSamples, 0.0) + , m_spectrum(SpectrumLengthSamples) +#ifdef SPECTRUM_ANALYSER_SEPARATE_THREAD + , m_thread(new QThread(this)) +#endif +{ +#ifdef SPECTRUM_ANALYSER_SEPARATE_THREAD + moveToThread(m_thread); + m_thread->start(); +#endif + calculateWindow(); +} + +SpectrumAnalyserThread::~SpectrumAnalyserThread() +{ +#ifndef DISABLE_FFT + delete m_fft; +#endif +} + +void SpectrumAnalyserThread::setWindowFunction(WindowFunction type) +{ + m_windowFunction = type; + calculateWindow(); +} + +void SpectrumAnalyserThread::calculateWindow() +{ + for (int i=0; i(ptr); + // Scale down to range [-1.0, 1.0] + const DataType realSample = pcmToReal(pcmSample); + const DataType windowedSample = realSample * m_window[i]; + m_input[i] = windowedSample; + ptr += bytesPerSample; + } + + // Calculate the FFT + m_fft->calculateFFT(m_output.data(), m_input.data()); + + // Analyse output to obtain amplitude and phase for each frequency + for (int i=2; i<=m_numSamples/2; ++i) { + // Calculate frequency of this complex sample + m_spectrum[i].frequency = qreal(i * inputFrequency) / (m_numSamples); + + const qreal real = m_output[i]; + qreal imag = 0.0; + if (i>0 && i 1.0); + amplitude = qMax(qreal(0.0), amplitude); + amplitude = qMin(qreal(1.0), amplitude); + m_spectrum[i].amplitude = amplitude; + } +#endif + + emit calculationComplete(m_spectrum); +} + + +//============================================================================= +// SpectrumAnalyser +//============================================================================= + +SpectrumAnalyser::SpectrumAnalyser(QObject *parent) + : QObject(parent) + , m_thread(new SpectrumAnalyserThread(this)) + , m_state(Idle) +#ifdef DUMP_SPECTRUMANALYSER + , m_count(0) +#endif +{ + CHECKED_CONNECT(m_thread, SIGNAL(calculationComplete(FrequencySpectrum)), + this, SLOT(calculationComplete(FrequencySpectrum))); +} + +SpectrumAnalyser::~SpectrumAnalyser() +{ + +} + +#ifdef DUMP_SPECTRUMANALYSER +void SpectrumAnalyser::setOutputPath(const QString &outputDir) +{ + m_outputDir.setPath(outputDir); + m_textFile.setFileName(m_outputDir.filePath("spectrum.txt")); + m_textFile.open(QIODevice::WriteOnly | QIODevice::Text); + m_textStream.setDevice(&m_textFile); +} +#endif + +//----------------------------------------------------------------------------- +// Public functions +//----------------------------------------------------------------------------- + +void SpectrumAnalyser::setWindowFunction(WindowFunction type) +{ + const bool b = QMetaObject::invokeMethod(m_thread, "setWindowFunction", + Qt::AutoConnection, + Q_ARG(WindowFunction, type)); + Q_ASSERT(b); + Q_UNUSED(b) // suppress warnings in release builds +} + +void SpectrumAnalyser::calculate(const QByteArray &buffer, + const QAudioFormat &format) +{ + // QThread::currentThread is marked 'for internal use only', but + // we're only using it for debug output here, so it's probably OK :) + SPECTRUMANALYSER_DEBUG << "SpectrumAnalyser::calculate" + << QThread::currentThread() + << "state" << m_state; + + if (isReady()) { + Q_ASSERT(isPCMS16LE(format)); + + const int bytesPerSample = format.sampleSize() * format.channels() / 8; + +#ifdef DUMP_SPECTRUMANALYSER + m_count++; + const QString pcmFileName = m_outputDir.filePath(QString("spectrum_%1.pcm").arg(m_count, 4, 10, QChar('0'))); + QFile pcmFile(pcmFileName); + pcmFile.open(QIODevice::WriteOnly); + const int bufferLength = m_numSamples * bytesPerSample; + pcmFile.write(buffer, bufferLength); + + m_textStream << "TimeDomain " << m_count << "\n"; + const qint16* input = reinterpret_cast(buffer); + for (int i=0; ifrequency << "\t" + << x->amplitude<< "\t" + << x->phase << "\n"; +#endif + } +} + +bool SpectrumAnalyser::isReady() const +{ + return (Idle == m_state); +} + +void SpectrumAnalyser::cancelCalculation() +{ + if (Busy == m_state) + m_state = Cancelled; +} + + +//----------------------------------------------------------------------------- +// Private slots +//----------------------------------------------------------------------------- + +void SpectrumAnalyser::calculationComplete(const FrequencySpectrum &spectrum) +{ + Q_ASSERT(Idle != m_state); + if (Busy == m_state) + emit spectrumChanged(spectrum); + m_state = Idle; +} + + + + diff --git a/demos/spectrum/app/spectrumanalyser.h b/demos/spectrum/app/spectrumanalyser.h new file mode 100644 index 0000000..9d7684a --- /dev/null +++ b/demos/spectrum/app/spectrumanalyser.h @@ -0,0 +1,188 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** You may use this file under the terms of the BSD license as follows: +** +** Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are met: +** - Redistributions of source code must retain the above copyright notice, +** this list of conditions and the following disclaimer. +** - Redistributions in binary form must reproduce the above copyright notice, +** this list of conditions and the following disclaimer in the documentation +** and/or other materials provided with the distribution. +** - Neither the name of Nokia Corporation and its Subsidiary(-ies) nor the +** names of its contributors may be used to endorse or promote products +** derived from this software without specific prior written permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +** AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +** LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +** INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +** CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +** ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +** POSSIBILITY OF SUCH DAMAGE. +** +*****************************************************************************/ + +#ifndef SPECTRUMANALYSER_H +#define SPECTRUMANALYSER_H + +#include +#include +#include + +#ifdef DUMP_SPECTRUMANALYSER +#include +#include +#include +#endif + +#include "frequencyspectrum.h" +#include "spectrum.h" + +#ifndef DISABLE_FFT +#include "FFTRealFixLenParam.h" +#endif + +class QAudioFormat; +class QThread; +class FFTRealWrapper; + +class SpectrumAnalyserThreadPrivate; + +/** + * Implementation of the spectrum analysis which can be run in a + * separate thread. + */ +class SpectrumAnalyserThread : public QObject +{ + Q_OBJECT +public: + SpectrumAnalyserThread(QObject *parent); + ~SpectrumAnalyserThread(); + +public slots: + void setWindowFunction(WindowFunction type); + void calculateSpectrum(const QByteArray &buffer, + int inputFrequency, + int bytesPerSample); + +signals: + void calculationComplete(const FrequencySpectrum &spectrum); + +private: + void calculateWindow(); + +private: +#ifndef DISABLE_FFT + FFTRealWrapper* m_fft; +#endif + + const int m_numSamples; + + WindowFunction m_windowFunction; + +#ifdef DISABLE_FFT + typedef qreal DataType; +#else + typedef FFTRealFixLenParam::DataType DataType; +#endif + QVector m_window; + + QVector m_input; + QVector m_output; + + FrequencySpectrum m_spectrum; + +#ifdef SPECTRUM_ANALYSER_SEPARATE_THREAD + QThread* m_thread; +#endif +}; + +/** + * Class which performs frequency spectrum analysis on a window of + * audio samples, provided to it by the Engine. + */ +class SpectrumAnalyser : public QObject +{ + Q_OBJECT +public: + SpectrumAnalyser(QObject *parent = 0); + ~SpectrumAnalyser(); + +#ifdef DUMP_SPECTRUMANALYSER + void setOutputPath(const QString &outputPath); +#endif + +public: + /* + * Set the windowing function which is applied before calculating the FFT + */ + void setWindowFunction(WindowFunction type); + + /* + * Calculate a frequency spectrum + * + * \param buffer Audio data + * \param format Format of audio data + * + * Frequency spectrum is calculated asynchronously. The result is returned + * via the spectrumChanged signal. + * + * An ongoing calculation can be cancelled by calling cancelCalculation(). + * + */ + void calculate(const QByteArray &buffer, const QAudioFormat &format); + + /* + * Check whether the object is ready to perform another calculation + */ + bool isReady() const; + + /* + * Cancel an ongoing calculation + * + * Note that cancelling is asynchronous. + */ + void cancelCalculation(); + +signals: + void spectrumChanged(const FrequencySpectrum &spectrum); + +private slots: + void calculationComplete(const FrequencySpectrum &spectrum); + +private: + void calculateWindow(); + +private: + + SpectrumAnalyserThread* m_thread; + + enum State { + Idle, + Busy, + Cancelled + }; + + State m_state; + +#ifdef DUMP_SPECTRUMANALYSER + QDir m_outputDir; + int m_count; + QFile m_textFile; + QTextStream m_textStream; +#endif +}; + +#endif // SPECTRUMANALYSER_H + diff --git a/demos/spectrum/app/tonegenerator.cpp b/demos/spectrum/app/tonegenerator.cpp new file mode 100644 index 0000000..6458a7d --- /dev/null +++ b/demos/spectrum/app/tonegenerator.cpp @@ -0,0 +1,92 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the Technology Preview License Agreement accompanying +** this package. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** If you have questions regarding the use of this file, please contact +** Nokia at qt-info@nokia.com. +** +** +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "spectrum.h" +#include "utils.h" +#include +#include +#include +#include + +void generateTone(const SweptTone &tone, const QAudioFormat &format, QByteArray &buffer) +{ + Q_ASSERT(isPCMS16LE(format)); + + const int channelBytes = format.sampleSize() / 8; + const int sampleBytes = format.channels() * channelBytes; + int length = buffer.size(); + const int numSamples = buffer.size() / sampleBytes; + + Q_ASSERT(length % sampleBytes == 0); + Q_UNUSED(sampleBytes) // suppress warning in release builds + + unsigned char *ptr = reinterpret_cast(buffer.data()); + + qreal phase = 0.0; + + const qreal d = 2 * M_PI / format.frequency(); + + // We can't generate a zero-frequency sine wave + const qreal startFreq = tone.startFreq ? tone.startFreq : 1.0; + + // Amount by which phase increases on each sample + qreal phaseStep = d * startFreq; + + // Amount by which phaseStep increases on each sample + // If this is non-zero, the output is a frequency-swept tone + const qreal phaseStepStep = d * (tone.endFreq - startFreq) / numSamples; + + while (length) { + const qreal x = tone.amplitude * qSin(phase); + const qint16 value = realToPcm(x); + for (int i=0; i(value, ptr); + ptr += channelBytes; + length -= channelBytes; + } + + phase += phaseStep; + while (phase > 2 * M_PI) + phase -= 2 * M_PI; + phaseStep += phaseStepStep; + } +} + diff --git a/demos/spectrum/app/tonegenerator.h b/demos/spectrum/app/tonegenerator.h new file mode 100644 index 0000000..05d4c17 --- /dev/null +++ b/demos/spectrum/app/tonegenerator.h @@ -0,0 +1,51 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** You may use this file under the terms of the BSD license as follows: +** +** Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are met: +** - Redistributions of source code must retain the above copyright notice, +** this list of conditions and the following disclaimer. +** - Redistributions in binary form must reproduce the above copyright notice, +** this list of conditions and the following disclaimer in the documentation +** and/or other materials provided with the distribution. +** - Neither the name of Nokia Corporation and its Subsidiary(-ies) nor the +** names of its contributors may be used to endorse or promote products +** derived from this software without specific prior written permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +** AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +** LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +** INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +** CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +** ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +** POSSIBILITY OF SUCH DAMAGE. +** +*****************************************************************************/ + +#ifndef TONEGENERATOR_H +#define TONEGENERATOR_H + +#include +#include "spectrum.h" + +class QAudioFormat; +class QByteArray; + +/** + * Generate a sine wave + */ +void generateTone(const SweptTone &tone, const QAudioFormat &format, QByteArray &buffer); + +#endif // TONEGENERATOR_H + diff --git a/demos/spectrum/app/tonegeneratordialog.cpp b/demos/spectrum/app/tonegeneratordialog.cpp new file mode 100644 index 0000000..06e453c --- /dev/null +++ b/demos/spectrum/app/tonegeneratordialog.cpp @@ -0,0 +1,148 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the Technology Preview License Agreement accompanying +** this package. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** If you have questions regarding the use of this file, please contact +** Nokia at qt-info@nokia.com. +** +** +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "tonegeneratordialog.h" +#include +#include +#include +#include +#include +#include +#include +#include + +const int ToneGeneratorFreqMin = 1; +const int ToneGeneratorFreqMax = 1000; +const int ToneGeneratorFreqDefault = 440; +const int ToneGeneratorAmplitudeDefault = 75; + +ToneGeneratorDialog::ToneGeneratorDialog(QWidget *parent) + : QDialog(parent) + , m_toneGeneratorSweepCheckBox(new QCheckBox(tr("Frequency sweep"), this)) + , m_frequencySweepEnabled(true) + , m_toneGeneratorControl(new QWidget(this)) + , m_toneGeneratorFrequencyControl(new QWidget(this)) + , m_frequencySlider(new QSlider(Qt::Horizontal, this)) + , m_frequencySpinBox(new QSpinBox(this)) + , m_frequency(ToneGeneratorFreqDefault) + , m_amplitudeSlider(new QSlider(Qt::Horizontal, this)) +{ + QVBoxLayout *dialogLayout = new QVBoxLayout(this); + + m_toneGeneratorSweepCheckBox->setChecked(true); + + // Configure tone generator controls + m_frequencySlider->setRange(ToneGeneratorFreqMin, ToneGeneratorFreqMax); + m_frequencySlider->setValue(ToneGeneratorFreqDefault); + m_frequencySpinBox->setRange(ToneGeneratorFreqMin, ToneGeneratorFreqMax); + m_frequencySpinBox->setValue(ToneGeneratorFreqDefault); + m_amplitudeSlider->setRange(0, 100); + m_amplitudeSlider->setValue(ToneGeneratorAmplitudeDefault); + + // Add widgets to layout + + QScopedPointer frequencyControlLayout(new QGridLayout); + QLabel *frequencyLabel = new QLabel(tr("Frequency (Hz)"), this); + frequencyControlLayout->addWidget(frequencyLabel, 0, 0, 2, 1); + frequencyControlLayout->addWidget(m_frequencySlider, 0, 1); + frequencyControlLayout->addWidget(m_frequencySpinBox, 1, 1); + m_toneGeneratorFrequencyControl->setLayout(frequencyControlLayout.data()); + frequencyControlLayout.take(); // ownership transferred to m_toneGeneratorFrequencyControl + m_toneGeneratorFrequencyControl->setEnabled(false); + + QScopedPointer toneGeneratorLayout(new QGridLayout); + QLabel *amplitudeLabel = new QLabel(tr("Amplitude"), this); + toneGeneratorLayout->addWidget(m_toneGeneratorSweepCheckBox, 0, 1); + toneGeneratorLayout->addWidget(m_toneGeneratorFrequencyControl, 1, 0, 1, 2); + toneGeneratorLayout->addWidget(amplitudeLabel, 2, 0); + toneGeneratorLayout->addWidget(m_amplitudeSlider, 2, 1); + m_toneGeneratorControl->setLayout(toneGeneratorLayout.data()); + m_toneGeneratorControl->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); + dialogLayout->addWidget(m_toneGeneratorControl); + toneGeneratorLayout.take(); // ownership transferred + + // Connect + CHECKED_CONNECT(m_toneGeneratorSweepCheckBox, SIGNAL(toggled(bool)), + this, SLOT(frequencySweepEnabled(bool))); + CHECKED_CONNECT(m_frequencySlider, SIGNAL(valueChanged(int)), + m_frequencySpinBox, SLOT(setValue(int))); + CHECKED_CONNECT(m_frequencySpinBox, SIGNAL(valueChanged(int)), + m_frequencySlider, SLOT(setValue(int))); + + // Add standard buttons to layout + QDialogButtonBox *buttonBox = new QDialogButtonBox(this); + buttonBox->setStandardButtons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); + dialogLayout->addWidget(buttonBox); + + // Connect standard buttons + CHECKED_CONNECT(buttonBox->button(QDialogButtonBox::Ok), SIGNAL(clicked()), + this, SLOT(accept())); + CHECKED_CONNECT(buttonBox->button(QDialogButtonBox::Cancel), SIGNAL(clicked()), + this, SLOT(reject())); + + setLayout(dialogLayout); +} + +ToneGeneratorDialog::~ToneGeneratorDialog() +{ + +} + +bool ToneGeneratorDialog::isFrequencySweepEnabled() const +{ + return m_toneGeneratorSweepCheckBox->isChecked(); +} + +qreal ToneGeneratorDialog::frequency() const +{ + return qreal(m_frequencySlider->value()); +} + +qreal ToneGeneratorDialog::amplitude() const +{ + return qreal(m_amplitudeSlider->value()) / 100.0; +} + +void ToneGeneratorDialog::frequencySweepEnabled(bool enabled) +{ + m_frequencySweepEnabled = enabled; + m_toneGeneratorFrequencyControl->setEnabled(!enabled); +} diff --git a/demos/spectrum/app/tonegeneratordialog.h b/demos/spectrum/app/tonegeneratordialog.h new file mode 100644 index 0000000..33b608d --- /dev/null +++ b/demos/spectrum/app/tonegeneratordialog.h @@ -0,0 +1,76 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** You may use this file under the terms of the BSD license as follows: +** +** Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are met: +** - Redistributions of source code must retain the above copyright notice, +** this list of conditions and the following disclaimer. +** - Redistributions in binary form must reproduce the above copyright notice, +** this list of conditions and the following disclaimer in the documentation +** and/or other materials provided with the distribution. +** - Neither the name of Nokia Corporation and its Subsidiary(-ies) nor the +** names of its contributors may be used to endorse or promote products +** derived from this software without specific prior written permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +** AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +** LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +** INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +** CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +** ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +** POSSIBILITY OF SUCH DAMAGE. +** +*****************************************************************************/ + +#ifndef TONEGENERATORDIALOG_H +#define TONEGENERATORDIALOG_H + +#include "spectrum.h" +#include +#include + +class QCheckBox; +class QSlider; +class QSpinBox; +class QGridLayout; + +/** + * Dialog which controls the parameters of the tone generator. + */ +class ToneGeneratorDialog : public QDialog { + Q_OBJECT +public: + ToneGeneratorDialog(QWidget *parent = 0); + ~ToneGeneratorDialog(); + + bool isFrequencySweepEnabled() const; + qreal frequency() const; + qreal amplitude() const; + +private slots: + void frequencySweepEnabled(bool enabled); + +private: + QCheckBox* m_toneGeneratorSweepCheckBox; + bool m_frequencySweepEnabled; + QWidget* m_toneGeneratorControl; + QWidget* m_toneGeneratorFrequencyControl; + QSlider* m_frequencySlider; + QSpinBox* m_frequencySpinBox; + qreal m_frequency; + QSlider* m_amplitudeSlider; + +}; + +#endif // TONEGENERATORDIALOG_H diff --git a/demos/spectrum/app/utils.cpp b/demos/spectrum/app/utils.cpp new file mode 100644 index 0000000..97dc6e3 --- /dev/null +++ b/demos/spectrum/app/utils.cpp @@ -0,0 +1,138 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the Technology Preview License Agreement accompanying +** this package. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** If you have questions regarding the use of this file, please contact +** Nokia at qt-info@nokia.com. +** +** +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include "utils.h" + +qint64 audioDuration(const QAudioFormat &format, qint64 bytes) +{ + return (bytes * 1000000) / + (format.frequency() * format.channels() * (format.sampleSize() / 8)); +} + +qint64 audioLength(const QAudioFormat &format, qint64 microSeconds) +{ + return (format.frequency() * format.channels() * (format.sampleSize() / 8)) + * microSeconds / 1000000; +} + +qreal nyquistFrequency(const QAudioFormat &format) +{ + return format.frequency() / 2; +} + +QString formatToString(const QAudioFormat &format) +{ + QString result; + + if (QAudioFormat() != format) { + if (format.codec() == "audio/pcm") { + Q_ASSERT(format.sampleType() == QAudioFormat::SignedInt); + + const QString formatEndian = (format.byteOrder() == QAudioFormat::LittleEndian) + ? QString("LE") : QString("BE"); + + QString formatType; + switch(format.sampleType()) { + case QAudioFormat::SignedInt: + formatType = "signed"; + break; + case QAudioFormat::UnSignedInt: + formatType = "unsigned"; + break; + case QAudioFormat::Float: + formatType = "float"; + break; + case QAudioFormat::Unknown: + formatType = "unknown"; + break; + } + + QString formatChannels = QString("%1 channels").arg(format.channels()); + switch (format.channels()) { + case 1: + formatChannels = "mono"; + break; + case 2: + formatChannels = "stereo"; + break; + } + + result = QString("%1 Hz %2 bit %3 %4 %5") + .arg(format.frequency()) + .arg(format.sampleSize()) + .arg(formatType) + .arg(formatEndian) + .arg(formatChannels); + } else { + result = format.codec(); + } + } + + return result; +} + +bool isPCM(const QAudioFormat &format) +{ + return (format.codec() == "audio/pcm"); +} + + +bool isPCMS16LE(const QAudioFormat &format) +{ + return (isPCM(format) && + format.sampleType() == QAudioFormat::SignedInt && + format.sampleSize() == 16 && + format.byteOrder() == QAudioFormat::LittleEndian); +} + +const qint16 PCMS16MaxValue = 32767; +const quint16 PCMS16MaxAmplitude = 32768; // because minimum is -32768 + +qreal pcmToReal(qint16 pcm) +{ + return qreal(pcm) / PCMS16MaxAmplitude; +} + +qint16 realToPcm(qreal real) +{ + return real * PCMS16MaxValue; +} diff --git a/demos/spectrum/app/utils.h b/demos/spectrum/app/utils.h new file mode 100644 index 0000000..cfa3633 --- /dev/null +++ b/demos/spectrum/app/utils.h @@ -0,0 +1,107 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** You may use this file under the terms of the BSD license as follows: +** +** Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are met: +** - Redistributions of source code must retain the above copyright notice, +** this list of conditions and the following disclaimer. +** - Redistributions in binary form must reproduce the above copyright notice, +** this list of conditions and the following disclaimer in the documentation +** and/or other materials provided with the distribution. +** - Neither the name of Nokia Corporation and its Subsidiary(-ies) nor the +** names of its contributors may be used to endorse or promote products +** derived from this software without specific prior written permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +** AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +** LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +** INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +** CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +** ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +** POSSIBILITY OF SUCH DAMAGE. +** +*****************************************************************************/ + +#ifndef UTILS_H +#define UTILS_H + +#include +#include + +class QAudioFormat; + +//----------------------------------------------------------------------------- +// Miscellaneous utility functions +//----------------------------------------------------------------------------- + +qint64 audioDuration(const QAudioFormat &format, qint64 bytes); +qint64 audioLength(const QAudioFormat &format, qint64 microSeconds); + +QString formatToString(const QAudioFormat &format); + +qreal nyquistFrequency(const QAudioFormat &format); + +// Scale PCM value to [-1.0, 1.0] +qreal pcmToReal(qint16 pcm); + +// Scale real value in [-1.0, 1.0] to PCM +qint16 realToPcm(qreal real); + +// Check whether the audio format is PCM +bool isPCM(const QAudioFormat &format); + +// Check whether the audio format is signed, little-endian, 16-bit PCM +bool isPCMS16LE(const QAudioFormat &format); + +// Compile-time calculation of powers of two + +template class PowerOfTwo +{ public: static const int Result = PowerOfTwo::Result * 2; }; + +template<> class PowerOfTwo<0> +{ public: static const int Result = 1; }; + + +//----------------------------------------------------------------------------- +// Debug output +//----------------------------------------------------------------------------- + +class NullDebug +{ +public: + template + NullDebug& operator<<(const T&) { return *this; } +}; + +inline NullDebug nullDebug() { return NullDebug(); } + +#ifdef LOG_ENGINE +# define ENGINE_DEBUG qDebug() +#else +# define ENGINE_DEBUG nullDebug() +#endif + +#ifdef LOG_SPECTRUMANALYSER +# define SPECTRUMANALYSER_DEBUG qDebug() +#else +# define SPECTRUMANALYSER_DEBUG nullDebug() +#endif + +#ifdef LOG_WAVEFORM +# define WAVEFORM_DEBUG qDebug() +#else +# define WAVEFORM_DEBUG nullDebug() +#endif + +#endif // UTILS_H diff --git a/demos/spectrum/app/waveform.cpp b/demos/spectrum/app/waveform.cpp new file mode 100644 index 0000000..3fc4f76 --- /dev/null +++ b/demos/spectrum/app/waveform.cpp @@ -0,0 +1,419 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the Technology Preview License Agreement accompanying +** this package. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** If you have questions regarding the use of this file, please contact +** Nokia at qt-info@nokia.com. +** +** +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "waveform.h" +#include "utils.h" +#include +#include +#include + + +Waveform::Waveform(const QByteArray &buffer, QWidget *parent) + : QWidget(parent) + , m_buffer(buffer) + , m_dataLength(0) + , m_position(0) + , m_active(false) + , m_tileLength(0) + , m_tileArrayStart(0) + , m_windowPosition(0) + , m_windowLength(0) +{ + setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); + setMinimumHeight(50); +} + +Waveform::~Waveform() +{ + deletePixmaps(); +} + +void Waveform::paintEvent(QPaintEvent * /*event*/) +{ + QPainter painter(this); + + painter.fillRect(rect(), Qt::black); + + if (m_active) { + WAVEFORM_DEBUG << "Waveform::paintEvent" + << "windowPosition" << m_windowPosition + << "windowLength" << m_windowLength; + qint64 pos = m_windowPosition; + const qint64 windowEnd = m_windowPosition + m_windowLength; + int destLeft = 0; + int destRight = 0; + while (pos < windowEnd) { + const TilePoint point = tilePoint(pos); + WAVEFORM_DEBUG << "Waveform::paintEvent" << "pos" << pos + << "tileIndex" << point.index + << "positionOffset" << point.positionOffset + << "pixelOffset" << point.pixelOffset; + + if (point.index != NullIndex) { + const Tile &tile = m_tiles[point.index]; + if (tile.painted) { + const qint64 sectionLength = qMin((m_tileLength - point.positionOffset), + (windowEnd - pos)); + Q_ASSERT(sectionLength > 0); + + const int sourceRight = tilePixelOffset(point.positionOffset + sectionLength); + destRight = windowPixelOffset(pos - m_windowPosition + sectionLength); + + QRect destRect = rect(); + destRect.setLeft(destLeft); + destRect.setRight(destRight); + + QRect sourceRect(QPoint(), m_pixmapSize); + sourceRect.setLeft(point.pixelOffset); + sourceRect.setRight(sourceRight); + + WAVEFORM_DEBUG << "Waveform::paintEvent" << "tileIndex" << point.index + << "source" << point.pixelOffset << sourceRight + << "dest" << destLeft << destRight; + + painter.drawPixmap(destRect, *tile.pixmap, sourceRect); + + destLeft = destRight; + + if (point.index < m_tiles.count()) { + pos = tilePosition(point.index + 1); + WAVEFORM_DEBUG << "Waveform::paintEvent" << "pos ->" << pos; + } else { + // Reached end of tile array + WAVEFORM_DEBUG << "Waveform::paintEvent" << "reached end of tile array"; + break; + } + } else { + // Passed last tile which is painted + WAVEFORM_DEBUG << "Waveform::paintEvent" << "tile" << point.index << "not painted"; + break; + } + } else { + // pos is past end of tile array + WAVEFORM_DEBUG << "Waveform::paintEvent" << "pos" << pos << "past end of tile array"; + break; + } + } + + WAVEFORM_DEBUG << "Waveform::paintEvent" << "final pos" << pos << "final x" << destRight; + } +} + +void Waveform::resizeEvent(QResizeEvent *event) +{ + if (event->size() != event->oldSize()) + createPixmaps(event->size()); +} + +void Waveform::initialize(const QAudioFormat &format, qint64 audioBufferSize, qint64 windowDurationUs) +{ + WAVEFORM_DEBUG << "Waveform::initialize" + << "audioBufferSize" << audioBufferSize + << "m_buffer.size()" << m_buffer.size() + << "windowDurationUs" << windowDurationUs; + + reset(); + + m_format = format; + + // Calculate tile size + m_tileLength = audioBufferSize; + + // Calculate window size + m_windowLength = audioLength(m_format, windowDurationUs); + + // Calculate number of tiles required + int nTiles; + if (m_tileLength > m_windowLength) { + nTiles = 2; + } else { + nTiles = m_windowLength / m_tileLength + 1; + if (m_windowLength % m_tileLength) + ++nTiles; + } + + WAVEFORM_DEBUG << "Waveform::initialize" + << "tileLength" << m_tileLength + << "windowLength" << m_windowLength + << "nTiles" << nTiles; + + m_pixmaps.fill(0, nTiles); + m_tiles.resize(nTiles); + + createPixmaps(rect().size()); + + m_active = true; +} + +void Waveform::reset() +{ + WAVEFORM_DEBUG << "Waveform::reset"; + + m_dataLength = 0; + m_position = 0; + m_format = QAudioFormat(); + m_active = false; + deletePixmaps(); + m_tiles.clear(); + m_tileLength = 0; + m_tileArrayStart = 0; + m_windowPosition = 0; + m_windowLength = 0; +} + +void Waveform::dataLengthChanged(qint64 length) +{ + WAVEFORM_DEBUG << "Waveform::dataLengthChanged" << length; + const qint64 oldLength = m_dataLength; + m_dataLength = length; + + if (m_active) { + if (m_dataLength < oldLength) + positionChanged(m_dataLength); + else + paintTiles(); + } +} + +void Waveform::positionChanged(qint64 position) +{ + WAVEFORM_DEBUG << "Waveform::positionChanged" << position; + + if (position + m_windowLength > m_dataLength) + position = m_dataLength - m_windowLength; + + m_position = position; + + setWindowPosition(position); +} + +void Waveform::deletePixmaps() +{ + QPixmap *pixmap; + foreach (pixmap, m_pixmaps) + delete pixmap; + m_pixmaps.clear(); +} + +void Waveform::createPixmaps(const QSize &widgetSize) +{ + m_pixmapSize = widgetSize; + m_pixmapSize.setWidth(qreal(widgetSize.width()) * m_tileLength / m_windowLength); + + WAVEFORM_DEBUG << "Waveform::createPixmaps" + << "widgetSize" << widgetSize + << "pixmapSize" << m_pixmapSize; + + Q_ASSERT(m_tiles.count() == m_pixmaps.count()); + + // (Re)create pixmaps + for (int i=0; i= oldPosition) && + (m_windowPosition - m_tileArrayStart < (m_tiles.count() * m_tileLength))) { + // Work out how many tiles need to be shuffled + const qint64 offset = m_windowPosition - m_tileArrayStart; + const int nTiles = offset / m_tileLength; + shuffleTiles(nTiles); + } else { + resetTiles(m_windowPosition); + } + + if(!paintTiles() && m_windowPosition != oldPosition) + update(); +} + +qint64 Waveform::tilePosition(int index) const +{ + return m_tileArrayStart + index * m_tileLength; +} + +Waveform::TilePoint Waveform::tilePoint(qint64 position) const +{ + TilePoint result; + if (position >= m_tileArrayStart) { + const qint64 tileArrayEnd = m_tileArrayStart + m_tiles.count() * m_tileLength; + if (position < tileArrayEnd) { + const qint64 offsetIntoTileArray = position - m_tileArrayStart; + result.index = offsetIntoTileArray / m_tileLength; + Q_ASSERT(result.index >= 0 && result.index <= m_tiles.count()); + result.positionOffset = offsetIntoTileArray % m_tileLength; + result.pixelOffset = tilePixelOffset(result.positionOffset); + Q_ASSERT(result.pixelOffset >= 0 && result.pixelOffset <= m_pixmapSize.width()); + } + } + + return result; +} + +int Waveform::tilePixelOffset(qint64 positionOffset) const +{ + Q_ASSERT(positionOffset >= 0 && positionOffset <= m_tileLength); + const int result = (qreal(positionOffset) / m_tileLength) * m_pixmapSize.width(); + return result; +} + +int Waveform::windowPixelOffset(qint64 positionOffset) const +{ + Q_ASSERT(positionOffset >= 0 && positionOffset <= m_windowLength); + const int result = (qreal(positionOffset) / m_windowLength) * rect().width(); + return result; +} + +bool Waveform::paintTiles() +{ + WAVEFORM_DEBUG << "Waveform::paintTiles"; + bool updateRequired = false; + + for (int i=0; i= tileEnd) { + paintTile(i); + updateRequired = true; + } + } + } + + if (updateRequired) + update(); + + return updateRequired; +} + +void Waveform::paintTile(int index) +{ + WAVEFORM_DEBUG << "Waveform::paintTile" << "index" << index; + + const qint64 tileStart = m_tileArrayStart + index * m_tileLength; + Q_ASSERT(m_dataLength >= tileStart + m_tileLength); + + Tile &tile = m_tiles[index]; + Q_ASSERT(!tile.painted); + + const qint16* base = reinterpret_cast(m_buffer.constData()); + const qint16* buffer = base + (tileStart / 2); + const int numSamples = m_tileLength / (2 * m_format.channels()); + + QPainter painter(tile.pixmap); + + painter.fillRect(tile.pixmap->rect(), Qt::black); + + QPen pen(Qt::white); + painter.setPen(pen); + + // Calculate initial PCM value + qint16 previousPcmValue = 0; + if (buffer > base) + previousPcmValue = *(buffer - m_format.channels()); + + // Calculate initial point + const qreal previousRealValue = pcmToReal(previousPcmValue); + const int originY = ((previousRealValue + 1.0) / 2) * m_pixmapSize.height(); + const QPoint origin(0, originY); + + QLine line(origin, origin); + + for (int i=0; i::iterator i = m_tiles.begin(); + for ( ; i != m_tiles.end(); ++i) + i->painted = false; + + m_tileArrayStart = newStartPos; +} + diff --git a/demos/spectrum/app/waveform.h b/demos/spectrum/app/waveform.h new file mode 100644 index 0000000..e5cde5c --- /dev/null +++ b/demos/spectrum/app/waveform.h @@ -0,0 +1,196 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** You may use this file under the terms of the BSD license as follows: +** +** Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are met: +** - Redistributions of source code must retain the above copyright notice, +** this list of conditions and the following disclaimer. +** - Redistributions in binary form must reproduce the above copyright notice, +** this list of conditions and the following disclaimer in the documentation +** and/or other materials provided with the distribution. +** - Neither the name of Nokia Corporation and its Subsidiary(-ies) nor the +** names of its contributors may be used to endorse or promote products +** derived from this software without specific prior written permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +** AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +** LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +** INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +** CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +** ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +** POSSIBILITY OF SUCH DAMAGE. +** +*****************************************************************************/ + +#ifndef WAVEFORM_H +#define WAVEFORM_H + +#include +#include +#include +#include + +class QByteArray; + +/** + * Widget which displays a section of the audio waveform. + * + * The waveform is rendered on a set of QPixmaps which form a group of tiles + * whose extent covers the widget. As the audio position is updated, these + * tiles are scrolled from left to right; when the left-most tile scrolls + * outside the widget, it is moved to the right end of the tile array and + * painted with the next section of the waveform. + */ +class Waveform : public QWidget { + Q_OBJECT +public: + Waveform(const QByteArray &buffer, QWidget *parent = 0); + ~Waveform(); + + // QWidget + void paintEvent(QPaintEvent *event); + void resizeEvent(QResizeEvent *event); + + void initialize(const QAudioFormat &format, qint64 audioBufferSize, qint64 windowDurationUs); + void reset(); + + void setAutoUpdatePosition(bool enabled); + +public slots: + void dataLengthChanged(qint64 length); + void positionChanged(qint64 position); + +private: + static const int NullIndex = -1; + + void deletePixmaps(); + + /* + * (Re)create all pixmaps, repaint and update the display. + * Triggers an update(); + */ + void createPixmaps(const QSize &newSize); + + /* + * Update window position. + * Triggers an update(). + */ + void setWindowPosition(qint64 position); + + /* + * Base position of tile + */ + qint64 tilePosition(int index) const; + + /* + * Structure which identifies a point within a given + * tile. + */ + struct TilePoint + { + TilePoint(int idx = 0, qint64 pos = 0, qint64 pix = 0) + : index(idx), positionOffset(pos), pixelOffset(pix) + { } + + // Index of tile + int index; + + // Number of bytes from start of tile + qint64 positionOffset; + + // Number of pixels from left of corresponding pixmap + int pixelOffset; + }; + + /* + * Convert position in m_buffer into a tile index and an offset in pixels + * into the corresponding pixmap. + * + * \param position Offset into m_buffer, in bytes + + * If position is outside the tile array, index is NullIndex and + * offset is zero. + */ + TilePoint tilePoint(qint64 position) const; + + /* + * Convert offset in bytes into a tile into an offset in pixels + * within that tile. + */ + int tilePixelOffset(qint64 positionOffset) const; + + /* + * Convert offset in bytes into the window into an offset in pixels + * within the widget rect(). + */ + int windowPixelOffset(qint64 positionOffset) const; + + /* + * Paint all tiles which can be painted. + * \return true iff update() was called + */ + bool paintTiles(); + + /* + * Paint the specified tile + * + * \pre Sufficient data is available to completely paint the tile, i.e. + * m_dataLength is greater than the upper bound of the tile. + */ + void paintTile(int index); + + /* + * Move the first n tiles to the end of the array, and mark them as not + * painted. + */ + void shuffleTiles(int n); + + /* + * Reset tile array + */ + void resetTiles(qint64 newStartPos); + +private: + const QByteArray& m_buffer; + qint64 m_dataLength; + qint64 m_position; + QAudioFormat m_format; + + bool m_active; + + QSize m_pixmapSize; + QVector m_pixmaps; + + struct Tile { + // Pointer into parent m_pixmaps array + QPixmap* pixmap; + + // Flag indicating whether this tile has been painted + bool painted; + }; + + QVector m_tiles; + + // Length of audio data in bytes depicted by each tile + qint64 m_tileLength; + + // Position in bytes of the first tile, relative to m_buffer + qint64 m_tileArrayStart; + + qint64 m_windowPosition; + qint64 m_windowLength; + +}; + +#endif // WAVEFORM_H diff --git a/demos/spectrum/app/wavfile.cpp b/demos/spectrum/app/wavfile.cpp new file mode 100644 index 0000000..163e5ee --- /dev/null +++ b/demos/spectrum/app/wavfile.cpp @@ -0,0 +1,247 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This device is part of the test suite of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This device contains pre-release code and may not be distributed. +** You may use this device in accordance with the terms and conditions +** contained in the Technology Preview License Agreement accompanying +** this package. +** +** GNU Lesser General Public License Usage +** Alternatively, this device may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the device LICENSE.LGPL included in the +** packaging of this device. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the device LGPL_EXCEPTION.txt in this package. +** +** If you have questions regarding the use of this device, please contact +** Nokia at qt-info@nokia.com. +** +** +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include +#include +#include "utils.h" +#include "wavfile.h" + +struct chunk +{ + char id[4]; + quint32 size; +}; + +struct RIFFHeader +{ + chunk descriptor; // "RIFF" + char type[4]; // "WAVE" +}; + +struct WAVEHeader +{ + chunk descriptor; + quint16 audioFormat; + quint16 numChannels; + quint32 sampleRate; + quint32 byteRate; + quint16 blockAlign; + quint16 bitsPerSample; +}; + +struct DATAHeader +{ + chunk descriptor; +}; + +struct CombinedHeader +{ + RIFFHeader riff; + WAVEHeader wave; + DATAHeader data; +}; + +static const int HeaderLength = sizeof(CombinedHeader); + + +WavFile::WavFile(const QAudioFormat &format, qint64 dataLength) + : m_format(format) + , m_dataLength(dataLength) +{ + +} + +bool WavFile::readHeader(QIODevice &device) +{ + bool result = true; + + if (!device.isSequential()) + result = device.seek(0); + // else, assume that current position is the start of the header + + if (result) { + CombinedHeader header; + result = (device.read(reinterpret_cast(&header), HeaderLength) == HeaderLength); + if (result) { + if ((memcmp(&header.riff.descriptor.id, "RIFF", 4) == 0 + || memcmp(&header.riff.descriptor.id, "RIFX", 4) == 0) + && memcmp(&header.riff.type, "WAVE", 4) == 0 + && memcmp(&header.wave.descriptor.id, "fmt ", 4) == 0 + && header.wave.audioFormat == 1 // PCM + ) { + if (memcmp(&header.riff.descriptor.id, "RIFF", 4) == 0) + m_format.setByteOrder(QAudioFormat::LittleEndian); + else + m_format.setByteOrder(QAudioFormat::BigEndian); + + m_format.setChannels(qFromLittleEndian(header.wave.numChannels)); + m_format.setCodec("audio/pcm"); + m_format.setFrequency(qFromLittleEndian(header.wave.sampleRate)); + m_format.setSampleSize(qFromLittleEndian(header.wave.bitsPerSample)); + + switch(header.wave.bitsPerSample) { + case 8: + m_format.setSampleType(QAudioFormat::UnSignedInt); + break; + case 16: + m_format.setSampleType(QAudioFormat::SignedInt); + break; + default: + result = false; + } + + m_dataLength = device.size() - HeaderLength; + } else { + result = false; + } + } + } + + return result; +} + +bool WavFile::writeHeader(QIODevice &device) +{ + CombinedHeader header; + + memset(&header, 0, HeaderLength); + + // RIFF header + if (m_format.byteOrder() == QAudioFormat::LittleEndian) + strncpy(&header.riff.descriptor.id[0], "RIFF", 4); + else + strncpy(&header.riff.descriptor.id[0], "RIFX", 4); + qToLittleEndian(quint32(m_dataLength + HeaderLength - 8), + reinterpret_cast(&header.riff.descriptor.size)); + strncpy(&header.riff.type[0], "WAVE", 4); + + // WAVE header + strncpy(&header.wave.descriptor.id[0], "fmt ", 4); + qToLittleEndian(quint32(16), + reinterpret_cast(&header.wave.descriptor.size)); + qToLittleEndian(quint16(1), + reinterpret_cast(&header.wave.audioFormat)); + qToLittleEndian(quint16(m_format.channels()), + reinterpret_cast(&header.wave.numChannels)); + qToLittleEndian(quint32(m_format.frequency()), + reinterpret_cast(&header.wave.sampleRate)); + qToLittleEndian(quint32(m_format.frequency() * m_format.channels() * m_format.sampleSize() / 8), + reinterpret_cast(&header.wave.byteRate)); + qToLittleEndian(quint16(m_format.channels() * m_format.sampleSize() / 8), + reinterpret_cast(&header.wave.blockAlign)); + qToLittleEndian(quint16(m_format.sampleSize()), + reinterpret_cast(&header.wave.bitsPerSample)); + + // DATA header + strncpy(&header.data.descriptor.id[0], "data", 4); + qToLittleEndian(quint32(m_dataLength), + reinterpret_cast(&header.data.descriptor.size)); + + return (device.write(reinterpret_cast(&header), HeaderLength) == HeaderLength); +} + +const QAudioFormat& WavFile::format() const +{ + return m_format; +} + +qint64 WavFile::dataLength() const +{ + return m_dataLength; +} + +qint64 WavFile::headerLength() +{ + return HeaderLength; +} + +bool WavFile::writeDataLength(QIODevice &device, qint64 dataLength) +{ + bool result = false; + if (!device.isSequential()) { + device.seek(40); + unsigned char dataLengthLE[4]; + qToLittleEndian(quint32(dataLength), dataLengthLE); + result = (device.write(reinterpret_cast(dataLengthLE), 4) == 4); + } + return result; +} + +#include +#include + +qint64 WavFile::readData(QIODevice &device, QByteArray &buffer, + QAudioFormat outputFormat) +{ + if (QAudioFormat() == outputFormat) + outputFormat = m_format; + + qint64 result = 0; + + QFile file("wav.txt"); + file.open(QIODevice::WriteOnly | QIODevice::Text); + QTextStream stream; + stream.setDevice(&file); + + if (isPCMS16LE(outputFormat) && isPCMS16LE(m_format)) { + QVector inputSample(2 * m_format.channels()); + + qint16 *output = reinterpret_cast(buffer.data()); + + while (result < buffer.size()) { + if (device.read(inputSample.data(), inputSample.count())) { + int inputIdx = 0; + for (int outputIdx = 0; outputIdx < outputFormat.channels(); ++outputIdx) { + const qint16* input = reinterpret_cast(inputSample.data() + 2 * inputIdx); + *output++ = qFromLittleEndian(*input); + result += 2; + if (inputIdx < m_format.channels()) + ++inputIdx; + } + } else { + break; + } + } + } + return result; +} + diff --git a/demos/spectrum/app/wavfile.h b/demos/spectrum/app/wavfile.h new file mode 100644 index 0000000..d8c54fa --- /dev/null +++ b/demos/spectrum/app/wavfile.h @@ -0,0 +1,78 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** You may use this file under the terms of the BSD license as follows: +** +** Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are met: +** - Redistributions of source code must retain the above copyright notice, +** this list of conditions and the following disclaimer. +** - Redistributions in binary form must reproduce the above copyright notice, +** this list of conditions and the following disclaimer in the documentation +** and/or other materials provided with the distribution. +** - Neither the name of Nokia Corporation and its Subsidiary(-ies) nor the +** names of its contributors may be used to endorse or promote products +** derived from this software without specific prior written permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +** AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +** LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +** INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +** CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +** ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +** POSSIBILITY OF SUCH DAMAGE. +** +*****************************************************************************/ + + +#ifndef WAVFILE_H +#define WAVFILE_H + +#include +#include +#include + +/** + * Helper class for reading WAV files + * + * See https://ccrma.stanford.edu/courses/422/projects/WaveFormat/ + */ +class WavFile +{ +public: + WavFile(const QAudioFormat &format = QAudioFormat(), + qint64 dataLength = 0); + + // Reads WAV header and seeks to start of data + bool readHeader(QIODevice &device); + + // Writes WAV header + bool writeHeader(QIODevice &device); + + // Read PCM data + qint64 readData(QIODevice &device, QByteArray &buffer, + QAudioFormat outputFormat = QAudioFormat()); + + const QAudioFormat& format() const; + qint64 dataLength() const; + + static qint64 headerLength(); + + static bool writeDataLength(QIODevice &device, qint64 dataLength); + +private: + QAudioFormat m_format; + qint64 m_dataLength; +}; + +#endif + diff --git a/demos/spectrum/fftreal/Array.h b/demos/spectrum/fftreal/Array.h new file mode 100644 index 0000000..a08e3cf --- /dev/null +++ b/demos/spectrum/fftreal/Array.h @@ -0,0 +1,97 @@ +/***************************************************************************** + + Array.h + Copyright (c) 2005 Laurent de Soras + +--- Legal stuff --- + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +*Tab=3***********************************************************************/ + + + +#if ! defined (Array_HEADER_INCLUDED) +#define Array_HEADER_INCLUDED + +#if defined (_MSC_VER) + #pragma once + #pragma warning (4 : 4250) // "Inherits via dominance." +#endif + + + +/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +template +class Array +{ + +/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +public: + + typedef T DataType; + + Array (); + + inline const DataType & + operator [] (long pos) const; + inline DataType & + operator [] (long pos); + + static inline long + size (); + + + +/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +protected: + + + +/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +private: + + DataType _data_arr [LEN]; + + + +/*\\\ FORBIDDEN MEMBER FUNCTIONS \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +private: + + Array (const Array &other); + Array & operator = (const Array &other); + bool operator == (const Array &other); + bool operator != (const Array &other); + +}; // class Array + + + +#include "Array.hpp" + + + +#endif // Array_HEADER_INCLUDED + + + +/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ diff --git a/demos/spectrum/fftreal/Array.hpp b/demos/spectrum/fftreal/Array.hpp new file mode 100644 index 0000000..8300077 --- /dev/null +++ b/demos/spectrum/fftreal/Array.hpp @@ -0,0 +1,98 @@ +/***************************************************************************** + + Array.hpp + Copyright (c) 2005 Laurent de Soras + +--- Legal stuff --- + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +*Tab=3***********************************************************************/ + + + +#if defined (Array_CURRENT_CODEHEADER) + #error Recursive inclusion of Array code header. +#endif +#define Array_CURRENT_CODEHEADER + +#if ! defined (Array_CODEHEADER_INCLUDED) +#define Array_CODEHEADER_INCLUDED + + + +/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +#include + + + +/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +template +Array ::Array () +{ + // Nothing +} + + + +template +const typename Array ::DataType & Array ::operator [] (long pos) const +{ + assert (pos >= 0); + assert (pos < LEN); + + return (_data_arr [pos]); +} + + + +template +typename Array ::DataType & Array ::operator [] (long pos) +{ + assert (pos >= 0); + assert (pos < LEN); + + return (_data_arr [pos]); +} + + + +template +long Array ::size () +{ + return (LEN); +} + + + +/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +#endif // Array_CODEHEADER_INCLUDED + +#undef Array_CURRENT_CODEHEADER + + + +/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ diff --git a/demos/spectrum/fftreal/DynArray.h b/demos/spectrum/fftreal/DynArray.h new file mode 100644 index 0000000..8041a0c --- /dev/null +++ b/demos/spectrum/fftreal/DynArray.h @@ -0,0 +1,100 @@ +/***************************************************************************** + + DynArray.h + Copyright (c) 2005 Laurent de Soras + +--- Legal stuff --- + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +*Tab=3***********************************************************************/ + + + +#if ! defined (DynArray_HEADER_INCLUDED) +#define DynArray_HEADER_INCLUDED + +#if defined (_MSC_VER) + #pragma once + #pragma warning (4 : 4250) // "Inherits via dominance." +#endif + + + +/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +template +class DynArray +{ + +/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +public: + + typedef T DataType; + + DynArray (); + explicit DynArray (long size); + ~DynArray (); + + inline long size () const; + inline void resize (long size); + + inline const DataType & + operator [] (long pos) const; + inline DataType & + operator [] (long pos); + + + +/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +protected: + + + +/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +private: + + DataType * _data_ptr; + long _len; + + + +/*\\\ FORBIDDEN MEMBER FUNCTIONS \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +private: + + DynArray (const DynArray &other); + DynArray & operator = (const DynArray &other); + bool operator == (const DynArray &other); + bool operator != (const DynArray &other); + +}; // class DynArray + + + +#include "DynArray.hpp" + + + +#endif // DynArray_HEADER_INCLUDED + + + +/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ diff --git a/demos/spectrum/fftreal/DynArray.hpp b/demos/spectrum/fftreal/DynArray.hpp new file mode 100644 index 0000000..e62b10f --- /dev/null +++ b/demos/spectrum/fftreal/DynArray.hpp @@ -0,0 +1,143 @@ +/***************************************************************************** + + DynArray.hpp + Copyright (c) 2005 Laurent de Soras + +--- Legal stuff --- + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +*Tab=3***********************************************************************/ + + + +#if defined (DynArray_CURRENT_CODEHEADER) + #error Recursive inclusion of DynArray code header. +#endif +#define DynArray_CURRENT_CODEHEADER + +#if ! defined (DynArray_CODEHEADER_INCLUDED) +#define DynArray_CODEHEADER_INCLUDED + + + +/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +#include + + + +/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +template +DynArray ::DynArray () +: _data_ptr (0) +, _len (0) +{ + // Nothing +} + + + +template +DynArray ::DynArray (long size) +: _data_ptr (0) +, _len (0) +{ + assert (size >= 0); + if (size > 0) + { + _data_ptr = new DataType [size]; + _len = size; + } +} + + + +template +DynArray ::~DynArray () +{ + delete [] _data_ptr; + _data_ptr = 0; + _len = 0; +} + + + +template +long DynArray ::size () const +{ + return (_len); +} + + + +template +void DynArray ::resize (long size) +{ + assert (size >= 0); + if (size > 0) + { + DataType * old_data_ptr = _data_ptr; + DataType * tmp_data_ptr = new DataType [size]; + + _data_ptr = tmp_data_ptr; + _len = size; + + delete [] old_data_ptr; + } +} + + + +template +const typename DynArray ::DataType & DynArray ::operator [] (long pos) const +{ + assert (pos >= 0); + assert (pos < _len); + + return (_data_ptr [pos]); +} + + + +template +typename DynArray ::DataType & DynArray ::operator [] (long pos) +{ + assert (pos >= 0); + assert (pos < _len); + + return (_data_ptr [pos]); +} + + + +/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +#endif // DynArray_CODEHEADER_INCLUDED + +#undef DynArray_CURRENT_CODEHEADER + + + +/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ diff --git a/demos/spectrum/fftreal/FFTReal.dsp b/demos/spectrum/fftreal/FFTReal.dsp new file mode 100644 index 0000000..fe970db --- /dev/null +++ b/demos/spectrum/fftreal/FFTReal.dsp @@ -0,0 +1,273 @@ +# Microsoft Developer Studio Project File - Name="FFTReal" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Console Application" 0x0103 + +CFG=FFTReal - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "FFTReal.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "FFTReal.mak" CFG="FFTReal - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "FFTReal - Win32 Release" (based on "Win32 (x86) Console Application") +!MESSAGE "FFTReal - Win32 Debug" (based on "Win32 (x86) Console Application") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "FFTReal - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD CPP /nologo /W3 /GR /GX /O2 /Ob2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD BASE RSC /l 0x40c /d "NDEBUG" +# ADD RSC /l 0x40c /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 + +!ELSEIF "$(CFG)" == "FFTReal - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Debug" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /Zi /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD CPP /nologo /G6 /MTd /W3 /Gm /GR /GX /Zi /Od /Gf /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /FR /YX /FD /c +# ADD BASE RSC /l 0x40c /d "_DEBUG" +# ADD RSC /l 0x40c /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept + +!ENDIF + +# Begin Target + +# Name "FFTReal - Win32 Release" +# Name "FFTReal - Win32 Debug" +# Begin Group "Library" + +# PROP Default_Filter "" +# Begin Source File + +SOURCE=.\Array.h +# End Source File +# Begin Source File + +SOURCE=.\Array.hpp +# End Source File +# Begin Source File + +SOURCE=.\def.h +# End Source File +# Begin Source File + +SOURCE=.\DynArray.h +# End Source File +# Begin Source File + +SOURCE=.\DynArray.hpp +# End Source File +# Begin Source File + +SOURCE=.\FFTReal.h +# End Source File +# Begin Source File + +SOURCE=.\FFTReal.hpp +# End Source File +# Begin Source File + +SOURCE=.\FFTRealFixLen.h +# End Source File +# Begin Source File + +SOURCE=.\FFTRealFixLen.hpp +# End Source File +# Begin Source File + +SOURCE=.\FFTRealFixLenParam.h +# End Source File +# Begin Source File + +SOURCE=.\FFTRealPassDirect.h +# End Source File +# Begin Source File + +SOURCE=.\FFTRealPassDirect.hpp +# End Source File +# Begin Source File + +SOURCE=.\FFTRealPassInverse.h +# End Source File +# Begin Source File + +SOURCE=.\FFTRealPassInverse.hpp +# End Source File +# Begin Source File + +SOURCE=.\FFTRealSelect.h +# End Source File +# Begin Source File + +SOURCE=.\FFTRealSelect.hpp +# End Source File +# Begin Source File + +SOURCE=.\FFTRealUseTrigo.h +# End Source File +# Begin Source File + +SOURCE=.\FFTRealUseTrigo.hpp +# End Source File +# Begin Source File + +SOURCE=.\OscSinCos.h +# End Source File +# Begin Source File + +SOURCE=.\OscSinCos.hpp +# End Source File +# End Group +# Begin Group "Test" + +# PROP Default_Filter "" +# Begin Group "stopwatch" + +# PROP Default_Filter "" +# Begin Source File + +SOURCE=.\stopwatch\ClockCycleCounter.cpp +# End Source File +# Begin Source File + +SOURCE=.\stopwatch\ClockCycleCounter.h +# End Source File +# Begin Source File + +SOURCE=.\stopwatch\ClockCycleCounter.hpp +# End Source File +# Begin Source File + +SOURCE=.\stopwatch\def.h +# End Source File +# Begin Source File + +SOURCE=.\stopwatch\fnc.h +# End Source File +# Begin Source File + +SOURCE=.\stopwatch\fnc.hpp +# End Source File +# Begin Source File + +SOURCE=.\stopwatch\Int64.h +# End Source File +# Begin Source File + +SOURCE=.\stopwatch\StopWatch.cpp +# End Source File +# Begin Source File + +SOURCE=.\stopwatch\StopWatch.h +# End Source File +# Begin Source File + +SOURCE=.\stopwatch\StopWatch.hpp +# End Source File +# End Group +# Begin Source File + +SOURCE=.\test.cpp +# End Source File +# Begin Source File + +SOURCE=.\test_fnc.h +# End Source File +# Begin Source File + +SOURCE=.\test_fnc.hpp +# End Source File +# Begin Source File + +SOURCE=.\test_settings.h +# End Source File +# Begin Source File + +SOURCE=.\TestAccuracy.h +# End Source File +# Begin Source File + +SOURCE=.\TestAccuracy.hpp +# End Source File +# Begin Source File + +SOURCE=.\TestHelperFixLen.h +# End Source File +# Begin Source File + +SOURCE=.\TestHelperFixLen.hpp +# End Source File +# Begin Source File + +SOURCE=.\TestHelperNormal.h +# End Source File +# Begin Source File + +SOURCE=.\TestHelperNormal.hpp +# End Source File +# Begin Source File + +SOURCE=.\TestSpeed.h +# End Source File +# Begin Source File + +SOURCE=.\TestSpeed.hpp +# End Source File +# Begin Source File + +SOURCE=.\TestWhiteNoiseGen.h +# End Source File +# Begin Source File + +SOURCE=.\TestWhiteNoiseGen.hpp +# End Source File +# End Group +# End Target +# End Project diff --git a/demos/spectrum/fftreal/FFTReal.dsw b/demos/spectrum/fftreal/FFTReal.dsw new file mode 100644 index 0000000..076b0ae --- /dev/null +++ b/demos/spectrum/fftreal/FFTReal.dsw @@ -0,0 +1,29 @@ +Microsoft Developer Studio Workspace File, Format Version 6.00 +# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! + +############################################################################### + +Project: "FFTReal"=.\FFTReal.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Global: + +Package=<5> +{{{ +}}} + +Package=<3> +{{{ +}}} + +############################################################################### + diff --git a/demos/spectrum/fftreal/FFTReal.h b/demos/spectrum/fftreal/FFTReal.h new file mode 100644 index 0000000..9fb2725 --- /dev/null +++ b/demos/spectrum/fftreal/FFTReal.h @@ -0,0 +1,142 @@ +/***************************************************************************** + + FFTReal.h + Copyright (c) 2005 Laurent de Soras + +--- Legal stuff --- + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +*Tab=3***********************************************************************/ + + + +#if ! defined (FFTReal_HEADER_INCLUDED) +#define FFTReal_HEADER_INCLUDED + +#if defined (_MSC_VER) + #pragma once + #pragma warning (4 : 4250) // "Inherits via dominance." +#endif + + + +/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +#include "def.h" +#include "DynArray.h" +#include "OscSinCos.h" + + + +template +class FFTReal +{ + +/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +public: + + enum { MAX_BIT_DEPTH = 30 }; // So length can be represented as long int + + typedef DT DataType; + + explicit FFTReal (long length); + virtual ~FFTReal () {} + + long get_length () const; + void do_fft (DataType f [], const DataType x []) const; + void do_ifft (const DataType f [], DataType x []) const; + void rescale (DataType x []) const; + DataType * use_buffer () const; + + + +/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +protected: + + + +/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +private: + + // Over this bit depth, we use direct calculation for sin/cos + enum { TRIGO_BD_LIMIT = 12 }; + + typedef OscSinCos OscType; + + void init_br_lut (); + void init_trigo_lut (); + void init_trigo_osc (); + + FORCEINLINE const long * + get_br_ptr () const; + FORCEINLINE const DataType * + get_trigo_ptr (int level) const; + FORCEINLINE long + get_trigo_level_index (int level) const; + + inline void compute_fft_general (DataType f [], const DataType x []) const; + inline void compute_direct_pass_1_2 (DataType df [], const DataType x []) const; + inline void compute_direct_pass_3 (DataType df [], const DataType sf []) const; + inline void compute_direct_pass_n (DataType df [], const DataType sf [], int pass) const; + inline void compute_direct_pass_n_lut (DataType df [], const DataType sf [], int pass) const; + inline void compute_direct_pass_n_osc (DataType df [], const DataType sf [], int pass) const; + + inline void compute_ifft_general (const DataType f [], DataType x []) const; + inline void compute_inverse_pass_n (DataType df [], const DataType sf [], int pass) const; + inline void compute_inverse_pass_n_osc (DataType df [], const DataType sf [], int pass) const; + inline void compute_inverse_pass_n_lut (DataType df [], const DataType sf [], int pass) const; + inline void compute_inverse_pass_3 (DataType df [], const DataType sf []) const; + inline void compute_inverse_pass_1_2 (DataType x [], const DataType sf []) const; + + const long _length; + const int _nbr_bits; + DynArray + _br_lut; + DynArray + _trigo_lut; + mutable DynArray + _buffer; + mutable DynArray + _trigo_osc; + + + +/*\\\ FORBIDDEN MEMBER FUNCTIONS \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +private: + + FFTReal (); + FFTReal (const FFTReal &other); + FFTReal & operator = (const FFTReal &other); + bool operator == (const FFTReal &other); + bool operator != (const FFTReal &other); + +}; // class FFTReal + + + +#include "FFTReal.hpp" + + + +#endif // FFTReal_HEADER_INCLUDED + + + +/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ diff --git a/demos/spectrum/fftreal/FFTReal.hpp b/demos/spectrum/fftreal/FFTReal.hpp new file mode 100644 index 0000000..335d771 --- /dev/null +++ b/demos/spectrum/fftreal/FFTReal.hpp @@ -0,0 +1,916 @@ +/***************************************************************************** + + FFTReal.hpp + Copyright (c) 2005 Laurent de Soras + +--- Legal stuff --- + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +*Tab=3***********************************************************************/ + + + +#if defined (FFTReal_CURRENT_CODEHEADER) + #error Recursive inclusion of FFTReal code header. +#endif +#define FFTReal_CURRENT_CODEHEADER + +#if ! defined (FFTReal_CODEHEADER_INCLUDED) +#define FFTReal_CODEHEADER_INCLUDED + + + +/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +#include +#include + + + +static inline bool FFTReal_is_pow2 (long x) +{ + assert (x > 0); + + return ((x & -x) == x); +} + + + +static inline int FFTReal_get_next_pow2 (long x) +{ + --x; + + int p = 0; + while ((x & ~0xFFFFL) != 0) + { + p += 16; + x >>= 16; + } + while ((x & ~0xFL) != 0) + { + p += 4; + x >>= 4; + } + while (x > 0) + { + ++p; + x >>= 1; + } + + return (p); +} + + + +/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +/* +============================================================================== +Name: ctor +Input parameters: + - length: length of the array on which we want to do a FFT. Range: power of + 2 only, > 0. +Throws: std::bad_alloc +============================================================================== +*/ + +template +FFTReal
::FFTReal (long length) +: _length (length) +, _nbr_bits (FFTReal_get_next_pow2 (length)) +, _br_lut () +, _trigo_lut () +, _buffer (length) +, _trigo_osc () +{ + assert (FFTReal_is_pow2 (length)); + assert (_nbr_bits <= MAX_BIT_DEPTH); + + init_br_lut (); + init_trigo_lut (); + init_trigo_osc (); +} + + + +/* +============================================================================== +Name: get_length +Description: + Returns the number of points processed by this FFT object. +Returns: The number of points, power of 2, > 0. +Throws: Nothing +============================================================================== +*/ + +template +long FFTReal
::get_length () const +{ + return (_length); +} + + + +/* +============================================================================== +Name: do_fft +Description: + Compute the FFT of the array. +Input parameters: + - x: pointer on the source array (time). +Output parameters: + - f: pointer on the destination array (frequencies). + f [0...length(x)/2] = real values, + f [length(x)/2+1...length(x)-1] = negative imaginary values of + coefficents 1...length(x)/2-1. +Throws: Nothing +============================================================================== +*/ + +template +void FFTReal
::do_fft (DataType f [], const DataType x []) const +{ + assert (f != 0); + assert (f != use_buffer ()); + assert (x != 0); + assert (x != use_buffer ()); + assert (x != f); + + // General case + if (_nbr_bits > 2) + { + compute_fft_general (f, x); + } + + // 4-point FFT + else if (_nbr_bits == 2) + { + f [1] = x [0] - x [2]; + f [3] = x [1] - x [3]; + + const DataType b_0 = x [0] + x [2]; + const DataType b_2 = x [1] + x [3]; + + f [0] = b_0 + b_2; + f [2] = b_0 - b_2; + } + + // 2-point FFT + else if (_nbr_bits == 1) + { + f [0] = x [0] + x [1]; + f [1] = x [0] - x [1]; + } + + // 1-point FFT + else + { + f [0] = x [0]; + } +} + + + +/* +============================================================================== +Name: do_ifft +Description: + Compute the inverse FFT of the array. Note that data must be post-scaled: + IFFT (FFT (x)) = x * length (x). +Input parameters: + - f: pointer on the source array (frequencies). + f [0...length(x)/2] = real values + f [length(x)/2+1...length(x)-1] = negative imaginary values of + coefficents 1...length(x)/2-1. +Output parameters: + - x: pointer on the destination array (time). +Throws: Nothing +============================================================================== +*/ + +template +void FFTReal
::do_ifft (const DataType f [], DataType x []) const +{ + assert (f != 0); + assert (f != use_buffer ()); + assert (x != 0); + assert (x != use_buffer ()); + assert (x != f); + + // General case + if (_nbr_bits > 2) + { + compute_ifft_general (f, x); + } + + // 4-point IFFT + else if (_nbr_bits == 2) + { + const DataType b_0 = f [0] + f [2]; + const DataType b_2 = f [0] - f [2]; + + x [0] = b_0 + f [1] * 2; + x [2] = b_0 - f [1] * 2; + x [1] = b_2 + f [3] * 2; + x [3] = b_2 - f [3] * 2; + } + + // 2-point IFFT + else if (_nbr_bits == 1) + { + x [0] = f [0] + f [1]; + x [1] = f [0] - f [1]; + } + + // 1-point IFFT + else + { + x [0] = f [0]; + } +} + + + +/* +============================================================================== +Name: rescale +Description: + Scale an array by divide each element by its length. This function should + be called after FFT + IFFT. +Input parameters: + - x: pointer on array to rescale (time or frequency). +Throws: Nothing +============================================================================== +*/ + +template +void FFTReal
::rescale (DataType x []) const +{ + const DataType mul = DataType (1.0 / _length); + + if (_length < 4) + { + long i = _length - 1; + do + { + x [i] *= mul; + --i; + } + while (i >= 0); + } + + else + { + assert ((_length & 3) == 0); + + // Could be optimized with SIMD instruction sets (needs alignment check) + long i = _length - 4; + do + { + x [i + 0] *= mul; + x [i + 1] *= mul; + x [i + 2] *= mul; + x [i + 3] *= mul; + i -= 4; + } + while (i >= 0); + } +} + + + +/* +============================================================================== +Name: use_buffer +Description: + Access the internal buffer, whose length is the FFT one. + Buffer content will be erased at each do_fft() / do_ifft() call! + This buffer cannot be used as: + - source for FFT or IFFT done with this object + - destination for FFT or IFFT done with this object +Returns: + Buffer start address +Throws: Nothing +============================================================================== +*/ + +template +typename FFTReal
::DataType * FFTReal
::use_buffer () const +{ + return (&_buffer [0]); +} + + + +/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +template +void FFTReal
::init_br_lut () +{ + const long length = 1L << _nbr_bits; + _br_lut.resize (length); + + _br_lut [0] = 0; + long br_index = 0; + for (long cnt = 1; cnt < length; ++cnt) + { + // ++br_index (bit reversed) + long bit = length >> 1; + while (((br_index ^= bit) & bit) == 0) + { + bit >>= 1; + } + + _br_lut [cnt] = br_index; + } +} + + + +template +void FFTReal
::init_trigo_lut () +{ + using namespace std; + + if (_nbr_bits > 3) + { + const long total_len = (1L << (_nbr_bits - 1)) - 4; + _trigo_lut.resize (total_len); + + for (int level = 3; level < _nbr_bits; ++level) + { + const long level_len = 1L << (level - 1); + DataType * const level_ptr = + &_trigo_lut [get_trigo_level_index (level)]; + const double mul = PI / (level_len << 1); + + for (long i = 0; i < level_len; ++ i) + { + level_ptr [i] = static_cast (cos (i * mul)); + } + } + } +} + + + +template +void FFTReal
::init_trigo_osc () +{ + const int nbr_osc = _nbr_bits - TRIGO_BD_LIMIT; + if (nbr_osc > 0) + { + _trigo_osc.resize (nbr_osc); + + for (int osc_cnt = 0; osc_cnt < nbr_osc; ++osc_cnt) + { + OscType & osc = _trigo_osc [osc_cnt]; + + const long len = 1L << (TRIGO_BD_LIMIT + osc_cnt); + const double mul = (0.5 * PI) / len; + osc.set_step (mul); + } + } +} + + + +template +const long * FFTReal
::get_br_ptr () const +{ + return (&_br_lut [0]); +} + + + +template +const typename FFTReal
::DataType * FFTReal
::get_trigo_ptr (int level) const +{ + assert (level >= 3); + + return (&_trigo_lut [get_trigo_level_index (level)]); +} + + + +template +long FFTReal
::get_trigo_level_index (int level) const +{ + assert (level >= 3); + + return ((1L << (level - 1)) - 4); +} + + + +// Transform in several passes +template +void FFTReal
::compute_fft_general (DataType f [], const DataType x []) const +{ + assert (f != 0); + assert (f != use_buffer ()); + assert (x != 0); + assert (x != use_buffer ()); + assert (x != f); + + DataType * sf; + DataType * df; + + if ((_nbr_bits & 1) != 0) + { + df = use_buffer (); + sf = f; + } + else + { + df = f; + sf = use_buffer (); + } + + compute_direct_pass_1_2 (df, x); + compute_direct_pass_3 (sf, df); + + for (int pass = 3; pass < _nbr_bits; ++ pass) + { + compute_direct_pass_n (df, sf, pass); + + DataType * const temp_ptr = df; + df = sf; + sf = temp_ptr; + } +} + + + +template +void FFTReal
::compute_direct_pass_1_2 (DataType df [], const DataType x []) const +{ + assert (df != 0); + assert (x != 0); + assert (df != x); + + const long * const bit_rev_lut_ptr = get_br_ptr (); + long coef_index = 0; + do + { + const long rev_index_0 = bit_rev_lut_ptr [coef_index]; + const long rev_index_1 = bit_rev_lut_ptr [coef_index + 1]; + const long rev_index_2 = bit_rev_lut_ptr [coef_index + 2]; + const long rev_index_3 = bit_rev_lut_ptr [coef_index + 3]; + + DataType * const df2 = df + coef_index; + df2 [1] = x [rev_index_0] - x [rev_index_1]; + df2 [3] = x [rev_index_2] - x [rev_index_3]; + + const DataType sf_0 = x [rev_index_0] + x [rev_index_1]; + const DataType sf_2 = x [rev_index_2] + x [rev_index_3]; + + df2 [0] = sf_0 + sf_2; + df2 [2] = sf_0 - sf_2; + + coef_index += 4; + } + while (coef_index < _length); +} + + + +template +void FFTReal
::compute_direct_pass_3 (DataType df [], const DataType sf []) const +{ + assert (df != 0); + assert (sf != 0); + assert (df != sf); + + const DataType sqrt2_2 = DataType (SQRT2 * 0.5); + long coef_index = 0; + do + { + DataType v; + + df [coef_index] = sf [coef_index] + sf [coef_index + 4]; + df [coef_index + 4] = sf [coef_index] - sf [coef_index + 4]; + df [coef_index + 2] = sf [coef_index + 2]; + df [coef_index + 6] = sf [coef_index + 6]; + + v = (sf [coef_index + 5] - sf [coef_index + 7]) * sqrt2_2; + df [coef_index + 1] = sf [coef_index + 1] + v; + df [coef_index + 3] = sf [coef_index + 1] - v; + + v = (sf [coef_index + 5] + sf [coef_index + 7]) * sqrt2_2; + df [coef_index + 5] = v + sf [coef_index + 3]; + df [coef_index + 7] = v - sf [coef_index + 3]; + + coef_index += 8; + } + while (coef_index < _length); +} + + + +template +void FFTReal
::compute_direct_pass_n (DataType df [], const DataType sf [], int pass) const +{ + assert (df != 0); + assert (sf != 0); + assert (df != sf); + assert (pass >= 3); + assert (pass < _nbr_bits); + + if (pass <= TRIGO_BD_LIMIT) + { + compute_direct_pass_n_lut (df, sf, pass); + } + else + { + compute_direct_pass_n_osc (df, sf, pass); + } +} + + + +template +void FFTReal
::compute_direct_pass_n_lut (DataType df [], const DataType sf [], int pass) const +{ + assert (df != 0); + assert (sf != 0); + assert (df != sf); + assert (pass >= 3); + assert (pass < _nbr_bits); + + const long nbr_coef = 1 << pass; + const long h_nbr_coef = nbr_coef >> 1; + const long d_nbr_coef = nbr_coef << 1; + long coef_index = 0; + const DataType * const cos_ptr = get_trigo_ptr (pass); + do + { + const DataType * const sf1r = sf + coef_index; + const DataType * const sf2r = sf1r + nbr_coef; + DataType * const dfr = df + coef_index; + DataType * const dfi = dfr + nbr_coef; + + // Extreme coefficients are always real + dfr [0] = sf1r [0] + sf2r [0]; + dfi [0] = sf1r [0] - sf2r [0]; // dfr [nbr_coef] = + dfr [h_nbr_coef] = sf1r [h_nbr_coef]; + dfi [h_nbr_coef] = sf2r [h_nbr_coef]; + + // Others are conjugate complex numbers + const DataType * const sf1i = sf1r + h_nbr_coef; + const DataType * const sf2i = sf1i + nbr_coef; + for (long i = 1; i < h_nbr_coef; ++ i) + { + const DataType c = cos_ptr [i]; // cos (i*PI/nbr_coef); + const DataType s = cos_ptr [h_nbr_coef - i]; // sin (i*PI/nbr_coef); + DataType v; + + v = sf2r [i] * c - sf2i [i] * s; + dfr [i] = sf1r [i] + v; + dfi [-i] = sf1r [i] - v; // dfr [nbr_coef - i] = + + v = sf2r [i] * s + sf2i [i] * c; + dfi [i] = v + sf1i [i]; + dfi [nbr_coef - i] = v - sf1i [i]; + } + + coef_index += d_nbr_coef; + } + while (coef_index < _length); +} + + + +template +void FFTReal
::compute_direct_pass_n_osc (DataType df [], const DataType sf [], int pass) const +{ + assert (df != 0); + assert (sf != 0); + assert (df != sf); + assert (pass > TRIGO_BD_LIMIT); + assert (pass < _nbr_bits); + + const long nbr_coef = 1 << pass; + const long h_nbr_coef = nbr_coef >> 1; + const long d_nbr_coef = nbr_coef << 1; + long coef_index = 0; + OscType & osc = _trigo_osc [pass - (TRIGO_BD_LIMIT + 1)]; + do + { + const DataType * const sf1r = sf + coef_index; + const DataType * const sf2r = sf1r + nbr_coef; + DataType * const dfr = df + coef_index; + DataType * const dfi = dfr + nbr_coef; + + osc.clear_buffers (); + + // Extreme coefficients are always real + dfr [0] = sf1r [0] + sf2r [0]; + dfi [0] = sf1r [0] - sf2r [0]; // dfr [nbr_coef] = + dfr [h_nbr_coef] = sf1r [h_nbr_coef]; + dfi [h_nbr_coef] = sf2r [h_nbr_coef]; + + // Others are conjugate complex numbers + const DataType * const sf1i = sf1r + h_nbr_coef; + const DataType * const sf2i = sf1i + nbr_coef; + for (long i = 1; i < h_nbr_coef; ++ i) + { + osc.step (); + const DataType c = osc.get_cos (); + const DataType s = osc.get_sin (); + DataType v; + + v = sf2r [i] * c - sf2i [i] * s; + dfr [i] = sf1r [i] + v; + dfi [-i] = sf1r [i] - v; // dfr [nbr_coef - i] = + + v = sf2r [i] * s + sf2i [i] * c; + dfi [i] = v + sf1i [i]; + dfi [nbr_coef - i] = v - sf1i [i]; + } + + coef_index += d_nbr_coef; + } + while (coef_index < _length); +} + + + +// Transform in several pass +template +void FFTReal
::compute_ifft_general (const DataType f [], DataType x []) const +{ + assert (f != 0); + assert (f != use_buffer ()); + assert (x != 0); + assert (x != use_buffer ()); + assert (x != f); + + DataType * sf = const_cast (f); + DataType * df; + DataType * df_temp; + + if (_nbr_bits & 1) + { + df = use_buffer (); + df_temp = x; + } + else + { + df = x; + df_temp = use_buffer (); + } + + for (int pass = _nbr_bits - 1; pass >= 3; -- pass) + { + compute_inverse_pass_n (df, sf, pass); + + if (pass < _nbr_bits - 1) + { + DataType * const temp_ptr = df; + df = sf; + sf = temp_ptr; + } + else + { + sf = df; + df = df_temp; + } + } + + compute_inverse_pass_3 (df, sf); + compute_inverse_pass_1_2 (x, df); +} + + + +template +void FFTReal
::compute_inverse_pass_n (DataType df [], const DataType sf [], int pass) const +{ + assert (df != 0); + assert (sf != 0); + assert (df != sf); + assert (pass >= 3); + assert (pass < _nbr_bits); + + if (pass <= TRIGO_BD_LIMIT) + { + compute_inverse_pass_n_lut (df, sf, pass); + } + else + { + compute_inverse_pass_n_osc (df, sf, pass); + } +} + + + +template +void FFTReal
::compute_inverse_pass_n_lut (DataType df [], const DataType sf [], int pass) const +{ + assert (df != 0); + assert (sf != 0); + assert (df != sf); + assert (pass >= 3); + assert (pass < _nbr_bits); + + const long nbr_coef = 1 << pass; + const long h_nbr_coef = nbr_coef >> 1; + const long d_nbr_coef = nbr_coef << 1; + long coef_index = 0; + const DataType * const cos_ptr = get_trigo_ptr (pass); + do + { + const DataType * const sfr = sf + coef_index; + const DataType * const sfi = sfr + nbr_coef; + DataType * const df1r = df + coef_index; + DataType * const df2r = df1r + nbr_coef; + + // Extreme coefficients are always real + df1r [0] = sfr [0] + sfi [0]; // + sfr [nbr_coef] + df2r [0] = sfr [0] - sfi [0]; // - sfr [nbr_coef] + df1r [h_nbr_coef] = sfr [h_nbr_coef] * 2; + df2r [h_nbr_coef] = sfi [h_nbr_coef] * 2; + + // Others are conjugate complex numbers + DataType * const df1i = df1r + h_nbr_coef; + DataType * const df2i = df1i + nbr_coef; + for (long i = 1; i < h_nbr_coef; ++ i) + { + df1r [i] = sfr [i] + sfi [-i]; // + sfr [nbr_coef - i] + df1i [i] = sfi [i] - sfi [nbr_coef - i]; + + const DataType c = cos_ptr [i]; // cos (i*PI/nbr_coef); + const DataType s = cos_ptr [h_nbr_coef - i]; // sin (i*PI/nbr_coef); + const DataType vr = sfr [i] - sfi [-i]; // - sfr [nbr_coef - i] + const DataType vi = sfi [i] + sfi [nbr_coef - i]; + + df2r [i] = vr * c + vi * s; + df2i [i] = vi * c - vr * s; + } + + coef_index += d_nbr_coef; + } + while (coef_index < _length); +} + + + +template +void FFTReal
::compute_inverse_pass_n_osc (DataType df [], const DataType sf [], int pass) const +{ + assert (df != 0); + assert (sf != 0); + assert (df != sf); + assert (pass > TRIGO_BD_LIMIT); + assert (pass < _nbr_bits); + + const long nbr_coef = 1 << pass; + const long h_nbr_coef = nbr_coef >> 1; + const long d_nbr_coef = nbr_coef << 1; + long coef_index = 0; + OscType & osc = _trigo_osc [pass - (TRIGO_BD_LIMIT + 1)]; + do + { + const DataType * const sfr = sf + coef_index; + const DataType * const sfi = sfr + nbr_coef; + DataType * const df1r = df + coef_index; + DataType * const df2r = df1r + nbr_coef; + + osc.clear_buffers (); + + // Extreme coefficients are always real + df1r [0] = sfr [0] + sfi [0]; // + sfr [nbr_coef] + df2r [0] = sfr [0] - sfi [0]; // - sfr [nbr_coef] + df1r [h_nbr_coef] = sfr [h_nbr_coef] * 2; + df2r [h_nbr_coef] = sfi [h_nbr_coef] * 2; + + // Others are conjugate complex numbers + DataType * const df1i = df1r + h_nbr_coef; + DataType * const df2i = df1i + nbr_coef; + for (long i = 1; i < h_nbr_coef; ++ i) + { + df1r [i] = sfr [i] + sfi [-i]; // + sfr [nbr_coef - i] + df1i [i] = sfi [i] - sfi [nbr_coef - i]; + + osc.step (); + const DataType c = osc.get_cos (); + const DataType s = osc.get_sin (); + const DataType vr = sfr [i] - sfi [-i]; // - sfr [nbr_coef - i] + const DataType vi = sfi [i] + sfi [nbr_coef - i]; + + df2r [i] = vr * c + vi * s; + df2i [i] = vi * c - vr * s; + } + + coef_index += d_nbr_coef; + } + while (coef_index < _length); +} + + + +template +void FFTReal
::compute_inverse_pass_3 (DataType df [], const DataType sf []) const +{ + assert (df != 0); + assert (sf != 0); + assert (df != sf); + + const DataType sqrt2_2 = DataType (SQRT2 * 0.5); + long coef_index = 0; + do + { + df [coef_index] = sf [coef_index] + sf [coef_index + 4]; + df [coef_index + 4] = sf [coef_index] - sf [coef_index + 4]; + df [coef_index + 2] = sf [coef_index + 2] * 2; + df [coef_index + 6] = sf [coef_index + 6] * 2; + + df [coef_index + 1] = sf [coef_index + 1] + sf [coef_index + 3]; + df [coef_index + 3] = sf [coef_index + 5] - sf [coef_index + 7]; + + const DataType vr = sf [coef_index + 1] - sf [coef_index + 3]; + const DataType vi = sf [coef_index + 5] + sf [coef_index + 7]; + + df [coef_index + 5] = (vr + vi) * sqrt2_2; + df [coef_index + 7] = (vi - vr) * sqrt2_2; + + coef_index += 8; + } + while (coef_index < _length); +} + + + +template +void FFTReal
::compute_inverse_pass_1_2 (DataType x [], const DataType sf []) const +{ + assert (x != 0); + assert (sf != 0); + assert (x != sf); + + const long * bit_rev_lut_ptr = get_br_ptr (); + const DataType * sf2 = sf; + long coef_index = 0; + do + { + { + const DataType b_0 = sf2 [0] + sf2 [2]; + const DataType b_2 = sf2 [0] - sf2 [2]; + const DataType b_1 = sf2 [1] * 2; + const DataType b_3 = sf2 [3] * 2; + + x [bit_rev_lut_ptr [0]] = b_0 + b_1; + x [bit_rev_lut_ptr [1]] = b_0 - b_1; + x [bit_rev_lut_ptr [2]] = b_2 + b_3; + x [bit_rev_lut_ptr [3]] = b_2 - b_3; + } + { + const DataType b_0 = sf2 [4] + sf2 [6]; + const DataType b_2 = sf2 [4] - sf2 [6]; + const DataType b_1 = sf2 [5] * 2; + const DataType b_3 = sf2 [7] * 2; + + x [bit_rev_lut_ptr [4]] = b_0 + b_1; + x [bit_rev_lut_ptr [5]] = b_0 - b_1; + x [bit_rev_lut_ptr [6]] = b_2 + b_3; + x [bit_rev_lut_ptr [7]] = b_2 - b_3; + } + + sf2 += 8; + coef_index += 8; + bit_rev_lut_ptr += 8; + } + while (coef_index < _length); +} + + + +#endif // FFTReal_CODEHEADER_INCLUDED + +#undef FFTReal_CURRENT_CODEHEADER + + + +/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ diff --git a/demos/spectrum/fftreal/FFTRealFixLen.h b/demos/spectrum/fftreal/FFTRealFixLen.h new file mode 100644 index 0000000..0b80266 --- /dev/null +++ b/demos/spectrum/fftreal/FFTRealFixLen.h @@ -0,0 +1,130 @@ +/***************************************************************************** + + FFTRealFixLen.h + Copyright (c) 2005 Laurent de Soras + +--- Legal stuff --- + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +*Tab=3***********************************************************************/ + + + +#if ! defined (FFTRealFixLen_HEADER_INCLUDED) +#define FFTRealFixLen_HEADER_INCLUDED + +#if defined (_MSC_VER) + #pragma once + #pragma warning (4 : 4250) // "Inherits via dominance." +#endif + + + +/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +#include "Array.h" +#include "DynArray.h" +#include "FFTRealFixLenParam.h" +#include "OscSinCos.h" + + + +template +class FFTRealFixLen +{ + typedef int CompileTimeCheck1 [(LL2 >= 0) ? 1 : -1]; + typedef int CompileTimeCheck2 [(LL2 <= 30) ? 1 : -1]; + +/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +public: + + typedef FFTRealFixLenParam::DataType DataType; + typedef OscSinCos OscType; + + enum { FFT_LEN_L2 = LL2 }; + enum { FFT_LEN = 1 << FFT_LEN_L2 }; + + FFTRealFixLen (); + + inline long get_length () const; + void do_fft (DataType f [], const DataType x []); + void do_ifft (const DataType f [], DataType x []); + void rescale (DataType x []) const; + + + +/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +protected: + + + +/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +private: + + enum { TRIGO_BD_LIMIT = FFTRealFixLenParam::TRIGO_BD_LIMIT }; + + enum { BR_ARR_SIZE_L2 = ((FFT_LEN_L2 - 3) < 0) ? 0 : (FFT_LEN_L2 - 2) }; + enum { BR_ARR_SIZE = 1 << BR_ARR_SIZE_L2 }; + + enum { TRIGO_BD = ((FFT_LEN_L2 - TRIGO_BD_LIMIT) < 0) + ? (int)FFT_LEN_L2 + : (int)TRIGO_BD_LIMIT }; + enum { TRIGO_TABLE_ARR_SIZE_L2 = (LL2 < 4) ? 0 : (TRIGO_BD - 2) }; + enum { TRIGO_TABLE_ARR_SIZE = 1 << TRIGO_TABLE_ARR_SIZE_L2 }; + + enum { NBR_TRIGO_OSC = FFT_LEN_L2 - TRIGO_BD }; + enum { TRIGO_OSC_ARR_SIZE = (NBR_TRIGO_OSC > 0) ? NBR_TRIGO_OSC : 1 }; + + void build_br_lut (); + void build_trigo_lut (); + void build_trigo_osc (); + + DynArray + _buffer; + DynArray + _br_data; + DynArray + _trigo_data; + Array + _trigo_osc; + + + +/*\\\ FORBIDDEN MEMBER FUNCTIONS \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +private: + + FFTRealFixLen (const FFTRealFixLen &other); + FFTRealFixLen& operator = (const FFTRealFixLen &other); + bool operator == (const FFTRealFixLen &other); + bool operator != (const FFTRealFixLen &other); + +}; // class FFTRealFixLen + + + +#include "FFTRealFixLen.hpp" + + + +#endif // FFTRealFixLen_HEADER_INCLUDED + + + +/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ diff --git a/demos/spectrum/fftreal/FFTRealFixLen.hpp b/demos/spectrum/fftreal/FFTRealFixLen.hpp new file mode 100644 index 0000000..6defb00 --- /dev/null +++ b/demos/spectrum/fftreal/FFTRealFixLen.hpp @@ -0,0 +1,322 @@ +/***************************************************************************** + + FFTRealFixLen.hpp + Copyright (c) 2005 Laurent de Soras + +--- Legal stuff --- + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +*Tab=3***********************************************************************/ + + + +#if defined (FFTRealFixLen_CURRENT_CODEHEADER) + #error Recursive inclusion of FFTRealFixLen code header. +#endif +#define FFTRealFixLen_CURRENT_CODEHEADER + +#if ! defined (FFTRealFixLen_CODEHEADER_INCLUDED) +#define FFTRealFixLen_CODEHEADER_INCLUDED + + + +/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +#include "def.h" +#include "FFTRealPassDirect.h" +#include "FFTRealPassInverse.h" +#include "FFTRealSelect.h" + +#include +#include + +namespace std { } + + + +/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +template +FFTRealFixLen ::FFTRealFixLen () +: _buffer (FFT_LEN) +, _br_data (BR_ARR_SIZE) +, _trigo_data (TRIGO_TABLE_ARR_SIZE) +, _trigo_osc () +{ + build_br_lut (); + build_trigo_lut (); + build_trigo_osc (); +} + + + +template +long FFTRealFixLen ::get_length () const +{ + return (FFT_LEN); +} + + + +// General case +template +void FFTRealFixLen ::do_fft (DataType f [], const DataType x []) +{ + assert (f != 0); + assert (x != 0); + assert (x != f); + assert (FFT_LEN_L2 >= 3); + + // Do the transform in several passes + const DataType * cos_ptr = &_trigo_data [0]; + const long * br_ptr = &_br_data [0]; + + FFTRealPassDirect ::process ( + FFT_LEN, + f, + &_buffer [0], + x, + cos_ptr, + TRIGO_TABLE_ARR_SIZE, + br_ptr, + &_trigo_osc [0] + ); +} + +// 4-point FFT +template <> +void FFTRealFixLen <2>::do_fft (DataType f [], const DataType x []) +{ + assert (f != 0); + assert (x != 0); + assert (x != f); + + f [1] = x [0] - x [2]; + f [3] = x [1] - x [3]; + + const DataType b_0 = x [0] + x [2]; + const DataType b_2 = x [1] + x [3]; + + f [0] = b_0 + b_2; + f [2] = b_0 - b_2; +} + +// 2-point FFT +template <> +void FFTRealFixLen <1>::do_fft (DataType f [], const DataType x []) +{ + assert (f != 0); + assert (x != 0); + assert (x != f); + + f [0] = x [0] + x [1]; + f [1] = x [0] - x [1]; +} + +// 1-point FFT +template <> +void FFTRealFixLen <0>::do_fft (DataType f [], const DataType x []) +{ + assert (f != 0); + assert (x != 0); + + f [0] = x [0]; +} + + + +// General case +template +void FFTRealFixLen ::do_ifft (const DataType f [], DataType x []) +{ + assert (f != 0); + assert (x != 0); + assert (x != f); + assert (FFT_LEN_L2 >= 3); + + // Do the transform in several passes + DataType * s_ptr = + FFTRealSelect ::sel_bin (&_buffer [0], x); + DataType * d_ptr = + FFTRealSelect ::sel_bin (x, &_buffer [0]); + const DataType * cos_ptr = &_trigo_data [0]; + const long * br_ptr = &_br_data [0]; + + FFTRealPassInverse ::process ( + FFT_LEN, + d_ptr, + s_ptr, + f, + cos_ptr, + TRIGO_TABLE_ARR_SIZE, + br_ptr, + &_trigo_osc [0] + ); +} + +// 4-point IFFT +template <> +void FFTRealFixLen <2>::do_ifft (const DataType f [], DataType x []) +{ + assert (f != 0); + assert (x != 0); + assert (x != f); + + const DataType b_0 = f [0] + f [2]; + const DataType b_2 = f [0] - f [2]; + + x [0] = b_0 + f [1] * 2; + x [2] = b_0 - f [1] * 2; + x [1] = b_2 + f [3] * 2; + x [3] = b_2 - f [3] * 2; +} + +// 2-point IFFT +template <> +void FFTRealFixLen <1>::do_ifft (const DataType f [], DataType x []) +{ + assert (f != 0); + assert (x != 0); + assert (x != f); + + x [0] = f [0] + f [1]; + x [1] = f [0] - f [1]; +} + +// 1-point IFFT +template <> +void FFTRealFixLen <0>::do_ifft (const DataType f [], DataType x []) +{ + assert (f != 0); + assert (x != 0); + assert (x != f); + + x [0] = f [0]; +} + + + + +template +void FFTRealFixLen ::rescale (DataType x []) const +{ + assert (x != 0); + + const DataType mul = DataType (1.0 / FFT_LEN); + + if (FFT_LEN < 4) + { + long i = FFT_LEN - 1; + do + { + x [i] *= mul; + --i; + } + while (i >= 0); + } + + else + { + assert ((FFT_LEN & 3) == 0); + + // Could be optimized with SIMD instruction sets (needs alignment check) + long i = FFT_LEN - 4; + do + { + x [i + 0] *= mul; + x [i + 1] *= mul; + x [i + 2] *= mul; + x [i + 3] *= mul; + i -= 4; + } + while (i >= 0); + } +} + + + +/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +template +void FFTRealFixLen ::build_br_lut () +{ + _br_data [0] = 0; + for (long cnt = 1; cnt < BR_ARR_SIZE; ++cnt) + { + long index = cnt << 2; + long br_index = 0; + + int bit_cnt = FFT_LEN_L2; + do + { + br_index <<= 1; + br_index += (index & 1); + index >>= 1; + + -- bit_cnt; + } + while (bit_cnt > 0); + + _br_data [cnt] = br_index; + } +} + + + +template +void FFTRealFixLen ::build_trigo_lut () +{ + const double mul = (0.5 * PI) / TRIGO_TABLE_ARR_SIZE; + for (long i = 0; i < TRIGO_TABLE_ARR_SIZE; ++ i) + { + using namespace std; + + _trigo_data [i] = DataType (cos (i * mul)); + } +} + + + +template +void FFTRealFixLen ::build_trigo_osc () +{ + for (int i = 0; i < NBR_TRIGO_OSC; ++i) + { + OscType & osc = _trigo_osc [i]; + + const long len = static_cast (TRIGO_TABLE_ARR_SIZE) << (i + 1); + const double mul = (0.5 * PI) / len; + osc.set_step (mul); + } +} + + + +#endif // FFTRealFixLen_CODEHEADER_INCLUDED + +#undef FFTRealFixLen_CURRENT_CODEHEADER + + + +/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ diff --git a/demos/spectrum/fftreal/FFTRealFixLenParam.h b/demos/spectrum/fftreal/FFTRealFixLenParam.h new file mode 100644 index 0000000..163c083 --- /dev/null +++ b/demos/spectrum/fftreal/FFTRealFixLenParam.h @@ -0,0 +1,93 @@ +/***************************************************************************** + + FFTRealFixLenParam.h + Copyright (c) 2005 Laurent de Soras + +--- Legal stuff --- + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +*Tab=3***********************************************************************/ + + + +#if ! defined (FFTRealFixLenParam_HEADER_INCLUDED) +#define FFTRealFixLenParam_HEADER_INCLUDED + +#if defined (_MSC_VER) + #pragma once + #pragma warning (4 : 4250) // "Inherits via dominance." +#endif + + + +/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +class FFTRealFixLenParam +{ + +/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +public: + + // Over this bit depth, we use direct calculation for sin/cos + enum { TRIGO_BD_LIMIT = 12 }; + + typedef float DataType; + + + +/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +protected: + + + +/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +private: + + + +/*\\\ FORBIDDEN MEMBER FUNCTIONS \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +private: + +#if 0 // To avoid GCC warning: + // All member functions in class 'FFTRealFixLenParam' are private + FFTRealFixLenParam (); + ~FFTRealFixLenParam (); + FFTRealFixLenParam (const FFTRealFixLenParam &other); + FFTRealFixLenParam & + operator = (const FFTRealFixLenParam &other); + bool operator == (const FFTRealFixLenParam &other); + bool operator != (const FFTRealFixLenParam &other); +#endif + +}; // class FFTRealFixLenParam + + + +//#include "FFTRealFixLenParam.hpp" + + + +#endif // FFTRealFixLenParam_HEADER_INCLUDED + + + +/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ diff --git a/demos/spectrum/fftreal/FFTRealPassDirect.h b/demos/spectrum/fftreal/FFTRealPassDirect.h new file mode 100644 index 0000000..7d19c02 --- /dev/null +++ b/demos/spectrum/fftreal/FFTRealPassDirect.h @@ -0,0 +1,96 @@ +/***************************************************************************** + + FFTRealPassDirect.h + Copyright (c) 2005 Laurent de Soras + +--- Legal stuff --- + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +*Tab=3***********************************************************************/ + + + +#if ! defined (FFTRealPassDirect_HEADER_INCLUDED) +#define FFTRealPassDirect_HEADER_INCLUDED + +#if defined (_MSC_VER) + #pragma once + #pragma warning (4 : 4250) // "Inherits via dominance." +#endif + + + +/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +#include "def.h" +#include "FFTRealFixLenParam.h" +#include "OscSinCos.h" + + + +template +class FFTRealPassDirect +{ + +/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +public: + + typedef FFTRealFixLenParam::DataType DataType; + typedef OscSinCos OscType; + + FORCEINLINE static void + process (long len, DataType dest_ptr [], DataType src_ptr [], const DataType x_ptr [], const DataType cos_ptr [], long cos_len, const long br_ptr [], OscType osc_list []); + + + +/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +protected: + + + +/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +private: + + + +/*\\\ FORBIDDEN MEMBER FUNCTIONS \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +private: + + FFTRealPassDirect (); + ~FFTRealPassDirect (); + FFTRealPassDirect (const FFTRealPassDirect &other); + FFTRealPassDirect & + operator = (const FFTRealPassDirect &other); + bool operator == (const FFTRealPassDirect &other); + bool operator != (const FFTRealPassDirect &other); + +}; // class FFTRealPassDirect + + + +#include "FFTRealPassDirect.hpp" + + + +#endif // FFTRealPassDirect_HEADER_INCLUDED + + + +/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ diff --git a/demos/spectrum/fftreal/FFTRealPassDirect.hpp b/demos/spectrum/fftreal/FFTRealPassDirect.hpp new file mode 100644 index 0000000..db9d568 --- /dev/null +++ b/demos/spectrum/fftreal/FFTRealPassDirect.hpp @@ -0,0 +1,204 @@ +/***************************************************************************** + + FFTRealPassDirect.hpp + Copyright (c) 2005 Laurent de Soras + +--- Legal stuff --- + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +*Tab=3***********************************************************************/ + + + +#if defined (FFTRealPassDirect_CURRENT_CODEHEADER) + #error Recursive inclusion of FFTRealPassDirect code header. +#endif +#define FFTRealPassDirect_CURRENT_CODEHEADER + +#if ! defined (FFTRealPassDirect_CODEHEADER_INCLUDED) +#define FFTRealPassDirect_CODEHEADER_INCLUDED + + + +/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +#include "FFTRealUseTrigo.h" + + + +/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +template <> +void FFTRealPassDirect <1>::process (long len, DataType dest_ptr [], DataType src_ptr [], const DataType x_ptr [], const DataType cos_ptr [], long cos_len, const long br_ptr [], OscType osc_list []) +{ + // First and second pass at once + const long qlen = len >> 2; + + long coef_index = 0; + do + { + // To do: unroll the loop (2x). + const long ri_0 = br_ptr [coef_index >> 2]; + const long ri_1 = ri_0 + 2 * qlen; // bit_rev_lut_ptr [coef_index + 1]; + const long ri_2 = ri_0 + 1 * qlen; // bit_rev_lut_ptr [coef_index + 2]; + const long ri_3 = ri_0 + 3 * qlen; // bit_rev_lut_ptr [coef_index + 3]; + + DataType * const df2 = dest_ptr + coef_index; + df2 [1] = x_ptr [ri_0] - x_ptr [ri_1]; + df2 [3] = x_ptr [ri_2] - x_ptr [ri_3]; + + const DataType sf_0 = x_ptr [ri_0] + x_ptr [ri_1]; + const DataType sf_2 = x_ptr [ri_2] + x_ptr [ri_3]; + + df2 [0] = sf_0 + sf_2; + df2 [2] = sf_0 - sf_2; + + coef_index += 4; + } + while (coef_index < len); +} + +template <> +void FFTRealPassDirect <2>::process (long len, DataType dest_ptr [], DataType src_ptr [], const DataType x_ptr [], const DataType cos_ptr [], long cos_len, const long br_ptr [], OscType osc_list []) +{ + // Executes "previous" passes first. Inverts source and destination buffers + FFTRealPassDirect <1>::process ( + len, + src_ptr, + dest_ptr, + x_ptr, + cos_ptr, + cos_len, + br_ptr, + osc_list + ); + + // Third pass + const DataType sqrt2_2 = DataType (SQRT2 * 0.5); + + long coef_index = 0; + do + { + dest_ptr [coef_index ] = src_ptr [coef_index] + src_ptr [coef_index + 4]; + dest_ptr [coef_index + 4] = src_ptr [coef_index] - src_ptr [coef_index + 4]; + dest_ptr [coef_index + 2] = src_ptr [coef_index + 2]; + dest_ptr [coef_index + 6] = src_ptr [coef_index + 6]; + + DataType v; + + v = (src_ptr [coef_index + 5] - src_ptr [coef_index + 7]) * sqrt2_2; + dest_ptr [coef_index + 1] = src_ptr [coef_index + 1] + v; + dest_ptr [coef_index + 3] = src_ptr [coef_index + 1] - v; + + v = (src_ptr [coef_index + 5] + src_ptr [coef_index + 7]) * sqrt2_2; + dest_ptr [coef_index + 5] = v + src_ptr [coef_index + 3]; + dest_ptr [coef_index + 7] = v - src_ptr [coef_index + 3]; + + coef_index += 8; + } + while (coef_index < len); +} + +template +void FFTRealPassDirect ::process (long len, DataType dest_ptr [], DataType src_ptr [], const DataType x_ptr [], const DataType cos_ptr [], long cos_len, const long br_ptr [], OscType osc_list []) +{ + // Executes "previous" passes first. Inverts source and destination buffers + FFTRealPassDirect ::process ( + len, + src_ptr, + dest_ptr, + x_ptr, + cos_ptr, + cos_len, + br_ptr, + osc_list + ); + + const long dist = 1L << (PASS - 1); + const long c1_r = 0; + const long c1_i = dist; + const long c2_r = dist * 2; + const long c2_i = dist * 3; + const long cend = dist * 4; + const long table_step = cos_len >> (PASS - 1); + + enum { TRIGO_OSC = PASS - FFTRealFixLenParam::TRIGO_BD_LIMIT }; + enum { TRIGO_DIRECT = (TRIGO_OSC >= 0) ? 1 : 0 }; + + long coef_index = 0; + do + { + const DataType * const sf = src_ptr + coef_index; + DataType * const df = dest_ptr + coef_index; + + // Extreme coefficients are always real + df [c1_r] = sf [c1_r] + sf [c2_r]; + df [c2_r] = sf [c1_r] - sf [c2_r]; + df [c1_i] = sf [c1_i]; + df [c2_i] = sf [c2_i]; + + FFTRealUseTrigo ::prepare (osc_list [TRIGO_OSC]); + + // Others are conjugate complex numbers + for (long i = 1; i < dist; ++ i) + { + DataType c; + DataType s; + FFTRealUseTrigo ::iterate ( + osc_list [TRIGO_OSC], + c, + s, + cos_ptr, + i * table_step, + (dist - i) * table_step + ); + + const DataType sf_r_i = sf [c1_r + i]; + const DataType sf_i_i = sf [c1_i + i]; + + const DataType v1 = sf [c2_r + i] * c - sf [c2_i + i] * s; + df [c1_r + i] = sf_r_i + v1; + df [c2_r - i] = sf_r_i - v1; + + const DataType v2 = sf [c2_r + i] * s + sf [c2_i + i] * c; + df [c2_r + i] = v2 + sf_i_i; + df [cend - i] = v2 - sf_i_i; + } + + coef_index += cend; + } + while (coef_index < len); +} + + + +/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +#endif // FFTRealPassDirect_CODEHEADER_INCLUDED + +#undef FFTRealPassDirect_CURRENT_CODEHEADER + + + +/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ diff --git a/demos/spectrum/fftreal/FFTRealPassInverse.h b/demos/spectrum/fftreal/FFTRealPassInverse.h new file mode 100644 index 0000000..2de8952 --- /dev/null +++ b/demos/spectrum/fftreal/FFTRealPassInverse.h @@ -0,0 +1,101 @@ +/***************************************************************************** + + FFTRealPassInverse.h + Copyright (c) 2005 Laurent de Soras + +--- Legal stuff --- + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +*Tab=3***********************************************************************/ + + + +#if ! defined (FFTRealPassInverse_HEADER_INCLUDED) +#define FFTRealPassInverse_HEADER_INCLUDED + +#if defined (_MSC_VER) + #pragma once + #pragma warning (4 : 4250) // "Inherits via dominance." +#endif + + + +/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +#include "def.h" +#include "FFTRealFixLenParam.h" +#include "OscSinCos.h" + + + + +template +class FFTRealPassInverse +{ + +/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +public: + + typedef FFTRealFixLenParam::DataType DataType; + typedef OscSinCos OscType; + + FORCEINLINE static void + process (long len, DataType dest_ptr [], DataType src_ptr [], const DataType f_ptr [], const DataType cos_ptr [], long cos_len, const long br_ptr [], OscType osc_list []); + FORCEINLINE static void + process_rec (long len, DataType dest_ptr [], DataType src_ptr [], const DataType cos_ptr [], long cos_len, const long br_ptr [], OscType osc_list []); + FORCEINLINE static void + process_internal (long len, DataType dest_ptr [], const DataType src_ptr [], const DataType cos_ptr [], long cos_len, const long br_ptr [], OscType osc_list []); + + + +/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +protected: + + + +/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +private: + + + +/*\\\ FORBIDDEN MEMBER FUNCTIONS \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +private: + + FFTRealPassInverse (); + ~FFTRealPassInverse (); + FFTRealPassInverse (const FFTRealPassInverse &other); + FFTRealPassInverse & + operator = (const FFTRealPassInverse &other); + bool operator == (const FFTRealPassInverse &other); + bool operator != (const FFTRealPassInverse &other); + +}; // class FFTRealPassInverse + + + +#include "FFTRealPassInverse.hpp" + + + +#endif // FFTRealPassInverse_HEADER_INCLUDED + + + +/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ diff --git a/demos/spectrum/fftreal/FFTRealPassInverse.hpp b/demos/spectrum/fftreal/FFTRealPassInverse.hpp new file mode 100644 index 0000000..5737546 --- /dev/null +++ b/demos/spectrum/fftreal/FFTRealPassInverse.hpp @@ -0,0 +1,229 @@ +/***************************************************************************** + + FFTRealPassInverse.hpp + Copyright (c) 2005 Laurent de Soras + +--- Legal stuff --- + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +*Tab=3***********************************************************************/ + + + +#if defined (FFTRealPassInverse_CURRENT_CODEHEADER) + #error Recursive inclusion of FFTRealPassInverse code header. +#endif +#define FFTRealPassInverse_CURRENT_CODEHEADER + +#if ! defined (FFTRealPassInverse_CODEHEADER_INCLUDED) +#define FFTRealPassInverse_CODEHEADER_INCLUDED + + + +/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +#include "FFTRealUseTrigo.h" + + + +/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +template +void FFTRealPassInverse ::process (long len, DataType dest_ptr [], DataType src_ptr [], const DataType f_ptr [], const DataType cos_ptr [], long cos_len, const long br_ptr [], OscType osc_list []) +{ + process_internal ( + len, + dest_ptr, + f_ptr, + cos_ptr, + cos_len, + br_ptr, + osc_list + ); + FFTRealPassInverse ::process_rec ( + len, + src_ptr, + dest_ptr, + cos_ptr, + cos_len, + br_ptr, + osc_list + ); +} + + + +template +void FFTRealPassInverse ::process_rec (long len, DataType dest_ptr [], DataType src_ptr [], const DataType cos_ptr [], long cos_len, const long br_ptr [], OscType osc_list []) +{ + process_internal ( + len, + dest_ptr, + src_ptr, + cos_ptr, + cos_len, + br_ptr, + osc_list + ); + FFTRealPassInverse ::process_rec ( + len, + src_ptr, + dest_ptr, + cos_ptr, + cos_len, + br_ptr, + osc_list + ); +} + +template <> +void FFTRealPassInverse <0>::process_rec (long len, DataType dest_ptr [], DataType src_ptr [], const DataType cos_ptr [], long cos_len, const long br_ptr [], OscType osc_list []) +{ + // Stops recursion +} + + + +template +void FFTRealPassInverse ::process_internal (long len, DataType dest_ptr [], const DataType src_ptr [], const DataType cos_ptr [], long cos_len, const long br_ptr [], OscType osc_list []) +{ + const long dist = 1L << (PASS - 1); + const long c1_r = 0; + const long c1_i = dist; + const long c2_r = dist * 2; + const long c2_i = dist * 3; + const long cend = dist * 4; + const long table_step = cos_len >> (PASS - 1); + + enum { TRIGO_OSC = PASS - FFTRealFixLenParam::TRIGO_BD_LIMIT }; + enum { TRIGO_DIRECT = (TRIGO_OSC >= 0) ? 1 : 0 }; + + long coef_index = 0; + do + { + const DataType * const sf = src_ptr + coef_index; + DataType * const df = dest_ptr + coef_index; + + // Extreme coefficients are always real + df [c1_r] = sf [c1_r] + sf [c2_r]; + df [c2_r] = sf [c1_r] - sf [c2_r]; + df [c1_i] = sf [c1_i] * 2; + df [c2_i] = sf [c2_i] * 2; + + FFTRealUseTrigo ::prepare (osc_list [TRIGO_OSC]); + + // Others are conjugate complex numbers + for (long i = 1; i < dist; ++ i) + { + df [c1_r + i] = sf [c1_r + i] + sf [c2_r - i]; + df [c1_i + i] = sf [c2_r + i] - sf [cend - i]; + + DataType c; + DataType s; + FFTRealUseTrigo ::iterate ( + osc_list [TRIGO_OSC], + c, + s, + cos_ptr, + i * table_step, + (dist - i) * table_step + ); + + const DataType vr = sf [c1_r + i] - sf [c2_r - i]; + const DataType vi = sf [c2_r + i] + sf [cend - i]; + + df [c2_r + i] = vr * c + vi * s; + df [c2_i + i] = vi * c - vr * s; + } + + coef_index += cend; + } + while (coef_index < len); +} + +template <> +void FFTRealPassInverse <2>::process_internal (long len, DataType dest_ptr [], const DataType src_ptr [], const DataType cos_ptr [], long cos_len, const long br_ptr [], OscType osc_list []) +{ + // Antepenultimate pass + const DataType sqrt2_2 = DataType (SQRT2 * 0.5); + + long coef_index = 0; + do + { + dest_ptr [coef_index ] = src_ptr [coef_index] + src_ptr [coef_index + 4]; + dest_ptr [coef_index + 4] = src_ptr [coef_index] - src_ptr [coef_index + 4]; + dest_ptr [coef_index + 2] = src_ptr [coef_index + 2] * 2; + dest_ptr [coef_index + 6] = src_ptr [coef_index + 6] * 2; + + dest_ptr [coef_index + 1] = src_ptr [coef_index + 1] + src_ptr [coef_index + 3]; + dest_ptr [coef_index + 3] = src_ptr [coef_index + 5] - src_ptr [coef_index + 7]; + + const DataType vr = src_ptr [coef_index + 1] - src_ptr [coef_index + 3]; + const DataType vi = src_ptr [coef_index + 5] + src_ptr [coef_index + 7]; + + dest_ptr [coef_index + 5] = (vr + vi) * sqrt2_2; + dest_ptr [coef_index + 7] = (vi - vr) * sqrt2_2; + + coef_index += 8; + } + while (coef_index < len); +} + +template <> +void FFTRealPassInverse <1>::process_internal (long len, DataType dest_ptr [], const DataType src_ptr [], const DataType cos_ptr [], long cos_len, const long br_ptr [], OscType osc_list []) +{ + // Penultimate and last pass at once + const long qlen = len >> 2; + + long coef_index = 0; + do + { + const long ri_0 = br_ptr [coef_index >> 2]; + + const DataType b_0 = src_ptr [coef_index ] + src_ptr [coef_index + 2]; + const DataType b_2 = src_ptr [coef_index ] - src_ptr [coef_index + 2]; + const DataType b_1 = src_ptr [coef_index + 1] * 2; + const DataType b_3 = src_ptr [coef_index + 3] * 2; + + dest_ptr [ri_0 ] = b_0 + b_1; + dest_ptr [ri_0 + 2 * qlen] = b_0 - b_1; + dest_ptr [ri_0 + 1 * qlen] = b_2 + b_3; + dest_ptr [ri_0 + 3 * qlen] = b_2 - b_3; + + coef_index += 4; + } + while (coef_index < len); +} + + + +/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +#endif // FFTRealPassInverse_CODEHEADER_INCLUDED + +#undef FFTRealPassInverse_CURRENT_CODEHEADER + + + +/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ diff --git a/demos/spectrum/fftreal/FFTRealSelect.h b/demos/spectrum/fftreal/FFTRealSelect.h new file mode 100644 index 0000000..bd722d4 --- /dev/null +++ b/demos/spectrum/fftreal/FFTRealSelect.h @@ -0,0 +1,77 @@ +/***************************************************************************** + + FFTRealSelect.h + Copyright (c) 2005 Laurent de Soras + +--- Legal stuff --- + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +*Tab=3***********************************************************************/ + + + +#if ! defined (FFTRealSelect_HEADER_INCLUDED) +#define FFTRealSelect_HEADER_INCLUDED + +#if defined (_MSC_VER) + #pragma once +#endif + + + +/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +#include "def.h" + + + +template +class FFTRealSelect +{ + +/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +public: + + FORCEINLINE static float * + sel_bin (float *e_ptr, float *o_ptr); + + + +/*\\\ FORBIDDEN MEMBER FUNCTIONS \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +private: + + FFTRealSelect (); + ~FFTRealSelect (); + FFTRealSelect (const FFTRealSelect &other); + FFTRealSelect& operator = (const FFTRealSelect &other); + bool operator == (const FFTRealSelect &other); + bool operator != (const FFTRealSelect &other); + +}; // class FFTRealSelect + + + +#include "FFTRealSelect.hpp" + + + +#endif // FFTRealSelect_HEADER_INCLUDED + + + +/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ diff --git a/demos/spectrum/fftreal/FFTRealSelect.hpp b/demos/spectrum/fftreal/FFTRealSelect.hpp new file mode 100644 index 0000000..9ddf586 --- /dev/null +++ b/demos/spectrum/fftreal/FFTRealSelect.hpp @@ -0,0 +1,62 @@ +/***************************************************************************** + + FFTRealSelect.hpp + Copyright (c) 2005 Laurent de Soras + +--- Legal stuff --- + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +*Tab=3***********************************************************************/ + + + +#if defined (FFTRealSelect_CURRENT_CODEHEADER) + #error Recursive inclusion of FFTRealSelect code header. +#endif +#define FFTRealSelect_CURRENT_CODEHEADER + +#if ! defined (FFTRealSelect_CODEHEADER_INCLUDED) +#define FFTRealSelect_CODEHEADER_INCLUDED + + + +/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +template +float * FFTRealSelect

::sel_bin (float *e_ptr, float *o_ptr) +{ + return (o_ptr); +} + + + +template <> +float * FFTRealSelect <0>::sel_bin (float *e_ptr, float *o_ptr) +{ + return (e_ptr); +} + + + +#endif // FFTRealSelect_CODEHEADER_INCLUDED + +#undef FFTRealSelect_CURRENT_CODEHEADER + + + +/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ diff --git a/demos/spectrum/fftreal/FFTRealUseTrigo.h b/demos/spectrum/fftreal/FFTRealUseTrigo.h new file mode 100644 index 0000000..c4368ee --- /dev/null +++ b/demos/spectrum/fftreal/FFTRealUseTrigo.h @@ -0,0 +1,101 @@ +/***************************************************************************** + + FFTRealUseTrigo.h + Copyright (c) 2005 Laurent de Soras + +Template parameters: + - ALGO: algorithm choice. 0 = table, other = oscillator + +--- Legal stuff --- + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +*Tab=3***********************************************************************/ + + + +#if ! defined (FFTRealUseTrigo_HEADER_INCLUDED) +#define FFTRealUseTrigo_HEADER_INCLUDED + +#if defined (_MSC_VER) + #pragma once + #pragma warning (4 : 4250) // "Inherits via dominance." +#endif + + + +/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +#include "def.h" +#include "FFTRealFixLenParam.h" +#include "OscSinCos.h" + + + +template +class FFTRealUseTrigo +{ + +/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +public: + + typedef FFTRealFixLenParam::DataType DataType; + typedef OscSinCos OscType; + + FORCEINLINE static void + prepare (OscType &osc); + FORCEINLINE static void + iterate (OscType &osc, DataType &c, DataType &s, const DataType cos_ptr [], long index_c, long index_s); + + + +/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +protected: + + + +/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +private: + + + +/*\\\ FORBIDDEN MEMBER FUNCTIONS \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +private: + + FFTRealUseTrigo (); + ~FFTRealUseTrigo (); + FFTRealUseTrigo (const FFTRealUseTrigo &other); + FFTRealUseTrigo & + operator = (const FFTRealUseTrigo &other); + bool operator == (const FFTRealUseTrigo &other); + bool operator != (const FFTRealUseTrigo &other); + +}; // class FFTRealUseTrigo + + + +#include "FFTRealUseTrigo.hpp" + + + +#endif // FFTRealUseTrigo_HEADER_INCLUDED + + + +/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ diff --git a/demos/spectrum/fftreal/FFTRealUseTrigo.hpp b/demos/spectrum/fftreal/FFTRealUseTrigo.hpp new file mode 100644 index 0000000..aa968b8 --- /dev/null +++ b/demos/spectrum/fftreal/FFTRealUseTrigo.hpp @@ -0,0 +1,91 @@ +/***************************************************************************** + + FFTRealUseTrigo.hpp + Copyright (c) 2005 Laurent de Soras + +--- Legal stuff --- + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +*Tab=3***********************************************************************/ + + + +#if defined (FFTRealUseTrigo_CURRENT_CODEHEADER) + #error Recursive inclusion of FFTRealUseTrigo code header. +#endif +#define FFTRealUseTrigo_CURRENT_CODEHEADER + +#if ! defined (FFTRealUseTrigo_CODEHEADER_INCLUDED) +#define FFTRealUseTrigo_CODEHEADER_INCLUDED + + + +/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +#include "OscSinCos.h" + + + +/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +template +void FFTRealUseTrigo ::prepare (OscType &osc) +{ + osc.clear_buffers (); +} + +template <> +void FFTRealUseTrigo <0>::prepare (OscType &osc) +{ + // Nothing +} + + + +template +void FFTRealUseTrigo ::iterate (OscType &osc, DataType &c, DataType &s, const DataType cos_ptr [], long index_c, long index_s) +{ + osc.step (); + c = osc.get_cos (); + s = osc.get_sin (); +} + +template <> +void FFTRealUseTrigo <0>::iterate (OscType &osc, DataType &c, DataType &s, const DataType cos_ptr [], long index_c, long index_s) +{ + c = cos_ptr [index_c]; + s = cos_ptr [index_s]; +} + + + +/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +#endif // FFTRealUseTrigo_CODEHEADER_INCLUDED + +#undef FFTRealUseTrigo_CURRENT_CODEHEADER + + + +/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ diff --git a/demos/spectrum/fftreal/OscSinCos.h b/demos/spectrum/fftreal/OscSinCos.h new file mode 100644 index 0000000..775fc14 --- /dev/null +++ b/demos/spectrum/fftreal/OscSinCos.h @@ -0,0 +1,106 @@ +/***************************************************************************** + + OscSinCos.h + Copyright (c) 2005 Laurent de Soras + +--- Legal stuff --- + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +*Tab=3***********************************************************************/ + + + +#if ! defined (OscSinCos_HEADER_INCLUDED) +#define OscSinCos_HEADER_INCLUDED + +#if defined (_MSC_VER) + #pragma once + #pragma warning (4 : 4250) // "Inherits via dominance." +#endif + + + +/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +#include "def.h" + + + +template +class OscSinCos +{ + +/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +public: + + typedef T DataType; + + OscSinCos (); + + FORCEINLINE void + set_step (double angle_rad); + + FORCEINLINE DataType + get_cos () const; + FORCEINLINE DataType + get_sin () const; + FORCEINLINE void + step (); + FORCEINLINE void + clear_buffers (); + + + +/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +protected: + + + +/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +private: + + DataType _pos_cos; // Current phase expressed with sin and cos. [-1 ; 1] + DataType _pos_sin; // - + DataType _step_cos; // Phase increment per step, [-1 ; 1] + DataType _step_sin; // - + + + +/*\\\ FORBIDDEN MEMBER FUNCTIONS \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +private: + + OscSinCos (const OscSinCos &other); + OscSinCos & operator = (const OscSinCos &other); + bool operator == (const OscSinCos &other); + bool operator != (const OscSinCos &other); + +}; // class OscSinCos + + + +#include "OscSinCos.hpp" + + + +#endif // OscSinCos_HEADER_INCLUDED + + + +/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ diff --git a/demos/spectrum/fftreal/OscSinCos.hpp b/demos/spectrum/fftreal/OscSinCos.hpp new file mode 100644 index 0000000..749aef0 --- /dev/null +++ b/demos/spectrum/fftreal/OscSinCos.hpp @@ -0,0 +1,122 @@ +/***************************************************************************** + + OscSinCos.hpp + Copyright (c) 2005 Laurent de Soras + +--- Legal stuff --- + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +*Tab=3***********************************************************************/ + + + +#if defined (OscSinCos_CURRENT_CODEHEADER) + #error Recursive inclusion of OscSinCos code header. +#endif +#define OscSinCos_CURRENT_CODEHEADER + +#if ! defined (OscSinCos_CODEHEADER_INCLUDED) +#define OscSinCos_CODEHEADER_INCLUDED + + + +/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +#include + +namespace std { } + + + +/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +template +OscSinCos ::OscSinCos () +: _pos_cos (1) +, _pos_sin (0) +, _step_cos (1) +, _step_sin (0) +{ + // Nothing +} + + + +template +void OscSinCos ::set_step (double angle_rad) +{ + using namespace std; + + _step_cos = static_cast (cos (angle_rad)); + _step_sin = static_cast (sin (angle_rad)); +} + + + +template +typename OscSinCos ::DataType OscSinCos ::get_cos () const +{ + return (_pos_cos); +} + + + +template +typename OscSinCos ::DataType OscSinCos ::get_sin () const +{ + return (_pos_sin); +} + + + +template +void OscSinCos ::step () +{ + const DataType old_cos = _pos_cos; + const DataType old_sin = _pos_sin; + + _pos_cos = old_cos * _step_cos - old_sin * _step_sin; + _pos_sin = old_cos * _step_sin + old_sin * _step_cos; +} + + + +template +void OscSinCos ::clear_buffers () +{ + _pos_cos = static_cast (1); + _pos_sin = static_cast (0); +} + + + +/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +#endif // OscSinCos_CODEHEADER_INCLUDED + +#undef OscSinCos_CURRENT_CODEHEADER + + + +/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ diff --git a/demos/spectrum/fftreal/TestAccuracy.h b/demos/spectrum/fftreal/TestAccuracy.h new file mode 100644 index 0000000..4b07a6b --- /dev/null +++ b/demos/spectrum/fftreal/TestAccuracy.h @@ -0,0 +1,105 @@ +/***************************************************************************** + + TestAccuracy.h + Copyright (c) 2005 Laurent de Soras + +--- Legal stuff --- + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +*Tab=3***********************************************************************/ + + + +#if ! defined (TestAccuracy_HEADER_INCLUDED) +#define TestAccuracy_HEADER_INCLUDED + +#if defined (_MSC_VER) + #pragma once + #pragma warning (4 : 4250) // "Inherits via dominance." +#endif + + + +/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +template +class TestAccuracy +{ + +/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +public: + + typedef typename FO::DataType DataType; + typedef long double BigFloat; // To get maximum accuracy during intermediate calculations + + static int perform_test_single_object (FO &fft); + static int perform_test_d (FO &fft, const char *class_name_0); + static int perform_test_i (FO &fft, const char *class_name_0); + static int perform_test_di (FO &fft, const char *class_name_0); + + + +/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +protected: + + + +/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +private: + + enum { NBR_ACC_TESTS = 10 * 1000 * 1000 }; + enum { MAX_NBR_TESTS = 10000 }; + + static void compute_tf (DataType s [], const DataType x [], long length); + static void compute_itf (DataType x [], const DataType s [], long length); + static int compare_vect_display (const DataType x_ptr [], const DataType y_ptr [], long len, BigFloat &max_err_rel); + static BigFloat + compute_power (const DataType x_ptr [], long len); + static BigFloat + compute_power (const DataType x_ptr [], const DataType y_ptr [], long len); + static void compare_vect (const DataType x_ptr [], const DataType y_ptr [], BigFloat &power, long &max_err_pos, long len); + + + +/*\\\ FORBIDDEN MEMBER FUNCTIONS \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +private: + + TestAccuracy (); + ~TestAccuracy (); + TestAccuracy (const TestAccuracy &other); + TestAccuracy & operator = (const TestAccuracy &other); + bool operator == (const TestAccuracy &other); + bool operator != (const TestAccuracy &other); + +}; // class TestAccuracy + + + +#include "TestAccuracy.hpp" + + + +#endif // TestAccuracy_HEADER_INCLUDED + + + +/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ diff --git a/demos/spectrum/fftreal/TestAccuracy.hpp b/demos/spectrum/fftreal/TestAccuracy.hpp new file mode 100644 index 0000000..5c794f7 --- /dev/null +++ b/demos/spectrum/fftreal/TestAccuracy.hpp @@ -0,0 +1,472 @@ +/***************************************************************************** + + TestAccuracy.hpp + Copyright (c) 2005 Laurent de Soras + +--- Legal stuff --- + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +*Tab=3***********************************************************************/ + + + +#if defined (TestAccuracy_CURRENT_CODEHEADER) + #error Recursive inclusion of TestAccuracy code header. +#endif +#define TestAccuracy_CURRENT_CODEHEADER + +#if ! defined (TestAccuracy_CODEHEADER_INCLUDED) +#define TestAccuracy_CODEHEADER_INCLUDED + + + +/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +#include "def.h" +#include "test_fnc.h" +#include "TestWhiteNoiseGen.h" + +#include +#include + +#include +#include + + + +static const double TestAccuracy_LN10 = 2.3025850929940456840179914546844; + + + +/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +template +int TestAccuracy ::perform_test_single_object (FO &fft) +{ + assert (&fft != 0); + + using namespace std; + + int ret_val = 0; + + const std::type_info & ti = typeid (fft); + const char * class_name_0 = ti.name (); + + if (ret_val == 0) + { + ret_val = perform_test_d (fft, class_name_0); + } + if (ret_val == 0) + { + ret_val = perform_test_i (fft, class_name_0); + } + if (ret_val == 0) + { + ret_val = perform_test_di (fft, class_name_0); + } + + if (ret_val == 0) + { + printf ("\n"); + } + + return (ret_val); +} + + + +template +int TestAccuracy ::perform_test_d (FO &fft, const char *class_name_0) +{ + assert (&fft != 0); + assert (class_name_0 != 0); + + using namespace std; + + int ret_val = 0; + const long len = fft.get_length (); + const long nbr_tests = limit ( + NBR_ACC_TESTS / len / len, + 1L, + static_cast (MAX_NBR_TESTS) + ); + + printf ("Testing %s::do_fft () [%ld samples]... ", class_name_0, len); + fflush (stdout); + TestWhiteNoiseGen noise; + std::vector x (len); + std::vector s1 (len); + std::vector s2 (len); + BigFloat err_avg = 0; + + for (long test = 0; test < nbr_tests && ret_val == 0; ++ test) + { + noise.generate (&x [0], len); + fft.do_fft (&s1 [0], &x [0]); + compute_tf (&s2 [0], &x [0], len); + + BigFloat max_err; + compare_vect_display (&s1 [0], &s2 [0], len, max_err); + err_avg += max_err; + } + err_avg /= NBR_ACC_TESTS; + + printf ("done.\n"); + printf ( + "Average maximum error: %.6f %% (%f dB)\n", + static_cast (err_avg * 100), + static_cast ((20 / TestAccuracy_LN10) * log (err_avg)) + ); + + return (ret_val); +} + + + +template +int TestAccuracy ::perform_test_i (FO &fft, const char *class_name_0) +{ + assert (&fft != 0); + assert (class_name_0 != 0); + + using namespace std; + + int ret_val = 0; + const long len = fft.get_length (); + const long nbr_tests = limit ( + NBR_ACC_TESTS / len / len, + 10L, + static_cast (MAX_NBR_TESTS) + ); + + printf ("Testing %s::do_ifft () [%ld samples]... ", class_name_0, len); + fflush (stdout); + TestWhiteNoiseGen noise; + std::vector s (len); + std::vector x1 (len); + std::vector x2 (len); + BigFloat err_avg = 0; + + for (long test = 0; test < nbr_tests && ret_val == 0; ++ test) + { + noise.generate (&s [0], len); + fft.do_ifft (&s [0], &x1 [0]); + compute_itf (&x2 [0], &s [0], len); + + BigFloat max_err; + compare_vect_display (&x1 [0], &x2 [0], len, max_err); + err_avg += max_err; + } + err_avg /= NBR_ACC_TESTS; + + printf ("done.\n"); + printf ( + "Average maximum error: %.6f %% (%f dB)\n", + static_cast (err_avg * 100), + static_cast ((20 / TestAccuracy_LN10) * log (err_avg)) + ); + + return (ret_val); +} + + + +template +int TestAccuracy ::perform_test_di (FO &fft, const char *class_name_0) +{ + assert (&fft != 0); + assert (class_name_0 != 0); + + using namespace std; + + int ret_val = 0; + const long len = fft.get_length (); + const long nbr_tests = limit ( + NBR_ACC_TESTS / len / len, + 1L, + static_cast (MAX_NBR_TESTS) + ); + + printf ( + "Testing %s::do_fft () / do_ifft () / rescale () [%ld samples]... ", + class_name_0, + len + ); + fflush (stdout); + TestWhiteNoiseGen noise; + std::vector x (len); + std::vector s (len); + std::vector y (len); + BigFloat err_avg = 0; + + for (long test = 0; test < nbr_tests && ret_val == 0; ++ test) + { + noise.generate (&x [0], len); + fft.do_fft (&s [0], &x [0]); + fft.do_ifft (&s [0], &y [0]); + fft.rescale (&y [0]); + + BigFloat max_err; + compare_vect_display (&x [0], &y [0], len, max_err); + err_avg += max_err; + } + err_avg /= NBR_ACC_TESTS; + + printf ("done.\n"); + printf ( + "Average maximum error: %.6f %% (%f dB)\n", + static_cast (err_avg * 100), + static_cast ((20 / TestAccuracy_LN10) * log (err_avg)) + ); + + return (ret_val); +} + + + +/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +// Positive transform +template +void TestAccuracy ::compute_tf (DataType s [], const DataType x [], long length) +{ + assert (s != 0); + assert (x != 0); + assert (length >= 2); + assert ((length & 1) == 0); + + const long nbr_bins = length >> 1; + + // DC and Nyquist + BigFloat dc = 0; + BigFloat ny = 0; + for (long pos = 0; pos < length; pos += 2) + { + const BigFloat even = x [pos ]; + const BigFloat odd = x [pos + 1]; + dc += even + odd; + ny += even - odd; + } + s [0 ] = static_cast (dc); + s [nbr_bins] = static_cast (ny); + + // Regular bins + for (long bin = 1; bin < nbr_bins; ++ bin) + { + BigFloat sum_r = 0; + BigFloat sum_i = 0; + + const BigFloat m = bin * static_cast (2 * PI) / length; + + for (long pos = 0; pos < length; ++pos) + { + using namespace std; + + const BigFloat phase = pos * m; + const BigFloat e_r = cos (phase); + const BigFloat e_i = sin (phase); + + sum_r += x [pos] * e_r; + sum_i += x [pos] * e_i; + } + + s [ bin] = static_cast (sum_r); + s [nbr_bins + bin] = static_cast (sum_i); + } +} + + + +// Negative transform +template +void TestAccuracy ::compute_itf (DataType x [], const DataType s [], long length) +{ + assert (s != 0); + assert (x != 0); + assert (length >= 2); + assert ((length & 1) == 0); + + const long nbr_bins = length >> 1; + + // DC and Nyquist + BigFloat dc = s [0 ]; + BigFloat ny = s [nbr_bins]; + + // Regular bins + for (long pos = 0; pos < length; ++pos) + { + BigFloat sum = dc + ny * (1 - 2 * (pos & 1)); + + const BigFloat m = pos * static_cast (-2 * PI) / length; + + for (long bin = 1; bin < nbr_bins; ++ bin) + { + using namespace std; + + const BigFloat phase = bin * m; + const BigFloat e_r = cos (phase); + const BigFloat e_i = sin (phase); + + sum += 2 * ( e_r * s [bin ] + - e_i * s [bin + nbr_bins]); + } + + x [pos] = static_cast (sum); + } +} + + + +template +int TestAccuracy ::compare_vect_display (const DataType x_ptr [], const DataType y_ptr [], long len, BigFloat &max_err_rel) +{ + assert (x_ptr != 0); + assert (y_ptr != 0); + assert (len > 0); + assert (&max_err_rel != 0); + + using namespace std; + + int ret_val = 0; + + BigFloat power = compute_power (&x_ptr [0], &y_ptr [0], len); + BigFloat power_dif; + long max_err_pos; + compare_vect (&x_ptr [0], &y_ptr [0], power_dif, max_err_pos, len); + + if (power == 0) + { + power = power_dif; + } + const BigFloat power_err_rel = power_dif / power; + + BigFloat max_err = 0; + max_err_rel = 0; + if (max_err_pos >= 0) + { + max_err = y_ptr [max_err_pos] - x_ptr [max_err_pos]; + max_err_rel = 2 * fabs (max_err) / ( fabs (y_ptr [max_err_pos]) + + fabs (x_ptr [max_err_pos])); + } + + if (power_err_rel > 0.001) + { + printf ("Power error : %f (%.6f %%)\n", + static_cast (power_err_rel), + static_cast (power_err_rel * 100) + ); + if (max_err_pos >= 0) + { + printf ( + "Maximum error: %f - %f = %f (%f)\n", + static_cast (y_ptr [max_err_pos]), + static_cast (x_ptr [max_err_pos]), + static_cast (max_err), + static_cast (max_err_pos) + ); + } + } + + return (ret_val); +} + + + +template +typename TestAccuracy ::BigFloat TestAccuracy ::compute_power (const DataType x_ptr [], long len) +{ + assert (x_ptr != 0); + assert (len > 0); + + BigFloat power = 0; + for (long pos = 0; pos < len; ++pos) + { + const BigFloat val = x_ptr [pos]; + + power += val * val; + } + + using namespace std; + + power = sqrt (power) / len; + + return (power); +} + + + +template +typename TestAccuracy ::BigFloat TestAccuracy ::compute_power (const DataType x_ptr [], const DataType y_ptr [], long len) +{ + assert (x_ptr != 0); + assert (y_ptr != 0); + assert (len > 0); + + return ((compute_power (x_ptr, len) + compute_power (y_ptr, len)) * 0.5); +} + + + +template +void TestAccuracy ::compare_vect (const DataType x_ptr [], const DataType y_ptr [], BigFloat &power, long &max_err_pos, long len) +{ + assert (x_ptr != 0); + assert (y_ptr != 0); + assert (len > 0); + assert (&power != 0); + assert (&max_err_pos != 0); + + power = 0; + BigFloat max_dif2 = 0; + max_err_pos = -1; + + for (long pos = 0; pos < len; ++pos) + { + const BigFloat x = x_ptr [pos]; + const BigFloat y = y_ptr [pos]; + const BigFloat dif = y - x; + const BigFloat dif2 = dif * dif; + + power += dif2; + if (dif2 > max_dif2) + { + max_err_pos = pos; + max_dif2 = dif2; + } + } + + using namespace std; + + power = sqrt (power) / len; +} + + + +#endif // TestAccuracy_CODEHEADER_INCLUDED + +#undef TestAccuracy_CURRENT_CODEHEADER + + + +/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ diff --git a/demos/spectrum/fftreal/TestHelperFixLen.h b/demos/spectrum/fftreal/TestHelperFixLen.h new file mode 100644 index 0000000..ecff96d --- /dev/null +++ b/demos/spectrum/fftreal/TestHelperFixLen.h @@ -0,0 +1,93 @@ +/***************************************************************************** + + TestHelperFixLen.h + Copyright (c) 2005 Laurent de Soras + +--- Legal stuff --- + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +*Tab=3***********************************************************************/ + + + +#if ! defined (TestHelperFixLen_HEADER_INCLUDED) +#define TestHelperFixLen_HEADER_INCLUDED + +#if defined (_MSC_VER) + #pragma once + #pragma warning (4 : 4250) // "Inherits via dominance." +#endif + + + +/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +#include "FFTRealFixLen.h" + + + +template +class TestHelperFixLen +{ + +/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +public: + + typedef FFTRealFixLen FftType; + + static void perform_test_accuracy (int &ret_val); + static void perform_test_speed (int &ret_val); + + + +/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +protected: + + + +/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +private: + + + +/*\\\ FORBIDDEN MEMBER FUNCTIONS \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +private: + + TestHelperFixLen (); + ~TestHelperFixLen (); + TestHelperFixLen (const TestHelperFixLen &other); + TestHelperFixLen & + operator = (const TestHelperFixLen &other); + bool operator == (const TestHelperFixLen &other); + bool operator != (const TestHelperFixLen &other); + +}; // class TestHelperFixLen + + + +#include "TestHelperFixLen.hpp" + + + +#endif // TestHelperFixLen_HEADER_INCLUDED + + + +/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ diff --git a/demos/spectrum/fftreal/TestHelperFixLen.hpp b/demos/spectrum/fftreal/TestHelperFixLen.hpp new file mode 100644 index 0000000..25048b9 --- /dev/null +++ b/demos/spectrum/fftreal/TestHelperFixLen.hpp @@ -0,0 +1,93 @@ +/***************************************************************************** + + TestHelperFixLen.hpp + Copyright (c) 2005 Laurent de Soras + +--- Legal stuff --- + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +*Tab=3***********************************************************************/ + + + +#if defined (TestHelperFixLen_CURRENT_CODEHEADER) + #error Recursive inclusion of TestHelperFixLen code header. +#endif +#define TestHelperFixLen_CURRENT_CODEHEADER + +#if ! defined (TestHelperFixLen_CODEHEADER_INCLUDED) +#define TestHelperFixLen_CODEHEADER_INCLUDED + + + +/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +#include "test_settings.h" + +#include "TestAccuracy.h" +#if defined (test_settings_SPEED_TEST_ENABLED) + #include "TestSpeed.h" +#endif + + + +/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +template +void TestHelperFixLen ::perform_test_accuracy (int &ret_val) +{ + if (ret_val == 0) + { + FftType fft; + ret_val = TestAccuracy ::perform_test_single_object (fft); + } +} + + + +template +void TestHelperFixLen ::perform_test_speed (int &ret_val) +{ +#if defined (test_settings_SPEED_TEST_ENABLED) + + if (ret_val == 0) + { + FftType fft; + ret_val = TestSpeed ::perform_test_single_object (fft); + } + +#endif +} + + + +/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +#endif // TestHelperFixLen_CODEHEADER_INCLUDED + +#undef TestHelperFixLen_CURRENT_CODEHEADER + + + +/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ diff --git a/demos/spectrum/fftreal/TestHelperNormal.h b/demos/spectrum/fftreal/TestHelperNormal.h new file mode 100644 index 0000000..a7bff5c --- /dev/null +++ b/demos/spectrum/fftreal/TestHelperNormal.h @@ -0,0 +1,94 @@ +/***************************************************************************** + + TestHelperNormal.h + Copyright (c) 2005 Laurent de Soras + +--- Legal stuff --- + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +*Tab=3***********************************************************************/ + + + +#if ! defined (TestHelperNormal_HEADER_INCLUDED) +#define TestHelperNormal_HEADER_INCLUDED + +#if defined (_MSC_VER) + #pragma once + #pragma warning (4 : 4250) // "Inherits via dominance." +#endif + + + +/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +#include "FFTReal.h" + + + +template +class TestHelperNormal +{ + +/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +public: + + typedef DT DataType; + typedef FFTReal FftType; + + static void perform_test_accuracy (int &ret_val); + static void perform_test_speed (int &ret_val); + + + +/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +protected: + + + +/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +private: + + + +/*\\\ FORBIDDEN MEMBER FUNCTIONS \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +private: + + TestHelperNormal (); + ~TestHelperNormal (); + TestHelperNormal (const TestHelperNormal &other); + TestHelperNormal & + operator = (const TestHelperNormal &other); + bool operator == (const TestHelperNormal &other); + bool operator != (const TestHelperNormal &other); + +}; // class TestHelperNormal + + + +#include "TestHelperNormal.hpp" + + + +#endif // TestHelperNormal_HEADER_INCLUDED + + + +/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ diff --git a/demos/spectrum/fftreal/TestHelperNormal.hpp b/demos/spectrum/fftreal/TestHelperNormal.hpp new file mode 100644 index 0000000..e037696 --- /dev/null +++ b/demos/spectrum/fftreal/TestHelperNormal.hpp @@ -0,0 +1,99 @@ +/***************************************************************************** + + TestHelperNormal.hpp + Copyright (c) 2005 Laurent de Soras + +--- Legal stuff --- + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +*Tab=3***********************************************************************/ + + + +#if defined (TestHelperNormal_CURRENT_CODEHEADER) + #error Recursive inclusion of TestHelperNormal code header. +#endif +#define TestHelperNormal_CURRENT_CODEHEADER + +#if ! defined (TestHelperNormal_CODEHEADER_INCLUDED) +#define TestHelperNormal_CODEHEADER_INCLUDED + + + +/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +#include "test_settings.h" + +#include "TestAccuracy.h" +#if defined (test_settings_SPEED_TEST_ENABLED) + #include "TestSpeed.h" +#endif + + + +/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +template +void TestHelperNormal

::perform_test_accuracy (int &ret_val) +{ + const int len_arr [] = { 1, 2, 3, 4, 7, 8, 10, 12 }; + const int nbr_len = sizeof (len_arr) / sizeof (len_arr [0]); + for (int k = 0; k < nbr_len && ret_val == 0; ++k) + { + const long len = 1L << (len_arr [k]); + FftType fft (len); + ret_val = TestAccuracy ::perform_test_single_object (fft); + } +} + + + +template +void TestHelperNormal
::perform_test_speed (int &ret_val) +{ +#if defined (test_settings_SPEED_TEST_ENABLED) + + const int len_arr [] = { 1, 2, 3, 4, 7, 8, 10, 12, 14, 16, 18, 20, 22 }; + const int nbr_len = sizeof (len_arr) / sizeof (len_arr [0]); + for (int k = 0; k < nbr_len && ret_val == 0; ++k) + { + const long len = 1L << (len_arr [k]); + FftType fft (len); + ret_val = TestSpeed ::perform_test_single_object (fft); + } + +#endif +} + + + +/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +#endif // TestHelperNormal_CODEHEADER_INCLUDED + +#undef TestHelperNormal_CURRENT_CODEHEADER + + + +/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ diff --git a/demos/spectrum/fftreal/TestSpeed.h b/demos/spectrum/fftreal/TestSpeed.h new file mode 100644 index 0000000..2295781 --- /dev/null +++ b/demos/spectrum/fftreal/TestSpeed.h @@ -0,0 +1,95 @@ +/***************************************************************************** + + TestSpeed.h + Copyright (c) 2005 Laurent de Soras + +--- Legal stuff --- + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foun