summaryrefslogtreecommitdiff
path: root/Audio
diff options
context:
space:
mode:
authorChristoph Berg <myon@debian.org>2025-01-09 22:12:06 +0100
committerChristoph Berg <myon@debian.org>2025-01-09 22:12:06 +0100
commit992d4b4b8d3f3a630a2cf00d593ee4ce4dfa7ce8 (patch)
treefbfdfe6bcb0a8a114be2480dac53d88c977e4869 /Audio
parent4320ce238aae1fe87fc9f379cdd816e9317885fa (diff)
New upstream version 2.7.0~rc8+repackupstream/2.7.0_rc8+repack
Diffstat (limited to 'Audio')
-rwxr-xr-xAudio/Audio.pri10
-rwxr-xr-xAudio/AudioDevice.cpp18
-rwxr-xr-xAudio/AudioDevice.hpp196
-rwxr-xr-xAudio/BWFFile.cpp2162
-rwxr-xr-xAudio/BWFFile.hpp420
-rwxr-xr-xAudio/soundin.cpp428
-rwxr-xr-xAudio/soundin.h110
-rwxr-xr-xAudio/soundout.cpp427
-rwxr-xr-xAudio/soundout.h119
-rwxr-xr-xAudio/tools/record_time_signal.cpp920
10 files changed, 2408 insertions, 2402 deletions
diff --git a/Audio/Audio.pri b/Audio/Audio.pri
index 707b60a9..e2237bbd 100755
--- a/Audio/Audio.pri
+++ b/Audio/Audio.pri
@@ -1,5 +1,5 @@
-SOURCES += Audio/AudioDevice.cpp Audio/BWFFile.cpp Audio/soundin.cpp \
- Audio/soundout.cpp
-
-HEADERS += Audio/AudioDevice.hpp Audio/BWFFile.hpp Audio/soundin.h \
- Audio/soundout.h
+SOURCES += Audio/AudioDevice.cpp Audio/BWFFile.cpp Audio/soundin.cpp \
+ Audio/soundout.cpp
+
+HEADERS += Audio/AudioDevice.hpp Audio/BWFFile.hpp Audio/soundin.h \
+ Audio/soundout.h
diff --git a/Audio/AudioDevice.cpp b/Audio/AudioDevice.cpp
index c663f423..16fec314 100755
--- a/Audio/AudioDevice.cpp
+++ b/Audio/AudioDevice.cpp
@@ -1,9 +1,9 @@
-#include "AudioDevice.hpp"
-
-bool AudioDevice::initialize (OpenMode mode, Channel channel)
-{
- m_channel = channel;
-
- // open and ensure we are unbuffered if possible
- return QIODevice::open (mode | QIODevice::Unbuffered);
-}
+#include "AudioDevice.hpp"
+
+bool AudioDevice::initialize (OpenMode mode, Channel channel)
+{
+ m_channel = channel;
+
+ // open and ensure we are unbuffered if possible
+ return QIODevice::open (mode | QIODevice::Unbuffered);
+}
diff --git a/Audio/AudioDevice.hpp b/Audio/AudioDevice.hpp
index df3e3f4c..2d47af89 100755
--- a/Audio/AudioDevice.hpp
+++ b/Audio/AudioDevice.hpp
@@ -1,98 +1,98 @@
-#ifndef AUDIODEVICE_HPP__
-#define AUDIODEVICE_HPP__
-
-#include <QIODevice>
-
-class QDataStream;
-
-//
-// abstract base class for audio devices
-//
-class AudioDevice : public QIODevice
-{
-public:
- enum Channel {Mono, Left, Right, Both}; // these are mapped to combobox index so don't change
-
- static char const * toString (Channel c)
- {
- return Mono == c ? "Mono" : Left == c ? "Left" : Right == c ? "Right" : "Both";
- }
-
- static Channel fromString (QString const& str)
- {
- QString s (str.toCaseFolded ().trimmed ().toLatin1 ());
- return "both" == s ? Both : "right" == s ? Right : "left" == s ? Left : Mono;
- }
-
- bool initialize (OpenMode mode, Channel channel);
-
- bool isSequential () const override {return true;}
-
- size_t bytesPerFrame () const {return sizeof (qint16) * (Mono == m_channel ? 1 : 2);}
-
- Channel channel () const {return m_channel;}
-
-protected:
- AudioDevice (QObject * parent = nullptr)
- : QIODevice {parent}
- {
- }
-
- void store (char const * source, size_t numFrames, qint16 * dest)
- {
- qint16 const * begin (reinterpret_cast<qint16 const *> (source));
- for ( qint16 const * i = begin; i != begin + numFrames * (bytesPerFrame () / sizeof (qint16)); i += bytesPerFrame () / sizeof (qint16))
- {
- switch (m_channel)
- {
- case Mono:
- *dest++ = *i;
- break;
-
- case Right:
- *dest++ = *(i + 1);
- break;
-
- case Both: // should be able to happen but if it
- // does we'll take left
- Q_ASSERT (Both == m_channel);
- case Left:
- *dest++ = *i;
- break;
- }
- }
- }
-
- qint16 * load (qint16 const sample, qint16 * dest)
- {
- switch (m_channel)
- {
- case Mono:
- *dest++ = sample;
- break;
-
- case Left:
- *dest++ = sample;
- *dest++ = 0;
- break;
-
- case Right:
- *dest++ = 0;
- *dest++ = sample;
- break;
-
- case Both:
- *dest++ = sample;
- *dest++ = sample;
- break;
- }
- return dest;
- }
-
-private:
- Channel m_channel;
-};
-
-Q_DECLARE_METATYPE (AudioDevice::Channel);
-
-#endif
+#ifndef AUDIODEVICE_HPP__
+#define AUDIODEVICE_HPP__
+
+#include <QIODevice>
+
+class QDataStream;
+
+//
+// abstract base class for audio devices
+//
+class AudioDevice : public QIODevice
+{
+public:
+ enum Channel {Mono, Left, Right, Both}; // these are mapped to combobox index so don't change
+
+ static char const * toString (Channel c)
+ {
+ return Mono == c ? "Mono" : Left == c ? "Left" : Right == c ? "Right" : "Both";
+ }
+
+ static Channel fromString (QString const& str)
+ {
+ QString s (str.toCaseFolded ().trimmed ().toLatin1 ());
+ return "both" == s ? Both : "right" == s ? Right : "left" == s ? Left : Mono;
+ }
+
+ bool initialize (OpenMode mode, Channel channel);
+
+ bool isSequential () const override {return true;}
+
+ size_t bytesPerFrame () const {return sizeof (qint16) * (Mono == m_channel ? 1 : 2);}
+
+ Channel channel () const {return m_channel;}
+
+protected:
+ AudioDevice (QObject * parent = nullptr)
+ : QIODevice {parent}
+ {
+ }
+
+ void store (char const * source, size_t numFrames, qint16 * dest)
+ {
+ qint16 const * begin (reinterpret_cast<qint16 const *> (source));
+ for ( qint16 const * i = begin; i != begin + numFrames * (bytesPerFrame () / sizeof (qint16)); i += bytesPerFrame () / sizeof (qint16))
+ {
+ switch (m_channel)
+ {
+ case Mono:
+ *dest++ = *i;
+ break;
+
+ case Right:
+ *dest++ = *(i + 1);
+ break;
+
+ case Both: // should be able to happen but if it
+ // does we'll take left
+ Q_ASSERT (Both == m_channel);
+ case Left:
+ *dest++ = *i;
+ break;
+ }
+ }
+ }
+
+ qint16 * load (qint16 const sample, qint16 * dest)
+ {
+ switch (m_channel)
+ {
+ case Mono:
+ *dest++ = sample;
+ break;
+
+ case Left:
+ *dest++ = sample;
+ *dest++ = 0;
+ break;
+
+ case Right:
+ *dest++ = 0;
+ *dest++ = sample;
+ break;
+
+ case Both:
+ *dest++ = sample;
+ *dest++ = sample;
+ break;
+ }
+ return dest;
+ }
+
+private:
+ Channel m_channel;
+};
+
+Q_DECLARE_METATYPE (AudioDevice::Channel);
+
+#endif
diff --git a/Audio/BWFFile.cpp b/Audio/BWFFile.cpp
index c9221758..78d6a79f 100755
--- a/Audio/BWFFile.cpp
+++ b/Audio/BWFFile.cpp
@@ -1,1081 +1,1081 @@
-#include "BWFFile.hpp"
-
-#include <cstring>
-#include <numeric>
-#include <algorithm>
-
-#include <qendian.h>
-#include <QAudioFormat>
-#include <QDateTime>
-#include <QDate>
-#include <QTime>
-#include <QString>
-#include <QUuid>
-
-#include "pimpl_impl.hpp"
-
-#include "moc_BWFFile.cpp"
-
-namespace
-{
- // chunk descriptor
- struct Desc
- {
- Desc ()
- : size_ {0}
- {
- }
-
- explicit Desc (char const * id, quint32 size = 0)
- : size_ {size}
- {
- set (id);
- }
-
- void set (char const * id = nullptr)
- {
- if (id)
- {
- auto end = reinterpret_cast<char const *> (::memchr (id, '\0', 4u));
- auto len = end ? end - id : 4u;
- ::memcpy (id_.data (), id, len);
- if (len < 4u)
- {
- memset (id_.data () + len, ' ', 4u - len);
- }
- }
- else
- {
- ::memcpy (id_.data (), "JUNK", 4u);
- }
- }
-
- void set (char const * id, quint32 size)
- {
- set (id);
- size_ = size;
- }
-
- char * operator & () {return reinterpret_cast<char *> (this);}
- char const * operator & () const {return reinterpret_cast<char const *> (this);}
-
- std::array<char, 4> id_;
- quint32 size_;
- };
-
- // "fmt " chunk contents
- struct FormatChunk
- {
- quint16 audio_format;
- quint16 num_channels;
- quint32 sample_rate;
- quint32 byte_rate;
- quint16 block_align;
- quint16 bits_per_sample;
- };
-
- // "bext" chunk contents
- struct BroadcastAudioExtension
- {
- using Version = BWFFile::BextVersion;
- using UMID = BWFFile::UMID;
-
- BroadcastAudioExtension (Version version = Version::v_0)
- : version_ {static_cast<quint16> (version)}
- , umid_ {{}}
- {
- // set some sensible defaults for the "bext" fields
- auto now = QDateTime::currentDateTimeUtc ();
- ::memcpy (origination_date_,
- now.date ().toString ("yyyy-MM-dd").toLocal8Bit ().constData (),
- sizeof origination_date_);
- ::memcpy (origination_time_,
- now.time ().toString ("hh-mm-ss").toLocal8Bit ().constData (),
- sizeof origination_time_);
- auto uuid = QUuid::createUuid ().toRfc4122 ();
- std::copy (uuid.cbegin (), uuid.cend (), umid_.data () + 16);
- }
-
- char description_[256];
- char originator_[32];
- char originator_reference_[32];
- char origination_date_[10];
- char origination_time_[10];
- quint32 time_reference_low_;
- quint32 time_reference_high_;
- quint16 version_;
- UMID umid_; // V1 zero for V0
- quint16 loudness_value_; // V2
- quint16 loudness_range_; // V2
- quint16 max_true_peak_level_; // V2
- quint16 max_momentary_loudness_; // V2
- quint16 max_short_term_loudness_; // V2
- quint8 reserved_[180];
- char coding_history_[];
- };
-}
-
-class BWFFile::impl final
-{
-public:
- using FileError = QFile::FileError;
-
- impl (QAudioFormat const& format)
- : header_dirty_ {true}
- , format_ {format}
- , header_length_ {-1}
- , data_size_ {-1}
- , error_ {FileError::NoError}
- {
- }
-
- impl (QAudioFormat const& format, QString const& name)
- : header_dirty_ {true}
- , format_ {format}
- , file_ {name}
- , header_length_ {-1}
- , data_size_ {-1}
- , error_ {FileError::NoError}
- {
- }
-
- impl (QAudioFormat const& format, QString const& name, InfoDictionary const& dictionary)
- : header_dirty_ {true}
- , format_ {format}
- , file_ {name}
- , info_dictionary_ {dictionary}
- , header_length_ {-1}
- , data_size_ {-1}
- , error_ {FileError::NoError}
- {
- }
-
- ~impl ()
- {
- if (file_.isOpen ()) file_.close ();
- }
-
- bool initialize (BWFFile * self, OpenMode mode);
- bool read_header ();
- bool write_header (QAudioFormat);
- bool update_header ();
-
- BroadcastAudioExtension const * bext () const
- {
- return bext_.isEmpty () ? nullptr : reinterpret_cast<BroadcastAudioExtension const *> (bext_.constData ());
- }
-
- BroadcastAudioExtension * bext ()
- {
- if (bext_.isEmpty ()) // create a "bext" chunk in place
- {
- bext_.data ();
- bext_.fill ('\0', sizeof (BroadcastAudioExtension));
- new (bext_.data ()) BroadcastAudioExtension {};
- }
- return reinterpret_cast<BroadcastAudioExtension *> (bext_.data ());
- }
-
- bool header_dirty_;
- QAudioFormat format_;
- QFile file_;
- QByteArray bext_;
- InfoDictionary info_dictionary_;
- qint64 header_length_;
- qint64 data_size_;
- FileError error_;
-};
-
-bool BWFFile::impl::initialize (BWFFile * self, OpenMode mode)
-{
- bool result {false};
- if (mode & Append)
- {
- result = file_.seek (file_.size ());
- if (result) result = self->seek (file_.size () - header_length_);
- }
- else
- {
- result = self->seek (0);
- }
- return result;
-}
-
-bool BWFFile::impl::read_header ()
-{
- header_length_ = -1;
- data_size_ = -1;
- if (!(file_.openMode () & ReadOnly)) return false;
- if (!file_.seek (0)) return false;
- Desc outer_desc;
- quint32 outer_offset = file_.pos ();
- quint32 outer_size {0};
- bool be {false};
- while (outer_offset < sizeof outer_desc + outer_desc.size_ - 1) // allow for uncounted pad
- {
- if (file_.read (&outer_desc, sizeof outer_desc) != sizeof outer_desc) return false;
- be = !memcmp (&outer_desc.id_, "RIFX", 4);
- outer_size = be ? qFromBigEndian<quint32> (outer_desc.size_) : qFromLittleEndian<quint32> (outer_desc.size_);
- if (!memcmp (&outer_desc.id_, "RIFF", 4) || be)
- {
- // RIFF or RIFX
- char riff_item[4];
- if (file_.read (riff_item, sizeof riff_item) != sizeof riff_item) return false;
- if (!memcmp (riff_item, "WAVE", 4))
- {
- // WAVE
- Desc wave_desc;
- quint32 wave_offset = file_.pos ();
- quint32 wave_size {0};
- while (wave_offset < outer_offset + sizeof outer_desc + outer_size - 1)
- {
- if (file_.read (&wave_desc, sizeof wave_desc) != sizeof wave_desc) return false;
- wave_size = be ? qFromBigEndian<quint32> (wave_desc.size_) : qFromLittleEndian<quint32> (wave_desc.size_);
- if (!memcmp (&wave_desc.id_, "bext", 4))
- {
- bext_ = file_.read (wave_size);
- }
- if (!memcmp (&wave_desc.id_, "fmt ", 4))
- {
- FormatChunk fmt;
- if (file_.read (reinterpret_cast<char *> (&fmt), sizeof fmt) != sizeof fmt) return false;
- auto audio_format = be ? qFromBigEndian<quint16> (fmt.audio_format) : qFromLittleEndian<quint16> (fmt.audio_format);
- if (audio_format != 0 && audio_format != 1) return false; // not PCM nor undefined
- format_.setByteOrder (be ? QAudioFormat::BigEndian : QAudioFormat::LittleEndian);
- format_.setChannelCount (be ? qFromBigEndian<quint16> (fmt.num_channels) : qFromLittleEndian<quint16> (fmt.num_channels));
- format_.setCodec ("audio/pcm");
- format_.setSampleRate (be ? qFromBigEndian<quint32> (fmt.sample_rate) : qFromLittleEndian<quint32> (fmt.sample_rate));
- int bits_per_sample {be ? qFromBigEndian<quint16> (fmt.bits_per_sample) : qFromLittleEndian<quint16> (fmt.bits_per_sample)};
- format_.setSampleSize (bits_per_sample);
- format_.setSampleType (8 == bits_per_sample ? QAudioFormat::UnSignedInt : QAudioFormat::SignedInt);
- }
- else if (!memcmp (&wave_desc.id_, "data", 4))
- {
- data_size_ = wave_size;
- header_length_ = file_.pos ();
- }
- else if (!memcmp (&wave_desc.id_, "LIST", 4))
- {
- char list_type[4];
- if (file_.read (list_type, sizeof list_type) != sizeof list_type) return false;
- if (!memcmp (list_type, "INFO", 4))
- {
- Desc info_desc;
- quint32 info_offset = file_.pos ();
- quint32 info_size {0};
- while (info_offset < wave_offset + sizeof wave_desc + wave_size - 1)
- {
- if (file_.read (&info_desc, sizeof info_desc) != sizeof info_desc) return false;
- info_size = be ? qFromBigEndian<quint32> (info_desc.size_) : qFromLittleEndian<quint32> (info_desc.size_);
- info_dictionary_[info_desc.id_] = file_.read (info_size);
- if (!file_.seek (info_offset + sizeof info_desc + (info_size + 1) / 2 * 2)) return false;;
- info_offset = file_.pos ();
- }
- }
- }
- if (!file_.seek (wave_offset + sizeof wave_desc + (wave_size + 1) / 2 * 2)) return false;
- wave_offset = file_.pos ();
- }
- }
- }
- if (!file_.seek (outer_offset + sizeof outer_desc + (outer_size + 1) / 2 * 2)) return false;
- outer_offset = file_.pos ();
- }
- return data_size_ >= 0 && file_.seek (header_length_);
-}
-
-bool BWFFile::impl::write_header (QAudioFormat format)
-{
- data_size_ = -1;
- if ("audio/pcm" != format.codec ()) return false;
- if (!(file_.openMode () & WriteOnly)) return false;
- if (!file_.seek (0)) return false;
- header_length_ = 0;
- bool be {QAudioFormat::BigEndian == format_.byteOrder ()};
- Desc desc {be ? "RIFX" : "RIFF"};
- if (file_.write (&desc, sizeof desc) != sizeof desc) return false;
- header_dirty_ = true;
- if (file_.write ("WAVE", 4) != 4) return false;
-
- FormatChunk fmt;
- if (be)
- {
- fmt.audio_format = qToBigEndian<quint16> (1); // PCM
- fmt.num_channels = qToBigEndian<quint16> (format.channelCount ());
- fmt.sample_rate = qToBigEndian<quint32> (format.sampleRate ());
- fmt.byte_rate = qToBigEndian<quint32> (format.bytesForDuration (1000000));
- fmt.block_align = qToBigEndian<quint16> (format.bytesPerFrame ());
- fmt.bits_per_sample = qToBigEndian<quint16> (format.sampleSize ());
- desc.set ("fmt", qToBigEndian<quint32> (sizeof fmt));
- }
- else
- {
- fmt.audio_format = qToLittleEndian<quint16> (1); // PCM
- fmt.num_channels = qToLittleEndian<quint16> (format.channelCount ());
- fmt.sample_rate = qToLittleEndian<quint32> (format.sampleRate ());
- fmt.byte_rate = qToLittleEndian<quint32> (format.bytesForDuration (1000000));
- fmt.block_align = qToLittleEndian<quint16> (format.bytesPerFrame ());
- fmt.bits_per_sample = qToLittleEndian<quint16> (format.sampleSize ());
- desc.set ("fmt", qToLittleEndian<quint32> (sizeof fmt));
- }
- if (file_.write (&desc, sizeof desc) != sizeof desc) return false;
- if (file_.write (reinterpret_cast<char const *> (&fmt), sizeof fmt) != sizeof fmt) return false;
-
- desc.set ("data");
- if (file_.write (&desc, sizeof desc) != sizeof desc) return false;
- header_length_ = file_.pos ();
- return true;
-}
-
-bool BWFFile::impl::update_header ()
-{
- if (header_length_ < 0 || !(file_.openMode () & WriteOnly)) return false;
- auto position = file_.pos ();
- bool be {QAudioFormat::BigEndian == format_.byteOrder ()};
- Desc desc;
- auto size = data_size_ < 0 ? file_.size () - header_length_ : data_size_;
- if (!file_.seek (header_length_ - sizeof desc)) return false;
- desc.set ("data", be ? qToBigEndian<quint32> (size) : qToLittleEndian<quint32> (size));
- if (file_.write (&desc, sizeof desc) != sizeof desc) return false;
-
- if (!bext_.isEmpty ())
- {
- if (!file_.seek (file_.size ())) return false;
- auto size = bext_.size ();
- desc.set ("bext", be ? qToBigEndian<quint32> (size) : qToLittleEndian<quint32> (size));
- if ((file_.size () % 2) && file_.write ("\0", 1) != 1) return false;
- if (file_.write (&desc, sizeof desc) != sizeof desc) return false;
- auto * data = reinterpret_cast<BroadcastAudioExtension *> (bext_.data ());
- if (be)
- {
- data->time_reference_low_ = qToBigEndian<quint32> (data->time_reference_low_);
- data->time_reference_high_ = qToBigEndian<quint32> (data->time_reference_high_);
- switch (static_cast<BextVersion> (data->version_))
- {
- case BextVersion::v_0:
- data->version_ = qToBigEndian<quint32> (data->version_);
- // fall through
- default:
- data->loudness_value_ = qToBigEndian<quint16> (data->loudness_value_);
- data->loudness_range_ = qToBigEndian<quint16> (data->loudness_range_);
- data->max_true_peak_level_ = qToBigEndian<quint16> (data->max_true_peak_level_);
- data->max_momentary_loudness_ = qToBigEndian<quint16> (data->max_momentary_loudness_);
- data->max_short_term_loudness_ = qToBigEndian<quint16> (data->max_short_term_loudness_);
- }
- }
- else
- {
- data->time_reference_low_ = qToLittleEndian<quint32> (data->time_reference_low_);
- data->time_reference_high_ = qToLittleEndian<quint32> (data->time_reference_high_);
- switch (static_cast<BextVersion> (data->version_))
- {
- case BextVersion::v_0:
- data->version_ = qToLittleEndian<quint32> (data->version_);
- // fall through
- default:
- data->loudness_value_ = qToLittleEndian<quint16> (data->loudness_value_);
- data->loudness_range_ = qToLittleEndian<quint16> (data->loudness_range_);
- data->max_true_peak_level_ = qToLittleEndian<quint16> (data->max_true_peak_level_);
- data->max_momentary_loudness_ = qToLittleEndian<quint16> (data->max_momentary_loudness_);
- data->max_short_term_loudness_ = qToLittleEndian<quint16> (data->max_short_term_loudness_);
- }
- }
- if (file_.write (bext_) != size) return false;
- }
-
- if (info_dictionary_.size ())
- {
- if (!file_.seek (file_.size ())) return false;
- desc.set ("LIST");
- if ((file_.size () % 2) && file_.write ("\0", 1) != 1) return false;
- if (file_.write (&desc, sizeof desc) != sizeof desc) return false;
- auto list_start = file_.pos ();
- if (file_.write ("INFO", 4) != 4) return false;
- for (auto iter = info_dictionary_.constBegin ()
- ; iter != info_dictionary_.constEnd (); ++iter)
- {
- auto value = iter.value ();
- auto len = value.size () + 1; // include terminating null char
- desc.set (iter.key ().data (), be ? qToBigEndian<quint32> (len) : qToLittleEndian<quint32> (len));
- if ((file_.size () % 2) && file_.write ("\0", 1) != 1) return false;
- if (file_.write (&desc, sizeof desc) != sizeof desc) return false;
- if (file_.write (value.constData (), len) != len) return false;
- }
- auto size = file_.pos () - list_start;
- if (!file_.seek (list_start - sizeof desc)) return false;
- desc.set ("LIST", be ? qToBigEndian<quint32> (size) : qToLittleEndian<quint32> (size));
- if (file_.write (&desc, sizeof desc) != sizeof desc) return false;
- }
-
- size = file_.size () - sizeof desc;
- if ((file_.size () % 2) && file_.seek (file_.size ()) && file_.write ("\0", 1) != 1) return false;
- if (!file_.seek (0)) return false;
- desc.set (be ? "RIFX" : "RIFF", be ? qToBigEndian<quint32> (size) : qToLittleEndian<quint32> (size));
- if (file_.write (&desc, sizeof desc) != sizeof desc) return false;
- return file_.seek (position);
-}
-
-//
-// BWFFile implementation
-//
-BWFFile::BWFFile (QAudioFormat const& format, QObject * parent)
- : QIODevice {parent}
- , m_ {format}
-{
-}
-
-BWFFile::BWFFile (QAudioFormat const& format, QString const& name, QObject * parent)
- : QIODevice {parent}
- , m_ {format, name}
-{
-}
-
-BWFFile::BWFFile (QAudioFormat const& format, QString const& name
- , InfoDictionary const& dictionary, QObject * parent)
- : QIODevice {parent}
- , m_ {format, name, dictionary}
-{
-}
-
-BWFFile::~BWFFile ()
-{
- if (isOpen ()) close ();
-}
-
-bool BWFFile::open (OpenMode mode)
-{
- bool success {false};
- if (!(mode & WriteOnly))
- {
- if (!(success = m_->file_.open (mode & ~Text)))
- {
- setErrorString (m_->file_.errorString ());
- }
- else
- {
- if (!(success = m_->read_header ()))
- {
- if (FileError::NoError == m_->file_.error ())
- {
- setErrorString ("Unable to read file header");
- m_->error_ = FileError::ReadError;
- }
- else
- {
- setErrorString (m_->file_.errorString ());
- }
- }
- }
- }
- else
- {
- if (!(success = m_->file_.open (mode & ~Text)))
- {
- setErrorString (m_->file_.errorString ());
- }
- else
- {
- if (!(success = (m_->read_header () || m_->write_header (m_->format_))))
- {
- if (FileError::NoError == m_->file_.error ())
- {
- setErrorString ("Unable to update file header");
- m_->error_ = FileError::WriteError;
- }
- else
- {
- setErrorString (m_->file_.errorString ());
- }
- }
- else if (!(success = m_->file_.resize (m_->header_length_)))
- {
- setErrorString (m_->file_.errorString ());
- }
- }
- }
- success && (success = QIODevice::open (mode | Unbuffered));
- if (success && !(success = m_->initialize (this, mode)))
- {
- if (FileError::NoError == m_->file_.error ())
- {
- setErrorString ("Unable to initialize file header");
- m_->error_ = FileError::WriteError;
- }
- else
- {
- setErrorString (m_->file_.errorString ());
- }
- }
- if (!success) close ();
- return success;
-}
-
-bool BWFFile::open(FILE * fh, OpenMode mode, FileHandleFlags flags)
-{
- bool success {false};
- if (!(mode & ReadOnly))
- {
- setErrorString ("Read or read/write access must be specified");
- m_->error_ = FileError::OpenError;
- return success;
- }
- if (!(mode & WriteOnly))
- {
- if (!(success = m_->file_.open (fh, mode & ~Text, flags)))
- {
- setErrorString (m_->file_.errorString ());
- }
- else
- {
- if (!(success = m_->read_header ()))
- {
- if (FileError::NoError == m_->file_.error ())
- {
- setErrorString ("Unable to read file header");
- m_->error_ = FileError::ReadError;
- }
- else
- {
- setErrorString (m_->file_.errorString ());
- }
- }
- }
- }
- else
- {
- if (!(success = m_->file_.open (fh, mode & ~Text, flags)))
- {
- setErrorString (m_->file_.errorString ());
- }
- else
- {
- if (!(success = (m_->read_header () || m_->write_header (m_->format_))))
- {
- if (FileError::NoError == m_->file_.error ())
- {
- setErrorString ("Unable to update file header");
- m_->error_ = FileError::WriteError;
- }
- else
- {
- setErrorString (m_->file_.errorString ());
- }
- }
- else if (!(success = m_->file_.resize (m_->header_length_)))
- {
- setErrorString (m_->file_.errorString ());
- }
- }
- }
- success && (success = QIODevice::open (mode | Unbuffered));
- if (success && !(success = m_->initialize (this, mode)))
- {
- if (FileError::NoError == m_->file_.error ())
- {
- setErrorString ("Unable to initialize file header");
- m_->error_ = FileError::WriteError;
- }
- else
- {
- setErrorString (m_->file_.errorString ());
- }
- }
- if (!success) close ();
- return success;
-}
-
-bool BWFFile::open (int fd, OpenMode mode, FileHandleFlags flags)
-{
- bool success {false};
- if (!(mode & ReadOnly))
- {
- setErrorString ("Read or read/write access must be specified");
- m_->error_ = FileError::OpenError;
- return success;
- }
- if (!(mode & WriteOnly))
- {
- if (!(success = m_->file_.open (fd, mode & ~Text, flags)))
- {
- setErrorString (m_->file_.errorString ());
- }
- else
- {
- if (!(success = m_->read_header ()))
- {
- if (FileError::NoError == m_->file_.error ())
- {
- setErrorString ("Unable to read file header");
- m_->error_ = FileError::ReadError;
- }
- else
- {
- setErrorString (m_->file_.errorString ());
- }
- }
- }
- }
- else
- {
- if (!(success = m_->file_.open (fd, mode & ~Text, flags)))
- {
- setErrorString (m_->file_.errorString ());
- }
- else
- {
- if (!(success = (m_->read_header () || m_->write_header (m_->format_))))
- {
- if (FileError::NoError == m_->file_.error ())
- {
- setErrorString ("Unable to update file header");
- m_->error_ = FileError::WriteError;
- }
- else
- {
- setErrorString (m_->file_.errorString ());
- }
- }
- else if (!(success = m_->file_.resize (m_->header_length_)))
- {
- setErrorString (m_->file_.errorString ());
- }
- }
- }
- success && (success = QIODevice::open (mode | Unbuffered));
- if (success && !(success = m_->initialize (this, mode)))
- {
- if (FileError::NoError == m_->file_.error ())
- {
- setErrorString ("Unable to initialize file header");
- m_->error_ = FileError::WriteError;
- }
- else
- {
- setErrorString (m_->file_.errorString ());
- }
- }
- if (!success) close ();
- return success;
-}
-
-QAudioFormat const& BWFFile::format () const {return m_->format_;}
-
-auto BWFFile::list_info () -> InfoDictionary&
-{
- m_->header_dirty_ = true;
- return m_->info_dictionary_;
-}
-
-
-// Broadcast Audio Extension fields
-auto BWFFile::bext_version () const -> BextVersion
-{
- return static_cast<BextVersion> (m_->bext () ? 0 : m_->bext ()->version_);
-}
-
-void BWFFile::bext_version (BextVersion version)
-{
- m_->header_dirty_ = true;
- m_->bext ()->version_ = static_cast<quint16> (version);
-}
-
-QByteArray BWFFile::bext_description () const
-{
- if (!m_->bext ()) return {};
- return QByteArray::fromRawData (m_->bext ()->description_, strlen (m_->bext ()->description_));
-}
-
-void BWFFile::bext_description (QByteArray const& description)
-{
- m_->header_dirty_ = true;
- ::memcpy (m_->bext ()->description_, description.constData (), sizeof BroadcastAudioExtension::description_);
-}
-
-QByteArray BWFFile::bext_originator () const
-{
- if (!m_->bext ()) return {};
- return QByteArray::fromRawData (m_->bext ()->originator_, strlen (m_->bext ()->originator_));
-}
-
-void BWFFile::bext_originator (QByteArray const& originator)
-{
- m_->header_dirty_ = true;
- ::memcpy (m_->bext ()->originator_, originator.constData (), sizeof BroadcastAudioExtension::originator_);
-}
-
-QByteArray BWFFile::bext_originator_reference () const
-{
- if (!m_->bext ()) return {};
- return QByteArray::fromRawData (m_->bext ()->originator_reference_, strlen (m_->bext ()->originator_reference_));
-}
-
-void BWFFile::bext_originator_reference (QByteArray const& reference)
-{
- m_->header_dirty_ = true;
- ::memcpy (m_->bext ()->originator_reference_, reference.constData (), sizeof BroadcastAudioExtension::originator_reference_);
-}
-
-QDateTime BWFFile::bext_origination_date_time () const
-{
- if (!m_->bext ()) return {};
- return {QDate::fromString (m_->bext ()->origination_date_, "yyyy-MM-dd"),
- QTime::fromString (m_->bext ()->origination_time_, "hh-mm-ss"), Qt::UTC};
-}
-
-void BWFFile::bext_origination_date_time (QDateTime const& dt)
-{
- m_->header_dirty_ = true;
- ::memcpy (m_->bext ()->origination_date_,
- dt.date ().toString ("yyyy-MM-dd").toLocal8Bit ().constData (),
- sizeof BroadcastAudioExtension::origination_date_);
- ::memcpy (m_->bext ()->origination_time_,
- dt.time ().toString ("hh-mm-ss").toLocal8Bit ().constData (),
- sizeof BroadcastAudioExtension::origination_time_);
-}
-
-quint64 BWFFile::bext_time_reference () const
-{
- if (!m_->bext ()) return 0;
- return (quint64 (m_->bext ()->time_reference_high_) << 32) + m_->bext ()->time_reference_low_;
-}
-
-void BWFFile::bext_time_reference (quint64 time_code)
-{
- m_->header_dirty_ = true;
- m_->bext ()->time_reference_low_ = time_code & 0x00000000ffffffffll;
- m_->bext ()->time_reference_high_ = time_code >> 32;
-}
-
-auto BWFFile::bext_umid () const -> UMID
-{
- UMID umid {{'\0'}};
- if (m_->bext ())
- {
- umid = m_->bext ()->umid_;
- }
- return umid;
-}
-
-void BWFFile::bext_umid (UMID const& umid)
-{
- m_->header_dirty_ = true;
- m_->bext ()->umid_ = umid;
-}
-
-quint16 BWFFile::bext_loudness_value () const
-{
- if (!m_->bext ()) return 0;
- return m_->bext ()->loudness_value_;
-}
-
-void BWFFile::bext_loudness_value (quint16 value)
-{
- m_->header_dirty_ = true;
- m_->bext ()->loudness_value_ = value;
-}
-
-quint16 BWFFile::bext_loudness_range () const
-{
- if (!m_->bext ()) return 0;
- return m_->bext ()->loudness_range_;
-}
-
-void BWFFile::bext_loudness_range (quint16 range)
-{
- m_->header_dirty_ = true;
- m_->bext ()->loudness_range_ = range;
-}
-
-quint16 BWFFile::bext_max_true_peak_level () const
-{
- if (!m_->bext ()) return 0;
- return m_->bext ()->max_true_peak_level_;
-}
-
-void BWFFile::bext_max_true_peak_level (quint16 level)
-{
- m_->header_dirty_ = true;
- m_->bext ()->max_true_peak_level_ = level;
-}
-
-quint16 BWFFile::bext_max_momentary_loudness () const
-{
- if (!m_->bext ()) return 0;
- return m_->bext ()->max_momentary_loudness_;
-}
-
-void BWFFile::bext_max_momentary_loudness (quint16 loudness)
-{
- m_->header_dirty_ = true;
- m_->bext ()->max_momentary_loudness_ = loudness;
-}
-
-quint16 BWFFile::bext_max_short_term_loudness () const
-{
- if (!m_->bext ()) return 0;
- return m_->bext ()->max_short_term_loudness_;
-}
-
-void BWFFile::bext_max_short_term_loudness (quint16 loudness)
-{
- m_->header_dirty_ = true;
- m_->bext ()->max_short_term_loudness_ = loudness;
-}
-
-QByteArray BWFFile::bext_coding_history () const
-{
- if (size_t (m_->bext_.size ()) <= sizeof (BroadcastAudioExtension)) return {};
- return QByteArray::fromRawData (m_->bext ()->coding_history_,
- m_->bext_.size () - sizeof (BroadcastAudioExtension));
-}
-
-void BWFFile::bext_coding_history (QByteArray const& text)
-{
- m_->header_dirty_ = true;
- m_->bext (); // ensure we have a correctly
- // initialized m_->bext_
- auto end = static_cast<char const *> (::memchr (text.constData (), '\0', size_t (text.size ())));
- auto length = end ? end - text.constData () : size_t (text.size ());
- m_->bext_.resize (sizeof (BroadcastAudioExtension) + length);
- std::strncpy (m_->bext ()->coding_history_, text.constData (), length);
-}
-
-
-bool BWFFile::reset ()
-{
- bool success {true};
- if (m_->file_.isOpen ())
- {
- m_->info_dictionary_.clear ();
- m_->bext_.clear ();
- auto size = m_->data_size_ < 0 ? m_->file_.size () - m_->header_length_ : m_->data_size_;
- m_->data_size_ = size;
- if (m_->header_length_ > qint64 (3 * sizeof (Desc) + 4 + sizeof (FormatChunk)))
- {
- // we need to move the data down
- auto old_pos = m_->header_length_;
- if (!(success = m_->write_header (m_->format_)))
- {
- auto new_pos = m_->header_length_;
- QByteArray buffer;
- while (size)
- {
- success = m_->file_.seek (old_pos);
- if (!success)
- {
- setErrorString (m_->file_.errorString ());
- }
- else
- {
- buffer = m_->file_.read (std::min (size, qint64 (32768)));
- success = m_->file_.seek (new_pos);
- if (!success)
- {
- setErrorString (m_->file_.errorString ());
- }
- else
- {
- qint64 bytes = m_->file_.write (buffer);
- if (bytes < 0)
- {
- setErrorString (m_->file_.errorString ());
- success = false;
- }
- else
- {
- new_pos += buffer.size ();
- old_pos += buffer.size ();
- size -= buffer.size ();
- }
- }
- }
- }
- }
- else
- {
- if (FileError::NoError == m_->file_.error ())
- {
- setErrorString ("Unable to update file header");
- m_->error_ = FileError::WriteError;
- }
- else
- {
- setErrorString (m_->file_.errorString ());
- }
- return success;
- }
- }
- if (success)
- {
- success = m_->file_.resize (m_->header_length_ + m_->data_size_);
- if (!success)
- {
- setErrorString (m_->file_.errorString ());
- }
- m_->header_dirty_ = true;
- }
- }
- else
- {
- setErrorString ("File not open");
- m_->error_ = FileError::WriteError;
- success = false;
- }
- return success && QIODevice::reset ();
-}
-
-qint64 BWFFile::size () const
-{
- return m_->data_size_ < 0 ? m_->file_.size () - m_->header_length_ : m_->data_size_;
-}
-
-bool BWFFile::isSequential () const
-{
- return m_->file_.isSequential ();
-}
-
-void BWFFile::close ()
-{
- if (isOpen ()) QIODevice::close ();
- if (m_->header_dirty_ || m_->data_size_ < 0)
- {
- m_->update_header ();
- }
- if (m_->file_.isOpen ())
- {
- m_->file_.close ();
- }
-}
-
-bool BWFFile::seek (qint64 pos)
-{
- if (pos < 0)
- {
- setErrorString ("Attempt to seek before beginning of data");
- m_->error_ = FileError::PositionError;
- return false;
- }
- bool success = QIODevice::seek (pos);
- if (success)
- {
- success = m_->file_.seek (pos + m_->header_length_);
- if (!success) setErrorString (m_->file_.errorString ());
- }
- return success;
-}
-
-qint64 BWFFile::readData (char * data, qint64 max_size)
-{
- return m_->file_.read (data, max_size);
-}
-
-qint64 BWFFile::writeData (char const* data, qint64 max_size)
-{
- auto bytes = m_->file_.write (data, max_size);
- if (bytes > 0 && atEnd ())
- {
- m_->header_dirty_ = true;
- m_->data_size_ = -1;
- }
- return bytes;
-}
-
-// forward to QFile
-bool BWFFile::copy (QString const& new_name)
-{
- close ();
- return m_->file_.copy (new_name);
-}
-
-bool BWFFile::exists () const {return m_->file_.exists ();}
-
-bool BWFFile::link (QString const& link_name) {return m_->file_.link (link_name);}
-
-bool BWFFile::remove ()
-{
- close ();
- return m_->file_.remove ();
-}
-
-bool BWFFile::rename (QString const& new_name)
-{
- close ();
- return m_->file_.rename (new_name);
-}
-
-void BWFFile::setFileName (QString const& name) {m_->file_.setFileName (name);}
-
-QString BWFFile::symLinkTarget () const {return m_->file_.symLinkTarget ();}
-
-QString BWFFile::fileName () const {return m_->file_.fileName ();}
-
-auto BWFFile::permissions () const -> Permissions {return m_->file_.permissions ();}
-
-bool BWFFile::resize (qint64 new_size)
-{
- auto size = m_->file_.size ();
- if (pos () > new_size) seek (new_size);
- auto result = m_->file_.resize (m_->header_length_ + new_size);
- if (m_->data_size_ >= 0)
- {
- // set any fresh bytes to zero
- auto end_of_data = m_->header_length_ + m_->data_size_;
- auto length = std::min (size - end_of_data, m_->file_.size () - end_of_data);
- if (length > 0)
- {
- auto position = m_->file_.pos ();
- m_->file_.seek (m_->header_length_ + m_->data_size_);
- m_->file_.write (QByteArray {int (length), '\0'});
- m_->file_.seek (position);
- }
- m_->data_size_ = -1;
- }
- m_->header_dirty_ = true;
- return result;
-}
-
-bool BWFFile::setPermissions (Permissions permissions)
-{
- bool success = m_->file_.setPermissions (permissions);
- if (!success) setErrorString (m_->file_.errorString ());
- return success;
-}
-
-auto BWFFile::error () const -> FileError
-{
- return m_->error_ != FileError::NoError ? m_->error_ : m_->file_.error ();
-}
-
-bool BWFFile::flush ()
-{
- bool success = m_->file_.flush ();
- if (!success) setErrorString (m_->file_.errorString ());
- return success;
-}
-
-int BWFFile::handle () const
-{
- int h {m_->file_.handle ()};
- if (h < 0) const_cast<BWFFile *> (this)->setErrorString (m_->file_.errorString ());
- return h;
-}
-
-uchar * BWFFile::map (qint64 offset, qint64 size, MemoryMapFlags flags)
-{
- uchar * address = m_->file_.map (offset + m_->header_length_, size, flags);
- if (!address) setErrorString (m_->file_.errorString ());
- return address;
-}
-
-bool BWFFile::unmap (uchar * address)
-{
- bool success = m_->file_.unmap (address);
- if (!success) setErrorString (m_->file_.errorString ());
- return success;
-}
-
-void BWFFile::unsetError ()
-{
- m_->error_ = FileError::NoError;
- m_->file_.unsetError ();
-}
+#include "BWFFile.hpp"
+
+#include <cstring>
+#include <numeric>
+#include <algorithm>
+
+#include <qendian.h>
+#include <QAudioFormat>
+#include <QDateTime>
+#include <QDate>
+#include <QTime>
+#include <QString>
+#include <QUuid>
+
+#include "pimpl_impl.hpp"
+
+#include "moc_BWFFile.cpp"
+
+namespace
+{
+ // chunk descriptor
+ struct Desc
+ {
+ Desc ()
+ : size_ {0}
+ {
+ }
+
+ explicit Desc (char const * id, quint32 size = 0)
+ : size_ {size}
+ {
+ set (id);
+ }
+
+ void set (char const * id = nullptr)
+ {
+ if (id)
+ {
+ auto end = reinterpret_cast<char const *> (::memchr (id, '\0', 4u));
+ auto len = end ? end - id : 4u;
+ ::memcpy (id_.data (), id, len);
+ if (len < 4u)
+ {
+ memset (id_.data () + len, ' ', 4u - len);
+ }
+ }
+ else
+ {
+ ::memcpy (id_.data (), "JUNK", 4u);
+ }
+ }
+
+ void set (char const * id, quint32 size)
+ {
+ set (id);
+ size_ = size;
+ }
+
+ char * operator & () {return reinterpret_cast<char *> (this);}
+ char const * operator & () const {return reinterpret_cast<char const *> (this);}
+
+ std::array<char, 4> id_;
+ quint32 size_;
+ };
+
+ // "fmt " chunk contents
+ struct FormatChunk
+ {
+ quint16 audio_format;
+ quint16 num_channels;
+ quint32 sample_rate;
+ quint32 byte_rate;
+ quint16 block_align;
+ quint16 bits_per_sample;
+ };
+
+ // "bext" chunk contents
+ struct BroadcastAudioExtension
+ {
+ using Version = BWFFile::BextVersion;
+ using UMID = BWFFile::UMID;
+
+ BroadcastAudioExtension (Version version = Version::v_0)
+ : version_ {static_cast<quint16> (version)}
+ , umid_ {{}}
+ {
+ // set some sensible defaults for the "bext" fields
+ auto now = QDateTime::currentDateTimeUtc ();
+ ::memcpy (origination_date_,
+ now.date ().toString ("yyyy-MM-dd").toLocal8Bit ().constData (),
+ sizeof origination_date_);
+ ::memcpy (origination_time_,
+ now.time ().toString ("hh-mm-ss").toLocal8Bit ().constData (),
+ sizeof origination_time_);
+ auto uuid = QUuid::createUuid ().toRfc4122 ();
+ std::copy (uuid.cbegin (), uuid.cend (), umid_.data () + 16);
+ }
+
+ char description_[256];
+ char originator_[32];
+ char originator_reference_[32];
+ char origination_date_[10];
+ char origination_time_[10];
+ quint32 time_reference_low_;
+ quint32 time_reference_high_;
+ quint16 version_;
+ UMID umid_; // V1 zero for V0
+ quint16 loudness_value_; // V2
+ quint16 loudness_range_; // V2
+ quint16 max_true_peak_level_; // V2
+ quint16 max_momentary_loudness_; // V2
+ quint16 max_short_term_loudness_; // V2
+ quint8 reserved_[180];
+ char coding_history_[];
+ };
+}
+
+class BWFFile::impl final
+{
+public:
+ using FileError = QFile::FileError;
+
+ impl (QAudioFormat const& format)
+ : header_dirty_ {true}
+ , format_ {format}
+ , header_length_ {-1}
+ , data_size_ {-1}
+ , error_ {FileError::NoError}
+ {
+ }
+
+ impl (QAudioFormat const& format, QString const& name)
+ : header_dirty_ {true}
+ , format_ {format}
+ , file_ {name}
+ , header_length_ {-1}
+ , data_size_ {-1}
+ , error_ {FileError::NoError}
+ {
+ }
+
+ impl (QAudioFormat const& format, QString const& name, InfoDictionary const& dictionary)
+ : header_dirty_ {true}
+ , format_ {format}
+ , file_ {name}
+ , info_dictionary_ {dictionary}
+ , header_length_ {-1}
+ , data_size_ {-1}
+ , error_ {FileError::NoError}
+ {
+ }
+
+ ~impl ()
+ {
+ if (file_.isOpen ()) file_.close ();
+ }
+
+ bool initialize (BWFFile * self, OpenMode mode);
+ bool read_header ();
+ bool write_header (QAudioFormat);
+ bool update_header ();
+
+ BroadcastAudioExtension const * bext () const
+ {
+ return bext_.isEmpty () ? nullptr : reinterpret_cast<BroadcastAudioExtension const *> (bext_.constData ());
+ }
+
+ BroadcastAudioExtension * bext ()
+ {
+ if (bext_.isEmpty ()) // create a "bext" chunk in place
+ {
+ bext_.data ();
+ bext_.fill ('\0', sizeof (BroadcastAudioExtension));
+ new (bext_.data ()) BroadcastAudioExtension {};
+ }
+ return reinterpret_cast<BroadcastAudioExtension *> (bext_.data ());
+ }
+
+ bool header_dirty_;
+ QAudioFormat format_;
+ QFile file_;
+ QByteArray bext_;
+ InfoDictionary info_dictionary_;
+ qint64 header_length_;
+ qint64 data_size_;
+ FileError error_;
+};
+
+bool BWFFile::impl::initialize (BWFFile * self, OpenMode mode)
+{
+ bool result {false};
+ if (mode & Append)
+ {
+ result = file_.seek (file_.size ());
+ if (result) result = self->seek (file_.size () - header_length_);
+ }
+ else
+ {
+ result = self->seek (0);
+ }
+ return result;
+}
+
+bool BWFFile::impl::read_header ()
+{
+ header_length_ = -1;
+ data_size_ = -1;
+ if (!(file_.openMode () & ReadOnly)) return false;
+ if (!file_.seek (0)) return false;
+ Desc outer_desc;
+ quint32 outer_offset = file_.pos ();
+ quint32 outer_size {0};
+ bool be {false};
+ while (outer_offset < sizeof outer_desc + outer_desc.size_ - 1) // allow for uncounted pad
+ {
+ if (file_.read (&outer_desc, sizeof outer_desc) != sizeof outer_desc) return false;
+ be = !memcmp (&outer_desc.id_, "RIFX", 4);
+ outer_size = be ? qFromBigEndian<quint32> (outer_desc.size_) : qFromLittleEndian<quint32> (outer_desc.size_);
+ if (!memcmp (&outer_desc.id_, "RIFF", 4) || be)
+ {
+ // RIFF or RIFX
+ char riff_item[4];
+ if (file_.read (riff_item, sizeof riff_item) != sizeof riff_item) return false;
+ if (!memcmp (riff_item, "WAVE", 4))
+ {
+ // WAVE
+ Desc wave_desc;
+ quint32 wave_offset = file_.pos ();
+ quint32 wave_size {0};
+ while (wave_offset < outer_offset + sizeof outer_desc + outer_size - 1)
+ {
+ if (file_.read (&wave_desc, sizeof wave_desc) != sizeof wave_desc) return false;
+ wave_size = be ? qFromBigEndian<quint32> (wave_desc.size_) : qFromLittleEndian<quint32> (wave_desc.size_);
+ if (!memcmp (&wave_desc.id_, "bext", 4))
+ {
+ bext_ = file_.read (wave_size);
+ }
+ if (!memcmp (&wave_desc.id_, "fmt ", 4))
+ {
+ FormatChunk fmt;
+ if (file_.read (reinterpret_cast<char *> (&fmt), sizeof fmt) != sizeof fmt) return false;
+ auto audio_format = be ? qFromBigEndian<quint16> (fmt.audio_format) : qFromLittleEndian<quint16> (fmt.audio_format);
+ if (audio_format != 0 && audio_format != 1) return false; // not PCM nor undefined
+ format_.setByteOrder (be ? QAudioFormat::BigEndian : QAudioFormat::LittleEndian);
+ format_.setChannelCount (be ? qFromBigEndian<quint16> (fmt.num_channels) : qFromLittleEndian<quint16> (fmt.num_channels));
+ format_.setCodec ("audio/pcm");
+ format_.setSampleRate (be ? qFromBigEndian<quint32> (fmt.sample_rate) : qFromLittleEndian<quint32> (fmt.sample_rate));
+ int bits_per_sample {be ? qFromBigEndian<quint16> (fmt.bits_per_sample) : qFromLittleEndian<quint16> (fmt.bits_per_sample)};
+ format_.setSampleSize (bits_per_sample);
+ format_.setSampleType (8 == bits_per_sample ? QAudioFormat::UnSignedInt : QAudioFormat::SignedInt);
+ }
+ else if (!memcmp (&wave_desc.id_, "data", 4))
+ {
+ data_size_ = wave_size;
+ header_length_ = file_.pos ();
+ }
+ else if (!memcmp (&wave_desc.id_, "LIST", 4))
+ {
+ char list_type[4];
+ if (file_.read (list_type, sizeof list_type) != sizeof list_type) return false;
+ if (!memcmp (list_type, "INFO", 4))
+ {
+ Desc info_desc;
+ quint32 info_offset = file_.pos ();
+ quint32 info_size {0};
+ while (info_offset < wave_offset + sizeof wave_desc + wave_size - 1)
+ {
+ if (file_.read (&info_desc, sizeof info_desc) != sizeof info_desc) return false;
+ info_size = be ? qFromBigEndian<quint32> (info_desc.size_) : qFromLittleEndian<quint32> (info_desc.size_);
+ info_dictionary_[info_desc.id_] = file_.read (info_size);
+ if (!file_.seek (info_offset + sizeof info_desc + (info_size + 1) / 2 * 2)) return false;;
+ info_offset = file_.pos ();
+ }
+ }
+ }
+ if (!file_.seek (wave_offset + sizeof wave_desc + (wave_size + 1) / 2 * 2)) return false;
+ wave_offset = file_.pos ();
+ }
+ }
+ }
+ if (!file_.seek (outer_offset + sizeof outer_desc + (outer_size + 1) / 2 * 2)) return false;
+ outer_offset = file_.pos ();
+ }
+ return data_size_ >= 0 && file_.seek (header_length_);
+}
+
+bool BWFFile::impl::write_header (QAudioFormat format)
+{
+ data_size_ = -1;
+ if ("audio/pcm" != format.codec ()) return false;
+ if (!(file_.openMode () & WriteOnly)) return false;
+ if (!file_.seek (0)) return false;
+ header_length_ = 0;
+ bool be {QAudioFormat::BigEndian == format_.byteOrder ()};
+ Desc desc {be ? "RIFX" : "RIFF"};
+ if (file_.write (&desc, sizeof desc) != sizeof desc) return false;
+ header_dirty_ = true;
+ if (file_.write ("WAVE", 4) != 4) return false;
+
+ FormatChunk fmt;
+ if (be)
+ {
+ fmt.audio_format = qToBigEndian<quint16> (1); // PCM
+ fmt.num_channels = qToBigEndian<quint16> (format.channelCount ());
+ fmt.sample_rate = qToBigEndian<quint32> (format.sampleRate ());
+ fmt.byte_rate = qToBigEndian<quint32> (format.bytesForDuration (1000000));
+ fmt.block_align = qToBigEndian<quint16> (format.bytesPerFrame ());
+ fmt.bits_per_sample = qToBigEndian<quint16> (format.sampleSize ());
+ desc.set ("fmt", qToBigEndian<quint32> (sizeof fmt));
+ }
+ else
+ {
+ fmt.audio_format = qToLittleEndian<quint16> (1); // PCM
+ fmt.num_channels = qToLittleEndian<quint16> (format.channelCount ());
+ fmt.sample_rate = qToLittleEndian<quint32> (format.sampleRate ());
+ fmt.byte_rate = qToLittleEndian<quint32> (format.bytesForDuration (1000000));
+ fmt.block_align = qToLittleEndian<quint16> (format.bytesPerFrame ());
+ fmt.bits_per_sample = qToLittleEndian<quint16> (format.sampleSize ());
+ desc.set ("fmt", qToLittleEndian<quint32> (sizeof fmt));
+ }
+ if (file_.write (&desc, sizeof desc) != sizeof desc) return false;
+ if (file_.write (reinterpret_cast<char const *> (&fmt), sizeof fmt) != sizeof fmt) return false;
+
+ desc.set ("data");
+ if (file_.write (&desc, sizeof desc) != sizeof desc) return false;
+ header_length_ = file_.pos ();
+ return true;
+}
+
+bool BWFFile::impl::update_header ()
+{
+ if (header_length_ < 0 || !(file_.openMode () & WriteOnly)) return false;
+ auto position = file_.pos ();
+ bool be {QAudioFormat::BigEndian == format_.byteOrder ()};
+ Desc desc;
+ auto size = data_size_ < 0 ? file_.size () - header_length_ : data_size_;
+ if (!file_.seek (header_length_ - sizeof desc)) return false;
+ desc.set ("data", be ? qToBigEndian<quint32> (size) : qToLittleEndian<quint32> (size));
+ if (file_.write (&desc, sizeof desc) != sizeof desc) return false;
+
+ if (!bext_.isEmpty ())
+ {
+ if (!file_.seek (file_.size ())) return false;
+ auto size = bext_.size ();
+ desc.set ("bext", be ? qToBigEndian<quint32> (size) : qToLittleEndian<quint32> (size));
+ if ((file_.size () % 2) && file_.write ("\0", 1) != 1) return false;
+ if (file_.write (&desc, sizeof desc) != sizeof desc) return false;
+ auto * data = reinterpret_cast<BroadcastAudioExtension *> (bext_.data ());
+ if (be)
+ {
+ data->time_reference_low_ = qToBigEndian<quint32> (data->time_reference_low_);
+ data->time_reference_high_ = qToBigEndian<quint32> (data->time_reference_high_);
+ switch (static_cast<BextVersion> (data->version_))
+ {
+ case BextVersion::v_0:
+ data->version_ = qToBigEndian<quint32> (data->version_);
+ // fall through
+ default:
+ data->loudness_value_ = qToBigEndian<quint16> (data->loudness_value_);
+ data->loudness_range_ = qToBigEndian<quint16> (data->loudness_range_);
+ data->max_true_peak_level_ = qToBigEndian<quint16> (data->max_true_peak_level_);
+ data->max_momentary_loudness_ = qToBigEndian<quint16> (data->max_momentary_loudness_);
+ data->max_short_term_loudness_ = qToBigEndian<quint16> (data->max_short_term_loudness_);
+ }
+ }
+ else
+ {
+ data->time_reference_low_ = qToLittleEndian<quint32> (data->time_reference_low_);
+ data->time_reference_high_ = qToLittleEndian<quint32> (data->time_reference_high_);
+ switch (static_cast<BextVersion> (data->version_))
+ {
+ case BextVersion::v_0:
+ data->version_ = qToLittleEndian<quint32> (data->version_);
+ // fall through
+ default:
+ data->loudness_value_ = qToLittleEndian<quint16> (data->loudness_value_);
+ data->loudness_range_ = qToLittleEndian<quint16> (data->loudness_range_);
+ data->max_true_peak_level_ = qToLittleEndian<quint16> (data->max_true_peak_level_);
+ data->max_momentary_loudness_ = qToLittleEndian<quint16> (data->max_momentary_loudness_);
+ data->max_short_term_loudness_ = qToLittleEndian<quint16> (data->max_short_term_loudness_);
+ }
+ }
+ if (file_.write (bext_) != size) return false;
+ }
+
+ if (info_dictionary_.size ())
+ {
+ if (!file_.seek (file_.size ())) return false;
+ desc.set ("LIST");
+ if ((file_.size () % 2) && file_.write ("\0", 1) != 1) return false;
+ if (file_.write (&desc, sizeof desc) != sizeof desc) return false;
+ auto list_start = file_.pos ();
+ if (file_.write ("INFO", 4) != 4) return false;
+ for (auto iter = info_dictionary_.constBegin ()
+ ; iter != info_dictionary_.constEnd (); ++iter)
+ {
+ auto value = iter.value ();
+ auto len = value.size () + 1; // include terminating null char
+ desc.set (iter.key ().data (), be ? qToBigEndian<quint32> (len) : qToLittleEndian<quint32> (len));
+ if ((file_.size () % 2) && file_.write ("\0", 1) != 1) return false;
+ if (file_.write (&desc, sizeof desc) != sizeof desc) return false;
+ if (file_.write (value.constData (), len) != len) return false;
+ }
+ auto size = file_.pos () - list_start;
+ if (!file_.seek (list_start - sizeof desc)) return false;
+ desc.set ("LIST", be ? qToBigEndian<quint32> (size) : qToLittleEndian<quint32> (size));
+ if (file_.write (&desc, sizeof desc) != sizeof desc) return false;
+ }
+
+ size = file_.size () - sizeof desc;
+ if ((file_.size () % 2) && file_.seek (file_.size ()) && file_.write ("\0", 1) != 1) return false;
+ if (!file_.seek (0)) return false;
+ desc.set (be ? "RIFX" : "RIFF", be ? qToBigEndian<quint32> (size) : qToLittleEndian<quint32> (size));
+ if (file_.write (&desc, sizeof desc) != sizeof desc) return false;
+ return file_.seek (position);
+}
+
+//
+// BWFFile implementation
+//
+BWFFile::BWFFile (QAudioFormat const& format, QObject * parent)
+ : QIODevice {parent}
+ , m_ {format}
+{
+}
+
+BWFFile::BWFFile (QAudioFormat const& format, QString const& name, QObject * parent)
+ : QIODevice {parent}
+ , m_ {format, name}
+{
+}
+
+BWFFile::BWFFile (QAudioFormat const& format, QString const& name
+ , InfoDictionary const& dictionary, QObject * parent)
+ : QIODevice {parent}
+ , m_ {format, name, dictionary}
+{
+}
+
+BWFFile::~BWFFile ()
+{
+ if (isOpen ()) close ();
+}
+
+bool BWFFile::open (OpenMode mode)
+{
+ bool success {false};
+ if (!(mode & WriteOnly))
+ {
+ if (!(success = m_->file_.open (mode & ~Text)))
+ {
+ setErrorString (m_->file_.errorString ());
+ }
+ else
+ {
+ if (!(success = m_->read_header ()))
+ {
+ if (FileError::NoError == m_->file_.error ())
+ {
+ setErrorString ("Unable to read file header");
+ m_->error_ = FileError::ReadError;
+ }
+ else
+ {
+ setErrorString (m_->file_.errorString ());
+ }
+ }
+ }
+ }
+ else
+ {
+ if (!(success = m_->file_.open (mode & ~Text)))
+ {
+ setErrorString (m_->file_.errorString ());
+ }
+ else
+ {
+ if (!(success = (m_->read_header () || m_->write_header (m_->format_))))
+ {
+ if (FileError::NoError == m_->file_.error ())
+ {
+ setErrorString ("Unable to update file header");
+ m_->error_ = FileError::WriteError;
+ }
+ else
+ {
+ setErrorString (m_->file_.errorString ());
+ }
+ }
+ else if (!(success = m_->file_.resize (m_->header_length_)))
+ {
+ setErrorString (m_->file_.errorString ());
+ }
+ }
+ }
+ success && (success = QIODevice::open (mode | Unbuffered));
+ if (success && !(success = m_->initialize (this, mode)))
+ {
+ if (FileError::NoError == m_->file_.error ())
+ {
+ setErrorString ("Unable to initialize file header");
+ m_->error_ = FileError::WriteError;
+ }
+ else
+ {
+ setErrorString (m_->file_.errorString ());
+ }
+ }
+ if (!success) close ();
+ return success;
+}
+
+bool BWFFile::open(FILE * fh, OpenMode mode, FileHandleFlags flags)
+{
+ bool success {false};
+ if (!(mode & ReadOnly))
+ {
+ setErrorString ("Read or read/write access must be specified");
+ m_->error_ = FileError::OpenError;
+ return success;
+ }
+ if (!(mode & WriteOnly))
+ {
+ if (!(success = m_->file_.open (fh, mode & ~Text, flags)))
+ {
+ setErrorString (m_->file_.errorString ());
+ }
+ else
+ {
+ if (!(success = m_->read_header ()))
+ {
+ if (FileError::NoError == m_->file_.error ())
+ {
+ setErrorString ("Unable to read file header");
+ m_->error_ = FileError::ReadError;
+ }
+ else
+ {
+ setErrorString (m_->file_.errorString ());
+ }
+ }
+ }
+ }
+ else
+ {
+ if (!(success = m_->file_.open (fh, mode & ~Text, flags)))
+ {
+ setErrorString (m_->file_.errorString ());
+ }
+ else
+ {
+ if (!(success = (m_->read_header () || m_->write_header (m_->format_))))
+ {
+ if (FileError::NoError == m_->file_.error ())
+ {
+ setErrorString ("Unable to update file header");
+ m_->error_ = FileError::WriteError;
+ }
+ else
+ {
+ setErrorString (m_->file_.errorString ());
+ }
+ }
+ else if (!(success = m_->file_.resize (m_->header_length_)))
+ {
+ setErrorString (m_->file_.errorString ());
+ }
+ }
+ }
+ success && (success = QIODevice::open (mode | Unbuffered));
+ if (success && !(success = m_->initialize (this, mode)))
+ {
+ if (FileError::NoError == m_->file_.error ())
+ {
+ setErrorString ("Unable to initialize file header");
+ m_->error_ = FileError::WriteError;
+ }
+ else
+ {
+ setErrorString (m_->file_.errorString ());
+ }
+ }
+ if (!success) close ();
+ return success;
+}
+
+bool BWFFile::open (int fd, OpenMode mode, FileHandleFlags flags)
+{
+ bool success {false};
+ if (!(mode & ReadOnly))
+ {
+ setErrorString ("Read or read/write access must be specified");
+ m_->error_ = FileError::OpenError;
+ return success;
+ }
+ if (!(mode & WriteOnly))
+ {
+ if (!(success = m_->file_.open (fd, mode & ~Text, flags)))
+ {
+ setErrorString (m_->file_.errorString ());
+ }
+ else
+ {
+ if (!(success = m_->read_header ()))
+ {
+ if (FileError::NoError == m_->file_.error ())
+ {
+ setErrorString ("Unable to read file header");
+ m_->error_ = FileError::ReadError;
+ }
+ else
+ {
+ setErrorString (m_->file_.errorString ());
+ }
+ }
+ }
+ }
+ else
+ {
+ if (!(success = m_->file_.open (fd, mode & ~Text, flags)))
+ {
+ setErrorString (m_->file_.errorString ());
+ }
+ else
+ {
+ if (!(success = (m_->read_header () || m_->write_header (m_->format_))))
+ {
+ if (FileError::NoError == m_->file_.error ())
+ {
+ setErrorString ("Unable to update file header");
+ m_->error_ = FileError::WriteError;
+ }
+ else
+ {
+ setErrorString (m_->file_.errorString ());
+ }
+ }
+ else if (!(success = m_->file_.resize (m_->header_length_)))
+ {
+ setErrorString (m_->file_.errorString ());
+ }
+ }
+ }
+ success && (success = QIODevice::open (mode | Unbuffered));
+ if (success && !(success = m_->initialize (this, mode)))
+ {
+ if (FileError::NoError == m_->file_.error ())
+ {
+ setErrorString ("Unable to initialize file header");
+ m_->error_ = FileError::WriteError;
+ }
+ else
+ {
+ setErrorString (m_->file_.errorString ());
+ }
+ }
+ if (!success) close ();
+ return success;
+}
+
+QAudioFormat const& BWFFile::format () const {return m_->format_;}
+
+auto BWFFile::list_info () -> InfoDictionary&
+{
+ m_->header_dirty_ = true;
+ return m_->info_dictionary_;
+}
+
+
+// Broadcast Audio Extension fields
+auto BWFFile::bext_version () const -> BextVersion
+{
+ return static_cast<BextVersion> (m_->bext () ? 0 : m_->bext ()->version_);
+}
+
+void BWFFile::bext_version (BextVersion version)
+{
+ m_->header_dirty_ = true;
+ m_->bext ()->version_ = static_cast<quint16> (version);
+}
+
+QByteArray BWFFile::bext_description () const
+{
+ if (!m_->bext ()) return {};
+ return QByteArray::fromRawData (m_->bext ()->description_, strlen (m_->bext ()->description_));
+}
+
+void BWFFile::bext_description (QByteArray const& description)
+{
+ m_->header_dirty_ = true;
+ ::memcpy (m_->bext ()->description_, description.constData (), sizeof BroadcastAudioExtension::description_);
+}
+
+QByteArray BWFFile::bext_originator () const
+{
+ if (!m_->bext ()) return {};
+ return QByteArray::fromRawData (m_->bext ()->originator_, strlen (m_->bext ()->originator_));
+}
+
+void BWFFile::bext_originator (QByteArray const& originator)
+{
+ m_->header_dirty_ = true;
+ ::memcpy (m_->bext ()->originator_, originator.constData (), sizeof BroadcastAudioExtension::originator_);
+}
+
+QByteArray BWFFile::bext_originator_reference () const
+{
+ if (!m_->bext ()) return {};
+ return QByteArray::fromRawData (m_->bext ()->originator_reference_, strlen (m_->bext ()->originator_reference_));
+}
+
+void BWFFile::bext_originator_reference (QByteArray const& reference)
+{
+ m_->header_dirty_ = true;
+ ::memcpy (m_->bext ()->originator_reference_, reference.constData (), sizeof BroadcastAudioExtension::originator_reference_);
+}
+
+QDateTime BWFFile::bext_origination_date_time () const
+{
+ if (!m_->bext ()) return {};
+ return {QDate::fromString (m_->bext ()->origination_date_, "yyyy-MM-dd"),
+ QTime::fromString (m_->bext ()->origination_time_, "hh-mm-ss"), Qt::UTC};
+}
+
+void BWFFile::bext_origination_date_time (QDateTime const& dt)
+{
+ m_->header_dirty_ = true;
+ ::memcpy (m_->bext ()->origination_date_,
+ dt.date ().toString ("yyyy-MM-dd").toLocal8Bit ().constData (),
+ sizeof BroadcastAudioExtension::origination_date_);
+ ::memcpy (m_->bext ()->origination_time_,
+ dt.time ().toString ("hh-mm-ss").toLocal8Bit ().constData (),
+ sizeof BroadcastAudioExtension::origination_time_);
+}
+
+quint64 BWFFile::bext_time_reference () const
+{
+ if (!m_->bext ()) return 0;
+ return (quint64 (m_->bext ()->time_reference_high_) << 32) + m_->bext ()->time_reference_low_;
+}
+
+void BWFFile::bext_time_reference (quint64 time_code)
+{
+ m_->header_dirty_ = true;
+ m_->bext ()->time_reference_low_ = time_code & 0x00000000ffffffffll;
+ m_->bext ()->time_reference_high_ = time_code >> 32;
+}
+
+auto BWFFile::bext_umid () const -> UMID
+{
+ UMID umid {{'\0'}};
+ if (m_->bext ())
+ {
+ umid = m_->bext ()->umid_;
+ }
+ return umid;
+}
+
+void BWFFile::bext_umid (UMID const& umid)
+{
+ m_->header_dirty_ = true;
+ m_->bext ()->umid_ = umid;
+}
+
+quint16 BWFFile::bext_loudness_value () const
+{
+ if (!m_->bext ()) return 0;
+ return m_->bext ()->loudness_value_;
+}
+
+void BWFFile::bext_loudness_value (quint16 value)
+{
+ m_->header_dirty_ = true;
+ m_->bext ()->loudness_value_ = value;
+}
+
+quint16 BWFFile::bext_loudness_range () const
+{
+ if (!m_->bext ()) return 0;
+ return m_->bext ()->loudness_range_;
+}
+
+void BWFFile::bext_loudness_range (quint16 range)
+{
+ m_->header_dirty_ = true;
+ m_->bext ()->loudness_range_ = range;
+}
+
+quint16 BWFFile::bext_max_true_peak_level () const
+{
+ if (!m_->bext ()) return 0;
+ return m_->bext ()->max_true_peak_level_;
+}
+
+void BWFFile::bext_max_true_peak_level (quint16 level)
+{
+ m_->header_dirty_ = true;
+ m_->bext ()->max_true_peak_level_ = level;
+}
+
+quint16 BWFFile::bext_max_momentary_loudness () const
+{
+ if (!m_->bext ()) return 0;
+ return m_->bext ()->max_momentary_loudness_;
+}
+
+void BWFFile::bext_max_momentary_loudness (quint16 loudness)
+{
+ m_->header_dirty_ = true;
+ m_->bext ()->max_momentary_loudness_ = loudness;
+}
+
+quint16 BWFFile::bext_max_short_term_loudness () const
+{
+ if (!m_->bext ()) return 0;
+ return m_->bext ()->max_short_term_loudness_;
+}
+
+void BWFFile::bext_max_short_term_loudness (quint16 loudness)
+{
+ m_->header_dirty_ = true;
+ m_->bext ()->max_short_term_loudness_ = loudness;
+}
+
+QByteArray BWFFile::bext_coding_history () const
+{
+ if (size_t (m_->bext_.size ()) <= sizeof (BroadcastAudioExtension)) return {};
+ return QByteArray::fromRawData (m_->bext ()->coding_history_,
+ m_->bext_.size () - sizeof (BroadcastAudioExtension));
+}
+
+void BWFFile::bext_coding_history (QByteArray const& text)
+{
+ m_->header_dirty_ = true;
+ m_->bext (); // ensure we have a correctly
+ // initialized m_->bext_
+ auto end = static_cast<char const *> (::memchr (text.constData (), '\0', size_t (text.size ())));
+ auto length = end ? end - text.constData () : size_t (text.size ());
+ m_->bext_.resize (sizeof (BroadcastAudioExtension) + length);
+ std::strncpy (m_->bext ()->coding_history_, text.constData (), length);
+}
+
+
+bool BWFFile::reset ()
+{
+ bool success {true};
+ if (m_->file_.isOpen ())
+ {
+ m_->info_dictionary_.clear ();
+ m_->bext_.clear ();
+ auto size = m_->data_size_ < 0 ? m_->file_.size () - m_->header_length_ : m_->data_size_;
+ m_->data_size_ = size;
+ if (m_->header_length_ > qint64 (3 * sizeof (Desc) + 4 + sizeof (FormatChunk)))
+ {
+ // we need to move the data down
+ auto old_pos = m_->header_length_;
+ if (!(success = m_->write_header (m_->format_)))
+ {
+ auto new_pos = m_->header_length_;
+ QByteArray buffer;
+ while (size)
+ {
+ success = m_->file_.seek (old_pos);
+ if (!success)
+ {
+ setErrorString (m_->file_.errorString ());
+ }
+ else
+ {
+ buffer = m_->file_.read (std::min (size, qint64 (32768)));
+ success = m_->file_.seek (new_pos);
+ if (!success)
+ {
+ setErrorString (m_->file_.errorString ());
+ }
+ else
+ {
+ qint64 bytes = m_->file_.write (buffer);
+ if (bytes < 0)
+ {
+ setErrorString (m_->file_.errorString ());
+ success = false;
+ }
+ else
+ {
+ new_pos += buffer.size ();
+ old_pos += buffer.size ();
+ size -= buffer.size ();
+ }
+ }
+ }
+ }
+ }
+ else
+ {
+ if (FileError::NoError == m_->file_.error ())
+ {
+ setErrorString ("Unable to update file header");
+ m_->error_ = FileError::WriteError;
+ }
+ else
+ {
+ setErrorString (m_->file_.errorString ());
+ }
+ return success;
+ }
+ }
+ if (success)
+ {
+ success = m_->file_.resize (m_->header_length_ + m_->data_size_);
+ if (!success)
+ {
+ setErrorString (m_->file_.errorString ());
+ }
+ m_->header_dirty_ = true;
+ }
+ }
+ else
+ {
+ setErrorString ("File not open");
+ m_->error_ = FileError::WriteError;
+ success = false;
+ }
+ return success && QIODevice::reset ();
+}
+
+qint64 BWFFile::size () const
+{
+ return m_->data_size_ < 0 ? m_->file_.size () - m_->header_length_ : m_->data_size_;
+}
+
+bool BWFFile::isSequential () const
+{
+ return m_->file_.isSequential ();
+}
+
+void BWFFile::close ()
+{
+ if (isOpen ()) QIODevice::close ();
+ if (m_->header_dirty_ || m_->data_size_ < 0)
+ {
+ m_->update_header ();
+ }
+ if (m_->file_.isOpen ())
+ {
+ m_->file_.close ();
+ }
+}
+
+bool BWFFile::seek (qint64 pos)
+{
+ if (pos < 0)
+ {
+ setErrorString ("Attempt to seek before beginning of data");
+ m_->error_ = FileError::PositionError;
+ return false;
+ }
+ bool success = QIODevice::seek (pos);
+ if (success)
+ {
+ success = m_->file_.seek (pos + m_->header_length_);
+ if (!success) setErrorString (m_->file_.errorString ());
+ }
+ return success;
+}
+
+qint64 BWFFile::readData (char * data, qint64 max_size)
+{
+ return m_->file_.read (data, max_size);
+}
+
+qint64 BWFFile::writeData (char const* data, qint64 max_size)
+{
+ auto bytes = m_->file_.write (data, max_size);
+ if (bytes > 0 && atEnd ())
+ {
+ m_->header_dirty_ = true;
+ m_->data_size_ = -1;
+ }
+ return bytes;
+}
+
+// forward to QFile
+bool BWFFile::copy (QString const& new_name)
+{
+ close ();
+ return m_->file_.copy (new_name);
+}
+
+bool BWFFile::exists () const {return m_->file_.exists ();}
+
+bool BWFFile::link (QString const& link_name) {return m_->file_.link (link_name);}
+
+bool BWFFile::remove ()
+{
+ close ();
+ return m_->file_.remove ();
+}
+
+bool BWFFile::rename (QString const& new_name)
+{
+ close ();
+ return m_->file_.rename (new_name);
+}
+
+void BWFFile::setFileName (QString const& name) {m_->file_.setFileName (name);}
+
+QString BWFFile::symLinkTarget () const {return m_->file_.symLinkTarget ();}
+
+QString BWFFile::fileName () const {return m_->file_.fileName ();}
+
+auto BWFFile::permissions () const -> Permissions {return m_->file_.permissions ();}
+
+bool BWFFile::resize (qint64 new_size)
+{
+ auto size = m_->file_.size ();
+ if (pos () > new_size) seek (new_size);
+ auto result = m_->file_.resize (m_->header_length_ + new_size);
+ if (m_->data_size_ >= 0)
+ {
+ // set any fresh bytes to zero
+ auto end_of_data = m_->header_length_ + m_->data_size_;
+ auto length = std::min (size - end_of_data, m_->file_.size () - end_of_data);
+ if (length > 0)
+ {
+ auto position = m_->file_.pos ();
+ m_->file_.seek (m_->header_length_ + m_->data_size_);
+ m_->file_.write (QByteArray {int (length), '\0'});
+ m_->file_.seek (position);
+ }
+ m_->data_size_ = -1;
+ }
+ m_->header_dirty_ = true;
+ return result;
+}
+
+bool BWFFile::setPermissions (Permissions permissions)
+{
+ bool success = m_->file_.setPermissions (permissions);
+ if (!success) setErrorString (m_->file_.errorString ());
+ return success;
+}
+
+auto BWFFile::error () const -> FileError
+{
+ return m_->error_ != FileError::NoError ? m_->error_ : m_->file_.error ();
+}
+
+bool BWFFile::flush ()
+{
+ bool success = m_->file_.flush ();
+ if (!success) setErrorString (m_->file_.errorString ());
+ return success;
+}
+
+int BWFFile::handle () const
+{
+ int h {m_->file_.handle ()};
+ if (h < 0) const_cast<BWFFile *> (this)->setErrorString (m_->file_.errorString ());
+ return h;
+}
+
+uchar * BWFFile::map (qint64 offset, qint64 size, MemoryMapFlags flags)
+{
+ uchar * address = m_->file_.map (offset + m_->header_length_, size, flags);
+ if (!address) setErrorString (m_->file_.errorString ());
+ return address;
+}
+
+bool BWFFile::unmap (uchar * address)
+{
+ bool success = m_->file_.unmap (address);
+ if (!success) setErrorString (m_->file_.errorString ());
+ return success;
+}
+
+void BWFFile::unsetError ()
+{
+ m_->error_ = FileError::NoError;
+ m_->file_.unsetError ();
+}
diff --git a/Audio/BWFFile.hpp b/Audio/BWFFile.hpp
index 33061141..a2f41b38 100755
--- a/Audio/BWFFile.hpp
+++ b/Audio/BWFFile.hpp
@@ -1,210 +1,210 @@
-#ifndef BWF_FILE_HPP__
-#define BWF_FILE_HPP__
-
-#include <array>
-
-#include <QFile>
-#include <QMap>
-#include <QByteArray>
-
-#include "pimpl_h.hpp"
-
-class QObject;
-class QString;
-class QAudioFormat;
-
-//
-// BWFFile - Broadcast Wave Format File (a.k.a. WAV file)
-//
-// The BWF file format is a backward compatible variation of the
-// Microsoft WAV file format. It contains an extra chunk with id
-// 'bext' that contains metadata defined by the EBU in:
-//
-// https://tech.ebu.ch/docs/tech/tech3285.pdf
-//
-// Also relevant is the recommendation document:
-//
-// https://tech.ebu.ch/docs/r/r098.pdf
-//
-// which suggests a format to the free text coding history field.
-//
-// This class also supports the LIST-INFO chunk type which also allows
-// metadata to be added to a WAV file, the defined INFO tag ids are
-// documented here:
-//
-// http://bwfmetaedit.sourceforge.net/listinfo.html
-//
-// These ids are not enforced but they are recommended as most
-// operating systems and audio applications recognize some or more of
-// them. Notably Microsoft Windows is not one of the operating systems
-// that does :( In fact there seems to be no documented metadata
-// tagging format that Windows Explorer recognizes.
-//
-// Changes to the 'bext' fields and the LIST-INFO dictionary may be
-// made right up until the file is closed as the relevant chunks are
-// saved to the end of the file after the end of the sample data.
-//
-// This class emulates the QFile class, in fact it uses a QFile object
-// instance internally and forwards many of its operations directly to
-// it.
-//
-// BWFFile is a QIODevice subclass and the implementation provides
-// access to the audio sample data contained in the BWF file as if
-// only that data were in the file. I.e. the first sample is at file
-// offset zero and the size of the file is the size of the sample
-// data. The headers, trailers and metadata are hidden but can be
-// accessed by the operations below.
-//
-class BWFFile
- : public QIODevice
-{
- Q_OBJECT
-public:
- using FileHandleFlags = QFile::FileHandleFlags;
- using Permissions = QFile::Permissions;
- using FileError = QFile::FileError;
- using MemoryMapFlags = QFile::MemoryMapFlags;
- using InfoDictionary = QMap<std::array<char, 4>, QByteArray>;
- using UMID = std::array<quint8, 64>;
-
- explicit BWFFile (QAudioFormat const&, QObject * parent = nullptr);
- explicit BWFFile (QAudioFormat const&, QString const& name,
- QObject * parent = nullptr);
-
- // The InfoDictionary should contain valid WAV format LIST-INFO
- // identifiers as keys, a list of them can be found here:
- //
- // http://bwfmetaedit.sourceforge.net/listinfo.html
- //
- // For files opened for ReadOnly access the dictionary is not
- // written to the file. For files opened ReadWrite, any existing
- // LIST-INFO tags will be merged into the dictionary when the file
- // is opened and if the file is modified the merged dictionary will
- // be written back to the file.
- //
- // Note that the sample data may no be in the native endian, it is
- // the callers responsibility to do any required endian
- // conversions. The internal data is always in native endian with
- // conversions being handled automatically. Use the BWF::format()
- // operation to access the format including the
- // QAudioFormat::byteOrder() operation to determine the data byte
- // ordering.
- //
- explicit BWFFile (QAudioFormat const&, QString const& name,
- InfoDictionary const&, QObject * parent = nullptr);
-
- ~BWFFile ();
- QAudioFormat const& format () const;
- InfoDictionary& list_info ();
-
- //
- // Broadcast Audio Extension fields
- //
- // If any of these modifiers are called then a "bext" chunk will be
- // written to the file if the file is writeable and the sample data
- // is modified.
- //
- enum class BextVersion : quint16 {v_0, v_1, v_2};
- BextVersion bext_version () const;
- void bext_version (BextVersion = BextVersion::v_2);
-
- QByteArray bext_description () const;
- void bext_description (QByteArray const&); // max 256 bytes
-
- QByteArray bext_originator () const;
- void bext_originator (QByteArray const&); // max 32 bytes
-
- QByteArray bext_originator_reference () const;
- void bext_originator_reference (QByteArray const&); // max 32 bytes
-
- QDateTime bext_origination_date_time () const;
- void bext_origination_date_time (QDateTime const&); // 1s resolution
-
- quint64 bext_time_reference () const;
- void bext_time_reference (quint64); // samples since midnight at start
-
- UMID bext_umid () const; // bext version >= 1 only
- void bext_umid (UMID const&);
-
- quint16 bext_loudness_value () const;
- void bext_loudness_value (quint16); // bext version >= 2 only
-
- quint16 bext_loudness_range () const;
- void bext_loudness_range (quint16); // bext version >= 2 only
-
- quint16 bext_max_true_peak_level () const;
- void bext_max_true_peak_level (quint16); // bext version >= 2 only
-
- quint16 bext_max_momentary_loudness () const;
- void bext_max_momentary_loudness (quint16); // bext version >= 2 only
-
- quint16 bext_max_short_term_loudness () const;
- void bext_max_short_term_loudness (quint16); // bext version >= 2 only
-
- QByteArray bext_coding_history () const;
- void bext_coding_history (QByteArray const&); // See EBU R 98
-
-
- // Emulate QFile interface
- bool open (OpenMode) override;
- bool open (FILE *, OpenMode, FileHandleFlags = QFile::DontCloseHandle);
- bool open (int fd, OpenMode, FileHandleFlags = QFile::DontCloseHandle);
- bool copy (QString const& new_name);
- bool exists () const;
- bool link (QString const& link_name);
- bool remove ();
- bool rename (QString const& new_name);
- void setFileName (QString const& name);
- QString symLinkTarget () const;
- QString fileName () const;
- Permissions permissions () const;
-
- // Resize is of the sample data portion, header and trailer chunks
- // are excess to the given size
- bool resize (qint64 new_size);
-
- bool setPermissions (Permissions permissions);
- FileError error () const;
- bool flush ();
- int handle () const;
-
- // The mapping offset is relative to the start of the sample data
- uchar * map (qint64 offset, qint64 size,
- MemoryMapFlags = QFile::NoOptions);
- bool unmap (uchar * address);
-
- void unsetError ();
-
-
- //
- // QIODevice implementation
- //
-
- // The size returned is of the sample data only, header and trailer
- // chunks are hidden and handled internally
- qint64 size () const override;
-
- bool isSequential () const override;
-
- // The reset operation clears the 'bext' and LIST-INFO as if they
- // were never supplied. If the file is writable the 'bext' and
- // LIST-INFO chunks will not be written making the resulting file a
- // lowest common denominator WAV file.
- bool reset () override;
-
- // Seek offsets are relative to the start of the sample data
- bool seek (qint64) override;
-
- // this can fail due to updating header issues, errors are ignored
- void close () override;
-
-protected:
- qint64 readData (char * data, qint64 max_size) override;
- qint64 writeData (char const* data, qint64 max_size) override;
-
-private:
- class impl;
- pimpl<impl> m_;
-};
-
-#endif
+#ifndef BWF_FILE_HPP__
+#define BWF_FILE_HPP__
+
+#include <array>
+
+#include <QFile>
+#include <QMap>
+#include <QByteArray>
+
+#include "pimpl_h.hpp"
+
+class QObject;
+class QString;
+class QAudioFormat;
+
+//
+// BWFFile - Broadcast Wave Format File (a.k.a. WAV file)
+//
+// The BWF file format is a backward compatible variation of the
+// Microsoft WAV file format. It contains an extra chunk with id
+// 'bext' that contains metadata defined by the EBU in:
+//
+// https://tech.ebu.ch/docs/tech/tech3285.pdf
+//
+// Also relevant is the recommendation document:
+//
+// https://tech.ebu.ch/docs/r/r098.pdf
+//
+// which suggests a format to the free text coding history field.
+//
+// This class also supports the LIST-INFO chunk type which also allows
+// metadata to be added to a WAV file, the defined INFO tag ids are
+// documented here:
+//
+// http://bwfmetaedit.sourceforge.net/listinfo.html
+//
+// These ids are not enforced but they are recommended as most
+// operating systems and audio applications recognize some or more of
+// them. Notably Microsoft Windows is not one of the operating systems
+// that does :( In fact there seems to be no documented metadata
+// tagging format that Windows Explorer recognizes.
+//
+// Changes to the 'bext' fields and the LIST-INFO dictionary may be
+// made right up until the file is closed as the relevant chunks are
+// saved to the end of the file after the end of the sample data.
+//
+// This class emulates the QFile class, in fact it uses a QFile object
+// instance internally and forwards many of its operations directly to
+// it.
+//
+// BWFFile is a QIODevice subclass and the implementation provides
+// access to the audio sample data contained in the BWF file as if
+// only that data were in the file. I.e. the first sample is at file
+// offset zero and the size of the file is the size of the sample
+// data. The headers, trailers and metadata are hidden but can be
+// accessed by the operations below.
+//
+class BWFFile
+ : public QIODevice
+{
+ Q_OBJECT
+public:
+ using FileHandleFlags = QFile::FileHandleFlags;
+ using Permissions = QFile::Permissions;
+ using FileError = QFile::FileError;
+ using MemoryMapFlags = QFile::MemoryMapFlags;
+ using InfoDictionary = QMap<std::array<char, 4>, QByteArray>;
+ using UMID = std::array<quint8, 64>;
+
+ explicit BWFFile (QAudioFormat const&, QObject * parent = nullptr);
+ explicit BWFFile (QAudioFormat const&, QString const& name,
+ QObject * parent = nullptr);
+
+ // The InfoDictionary should contain valid WAV format LIST-INFO
+ // identifiers as keys, a list of them can be found here:
+ //
+ // http://bwfmetaedit.sourceforge.net/listinfo.html
+ //
+ // For files opened for ReadOnly access the dictionary is not
+ // written to the file. For files opened ReadWrite, any existing
+ // LIST-INFO tags will be merged into the dictionary when the file
+ // is opened and if the file is modified the merged dictionary will
+ // be written back to the file.
+ //
+ // Note that the sample data may no be in the native endian, it is
+ // the callers responsibility to do any required endian
+ // conversions. The internal data is always in native endian with
+ // conversions being handled automatically. Use the BWF::format()
+ // operation to access the format including the
+ // QAudioFormat::byteOrder() operation to determine the data byte
+ // ordering.
+ //
+ explicit BWFFile (QAudioFormat const&, QString const& name,
+ InfoDictionary const&, QObject * parent = nullptr);
+
+ ~BWFFile ();
+ QAudioFormat const& format () const;
+ InfoDictionary& list_info ();
+
+ //
+ // Broadcast Audio Extension fields
+ //
+ // If any of these modifiers are called then a "bext" chunk will be
+ // written to the file if the file is writeable and the sample data
+ // is modified.
+ //
+ enum class BextVersion : quint16 {v_0, v_1, v_2};
+ BextVersion bext_version () const;
+ void bext_version (BextVersion = BextVersion::v_2);
+
+ QByteArray bext_description () const;
+ void bext_description (QByteArray const&); // max 256 bytes
+
+ QByteArray bext_originator () const;
+ void bext_originator (QByteArray const&); // max 32 bytes
+
+ QByteArray bext_originator_reference () const;
+ void bext_originator_reference (QByteArray const&); // max 32 bytes
+
+ QDateTime bext_origination_date_time () const;
+ void bext_origination_date_time (QDateTime const&); // 1s resolution
+
+ quint64 bext_time_reference () const;
+ void bext_time_reference (quint64); // samples since midnight at start
+
+ UMID bext_umid () const; // bext version >= 1 only
+ void bext_umid (UMID const&);
+
+ quint16 bext_loudness_value () const;
+ void bext_loudness_value (quint16); // bext version >= 2 only
+
+ quint16 bext_loudness_range () const;
+ void bext_loudness_range (quint16); // bext version >= 2 only
+
+ quint16 bext_max_true_peak_level () const;
+ void bext_max_true_peak_level (quint16); // bext version >= 2 only
+
+ quint16 bext_max_momentary_loudness () const;
+ void bext_max_momentary_loudness (quint16); // bext version >= 2 only
+
+ quint16 bext_max_short_term_loudness () const;
+ void bext_max_short_term_loudness (quint16); // bext version >= 2 only
+
+ QByteArray bext_coding_history () const;
+ void bext_coding_history (QByteArray const&); // See EBU R 98
+
+
+ // Emulate QFile interface
+ bool open (OpenMode) override;
+ bool open (FILE *, OpenMode, FileHandleFlags = QFile::DontCloseHandle);
+ bool open (int fd, OpenMode, FileHandleFlags = QFile::DontCloseHandle);
+ bool copy (QString const& new_name);
+ bool exists () const;
+ bool link (QString const& link_name);
+ bool remove ();
+ bool rename (QString const& new_name);
+ void setFileName (QString const& name);
+ QString symLinkTarget () const;
+ QString fileName () const;
+ Permissions permissions () const;
+
+ // Resize is of the sample data portion, header and trailer chunks
+ // are excess to the given size
+ bool resize (qint64 new_size);
+
+ bool setPermissions (Permissions permissions);
+ FileError error () const;
+ bool flush ();
+ int handle () const;
+
+ // The mapping offset is relative to the start of the sample data
+ uchar * map (qint64 offset, qint64 size,
+ MemoryMapFlags = QFile::NoOptions);
+ bool unmap (uchar * address);
+
+ void unsetError ();
+
+
+ //
+ // QIODevice implementation
+ //
+
+ // The size returned is of the sample data only, header and trailer
+ // chunks are hidden and handled internally
+ qint64 size () const override;
+
+ bool isSequential () const override;
+
+ // The reset operation clears the 'bext' and LIST-INFO as if they
+ // were never supplied. If the file is writable the 'bext' and
+ // LIST-INFO chunks will not be written making the resulting file a
+ // lowest common denominator WAV file.
+ bool reset () override;
+
+ // Seek offsets are relative to the start of the sample data
+ bool seek (qint64) override;
+
+ // this can fail due to updating header issues, errors are ignored
+ void close () override;
+
+protected:
+ qint64 readData (char * data, qint64 max_size) override;
+ qint64 writeData (char const* data, qint64 max_size) override;
+
+private:
+ class impl;
+ pimpl<impl> m_;
+};
+
+#endif
diff --git a/Audio/soundin.cpp b/Audio/soundin.cpp
index affb8104..ecab8e05 100755
--- a/Audio/soundin.cpp
+++ b/Audio/soundin.cpp
@@ -1,214 +1,214 @@
-#include "soundin.h"
-
-#include <cstdlib>
-#include <cmath>
-#include <iomanip>
-#include <QAudioDeviceInfo>
-#include <QAudioFormat>
-#include <QAudioInput>
-#include <QSysInfo>
-#include <QDebug>
-
-#include "Logger.hpp"
-
-#include "moc_soundin.cpp"
-
-bool SoundInput::checkStream ()
-{
- bool result (false);
- if (m_stream)
- {
- switch (m_stream->error ())
- {
- case QAudio::OpenError:
- Q_EMIT error (tr ("An error opening the audio input device has occurred."));
- break;
-
- case QAudio::IOError:
- Q_EMIT error (tr ("An error occurred during read from the audio input device."));
- break;
-
- // case QAudio::UnderrunError:
- // Q_EMIT error (tr ("Audio data not being fed to the audio input device fast enough."));
- // break;
-
- case QAudio::FatalError:
- Q_EMIT error (tr ("Non-recoverable error, audio input device not usable at this time."));
- break;
-
- case QAudio::UnderrunError: // TODO G4WJS: stop ignoring this
- // when we find the cause on macOS
- case QAudio::NoError:
- result = true;
- break;
- }
- }
- return result;
-}
-
-void SoundInput::start(QAudioDeviceInfo const& device, int framesPerBuffer, AudioDevice * sink
- , unsigned downSampleFactor, AudioDevice::Channel channel)
-{
- Q_ASSERT (sink);
-
- stop ();
-
- m_sink = sink;
-
- QAudioFormat format (device.preferredFormat());
-// qDebug () << "Preferred audio input format:" << format;
- format.setChannelCount (AudioDevice::Mono == channel ? 1 : 2);
- format.setCodec ("audio/pcm");
- format.setSampleRate (12000 * downSampleFactor);
- format.setSampleType (QAudioFormat::SignedInt);
- format.setSampleSize (16);
- format.setByteOrder (QAudioFormat::Endian (QSysInfo::ByteOrder));
- if (!format.isValid ())
- {
- Q_EMIT error (tr ("Requested input audio format is not valid."));
- return;
- }
- else if (!device.isFormatSupported (format))
- {
-// qDebug () << "Nearest supported audio format:" << device.nearestFormat (format);
- Q_EMIT error (tr ("Requested input audio format is not supported on device."));
- return;
- }
- // qDebug () << "Selected audio input format:" << format;
-
- m_stream.reset (new QAudioInput {device, format});
- if (!checkStream ())
- {
- return;
- }
-
- connect (m_stream.data(), &QAudioInput::stateChanged, this, &SoundInput::handleStateChanged);
- connect (m_stream.data(), &QAudioInput::notify, [this] () {checkStream ();});
-
- //qDebug () << "SoundIn default buffer size (bytes):" << m_stream->bufferSize () << "period size:" << m_stream->periodSize ();
- // the Windows MME version of QAudioInput uses 1/5 of the buffer
- // size for period size other platforms seem to optimize themselves
- if (framesPerBuffer > 0)
- {
- m_stream->setBufferSize (m_stream->format ().bytesForFrames (framesPerBuffer));
- }
- if (m_sink->initialize (QIODevice::WriteOnly, channel))
- {
- m_stream->start (sink);
- checkStream ();
- cummulative_lost_usec_ = -1;
-// LOG_DEBUG ("Selected buffer size (bytes): " << m_stream->bufferSize () << " period size: " << m_stream->periodSize ());
- }
- else
- {
- Q_EMIT error (tr ("Failed to initialize audio sink device"));
- }
-}
-
-void SoundInput::suspend ()
-{
- if (m_stream)
- {
- m_stream->suspend ();
- checkStream ();
- }
-}
-
-void SoundInput::resume ()
-{
-// qDebug() << "Resume" << fmod(0.001*QDateTime::currentMSecsSinceEpoch(),6.0);
- if (m_sink)
- {
- m_sink->reset ();
- }
-
- if (m_stream)
- {
- m_stream->resume ();
- checkStream ();
- }
-}
-
-void SoundInput::handleStateChanged (QAudio::State newState)
-{
- switch (newState)
- {
- case QAudio::IdleState:
- Q_EMIT status (tr ("Idle"));
- break;
-
- case QAudio::ActiveState:
- reset (false);
- Q_EMIT status (tr ("Receiving"));
- break;
-
- case QAudio::SuspendedState:
- Q_EMIT status (tr ("Suspended"));
- break;
-
-#if QT_VERSION >= QT_VERSION_CHECK (5, 10, 0)
- case QAudio::InterruptedState:
- Q_EMIT status (tr ("Interrupted"));
- break;
-#endif
-
- case QAudio::StoppedState:
- if (!checkStream ())
- {
- Q_EMIT status (tr ("Error"));
- }
- else
- {
- Q_EMIT status (tr ("Stopped"));
- }
- break;
- }
-}
-
-void SoundInput::reset (bool report_dropped_frames)
-{
- if (m_stream)
- {
- auto elapsed_usecs = m_stream->elapsedUSecs ();
- while (std::abs (elapsed_usecs - m_stream->processedUSecs ())
- > 24 * 60 * 60 * 500000ll) // half day
- {
- // QAudioInput::elapsedUSecs() wraps after 24 hours
- elapsed_usecs += 24 * 60 * 60 * 1000000ll;
- }
- // don't report first time as we don't yet known latency
- if (cummulative_lost_usec_ != std::numeric_limits<qint64>::min () && report_dropped_frames)
- {
- auto lost_usec = elapsed_usecs - m_stream->processedUSecs () - cummulative_lost_usec_;
- // disable log warnings on dropped audio for now, as detection is not reliable
-// if (std::abs (lost_usec) > 48000 / 5)
-// {
-// LOG_WARN ("Detected dropped audio source samples: "
-// << m_stream->format ().framesForDuration (lost_usec)
-// << " (" << std::setprecision (4) << lost_usec / 1.e6 << " S)");
-// }
-// else if (std::abs (lost_usec) > 5 * 48000)
- if (std::abs (lost_usec) > 5 * 48000)
- {
- LOG_ERROR ("Detected excessive dropped audio source samples: "
- << m_stream->format ().framesForDuration (lost_usec)
- << " (" << std::setprecision (4) << lost_usec / 1.e6 << " S)");
- }
- }
- cummulative_lost_usec_ = elapsed_usecs - m_stream->processedUSecs ();
- }
-}
-
-void SoundInput::stop()
-{
- if (m_stream)
- {
- m_stream->stop ();
- }
- m_stream.reset ();
-}
-
-SoundInput::~SoundInput ()
-{
- stop ();
-}
+#include "soundin.h"
+
+#include <cstdlib>
+#include <cmath>
+#include <iomanip>
+#include <QAudioDeviceInfo>
+#include <QAudioFormat>
+#include <QAudioInput>
+#include <QSysInfo>
+#include <QDebug>
+
+#include "Logger.hpp"
+
+#include "moc_soundin.cpp"
+
+bool SoundInput::checkStream ()
+{
+ bool result (false);
+ if (m_stream)
+ {
+ switch (m_stream->error ())
+ {
+ case QAudio::OpenError:
+ Q_EMIT error (tr ("An error opening the audio input device has occurred."));
+ break;
+
+ case QAudio::IOError:
+ Q_EMIT error (tr ("An error occurred during read from the audio input device."));
+ break;
+
+ // case QAudio::UnderrunError:
+ // Q_EMIT error (tr ("Audio data not being fed to the audio input device fast enough."));
+ // break;
+
+ case QAudio::FatalError:
+ Q_EMIT error (tr ("Non-recoverable error, audio input device not usable at this time."));
+ break;
+
+ case QAudio::UnderrunError: // TODO G4WJS: stop ignoring this
+ // when we find the cause on macOS
+ case QAudio::NoError:
+ result = true;
+ break;
+ }
+ }
+ return result;
+}
+
+void SoundInput::start(QAudioDeviceInfo const& device, int framesPerBuffer, AudioDevice * sink
+ , unsigned downSampleFactor, AudioDevice::Channel channel)
+{
+ Q_ASSERT (sink);
+
+ stop ();
+
+ m_sink = sink;
+
+ QAudioFormat format (device.preferredFormat());
+// qDebug () << "Preferred audio input format:" << format;
+ format.setChannelCount (AudioDevice::Mono == channel ? 1 : 2);
+ format.setCodec ("audio/pcm");
+ format.setSampleRate (12000 * downSampleFactor);
+ format.setSampleType (QAudioFormat::SignedInt);
+ format.setSampleSize (16);
+ format.setByteOrder (QAudioFormat::Endian (QSysInfo::ByteOrder));
+ if (!format.isValid ())
+ {
+ Q_EMIT error (tr ("Requested input audio format is not valid."));
+ return;
+ }
+ else if (!device.isFormatSupported (format))
+ {
+// qDebug () << "Nearest supported audio format:" << device.nearestFormat (format);
+ Q_EMIT error (tr ("Requested input audio format is not supported on device."));
+ return;
+ }
+ // qDebug () << "Selected audio input format:" << format;
+
+ m_stream.reset (new QAudioInput {device, format});
+ if (!checkStream ())
+ {
+ return;
+ }
+
+ connect (m_stream.data(), &QAudioInput::stateChanged, this, &SoundInput::handleStateChanged);
+ connect (m_stream.data(), &QAudioInput::notify, [this] () {checkStream ();});
+
+ //qDebug () << "SoundIn default buffer size (bytes):" << m_stream->bufferSize () << "period size:" << m_stream->periodSize ();
+ // the Windows MME version of QAudioInput uses 1/5 of the buffer
+ // size for period size other platforms seem to optimize themselves
+ if (framesPerBuffer > 0)
+ {
+ m_stream->setBufferSize (m_stream->format ().bytesForFrames (framesPerBuffer));
+ }
+ if (m_sink->initialize (QIODevice::WriteOnly, channel))
+ {
+ m_stream->start (sink);
+ checkStream ();
+ cummulative_lost_usec_ = -1;
+// LOG_DEBUG ("Selected buffer size (bytes): " << m_stream->bufferSize () << " period size: " << m_stream->periodSize ());
+ }
+ else
+ {
+ Q_EMIT error (tr ("Failed to initialize audio sink device"));
+ }
+}
+
+void SoundInput::suspend ()
+{
+ if (m_stream)
+ {
+ m_stream->suspend ();
+ checkStream ();
+ }
+}
+
+void SoundInput::resume ()
+{
+// qDebug() << "Resume" << fmod(0.001*QDateTime::currentMSecsSinceEpoch(),6.0);
+ if (m_sink)
+ {
+ m_sink->reset ();
+ }
+
+ if (m_stream)
+ {
+ m_stream->resume ();
+ checkStream ();
+ }
+}
+
+void SoundInput::handleStateChanged (QAudio::State newState)
+{
+ switch (newState)
+ {
+ case QAudio::IdleState:
+ Q_EMIT status (tr ("Idle"));
+ break;
+
+ case QAudio::ActiveState:
+ reset (false);
+ Q_EMIT status (tr ("Receiving"));
+ break;
+
+ case QAudio::SuspendedState:
+ Q_EMIT status (tr ("Suspended"));
+ break;
+
+#if QT_VERSION >= QT_VERSION_CHECK (5, 10, 0)
+ case QAudio::InterruptedState:
+ Q_EMIT status (tr ("Interrupted"));
+ break;
+#endif
+
+ case QAudio::StoppedState:
+ if (!checkStream ())
+ {
+ Q_EMIT status (tr ("Error"));
+ }
+ else
+ {
+ Q_EMIT status (tr ("Stopped"));
+ }
+ break;
+ }
+}
+
+void SoundInput::reset (bool report_dropped_frames)
+{
+ if (m_stream)
+ {
+ auto elapsed_usecs = m_stream->elapsedUSecs ();
+ while (std::abs (elapsed_usecs - m_stream->processedUSecs ())
+ > 24 * 60 * 60 * 500000ll) // half day
+ {
+ // QAudioInput::elapsedUSecs() wraps after 24 hours
+ elapsed_usecs += 24 * 60 * 60 * 1000000ll;
+ }
+ // don't report first time as we don't yet known latency
+ if (cummulative_lost_usec_ != std::numeric_limits<qint64>::min () && report_dropped_frames)
+ {
+ auto lost_usec = elapsed_usecs - m_stream->processedUSecs () - cummulative_lost_usec_;
+ // disable log warnings on dropped audio for now, as detection is not reliable
+// if (std::abs (lost_usec) > 48000 / 5)
+// {
+// LOG_WARN ("Detected dropped audio source samples: "
+// << m_stream->format ().framesForDuration (lost_usec)
+// << " (" << std::setprecision (4) << lost_usec / 1.e6 << " S)");
+// }
+// else if (std::abs (lost_usec) > 5 * 48000)
+ if (std::abs (lost_usec) > 5 * 48000)
+ {
+ LOG_ERROR ("Detected excessive dropped audio source samples: "
+ << m_stream->format ().framesForDuration (lost_usec)
+ << " (" << std::setprecision (4) << lost_usec / 1.e6 << " S)");
+ }
+ }
+ cummulative_lost_usec_ = elapsed_usecs - m_stream->processedUSecs ();
+ }
+}
+
+void SoundInput::stop()
+{
+ if (m_stream)
+ {
+ m_stream->stop ();
+ }
+ m_stream.reset ();
+}
+
+SoundInput::~SoundInput ()
+{
+ stop ();
+}
diff --git a/Audio/soundin.h b/Audio/soundin.h
index dae856e2..823993c6 100755
--- a/Audio/soundin.h
+++ b/Audio/soundin.h
@@ -1,55 +1,55 @@
-// -*- Mode: C++ -*-
-#ifndef SOUNDIN_H__
-#define SOUNDIN_H__
-
-#include <limits>
-#include <QObject>
-#include <QString>
-#include <QDateTime>
-#include <QScopedPointer>
-#include <QPointer>
-#include <QAudioInput>
-
-#include "Audio/AudioDevice.hpp"
-
-class QAudioDeviceInfo;
-class QAudioInput;
-
-// Gets audio data from sound sample source and passes it to a sink device
-class SoundInput
- : public QObject
-{
- Q_OBJECT;
-
-public:
- SoundInput (QObject * parent = nullptr)
- : QObject {parent}
- , cummulative_lost_usec_ {std::numeric_limits<qint64>::min ()}
- {
- }
-
- ~SoundInput ();
-
- // sink must exist from the start call until the next start call or
- // stop call
- Q_SLOT void start(QAudioDeviceInfo const&, int framesPerBuffer, AudioDevice * sink, unsigned downSampleFactor, AudioDevice::Channel = AudioDevice::Mono);
- Q_SLOT void suspend ();
- Q_SLOT void resume ();
- Q_SLOT void stop ();
- Q_SLOT void reset (bool report_dropped_frames);
-
- Q_SIGNAL void error (QString message) const;
- Q_SIGNAL void status (QString message) const;
-
-private:
- // used internally
- Q_SLOT void handleStateChanged (QAudio::State);
-
- bool checkStream ();
-
- QScopedPointer<QAudioInput> m_stream;
- QPointer<AudioDevice> m_sink;
- qint64 cummulative_lost_usec_;
-};
-
-#endif
+// -*- Mode: C++ -*-
+#ifndef SOUNDIN_H__
+#define SOUNDIN_H__
+
+#include <limits>
+#include <QObject>
+#include <QString>
+#include <QDateTime>
+#include <QScopedPointer>
+#include <QPointer>
+#include <QAudioInput>
+
+#include "Audio/AudioDevice.hpp"
+
+class QAudioDeviceInfo;
+class QAudioInput;
+
+// Gets audio data from sound sample source and passes it to a sink device
+class SoundInput
+ : public QObject
+{
+ Q_OBJECT;
+
+public:
+ SoundInput (QObject * parent = nullptr)
+ : QObject {parent}
+ , cummulative_lost_usec_ {std::numeric_limits<qint64>::min ()}
+ {
+ }
+
+ ~SoundInput ();
+
+ // sink must exist from the start call until the next start call or
+ // stop call
+ Q_SLOT void start(QAudioDeviceInfo const&, int framesPerBuffer, AudioDevice * sink, unsigned downSampleFactor, AudioDevice::Channel = AudioDevice::Mono);
+ Q_SLOT void suspend ();
+ Q_SLOT void resume ();
+ Q_SLOT void stop ();
+ Q_SLOT void reset (bool report_dropped_frames);
+
+ Q_SIGNAL void error (QString message) const;
+ Q_SIGNAL void status (QString message) const;
+
+private:
+ // used internally
+ Q_SLOT void handleStateChanged (QAudio::State);
+
+ bool checkStream ();
+
+ QScopedPointer<QAudioInput> m_stream;
+ QPointer<AudioDevice> m_sink;
+ qint64 cummulative_lost_usec_;
+};
+
+#endif
diff --git a/Audio/soundout.cpp b/Audio/soundout.cpp
index b4b7302f..4fad630c 100755
--- a/Audio/soundout.cpp
+++ b/Audio/soundout.cpp
@@ -1,211 +1,216 @@
-#include "soundout.h"
-
-#include <QDateTime>
-#include <QAudioDeviceInfo>
-#include <QAudioOutput>
-#include <QSysInfo>
-#include <qmath.h>
-#include <QDebug>
-
-#include "Logger.hpp"
-#include "Audio/AudioDevice.hpp"
-
-#include "moc_soundout.cpp"
-
-bool SoundOutput::checkStream () const
-{
- bool result {false};
-
- Q_ASSERT_X (m_stream, "SoundOutput", "programming error");
- if (m_stream) {
- switch (m_stream->error ())
- {
- case QAudio::OpenError:
- Q_EMIT error (tr ("An error opening the audio output device has occurred."));
- break;
-
- case QAudio::IOError:
- Q_EMIT error (tr ("An error occurred during write to the audio output device."));
- break;
-
- case QAudio::UnderrunError:
- Q_EMIT error (tr ("Audio data not being fed to the audio output device fast enough."));
- break;
-
- case QAudio::FatalError:
- Q_EMIT error (tr ("Non-recoverable error, audio output device not usable at this time."));
- break;
-
- case QAudio::NoError:
- result = true;
- break;
- }
- }
- return result;
-}
-
-void SoundOutput::setFormat (QAudioDeviceInfo const& device, unsigned channels, int frames_buffered)
-{
- Q_ASSERT (0 < channels && channels < 3);
- m_device = device;
- m_channels = channels;
- m_framesBuffered = frames_buffered;
-}
-
-void SoundOutput::restart (QIODevice * source)
-{
- if (!m_device.isNull ())
- {
- QAudioFormat format (m_device.preferredFormat ());
- // qDebug () << "Preferred audio output format:" << format;
- format.setChannelCount (m_channels);
- format.setCodec ("audio/pcm");
- format.setSampleRate (48000);
- format.setSampleType (QAudioFormat::SignedInt);
- format.setSampleSize (16);
- format.setByteOrder (QAudioFormat::Endian (QSysInfo::ByteOrder));
- if (!format.isValid ())
- {
- Q_EMIT error (tr ("Requested output audio format is not valid."));
- }
- else if (!m_device.isFormatSupported (format))
- {
- Q_EMIT error (tr ("Requested output audio format is not supported on device."));
- }
- else
- {
- // qDebug () << "Selected audio output format:" << format;
- m_stream.reset (new QAudioOutput (m_device, format));
- checkStream ();
- m_stream->setVolume (m_volume);
- m_stream->setNotifyInterval(1000);
- error_ = false;
-
- connect (m_stream.data(), &QAudioOutput::stateChanged, this, &SoundOutput::handleStateChanged);
- connect (m_stream.data(), &QAudioOutput::notify, [this] () {checkStream ();});
-
- // qDebug() << "A" << m_volume << m_stream->notifyInterval();
- }
- }
- if (!m_stream)
- {
- if (!error_)
- {
- error_ = true; // only signal error once
- Q_EMIT error (tr ("No audio output device configured."));
- }
- return;
- }
- else
- {
- error_ = false;
- }
-
- // we have to set this before every start on the stream because the
- // Windows implementation seems to forget the buffer size after a
- // stop.
- //qDebug () << "SoundOut default buffer size (bytes):" << m_stream->bufferSize () << "period size:" << m_stream->periodSize ();
- if (m_framesBuffered > 0)
- {
- m_stream->setBufferSize (m_stream->format().bytesForFrames (m_framesBuffered));
- }
- m_stream->setCategory ("production");
- m_stream->start (source);
-// LOG_DEBUG ("Selected buffer size (bytes): " << m_stream->bufferSize () << " period size: " << m_stream->periodSize ());
-}
-
-void SoundOutput::suspend ()
-{
- if (m_stream && QAudio::ActiveState == m_stream->state ())
- {
- m_stream->suspend ();
- checkStream ();
- }
-}
-
-void SoundOutput::resume ()
-{
- if (m_stream && QAudio::SuspendedState == m_stream->state ())
- {
- m_stream->resume ();
- checkStream ();
- }
-}
-
-void SoundOutput::reset ()
-{
- if (m_stream)
- {
- m_stream->reset ();
- checkStream ();
- }
-}
-
-void SoundOutput::stop ()
-{
- if (m_stream)
- {
- m_stream->reset ();
- m_stream->stop ();
- }
-}
-
-qreal SoundOutput::attenuation () const
-{
- return -(20. * qLn (m_volume) / qLn (10.));
-}
-
-void SoundOutput::setAttenuation (qreal a)
-{
- Q_ASSERT (0. <= a && a <= 999.);
- m_volume = qPow(10.0, -a/20.0);
- // qDebug () << "SoundOut: attn = " << a << ", vol = " << m_volume;
- if (m_stream)
- {
- m_stream->setVolume (m_volume);
- }
-}
-
-void SoundOutput::resetAttenuation ()
-{
- m_volume = 1.;
- if (m_stream)
- {
- m_stream->setVolume (m_volume);
- }
-}
-
-void SoundOutput::handleStateChanged (QAudio::State newState)
-{
- switch (newState)
- {
- case QAudio::IdleState:
- Q_EMIT status (tr ("Idle"));
- break;
-
- case QAudio::ActiveState:
- Q_EMIT status (tr ("Sending"));
- break;
-
- case QAudio::SuspendedState:
- Q_EMIT status (tr ("Suspended"));
- break;
-
-#if QT_VERSION >= QT_VERSION_CHECK (5, 10, 0)
- case QAudio::InterruptedState:
- Q_EMIT status (tr ("Interrupted"));
- break;
-#endif
-
- case QAudio::StoppedState:
- if (!checkStream ())
- {
- Q_EMIT status (tr ("Error"));
- }
- else
- {
- Q_EMIT status (tr ("Stopped"));
- }
- break;
- }
-}
+#include "soundout.h"
+
+#include <QDateTime>
+#include <QAudioDeviceInfo>
+#include <QAudioOutput>
+#include <QSysInfo>
+#include <qmath.h>
+#include <QDebug>
+
+#include "Logger.hpp"
+#include "Audio/AudioDevice.hpp"
+
+#include "moc_soundout.cpp"
+
+bool SoundOutput::checkStream () const
+{
+ bool result {false};
+
+ Q_ASSERT_X (m_stream, "SoundOutput", "programming error");
+ if (m_stream) {
+ switch (m_stream->error ())
+ {
+ case QAudio::OpenError:
+ Q_EMIT error (tr ("An error opening the audio output device has occurred."));
+ break;
+
+ case QAudio::IOError:
+ Q_EMIT error (tr ("An error occurred during write to the audio output device."));
+ break;
+
+ case QAudio::UnderrunError:
+ Q_EMIT error (tr ("Audio data not being fed to the audio output device fast enough."));
+ break;
+
+ case QAudio::FatalError:
+ Q_EMIT error (tr ("Non-recoverable error, audio output device not usable at this time."));
+ break;
+
+ case QAudio::NoError:
+ result = true;
+ break;
+ }
+ }
+ return result;
+}
+
+void SoundOutput::setFormat (QAudioDeviceInfo const& device, unsigned channels, int frames_buffered)
+{
+ Q_ASSERT (0 < channels && channels < 3);
+ m_device = device;
+ m_channels = channels;
+ m_framesBuffered = frames_buffered;
+}
+
+void SoundOutput::restart (QIODevice * source)
+{
+ if (!m_device.isNull ())
+ {
+ QAudioFormat format (m_device.preferredFormat ());
+ // qDebug () << "Preferred audio output format:" << format;
+ format.setChannelCount (m_channels);
+ format.setCodec ("audio/pcm");
+ format.setSampleRate (48000);
+ format.setSampleType (QAudioFormat::SignedInt);
+ format.setSampleSize (16);
+ format.setByteOrder (QAudioFormat::Endian (QSysInfo::ByteOrder));
+ if (!format.isValid ())
+ {
+ Q_EMIT error (tr ("Requested output audio format is not valid."));
+ }
+ else if (!m_device.isFormatSupported (format))
+ {
+ Q_EMIT error (tr ("Requested output audio format is not supported on device."));
+ }
+ else
+ {
+ // qDebug () << "Selected audio output format:" << format;
+ m_stream.reset (new QAudioOutput (m_device, format));
+ checkStream ();
+ m_stream->setVolume (m_volume);
+ m_stream->setNotifyInterval(1000);
+ error_ = false;
+
+ connect (m_stream.data(), &QAudioOutput::stateChanged, this, &SoundOutput::handleStateChanged);
+ connect (m_stream.data(), &QAudioOutput::notify, [this] () {checkStream ();});
+
+ // qDebug() << "A" << m_volume << m_stream->notifyInterval();
+ }
+ }
+ if (!m_stream)
+ {
+ if (!error_)
+ {
+ error_ = true; // only signal error once
+ Q_EMIT error (tr ("No audio output device configured."));
+ }
+ return;
+ }
+ else
+ {
+ error_ = false;
+ }
+
+ // we have to set this before every start on the stream because the
+ // Windows implementation seems to forget the buffer size after a
+ // stop.
+ //qDebug () << "SoundOut default buffer size (bytes):" << m_stream->bufferSize () << "period size:" << m_stream->periodSize ();
+ if (m_framesBuffered > 0)
+ {
+ m_stream->setBufferSize (m_stream->format().bytesForFrames (m_framesBuffered));
+ }
+ m_stream->setCategory ("production");
+ m_stream->start (source);
+// LOG_DEBUG ("Selected buffer size (bytes): " << m_stream->bufferSize () << " period size: " << m_stream->periodSize ());
+}
+
+void SoundOutput::suspend ()
+{
+ if (m_stream && QAudio::ActiveState == m_stream->state ())
+ {
+ m_stream->suspend ();
+ checkStream ();
+ }
+}
+
+void SoundOutput::resume ()
+{
+ if (m_stream && QAudio::SuspendedState == m_stream->state ())
+ {
+ m_stream->resume ();
+ checkStream ();
+ }
+}
+
+void SoundOutput::reset ()
+{
+ if (m_stream)
+ {
+ m_stream->reset ();
+ checkStream ();
+ }
+}
+
+void SoundOutput::stop ()
+{
+ if (m_stream)
+ {
+ m_stream->reset ();
+ m_stream->stop ();
+ }
+#ifdef __APPLE__
+ // this code is here to help certain rigs not drop audio, however on Sequoia this causes audio to drop, so we don't do it!
+ if( QOperatingSystemVersion::current() < QOperatingSystemVersion(QOperatingSystemVersion::MacOS, 15) )
+ m_stream.reset ();
+#endif
+}
+
+qreal SoundOutput::attenuation () const
+{
+ return -(20. * qLn (m_volume) / qLn (10.));
+}
+
+void SoundOutput::setAttenuation (qreal a)
+{
+ Q_ASSERT (0. <= a && a <= 999.);
+ m_volume = qPow(10.0, -a/20.0);
+ // qDebug () << "SoundOut: attn = " << a << ", vol = " << m_volume;
+ if (m_stream)
+ {
+ m_stream->setVolume (m_volume);
+ }
+}
+
+void SoundOutput::resetAttenuation ()
+{
+ m_volume = 1.;
+ if (m_stream)
+ {
+ m_stream->setVolume (m_volume);
+ }
+}
+
+void SoundOutput::handleStateChanged (QAudio::State newState)
+{
+ switch (newState)
+ {
+ case QAudio::IdleState:
+ Q_EMIT status (tr ("Idle"));
+ break;
+
+ case QAudio::ActiveState:
+ Q_EMIT status (tr ("Sending"));
+ break;
+
+ case QAudio::SuspendedState:
+ Q_EMIT status (tr ("Suspended"));
+ break;
+
+#if QT_VERSION >= QT_VERSION_CHECK (5, 10, 0)
+ case QAudio::InterruptedState:
+ Q_EMIT status (tr ("Interrupted"));
+ break;
+#endif
+
+ case QAudio::StoppedState:
+ if (!checkStream ())
+ {
+ Q_EMIT status (tr ("Error"));
+ }
+ else
+ {
+ Q_EMIT status (tr ("Stopped"));
+ }
+ break;
+ }
+}
diff --git a/Audio/soundout.h b/Audio/soundout.h
index 8bc06e7c..387c1b0f 100755
--- a/Audio/soundout.h
+++ b/Audio/soundout.h
@@ -1,59 +1,60 @@
-// -*- Mode: C++ -*-
-#ifndef SOUNDOUT_H__
-#define SOUNDOUT_H__
-
-#include <QObject>
-#include <QString>
-#include <QAudioOutput>
-#include <QAudioDeviceInfo>
-
-class QIODevice;
-class QAudioDeviceInfo;
-
-// An instance of this sends audio data to a specified soundcard.
-
-class SoundOutput
- : public QObject
-{
- Q_OBJECT;
-
-public:
- SoundOutput ()
- : m_framesBuffered {0}
- , m_volume {1.0}
- , error_ {false}
- {
- }
-
- qreal attenuation () const;
-
-public Q_SLOTS:
- void setFormat (QAudioDeviceInfo const& device, unsigned channels, int frames_buffered = 0);
- void restart (QIODevice *);
- void suspend ();
- void resume ();
- void reset ();
- void stop ();
- void setAttenuation (qreal); /* unsigned */
- void resetAttenuation (); /* to zero */
-
-Q_SIGNALS:
- void error (QString message) const;
- void status (QString message) const;
-
-private:
- bool checkStream () const;
-
-private Q_SLOTS:
- void handleStateChanged (QAudio::State);
-
-private:
- QAudioDeviceInfo m_device;
- unsigned m_channels;
- QScopedPointer<QAudioOutput> m_stream;
- int m_framesBuffered;
- qreal m_volume;
- bool error_;
-};
-
-#endif
+// -*- Mode: C++ -*-
+#ifndef SOUNDOUT_H__
+#define SOUNDOUT_H__
+
+#include <QObject>
+#include <QString>
+#include <QAudioOutput>
+#include <QAudioDeviceInfo>
+#include <QOperatingSystemVersion>
+
+class QIODevice;
+class QAudioDeviceInfo;
+
+// An instance of this sends audio data to a specified soundcard.
+
+class SoundOutput
+ : public QObject
+{
+ Q_OBJECT;
+
+public:
+ SoundOutput ()
+ : m_framesBuffered {0}
+ , m_volume {1.0}
+ , error_ {false}
+ {
+ }
+
+ qreal attenuation () const;
+
+public Q_SLOTS:
+ void setFormat (QAudioDeviceInfo const& device, unsigned channels, int frames_buffered = 0);
+ void restart (QIODevice *);
+ void suspend ();
+ void resume ();
+ void reset ();
+ void stop ();
+ void setAttenuation (qreal); /* unsigned */
+ void resetAttenuation (); /* to zero */
+
+Q_SIGNALS:
+ void error (QString message) const;
+ void status (QString message) const;
+
+private:
+ bool checkStream () const;
+
+private Q_SLOTS:
+ void handleStateChanged (QAudio::State);
+
+private:
+ QAudioDeviceInfo m_device;
+ unsigned m_channels;
+ QScopedPointer<QAudioOutput> m_stream;
+ int m_framesBuffered;
+ qreal m_volume;
+ bool error_;
+};
+
+#endif
diff --git a/Audio/tools/record_time_signal.cpp b/Audio/tools/record_time_signal.cpp
index 6946eef8..985fb00b 100755
--- a/Audio/tools/record_time_signal.cpp
+++ b/Audio/tools/record_time_signal.cpp
@@ -1,460 +1,460 @@
-#include <iostream>
-#include <exception>
-#include <stdexcept>
-#include <string>
-#include <memory>
-#include <locale>
-
-#include <QCoreApplication>
-#include <QTextStream>
-#include <QCommandLineParser>
-#include <QCommandLineOption>
-#include <QStringList>
-#include <QFileInfo>
-#include <QAudioFormat>
-#include <QAudioDeviceInfo>
-#include <QAudioInput>
-#include <QAudioOutput>
-#include <QTimer>
-#include <QDateTime>
-#include <QDebug>
-
-#include "revision_utils.hpp"
-#include "Audio/BWFFile.hpp"
-
-namespace
-{
- QTextStream qtout {stdout};
-}
-
-class Record final
- : public QObject
-{
- Q_OBJECT;
-
-public:
- Record (int start, int duration, QAudioDeviceInfo const& source_device, BWFFile * output, int notify_interval, int buffer_size)
- : source_ {source_device, output->format ()}
- , notify_interval_ {notify_interval}
- , output_ {output}
- , duration_ {duration}
- {
- if (buffer_size) source_.setBufferSize (output_->format ().bytesForFrames (buffer_size));
- if (notify_interval_)
- {
- source_.setNotifyInterval (notify_interval);
- connect (&source_, &QAudioInput::notify, this, &Record::notify);
- }
-
- if (start == -1)
- {
- start_recording ();
- }
- else
- {
- auto now = QDateTime::currentDateTimeUtc ();
- auto time = now.time ();
- auto then = now;
- then.setTime (QTime {time.hour (), time.minute (), start});
- auto delta_ms = (now.msecsTo (then) + (60 * 1000)) % (60 * 1000);
- QTimer::singleShot (int (delta_ms), Qt::PreciseTimer, this, &Record::start_recording);
- }
- }
-
- Q_SIGNAL void done ();
-
-private:
- Q_SLOT void start_recording ()
- {
- qtout << "started recording at " << QDateTime::currentDateTimeUtc ().toString ("hh:mm:ss.zzz UTC")
-#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
- << Qt::endl
-#else
- << endl
-#endif
- ;
- source_.start (output_);
- if (!notify_interval_) QTimer::singleShot (duration_ * 1000, Qt::PreciseTimer, this, &Record::stop_recording);
- qtout << QString {"buffer size used is: %1"}.arg (source_.bufferSize ())
-#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
- << Qt::endl
-#else
- << endl
-#endif
- ;
- }
-
- Q_SLOT void notify ()
- {
- auto length = source_.elapsedUSecs ();
- qtout << QString {"%1 μs recorded\r"}.arg (length)
-#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
- << Qt::flush
-#else
- << flush
-#endif
- ;
- if (length >= duration_ * 1000 * 1000) stop_recording ();
- }
-
- Q_SLOT void stop_recording ()
- {
- auto length = source_.elapsedUSecs ();
- source_.stop ();
- qtout << QString {"%1 μs recorded "}.arg (length) << '(' << source_.format ().framesForBytes (output_->size ()) << " frames recorded)\n";
- qtout << "stopped recording at " << QDateTime::currentDateTimeUtc ().toString ("hh:mm:ss.zzz UTC")
-#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
- << Qt::endl
-#else
- << endl
-#endif
- ;
- Q_EMIT done ();
- }
-
- QAudioInput source_;
- int notify_interval_;
- BWFFile * output_;
- int duration_;
-};
-
-class Playback final
- : public QObject
-{
- Q_OBJECT;
-
-public:
- Playback (int start, BWFFile * input, QAudioDeviceInfo const& sink_device, int notify_interval, int buffer_size, QString const& category)
- : input_ {input}
- , sink_ {sink_device, input->format ()}
- , notify_interval_ {notify_interval}
- {
- if (buffer_size) sink_.setBufferSize (input_->format ().bytesForFrames (buffer_size));
- if (category.size ()) sink_.setCategory (category);
- if (notify_interval_)
- {
- sink_.setNotifyInterval (notify_interval);
- connect (&sink_, &QAudioOutput::notify, this, &Playback::notify);
- }
- connect (&sink_, &QAudioOutput::stateChanged, this, &Playback::sink_state_changed);
- if (start == -1)
- {
- start_playback ();
- }
- else
- {
- auto now = QDateTime::currentDateTimeUtc ();
- auto time = now.time ();
- auto then = now;
- then.setTime (QTime {time.hour (), time.minute (), start});
- auto delta_ms = (now.msecsTo (then) + (60 * 1000)) % (60 * 1000);
- QTimer::singleShot (int (delta_ms), Qt::PreciseTimer, this, &Playback::start_playback);
- }
- }
-
- Q_SIGNAL void done ();
-
-private:
- Q_SLOT void start_playback ()
- {
- qtout << "started playback at " << QDateTime::currentDateTimeUtc ().toString ("hh:mm:ss.zzz UTC")
-#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
- << Qt::endl
-#else
- << endl
-#endif
- ;
- sink_.start (input_);
- qtout << QString {"buffer size used is: %1 (%2 frames)"}.arg (sink_.bufferSize ()).arg (sink_.format ().framesForBytes (sink_.bufferSize ()))
-#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
- << Qt::endl
-#else
- << endl
-#endif
- ;
- }
-
- Q_SLOT void notify ()
- {
- auto length = sink_.elapsedUSecs ();
- qtout << QString {"%1 μs rendered\r"}.arg (length) <<
-#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
- Qt::flush
-#else
- flush
-#endif
- ;
- }
-
- Q_SLOT void sink_state_changed (QAudio::State state)
- {
- switch (state)
- {
- case QAudio::ActiveState:
- qtout << "\naudio output state changed to active\n";
- break;
- case QAudio::SuspendedState:
- qtout << "\naudio output state changed to suspended\n";
- break;
- case QAudio::StoppedState:
- qtout << "\naudio output state changed to stopped\n";
- break;
- case QAudio::IdleState:
- stop_playback ();
- qtout << "\naudio output state changed to idle\n";
- break;
-#if QT_VERSION >= QT_VERSION_CHECK (5, 10, 0)
- case QAudio::InterruptedState:
- qtout << "\naudio output state changed to interrupted\n";
- break;
-#endif
- }
- }
-
- Q_SLOT void stop_playback ()
- {
- auto length = sink_.elapsedUSecs ();
- sink_.stop ();
- qtout << QString {"%1 μs rendered "}.arg (length) << '(' << sink_.format ().framesForBytes (input_->size ()) << " frames rendered)\n";
- qtout << "stopped playback at " << QDateTime::currentDateTimeUtc ().toString ("hh:mm:ss.zzz UTC")
-#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
- << Qt::endl
-#else
- << endl
-#endif
- ;
- Q_EMIT done ();
- }
-
- BWFFile * input_;
- QAudioOutput sink_;
- int notify_interval_;
-};
-
-#include "record_time_signal.moc"
-
-int main(int argc, char *argv[])
-{
- QCoreApplication app {argc, argv};
- try
- {
- // ensure number forms are in consistent format, do this after
- // instantiating QApplication so that Qt has correct l18n
- std::locale::global (std::locale::classic ());
-
- // Override programs executable basename as application name.
- app.setApplicationName ("WSJT-X Record Time Signal");
- app.setApplicationVersion (version ());
-
- QCommandLineParser parser;
- parser.setApplicationDescription (
- "\nTool to determine and experiment with QAudioInput latencies\n\n"
- "\tUse the -I option to list available recording device numbers\n"
- );
- auto help_option = parser.addHelpOption ();
- auto version_option = parser.addVersionOption ();
-
- parser.addOptions ({
- {{"I", "list-audio-inputs"},
- app.translate ("main", "List the available audio input devices")},
- {{"O", "list-audio-outputs"},
- app.translate ("main", "List the available audio output devices")},
- {{"s", "start-time"},
- app.translate ("main", "Record from <start-time> seconds, default start immediately"),
- app.translate ("main", "start-time")},
- {{"d", "duration"},
- app.translate ("main", "Recording <duration> seconds"),
- app.translate ("main", "duration")},
- {{"o", "output"},
- app.translate ("main", "Save output as <output-file>"),
- app.translate ("main", "output-file")},
- {{"i", "input"},
- app.translate ("main", "Playback <input-file>"),
- app.translate ("main", "input-file")},
- {{"f", "force"},
- app.translate ("main", "Overwrite existing file")},
- {{"r", "sample-rate"},
- app.translate ("main", "Record at <sample-rate>, default 48000 Hz"),
- app.translate ("main", "sample-rate")},
- {{"c", "num-channels"},
- app.translate ("main", "Record <num> channels, default 2"),
- app.translate ("main", "num")},
- {{"R", "recording-device-number"},
- app.translate ("main", "Record from <device-number>"),
- app.translate ("main", "device-number")},
- {{"P", "playback-device-number"},
- app.translate ("main", "Playback to <device-number>"),
- app.translate ("main", "device-number")},
- {{"C", "category"},
- app.translate ("main", "Playback <category-name>"),
- app.translate ("main", "category-name")},
- {{"n", "notify-interval"},
- app.translate ("main", "use notify signals every <interval> milliseconds, zero to use a timer"),
- app.translate ("main", "interval")},
- {{"b", "buffer-size"},
- app.translate ("main", "audio buffer size <frames>"),
- app.translate ("main", "frames")},
- });
- parser.process (app);
-
- auto input_devices = QAudioDeviceInfo::availableDevices (QAudio::AudioInput);
- if (parser.isSet ("I"))
- {
- int n {0};
- for (auto const& device : input_devices)
- {
- qtout << ++n << " - [" << device.deviceName () << ']'
-#if QT_VERSION >= QT_VERSION_CHECK (5, 15, 0)
- << Qt::endl
-#else
- << endl
-#endif
- ;
- }
- return 0;
- }
-
- auto output_devices = QAudioDeviceInfo::availableDevices (QAudio::AudioOutput);
- if (parser.isSet ("O"))
- {
- int n {0};
- for (auto const& device : output_devices)
- {
- qtout << ++n << " - [" << device.deviceName () << ']'
-#if QT_VERSION >= QT_VERSION_CHECK (5, 15, 0)
- << Qt::endl
-#else
- << endl
-#endif
- ;
- }
- return 0;
- }
-
- bool ok;
- int start {-1};
- if (parser.isSet ("s"))
- {
- start = parser.value ("s").toInt (&ok);
- if (!ok) throw std::invalid_argument {"start time not a number"};
- if (0 > start || start > 59) throw std::invalid_argument {"0 > start > 59"};
- }
- int sample_rate {48000};
- if (parser.isSet ("r"))
- {
- sample_rate = parser.value ("r").toInt (&ok);
- if (!ok) throw std::invalid_argument {"sample rate not a number"};
- }
- int num_channels {2};
- if (parser.isSet ("c"))
- {
- num_channels = parser.value ("c").toInt (&ok);
- if (!ok) throw std::invalid_argument {"channel count not a number"};
- }
- int notify_interval {0};
- if (parser.isSet ("n"))
- {
- notify_interval = parser.value ("n").toInt (&ok);
- if (!ok) throw std::invalid_argument {"notify interval not a number"};
- }
- int buffer_size {0};
- if (parser.isSet ("b"))
- {
- buffer_size = parser.value ("b").toInt (&ok);
- if (!ok) throw std::invalid_argument {"buffer size not a number"};
- }
- int input_device {0};
- if (parser.isSet ("R"))
- {
- input_device = parser.value ("R").toInt (&ok);
- if (!ok || 0 >= input_device || input_device > input_devices.size ())
- {
- throw std::invalid_argument {"invalid recording device"};
- }
- }
- int output_device {0};
- if (parser.isSet ("P"))
- {
- output_device = parser.value ("P").toInt (&ok);
- if (!ok || 0 >= output_device || output_device > output_devices.size ())
- {
- throw std::invalid_argument {"invalid playback device"};
- }
- }
- if (!(parser.isSet ("o") || parser.isSet ("i"))) throw std::invalid_argument {"file required"};
- if (parser.isSet ("o") && parser.isSet ("i")) throw std::invalid_argument {"specify either input or output"};
-
- QAudioFormat audio_format;
- if (parser.isSet ("o")) // Record
- {
- int duration = parser.value ("d").toInt (&ok);
- if (!ok) throw std::invalid_argument {"duration not a number"};
-
- QFileInfo ofi {parser.value ("o")};
- if (!ofi.suffix ().size () && ofi.fileName ()[ofi.fileName ().size () - 1] != QChar {'.'})
- {
- ofi.setFile (ofi.filePath () + ".wav");
- }
- if (!parser.isSet ("f") && ofi.isFile ())
- {
- throw std::invalid_argument {"set the `-force' option to overwrite an existing output file"};
- }
-
- audio_format.setSampleRate (sample_rate);
- audio_format.setChannelCount (num_channels);
- audio_format.setSampleSize (16);
- audio_format.setSampleType (QAudioFormat::SignedInt);
- audio_format.setCodec ("audio/pcm");
-
- auto source = input_device ? input_devices[input_device - 1] : QAudioDeviceInfo::defaultInputDevice ();
- if (!source.isFormatSupported (audio_format))
- {
- qtout << "warning, requested format not supported, using nearest"
-#if QT_VERSION >= QT_VERSION_CHECK (5, 15, 0)
- << Qt::endl
-#else
- << endl
-#endif
- ;
- audio_format = source.nearestFormat (audio_format);
- }
- BWFFile output_file {audio_format, ofi.filePath ()};
- if (!output_file.open (BWFFile::WriteOnly)) throw std::invalid_argument {QString {"cannot open output file \"%1\""}.arg (ofi.filePath ()).toStdString ()};
-
- // run the application
- Record record {start, duration, source, &output_file, notify_interval, buffer_size};
- QObject::connect (&record, &Record::done, &app, &QCoreApplication::quit);
- return app.exec();
- }
- else // Playback
- {
- QFileInfo ifi {parser.value ("i")};
- if (!ifi.isFile () && !ifi.suffix ().size () && ifi.fileName ()[ifi.fileName ().size () - 1] != QChar {'.'})
- {
- ifi.setFile (ifi.filePath () + ".wav");
- }
- BWFFile input_file {audio_format, ifi.filePath ()};
- if (!input_file.open (BWFFile::ReadOnly)) throw std::invalid_argument {QString {"cannot open input file \"%1\""}.arg (ifi.filePath ()).toStdString ()};
- auto sink = output_device ? output_devices[output_device - 1] : QAudioDeviceInfo::defaultOutputDevice ();
- if (!sink.isFormatSupported (input_file.format ()))
- {
- throw std::invalid_argument {"audio output device does not support input file audio format"};
- }
-
- // run the application
- Playback play {start, &input_file, sink, notify_interval, buffer_size, parser.value ("category")};
- QObject::connect (&play, &Playback::done, &app, &QCoreApplication::quit);
- return app.exec();
- }
- }
- catch (std::exception const& e)
- {
- std::cerr << "Error: " << e.what () << '\n';
- }
- catch (...)
- {
- std::cerr << "Unexpected fatal error\n";
- throw; // hoping the runtime might tell us more about the exception
- }
- return -1;
-}
+#include <iostream>
+#include <exception>
+#include <stdexcept>
+#include <string>
+#include <memory>
+#include <locale>
+
+#include <QCoreApplication>
+#include <QTextStream>
+#include <QCommandLineParser>
+#include <QCommandLineOption>
+#include <QStringList>
+#include <QFileInfo>
+#include <QAudioFormat>
+#include <QAudioDeviceInfo>
+#include <QAudioInput>
+#include <QAudioOutput>
+#include <QTimer>
+#include <QDateTime>
+#include <QDebug>
+
+#include "revision_utils.hpp"
+#include "Audio/BWFFile.hpp"
+
+namespace
+{
+ QTextStream qtout {stdout};
+}
+
+class Record final
+ : public QObject
+{
+ Q_OBJECT;
+
+public:
+ Record (int start, int duration, QAudioDeviceInfo const& source_device, BWFFile * output, int notify_interval, int buffer_size)
+ : source_ {source_device, output->format ()}
+ , notify_interval_ {notify_interval}
+ , output_ {output}
+ , duration_ {duration}
+ {
+ if (buffer_size) source_.setBufferSize (output_->format ().bytesForFrames (buffer_size));
+ if (notify_interval_)
+ {
+ source_.setNotifyInterval (notify_interval);
+ connect (&source_, &QAudioInput::notify, this, &Record::notify);
+ }
+
+ if (start == -1)
+ {
+ start_recording ();
+ }
+ else
+ {
+ auto now = QDateTime::currentDateTimeUtc ();
+ auto time = now.time ();
+ auto then = now;
+ then.setTime (QTime {time.hour (), time.minute (), start});
+ auto delta_ms = (now.msecsTo (then) + (60 * 1000)) % (60 * 1000);
+ QTimer::singleShot (int (delta_ms), Qt::PreciseTimer, this, &Record::start_recording);
+ }
+ }
+
+ Q_SIGNAL void done ();
+
+private:
+ Q_SLOT void start_recording ()
+ {
+ qtout << "started recording at " << QDateTime::currentDateTimeUtc ().toString ("hh:mm:ss.zzz UTC")
+#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
+ << Qt::endl
+#else
+ << endl
+#endif
+ ;
+ source_.start (output_);
+ if (!notify_interval_) QTimer::singleShot (duration_ * 1000, Qt::PreciseTimer, this, &Record::stop_recording);
+ qtout << QString {"buffer size used is: %1"}.arg (source_.bufferSize ())
+#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
+ << Qt::endl
+#else
+ << endl
+#endif
+ ;
+ }
+
+ Q_SLOT void notify ()
+ {
+ auto length = source_.elapsedUSecs ();
+ qtout << QString {"%1 μs recorded\r"}.arg (length)
+#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
+ << Qt::flush
+#else
+ << flush
+#endif
+ ;
+ if (length >= duration_ * 1000 * 1000) stop_recording ();
+ }
+
+ Q_SLOT void stop_recording ()
+ {
+ auto length = source_.elapsedUSecs ();
+ source_.stop ();
+ qtout << QString {"%1 μs recorded "}.arg (length) << '(' << source_.format ().framesForBytes (output_->size ()) << " frames recorded)\n";
+ qtout << "stopped recording at " << QDateTime::currentDateTimeUtc ().toString ("hh:mm:ss.zzz UTC")
+#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
+ << Qt::endl
+#else
+ << endl
+#endif
+ ;
+ Q_EMIT done ();
+ }
+
+ QAudioInput source_;
+ int notify_interval_;
+ BWFFile * output_;
+ int duration_;
+};
+
+class Playback final
+ : public QObject
+{
+ Q_OBJECT;
+
+public:
+ Playback (int start, BWFFile * input, QAudioDeviceInfo const& sink_device, int notify_interval, int buffer_size, QString const& category)
+ : input_ {input}
+ , sink_ {sink_device, input->format ()}
+ , notify_interval_ {notify_interval}
+ {
+ if (buffer_size) sink_.setBufferSize (input_->format ().bytesForFrames (buffer_size));
+ if (category.size ()) sink_.setCategory (category);
+ if (notify_interval_)
+ {
+ sink_.setNotifyInterval (notify_interval);
+ connect (&sink_, &QAudioOutput::notify, this, &Playback::notify);
+ }
+ connect (&sink_, &QAudioOutput::stateChanged, this, &Playback::sink_state_changed);
+ if (start == -1)
+ {
+ start_playback ();
+ }
+ else
+ {
+ auto now = QDateTime::currentDateTimeUtc ();
+ auto time = now.time ();
+ auto then = now;
+ then.setTime (QTime {time.hour (), time.minute (), start});
+ auto delta_ms = (now.msecsTo (then) + (60 * 1000)) % (60 * 1000);
+ QTimer::singleShot (int (delta_ms), Qt::PreciseTimer, this, &Playback::start_playback);
+ }
+ }
+
+ Q_SIGNAL void done ();
+
+private:
+ Q_SLOT void start_playback ()
+ {
+ qtout << "started playback at " << QDateTime::currentDateTimeUtc ().toString ("hh:mm:ss.zzz UTC")
+#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
+ << Qt::endl
+#else
+ << endl
+#endif
+ ;
+ sink_.start (input_);
+ qtout << QString {"buffer size used is: %1 (%2 frames)"}.arg (sink_.bufferSize ()).arg (sink_.format ().framesForBytes (sink_.bufferSize ()))
+#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
+ << Qt::endl
+#else
+ << endl
+#endif
+ ;
+ }
+
+ Q_SLOT void notify ()
+ {
+ auto length = sink_.elapsedUSecs ();
+ qtout << QString {"%1 μs rendered\r"}.arg (length) <<
+#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
+ Qt::flush
+#else
+ flush
+#endif
+ ;
+ }
+
+ Q_SLOT void sink_state_changed (QAudio::State state)
+ {
+ switch (state)
+ {
+ case QAudio::ActiveState:
+ qtout << "\naudio output state changed to active\n";
+ break;
+ case QAudio::SuspendedState:
+ qtout << "\naudio output state changed to suspended\n";
+ break;
+ case QAudio::StoppedState:
+ qtout << "\naudio output state changed to stopped\n";
+ break;
+ case QAudio::IdleState:
+ stop_playback ();
+ qtout << "\naudio output state changed to idle\n";
+ break;
+#if QT_VERSION >= QT_VERSION_CHECK (5, 10, 0)
+ case QAudio::InterruptedState:
+ qtout << "\naudio output state changed to interrupted\n";
+ break;
+#endif
+ }
+ }
+
+ Q_SLOT void stop_playback ()
+ {
+ auto length = sink_.elapsedUSecs ();
+ sink_.stop ();
+ qtout << QString {"%1 μs rendered "}.arg (length) << '(' << sink_.format ().framesForBytes (input_->size ()) << " frames rendered)\n";
+ qtout << "stopped playback at " << QDateTime::currentDateTimeUtc ().toString ("hh:mm:ss.zzz UTC")
+#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
+ << Qt::endl
+#else
+ << endl
+#endif
+ ;
+ Q_EMIT done ();
+ }
+
+ BWFFile * input_;
+ QAudioOutput sink_;
+ int notify_interval_;
+};
+
+#include "record_time_signal.moc"
+
+int main(int argc, char *argv[])
+{
+ QCoreApplication app {argc, argv};
+ try
+ {
+ // ensure number forms are in consistent format, do this after
+ // instantiating QApplication so that Qt has correct l18n
+ std::locale::global (std::locale::classic ());
+
+ // Override programs executable basename as application name.
+ app.setApplicationName ("WSJT-X Record Time Signal");
+ app.setApplicationVersion (version ());
+
+ QCommandLineParser parser;
+ parser.setApplicationDescription (
+ "\nTool to determine and experiment with QAudioInput latencies\n\n"
+ "\tUse the -I option to list available recording device numbers\n"
+ );
+ auto help_option = parser.addHelpOption ();
+ auto version_option = parser.addVersionOption ();
+
+ parser.addOptions ({
+ {{"I", "list-audio-inputs"},
+ app.translate ("main", "List the available audio input devices")},
+ {{"O", "list-audio-outputs"},
+ app.translate ("main", "List the available audio output devices")},
+ {{"s", "start-time"},
+ app.translate ("main", "Record from <start-time> seconds, default start immediately"),
+ app.translate ("main", "start-time")},
+ {{"d", "duration"},
+ app.translate ("main", "Recording <duration> seconds"),
+ app.translate ("main", "duration")},
+ {{"o", "output"},
+ app.translate ("main", "Save output as <output-file>"),
+ app.translate ("main", "output-file")},
+ {{"i", "input"},
+ app.translate ("main", "Playback <input-file>"),
+ app.translate ("main", "input-file")},
+ {{"f", "force"},
+ app.translate ("main", "Overwrite existing file")},
+ {{"r", "sample-rate"},
+ app.translate ("main", "Record at <sample-rate>, default 48000 Hz"),
+ app.translate ("main", "sample-rate")},
+ {{"c", "num-channels"},
+ app.translate ("main", "Record <num> channels, default 2"),
+ app.translate ("main", "num")},
+ {{"R", "recording-device-number"},
+ app.translate ("main", "Record from <device-number>"),
+ app.translate ("main", "device-number")},
+ {{"P", "playback-device-number"},
+ app.translate ("main", "Playback to <device-number>"),
+ app.translate ("main", "device-number")},
+ {{"C", "category"},
+ app.translate ("main", "Playback <category-name>"),
+ app.translate ("main", "category-name")},
+ {{"n", "notify-interval"},
+ app.translate ("main", "use notify signals every <interval> milliseconds, zero to use a timer"),
+ app.translate ("main", "interval")},
+ {{"b", "buffer-size"},
+ app.translate ("main", "audio buffer size <frames>"),
+ app.translate ("main", "frames")},
+ });
+ parser.process (app);
+
+ auto input_devices = QAudioDeviceInfo::availableDevices (QAudio::AudioInput);
+ if (parser.isSet ("I"))
+ {
+ int n {0};
+ for (auto const& device : input_devices)
+ {
+ qtout << ++n << " - [" << device.deviceName () << ']'
+#if QT_VERSION >= QT_VERSION_CHECK (5, 15, 0)
+ << Qt::endl
+#else
+ << endl
+#endif
+ ;
+ }
+ return 0;
+ }
+
+ auto output_devices = QAudioDeviceInfo::availableDevices (QAudio::AudioOutput);
+ if (parser.isSet ("O"))
+ {
+ int n {0};
+ for (auto const& device : output_devices)
+ {
+ qtout << ++n << " - [" << device.deviceName () << ']'
+#if QT_VERSION >= QT_VERSION_CHECK (5, 15, 0)
+ << Qt::endl
+#else
+ << endl
+#endif
+ ;
+ }
+ return 0;
+ }
+
+ bool ok;
+ int start {-1};
+ if (parser.isSet ("s"))
+ {
+ start = parser.value ("s").toInt (&ok);
+ if (!ok) throw std::invalid_argument {"start time not a number"};
+ if (0 > start || start > 59) throw std::invalid_argument {"0 > start > 59"};
+ }
+ int sample_rate {48000};
+ if (parser.isSet ("r"))
+ {
+ sample_rate = parser.value ("r").toInt (&ok);
+ if (!ok) throw std::invalid_argument {"sample rate not a number"};
+ }
+ int num_channels {2};
+ if (parser.isSet ("c"))
+ {
+ num_channels = parser.value ("c").toInt (&ok);
+ if (!ok) throw std::invalid_argument {"channel count not a number"};
+ }
+ int notify_interval {0};
+ if (parser.isSet ("n"))
+ {
+ notify_interval = parser.value ("n").toInt (&ok);
+ if (!ok) throw std::invalid_argument {"notify interval not a number"};
+ }
+ int buffer_size {0};
+ if (parser.isSet ("b"))
+ {
+ buffer_size = parser.value ("b").toInt (&ok);
+ if (!ok) throw std::invalid_argument {"buffer size not a number"};
+ }
+ int input_device {0};
+ if (parser.isSet ("R"))
+ {
+ input_device = parser.value ("R").toInt (&ok);
+ if (!ok || 0 >= input_device || input_device > input_devices.size ())
+ {
+ throw std::invalid_argument {"invalid recording device"};
+ }
+ }
+ int output_device {0};
+ if (parser.isSet ("P"))
+ {
+ output_device = parser.value ("P").toInt (&ok);
+ if (!ok || 0 >= output_device || output_device > output_devices.size ())
+ {
+ throw std::invalid_argument {"invalid playback device"};
+ }
+ }
+ if (!(parser.isSet ("o") || parser.isSet ("i"))) throw std::invalid_argument {"file required"};
+ if (parser.isSet ("o") && parser.isSet ("i")) throw std::invalid_argument {"specify either input or output"};
+
+ QAudioFormat audio_format;
+ if (parser.isSet ("o")) // Record
+ {
+ int duration = parser.value ("d").toInt (&ok);
+ if (!ok) throw std::invalid_argument {"duration not a number"};
+
+ QFileInfo ofi {parser.value ("o")};
+ if (!ofi.suffix ().size () && ofi.fileName ()[ofi.fileName ().size () - 1] != QChar {'.'})
+ {
+ ofi.setFile (ofi.filePath () + ".wav");
+ }
+ if (!parser.isSet ("f") && ofi.isFile ())
+ {
+ throw std::invalid_argument {"set the `-force' option to overwrite an existing output file"};
+ }
+
+ audio_format.setSampleRate (sample_rate);
+ audio_format.setChannelCount (num_channels);
+ audio_format.setSampleSize (16);
+ audio_format.setSampleType (QAudioFormat::SignedInt);
+ audio_format.setCodec ("audio/pcm");
+
+ auto source = input_device ? input_devices[input_device - 1] : QAudioDeviceInfo::defaultInputDevice ();
+ if (!source.isFormatSupported (audio_format))
+ {
+ qtout << "warning, requested format not supported, using nearest"
+#if QT_VERSION >= QT_VERSION_CHECK (5, 15, 0)
+ << Qt::endl
+#else
+ << endl
+#endif
+ ;
+ audio_format = source.nearestFormat (audio_format);
+ }
+ BWFFile output_file {audio_format, ofi.filePath ()};
+ if (!output_file.open (BWFFile::WriteOnly)) throw std::invalid_argument {QString {"cannot open output file \"%1\""}.arg (ofi.filePath ()).toStdString ()};
+
+ // run the application
+ Record record {start, duration, source, &output_file, notify_interval, buffer_size};
+ QObject::connect (&record, &Record::done, &app, &QCoreApplication::quit);
+ return app.exec();
+ }
+ else // Playback
+ {
+ QFileInfo ifi {parser.value ("i")};
+ if (!ifi.isFile () && !ifi.suffix ().size () && ifi.fileName ()[ifi.fileName ().size () - 1] != QChar {'.'})
+ {
+ ifi.setFile (ifi.filePath () + ".wav");
+ }
+ BWFFile input_file {audio_format, ifi.filePath ()};
+ if (!input_file.open (BWFFile::ReadOnly)) throw std::invalid_argument {QString {"cannot open input file \"%1\""}.arg (ifi.filePath ()).toStdString ()};
+ auto sink = output_device ? output_devices[output_device - 1] : QAudioDeviceInfo::defaultOutputDevice ();
+ if (!sink.isFormatSupported (input_file.format ()))
+ {
+ throw std::invalid_argument {"audio output device does not support input file audio format"};
+ }
+
+ // run the application
+ Playback play {start, &input_file, sink, notify_interval, buffer_size, parser.value ("category")};
+ QObject::connect (&play, &Playback::done, &app, &QCoreApplication::quit);
+ return app.exec();
+ }
+ }
+ catch (std::exception const& e)
+ {
+ std::cerr << "Error: " << e.what () << '\n';
+ }
+ catch (...)
+ {
+ std::cerr << "Unexpected fatal error\n";
+ throw; // hoping the runtime might tell us more about the exception
+ }
+ return -1;
+}