diff options
| author | Christoph Berg <myon@debian.org> | 2026-09-26 23:24:03 +0200 |
|---|---|---|
| committer | Christoph Berg <myon@debian.org> | 2026-09-26 23:24:03 +0200 |
| commit | 059831534c7e884f0a607ed86b582fd00d821731 (patch) | |
| tree | 76bcb67a78f8aa2654fd34c2ad801a62136b0170 /Audio | |
| parent | d83a420f0517d7fc47aeb288a6a0cf4891784fcc (diff) | |
New upstream version 3.2.0~rc1+dfsgupstream/3.2.0_rc1+dfsg
Diffstat (limited to 'Audio')
27 files changed, 2921 insertions, 26 deletions
diff --git a/Audio/Audio.pri b/Audio/Audio.pri deleted file mode 100644 index e2237bbd..00000000 --- a/Audio/Audio.pri +++ /dev/null @@ -1,5 +0,0 @@ -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/AudioInputSource.hpp b/Audio/AudioInputSource.hpp new file mode 100644 index 00000000..220e1309 --- /dev/null +++ b/Audio/AudioInputSource.hpp @@ -0,0 +1,71 @@ +// -*- Mode: C++ -*- +#ifndef AUDIO_INPUT_SOURCE_HPP__ +#define AUDIO_INPUT_SOURCE_HPP__ + +#include <QObject> +#include <QMutex> +#include <QMutexLocker> +#include <QString> + +#include "Audio/AudioDevice.hpp" +#include "Audio/AudioStreamDescriptor.hpp" + +class QAudioDeviceInfo; + +class AudioInputSource + : public QObject +{ + Q_OBJECT + +public: + explicit AudioInputSource (QObject * parent = nullptr) + : QObject {parent} + { + } + + ~AudioInputSource () override = default; + + // Return a consistent snapshot that is safe to read from another thread. + AudioStreamDescriptor streamDescriptor () const + { + QMutexLocker locker {&stream_descriptor_mutex_}; + return stream_descriptor_; + } + + Q_SLOT virtual void start (QAudioDeviceInfo const&, int framesPerBuffer, + AudioDevice * sink, unsigned downSampleFactor, + AudioDevice::Channel = AudioDevice::Mono) = 0; + Q_SLOT virtual void suspend () = 0; + Q_SLOT virtual void resume () = 0; + Q_SLOT virtual void stop () = 0; + Q_SLOT virtual void reset (bool reportDroppedFrames) = 0; + + Q_SIGNAL void error (QString message) const; + Q_SIGNAL void status (QString message) const; + Q_SIGNAL void streamDescriptorChanged (AudioStreamDescriptor descriptor) const; + +protected: + void setStreamDescriptor (AudioStreamDescriptor descriptor) + { + { + QMutexLocker locker {&stream_descriptor_mutex_}; + if (descriptor == stream_descriptor_) + { + return; + } + stream_descriptor_ = descriptor; + } + Q_EMIT streamDescriptorChanged (descriptor); + } + + void clearStreamDescriptor () + { + setStreamDescriptor ({}); + } + +private: + mutable QMutex stream_descriptor_mutex_; + AudioStreamDescriptor stream_descriptor_; +}; + +#endif diff --git a/Audio/AudioStreamClock.hpp b/Audio/AudioStreamClock.hpp new file mode 100644 index 00000000..65e5b1e1 --- /dev/null +++ b/Audio/AudioStreamClock.hpp @@ -0,0 +1,59 @@ +// -*- Mode: C++ -*- +#ifndef AUDIO_STREAM_CLOCK_HPP__ +#define AUDIO_STREAM_CLOCK_HPP__ + +#include <QtGlobal> + +#include "Audio/AudioStreamDescriptor.hpp" + +class AudioStreamClock +{ +public: + enum class Reference + { + ArrivalWallClock, + CaptureAnchor + }; + + void setDescriptor (AudioStreamDescriptor descriptor) noexcept + { + descriptor_ = descriptor; + captured_frames_ = 0; + } + + Reference reference () const noexcept + { + return descriptor_.isValid () + && descriptor_.clock_domain + == AudioStreamDescriptor::ClockDomain::SystemClock + && descriptor_.timing_evidence + == AudioStreamDescriptor::TimingEvidence::CaptureTimeAnchored + && descriptor_.capture_anchor_utc_ms > 0 + ? Reference::CaptureAnchor : Reference::ArrivalWallClock; + } + + qint64 timestamp (qint64 arrival_utc_ms) const noexcept + { + if (Reference::CaptureAnchor != reference ()) + { + return arrival_utc_ms; + } + + return descriptor_.capture_anchor_utc_ms + + captured_frames_ * 1000 / descriptor_.sample_rate_hz; + } + + void advance (qint64 frames) noexcept + { + if (Reference::CaptureAnchor == reference () && frames > 0) + { + captured_frames_ += frames; + } + } + +private: + AudioStreamDescriptor descriptor_; + qint64 captured_frames_ {0}; +}; + +#endif diff --git a/Audio/AudioStreamDescriptor.cpp b/Audio/AudioStreamDescriptor.cpp new file mode 100644 index 00000000..6baaf76a --- /dev/null +++ b/Audio/AudioStreamDescriptor.cpp @@ -0,0 +1,64 @@ +#include "Audio/AudioStreamDescriptor.hpp" + +#include <QAudioFormat> + +AudioStreamDescriptor audioStreamDescriptorFromQAudioFormat ( + QAudioFormat const& format) +{ + AudioStreamDescriptor descriptor; + if (!format.isValid () || format.codec () != "audio/pcm" + || format.sampleSize () <= 0 || format.sampleSize () % 8) + { + return descriptor; + } + + descriptor.sample_rate_hz = format.sampleRate (); + descriptor.sample_size_bits = format.sampleSize (); + descriptor.channel_count = format.channelCount (); + + switch (format.sampleType ()) + { + case QAudioFormat::SignedInt: + descriptor.sample_encoding = + AudioStreamDescriptor::SampleEncoding::SignedInteger; + break; + + case QAudioFormat::UnSignedInt: + descriptor.sample_encoding = + AudioStreamDescriptor::SampleEncoding::UnsignedInteger; + break; + + case QAudioFormat::Float: + descriptor.sample_encoding = + AudioStreamDescriptor::SampleEncoding::FloatingPoint; + break; + + case QAudioFormat::Unknown: + break; + } + + if (format.sampleSize () > 8) + { + switch (format.byteOrder ()) + { + case QAudioFormat::LittleEndian: + descriptor.byte_order = AudioStreamDescriptor::ByteOrder::LittleEndian; + break; + + case QAudioFormat::BigEndian: + descriptor.byte_order = AudioStreamDescriptor::ByteOrder::BigEndian; + break; + } + } + + if (1 == descriptor.channel_count) + { + descriptor.channel_layout = AudioStreamDescriptor::ChannelLayout::Mono; + } + else if (2 == descriptor.channel_count) + { + descriptor.channel_layout = AudioStreamDescriptor::ChannelLayout::Stereo; + } + + return descriptor.isValid () ? descriptor : AudioStreamDescriptor {}; +} diff --git a/Audio/AudioStreamDescriptor.hpp b/Audio/AudioStreamDescriptor.hpp new file mode 100644 index 00000000..9193c321 --- /dev/null +++ b/Audio/AudioStreamDescriptor.hpp @@ -0,0 +1,98 @@ +// -*- Mode: C++ -*- +#ifndef AUDIO_STREAM_DESCRIPTOR_HPP__ +#define AUDIO_STREAM_DESCRIPTOR_HPP__ + +#include <QMetaType> + +class QAudioFormat; + +struct AudioStreamDescriptor +{ + enum class SampleEncoding + { + Unknown, + SignedInteger, + UnsignedInteger, + FloatingPoint + }; + + enum class ByteOrder + { + Unknown, + LittleEndian, + BigEndian + }; + + enum class ChannelLayout + { + Unknown, + Mono, + Stereo + }; + + enum class ClockDomain + { + Unknown, + DeviceClock, + SystemClock + }; + + enum class TimingEvidence + { + Unavailable, + PositionCountable, + CaptureTimeAnchored + }; + + int sample_rate_hz {0}; + SampleEncoding sample_encoding {SampleEncoding::Unknown}; + int sample_size_bits {0}; + ByteOrder byte_order {ByteOrder::Unknown}; + int channel_count {0}; + ChannelLayout channel_layout {ChannelLayout::Unknown}; + ClockDomain clock_domain {ClockDomain::Unknown}; + TimingEvidence timing_evidence {TimingEvidence::Unavailable}; + + // UTC timestamp for the first frame in this descriptor epoch, when anchored. + qint64 capture_anchor_utc_ms {0}; + + // True only when the source has a mechanism for reporting discontinuities. + bool can_report_discontinuities {false}; + + bool isValid () const noexcept + { + return sample_rate_hz > 0 + && SampleEncoding::Unknown != sample_encoding + && sample_size_bits > 0 + && (sample_size_bits <= 8 || ByteOrder::Unknown != byte_order) + && channel_count > 0; + } +}; + +inline bool operator== (AudioStreamDescriptor const& lhs, + AudioStreamDescriptor const& rhs) noexcept +{ + return lhs.sample_rate_hz == rhs.sample_rate_hz + && lhs.sample_encoding == rhs.sample_encoding + && lhs.sample_size_bits == rhs.sample_size_bits + && lhs.byte_order == rhs.byte_order + && lhs.channel_count == rhs.channel_count + && lhs.channel_layout == rhs.channel_layout + && lhs.clock_domain == rhs.clock_domain + && lhs.timing_evidence == rhs.timing_evidence + && lhs.capture_anchor_utc_ms == rhs.capture_anchor_utc_ms + && lhs.can_report_discontinuities == rhs.can_report_discontinuities; +} + +inline bool operator!= (AudioStreamDescriptor const& lhs, + AudioStreamDescriptor const& rhs) noexcept +{ + return !(lhs == rhs); +} + +AudioStreamDescriptor audioStreamDescriptorFromQAudioFormat ( + QAudioFormat const& format); + +Q_DECLARE_METATYPE (AudioStreamDescriptor) + +#endif diff --git a/Audio/FixtureAudioInput.cpp b/Audio/FixtureAudioInput.cpp new file mode 100644 index 00000000..e72118ef --- /dev/null +++ b/Audio/FixtureAudioInput.cpp @@ -0,0 +1,468 @@ +#include "Audio/FixtureAudioInput.hpp" + +#include "Audio/BWFFile.hpp" +#include "Detector/Detector.hpp" + +#include <algorithm> +#include <cstring> +#include <utility> + +#include <QAudioFormat> +#include <QDateTime> +#include <QDebug> +#include <QSysInfo> +#include <QTimer> + +#include "moc_FixtureAudioInput.cpp" + +FixtureAudioInput::FixtureAudioInput (QString path, Profile profile, + QObject * parent) + : AudioInputSource {parent} + , m_path {std::move (path)} + , m_profile {profile} + , m_timer {new QTimer {this}} +{ + m_timer->setSingleShot (true); + m_timer->setTimerType (Qt::PreciseTimer); + connect (m_timer, &QTimer::timeout, this, &FixtureAudioInput::emitNextChunk); +} + +void FixtureAudioInput::start (QAudioDeviceInfo const&, int, AudioDevice * sink, + unsigned downSampleFactor, AudioDevice::Channel channel) +{ + stop (); + if (!sink) + { + fail (tr ("Synthetic audio input has no detector sink.")); + return; + } + if (Profile::Ft8 == m_profile + && downSampleFactor != 1 && downSampleFactor != 4) + { + fail (tr ("Synthetic FT8 audio input requires a downsample factor of 1 or 4.")); + return; + } + if (Profile::Jtty == m_profile + && downSampleFactor != 1 && downSampleFactor != 4) + { + fail (tr ("Synthetic JTTY audio input requires a downsample factor of 1 or 4.")); + return; + } + if (channel != AudioDevice::Mono) + { + fail (tr ("Synthetic audio input requires the mono input channel.")); + return; + } + + if (Profile::ReceiveHandoff == m_profile) + { + if (downSampleFactor != 1) + { + fail (tr ("Receive handoff fixture requires a downsample factor of 1.")); + return; + } + if (!sink->initialize (QIODevice::WriteOnly, channel)) + { + fail (tr ("Unable to initialize the detector for receive handoff input.")); + return; + } + constexpr qint64 periodFrames = 15 * detectorSampleRate; + m_pcm.resize (static_cast<int> (2 * periodFrames * bytesPerFrame)); + auto * samples = reinterpret_cast<qint16 *> (m_pcm.data ()); + for (qint64 frame = 0; frame < 2 * periodFrames; ++frame) + samples[frame] = handoffSample (frame / periodFrames, frame % periodFrames); + m_sink = sink; + m_inputSampleRate = detectorSampleRate; + m_chunkFrames = {3456}; + m_started = true; + m_suspended = false; + AudioStreamDescriptor descriptor; + descriptor.sample_rate_hz = detectorSampleRate; + descriptor.sample_encoding = AudioStreamDescriptor::SampleEncoding::SignedInteger; + descriptor.sample_size_bits = 16; + descriptor.byte_order = AudioStreamDescriptor::ByteOrder::LittleEndian; + descriptor.channel_count = 1; + descriptor.channel_layout = AudioStreamDescriptor::ChannelLayout::Mono; + descriptor.clock_domain = AudioStreamDescriptor::ClockDomain::SystemClock; + descriptor.timing_evidence = + AudioStreamDescriptor::TimingEvidence::CaptureTimeAnchored; + setStreamDescriptor (descriptor); + Q_EMIT status (tr ("Synthetic receive handoff fixture ready")); + maybeSchedule (); + return; + } + + BWFFile file {QAudioFormat {}, m_path}; + if (!file.open (BWFFile::ReadOnly)) + { + fail (tr ("Unable to open synthetic audio fixture %1: %2") + .arg (m_path, file.errorString ())); + return; + } + + auto const& format = file.format (); + if (format.codec () != "audio/pcm" || format.channelCount () != 1 + || format.sampleSize () != 16 + || format.sampleType () != QAudioFormat::SignedInt + || format.byteOrder () != QAudioFormat::LittleEndian) + { + fail (tr ("Synthetic audio fixture must be mono, signed 16-bit little-endian PCM.")); + return; + } + auto const expectedSampleRate = detectorSampleRate + * static_cast<int> (downSampleFactor); + if (format.sampleRate () != expectedSampleRate) + { + fail (tr ("Synthetic audio fixture must be %1 Hz for downsample factor %2; found %3 Hz.") + .arg (expectedSampleRate).arg (downSampleFactor).arg (format.sampleRate ())); + return; + } + + if (Profile::Ft8 == m_profile) + { + auto const expectedFrames = qint64 {15} * format.sampleRate (); + if (file.size () != expectedFrames * bytesPerFrame) + { + fail (tr ("Synthetic FT8 audio fixture must contain exactly %1 frames; found %2.") + .arg (expectedFrames).arg (file.size () / bytesPerFrame)); + return; + } + } + else if (file.size () <= 0 || file.size () % bytesPerFrame) + { + fail (tr ("Synthetic JTTY audio fixture must contain complete PCM frames.")); + return; + } + + m_pcm = file.readAll (); + if (m_pcm.size () != file.size ()) + { + fail (tr ("Unable to read all PCM data from synthetic audio fixture.")); + return; + } + if (QSysInfo::ByteOrder != QSysInfo::LittleEndian) + { + fail (tr ("Synthetic audio input does not yet support big-endian hosts.")); + return; + } + if (!sink->initialize (QIODevice::WriteOnly, channel)) + { + fail (tr ("Unable to initialize the detector for synthetic audio input.")); + return; + } + + m_sink = sink; + m_inputSampleRate = format.sampleRate (); + if (Profile::Jtty == m_profile) + { + m_leadInFrames = m_inputSampleRate / 2; + m_tailFrames = 2 * m_inputSampleRate; + } + m_started = true; + auto descriptor = audioStreamDescriptorFromQAudioFormat (format); + if (descriptor.isValid ()) + { + descriptor.clock_domain = AudioStreamDescriptor::ClockDomain::SystemClock; + descriptor.timing_evidence = + AudioStreamDescriptor::TimingEvidence::CaptureTimeAnchored; + descriptor.can_report_discontinuities = false; + setStreamDescriptor (descriptor); + } + else + { + qWarning () << "Opened fixture audio stream has an unrecognized format"; + } + Q_EMIT status (tr ("Synthetic audio fixture ready")); + maybeSchedule (); +} + +void FixtureAudioInput::suspend () +{ + m_suspended = true; + m_timer->stop (); + Q_EMIT status (tr ("Synthetic audio input suspended")); +} + +void FixtureAudioInput::resume () +{ + if (m_sink) + { + m_sink->reset (); + } + m_suspended = false; + if (m_emitting && m_framesEmitted) + { + m_periodStartMs = QDateTime::currentMSecsSinceEpoch () + - (m_framesEmitted * 1000 / m_inputSampleRate); + publishCaptureAnchor (m_framesEmitted); + } + Q_EMIT status (tr ("Synthetic audio input receiving")); + maybeSchedule (); +} + +qint64 FixtureAudioInput::captureTimestamp (qint64 frameIndex) const +{ + return m_periodStartMs + frameIndex * 1000 / m_inputSampleRate; +} + +void FixtureAudioInput::publishCaptureAnchor (qint64 firstFrame) +{ + auto descriptor = streamDescriptor (); + if (descriptor.isValid () && m_periodStartMs > 0) + { + descriptor.capture_anchor_utc_ms = captureTimestamp (firstFrame); + setStreamDescriptor (descriptor); + } +} + +void FixtureAudioInput::stop () +{ + m_timer->stop (); + m_sink.clear (); + m_pcm.clear (); + m_leadInFrames = 0; + m_tailFrames = 0; + m_framesEmitted = 0; + m_periodStartMs = 0; + m_jttyAcknowledgedInputFrames = 0; + m_chunkIndex = 0; + m_started = false; + m_suspended = true; + m_emitting = false; + m_jttyDecoderReady = false; + m_waitingForJttyDecoder = false; + clearStreamDescriptor (); +} + +void FixtureAudioInput::reset (bool) +{ +} + +void FixtureAudioInput::arm () +{ + if (Profile::ReceiveHandoff == m_profile) m_suspended = false; + m_armed = true; + maybeSchedule (); +} + +void FixtureAudioInput::acknowledgeJttyFrames (qint64 detectorFrames) +{ + if (Profile::Jtty != m_profile || detectorFrames < 0) return; + + auto const inputFrames = detectorFrames * m_inputSampleRate / detectorSampleRate; + m_jttyAcknowledgedInputFrames = std::max ( + m_jttyAcknowledgedInputFrames, inputFrames); + m_jttyDecoderReady = true; + if (m_waitingForJttyDecoder) + { + m_waitingForJttyDecoder = false; + scheduleNextChunk (); + } +} + +void FixtureAudioInput::advanceHandoff (qint64 captureFrames, bool fresh, bool flush) +{ + if (m_profile != Profile::ReceiveHandoff || !m_started || !m_sink + || captureFrames < 0 || captureFrames > totalFrames ()) + { + fail (tr ("Invalid receive handoff checkpoint %1.").arg (captureFrames)); + return; + } + if (!m_emitting) + { + m_armed = true; + m_suspended = false; + maybeSchedule (); + } + if (fresh) + { + m_framesEmitted = 0; + m_chunkIndex = 0; + m_periodStartMs += 45000; + publishCaptureAnchor (0); + } + if (captureFrames < m_framesEmitted) + { + fail (tr ("Receive handoff capture moved backwards: %1 to %2.") + .arg (m_framesEmitted).arg (captureFrames)); + return; + } + constexpr qint64 periodFrames = 15 * detectorSampleRate; + while (m_framesEmitted < captureFrames) + { + auto const frames = std::min ({qint64 {3456}, captureFrames - m_framesEmitted, + periodFrames - m_framesEmitted % periodFrames}); + auto const bytes = frames * bytesPerFrame; + if (m_sink->write (m_pcm.constData () + m_framesEmitted * bytesPerFrame, bytes) + != bytes) + { + fail (tr ("Detector did not accept handoff audio at %1.") + .arg (m_framesEmitted)); + return; + } + m_framesEmitted += frames; + } + if (flush) + { + auto * detector = qobject_cast<Detector *> (m_sink.data ()); + if (!detector) + { + fail (tr ("Receive handoff sink is not a Detector.")); + return; + } + detector->flushBufferedFrames (captureFrames % periodFrames); + } + Q_EMIT handoffCheckpoint (m_framesEmitted); +} + +QString FixtureAudioInput::emitFt8RolloverPrefix () +{ + if (Profile::Ft8 != m_profile || !m_sink || m_emitting + || m_framesEmitted != 15 * m_inputSampleRate) + { + return tr ("FT8 rollover requires exhausted period A: frames=%1 emitting=%2.") + .arg (m_framesEmitted).arg (m_emitting); + } + auto const frames = ft8RolloverFrames () * m_inputSampleRate / detectorSampleRate; + QByteArray prefix (frames * bytesPerFrame, '\0'); + std::fill_n (reinterpret_cast<qint16 *> (prefix.data ()), frames, + ft8RolloverSample ()); + auto const written = m_sink->write (prefix.constData (), prefix.size ()); + if (written != prefix.size ()) + { + return tr ("FT8 rollover accepted %1 of %2 bytes.") + .arg (written).arg (prefix.size ()); + } + m_framesEmitted += frames; + return {}; +} + +void FixtureAudioInput::fail (QString const& message) +{ + stop (); + Q_EMIT error (message); +} + +void FixtureAudioInput::maybeSchedule () +{ + if (!m_started || !m_armed || m_suspended || m_emitting) + { + return; + } + + auto const now = QDateTime::currentMSecsSinceEpoch (); + if (Profile::Ft8 == m_profile || Profile::ReceiveHandoff == m_profile) + { + constexpr qint64 periodMs = 15000; + m_periodStartMs = ((now / periodMs) + 1) * periodMs; + } + else + { + constexpr qint64 periodMs = 180000; + auto const fixtureDurationMs = (totalFrames () * 1000 + m_inputSampleRate - 1) + / m_inputSampleRate; + auto const periodOffsetMs = now % periodMs; + m_periodStartMs = periodOffsetMs + fixtureDurationMs <= periodMs + ? now : ((now / periodMs) + 1) * periodMs; + } + m_emitting = true; + publishCaptureAnchor (m_framesEmitted); + if (Profile::ReceiveHandoff == m_profile) return; + auto const delay = Profile::ReceiveHandoff == m_profile ? qint64 {0} + : std::max<qint64> (0, m_periodStartMs - now); + m_timer->start (static_cast<int> (delay)); +} + +void FixtureAudioInput::scheduleNextChunk () +{ + if (Profile::ReceiveHandoff == m_profile) + { + m_timer->start (0); + return; + } + auto const target = captureTimestamp (m_framesEmitted); + auto const delay = std::max<qint64> (0, target - QDateTime::currentMSecsSinceEpoch ()); + m_timer->start (static_cast<int> (delay)); +} + +void FixtureAudioInput::emitNextChunk () +{ + if (!m_emitting || m_suspended || !m_sink) + { + return; + } + + auto const target = captureTimestamp (m_framesEmitted); + auto const now = QDateTime::currentMSecsSinceEpoch (); + if (Profile::ReceiveHandoff != m_profile && now < target) + { + m_timer->start (static_cast<int> (target - now)); + return; + } + + if (!m_framesEmitted) + { + Q_EMIT emissionStarted (m_periodStartMs); + } + + auto remainingFrames = totalFrames () - m_framesEmitted; + if (Profile::Jtty == m_profile) + { + constexpr qint64 maxDetectorLeadFrames = 10240; + auto const maxInputLeadFrames = + maxDetectorLeadFrames * m_inputSampleRate / detectorSampleRate; + auto const allowedFrames = m_jttyDecoderReady + ? m_jttyAcknowledgedInputFrames + maxInputLeadFrames + : m_leadInFrames; + remainingFrames = std::min ( + remainingFrames, allowedFrames - m_framesEmitted); + if (remainingFrames <= 0) + { + m_waitingForJttyDecoder = true; + return; + } + } + auto chunkFrames = std::min<qint64> ( + remainingFrames, m_chunkFrames.at (m_chunkIndex % m_chunkFrames.size ())); + if (Profile::ReceiveHandoff == m_profile) + { + constexpr qint64 periodFrames = 15 * detectorSampleRate; + auto const untilBoundary = periodFrames - m_framesEmitted % periodFrames; + chunkFrames = std::min (chunkFrames, untilBoundary); + } + auto const chunkBytes = chunkFrames * bytesPerFrame; + QByteArray chunk (static_cast<int> (chunkBytes), '\0'); + auto const chunkStart = m_framesEmitted; + auto const chunkEnd = chunkStart + chunkFrames; + auto const fixtureStart = m_leadInFrames; + auto const fixtureEnd = fixtureStart + fixtureFrames (); + auto const copyStart = std::max (chunkStart, fixtureStart); + auto const copyEnd = std::min (chunkEnd, fixtureEnd); + if (copyStart < copyEnd) + { + auto const sourceOffset = (copyStart - fixtureStart) * bytesPerFrame; + auto const targetOffset = (copyStart - chunkStart) * bytesPerFrame; + auto const copyBytes = (copyEnd - copyStart) * bytesPerFrame; + std::memcpy (chunk.data () + targetOffset, + m_pcm.constData () + sourceOffset, + static_cast<size_t> (copyBytes)); + } + auto const written = m_sink->write (chunk.constData (), chunkBytes); + if (written != chunkBytes) + { + fail (tr ("Detector accepted %1 of %2 synthetic PCM bytes.") + .arg (written).arg (chunkBytes)); + return; + } + + m_framesEmitted += chunkFrames; + ++m_chunkIndex; + if (m_framesEmitted == totalFrames ()) + { + m_emitting = false; + Q_EMIT status (tr ("Synthetic audio fixture exhausted")); + Q_EMIT emissionFinished (m_framesEmitted); + return; + } + scheduleNextChunk (); +} diff --git a/Audio/FixtureAudioInput.hpp b/Audio/FixtureAudioInput.hpp new file mode 100644 index 00000000..8bca1af9 --- /dev/null +++ b/Audio/FixtureAudioInput.hpp @@ -0,0 +1,89 @@ +// -*- Mode: C++ -*- +#ifndef FIXTURE_AUDIO_INPUT_HPP__ +#define FIXTURE_AUDIO_INPUT_HPP__ + +#include "Audio/AudioInputSource.hpp" + +#include <QByteArray> +#include <QPointer> +#include <QString> +#include <QVector> + +class QTimer; + +class FixtureAudioInput final + : public AudioInputSource +{ + Q_OBJECT + +public: + enum class Profile + { + Ft8, + Jtty, + ReceiveHandoff + }; + + explicit FixtureAudioInput (QString path, Profile profile = Profile::Ft8, + QObject * parent = nullptr); + + Q_SLOT void start (QAudioDeviceInfo const&, int framesPerBuffer, + AudioDevice * sink, unsigned downSampleFactor, + AudioDevice::Channel channel = AudioDevice::Mono) override; + Q_SLOT void suspend () override; + Q_SLOT void resume () override; + Q_SLOT void stop () override; + Q_SLOT void reset (bool reportDroppedFrames) override; + Q_SLOT void arm (); + Q_SLOT void acknowledgeJttyFrames (qint64 detectorFrames); + QString emitFt8RolloverPrefix (); + static constexpr int ft8RolloverFrames () {return 6912;} + static constexpr qint16 ft8RolloverSample () {return -12345;} + Q_SLOT void advanceHandoff (qint64 captureFrames, bool fresh, bool flush); + static qint16 handoffSample (qint64 period, qint64 offset) + { + return static_cast<qint16> ((period ? -1 : 1) * (1000 + offset % 7001)); + } + + Q_SIGNAL void emissionStarted (qint64 utcStartMilliseconds) const; + Q_SIGNAL void emissionFinished (qint64 frames) const; + Q_SIGNAL void handoffCheckpoint (qint64 captureFrames) const; + +private: + qint64 fixtureFrames () const {return m_pcm.size () / bytesPerFrame;} + qint64 totalFrames () const + { + return m_leadInFrames + fixtureFrames () + m_tailFrames; + } + void fail (QString const& message); + qint64 captureTimestamp (qint64 frameIndex) const; + void publishCaptureAnchor (qint64 firstFrame); + void maybeSchedule (); + void scheduleNextChunk (); + Q_SLOT void emitNextChunk (); + + static constexpr int detectorSampleRate = 12000; + static constexpr int bytesPerFrame = 2; + + QString m_path; + Profile m_profile; + QByteArray m_pcm; + QPointer<AudioDevice> m_sink; + QTimer * m_timer; + QVector<int> m_chunkFrames {257, 509, 1021, 2039}; + int m_inputSampleRate {detectorSampleRate}; + qint64 m_leadInFrames {0}; + qint64 m_tailFrames {0}; + qint64 m_framesEmitted {0}; + qint64 m_periodStartMs {0}; + qint64 m_jttyAcknowledgedInputFrames {0}; + int m_chunkIndex {0}; + bool m_started {false}; + bool m_armed {false}; + bool m_suspended {true}; + bool m_emitting {false}; + bool m_jttyDecoderReady {false}; + bool m_waitingForJttyDecoder {false}; +}; + +#endif diff --git a/Audio/FixtureSoundOutput.cpp b/Audio/FixtureSoundOutput.cpp new file mode 100644 index 00000000..ce5ca1ca --- /dev/null +++ b/Audio/FixtureSoundOutput.cpp @@ -0,0 +1,298 @@ +#include "Audio/FixtureSoundOutput.hpp" + +#include "Audio/AudioDevice.hpp" +#include "Audio/BWFFile.hpp" + +#include <algorithm> +#include <cstring> +#include <utility> + +#include <QAudioFormat> +#include <QDateTime> +#include <QIODevice> +#include <QSysInfo> +#include <QTimer> +#include <QtEndian> + +#include "moc_FixtureSoundOutput.cpp" + +FixtureSoundOutput::FixtureSoundOutput (QString capturePath, Profile profile, + QObject * parent) + : SoundOutput {parent} + , m_capturePath {std::move (capturePath)} + , m_profile {profile} + , m_timer {new QTimer {this}} +{ + m_timer->setSingleShot (true); + connect (m_timer, &QTimer::timeout, this, &FixtureSoundOutput::pullAudio); +} + +FixtureSoundOutput::~FixtureSoundOutput () +{ + finishCapture (); +} + +int FixtureSoundOutput::bufferSize () const +{ + return simulatedBufferBytes; +} + +void FixtureSoundOutput::setFormat (QAudioDeviceInfo const&, unsigned, int) +{ +} + +void FixtureSoundOutput::restart (QIODevice * source) +{ + restart (source, -1); +} + +void FixtureSoundOutput::restart (QIODevice * source, qint64 periodOffsetMs) +{ + ++m_restartCount; + finishCapture (); + + if (!source || !source->isReadable ()) + { + fail (tr ("Synthetic audio output requires a readable source.")); + return; + } + if (m_capturePath.isEmpty ()) + { + fail (tr ("Synthetic audio output requires a capture path.")); + return; + } + if (QSysInfo::ByteOrder != QSysInfo::LittleEndian) + { + fail (tr ("Synthetic audio output does not yet support big-endian hosts.")); + return; + } + + m_sourceBytesPerFrame = bytesPerCapturedFrame; + m_sourceSampleOffset = 0; + if (auto const audioSource = dynamic_cast<AudioDevice *> (source)) + { + m_sourceBytesPerFrame = static_cast<int> (audioSource->bytesPerFrame ()); + if (audioSource->channel () == AudioDevice::Right) + { + m_sourceSampleOffset = bytesPerCapturedFrame; + } + } + if (m_sourceBytesPerFrame != bytesPerCapturedFrame + && m_sourceBytesPerFrame != 2 * bytesPerCapturedFrame) + { + fail (tr ("Synthetic audio output received an unsupported source frame size.")); + return; + } + + QAudioFormat format; + format.setByteOrder (QAudioFormat::LittleEndian); + format.setChannelCount (1); + format.setCodec ("audio/pcm"); + format.setSampleRate (sampleRate); + format.setSampleSize (16); + format.setSampleType (QAudioFormat::SignedInt); + m_capture.reset (new BWFFile {format, m_capturePath}); + if (!m_capture->open (BWFFile::WriteOnly)) + { + auto const detail = m_capture->errorString (); + m_capture.reset (); + fail (tr ("Unable to open synthetic audio output capture %1: %2") + .arg (m_capturePath, detail)); + return; + } + + m_source = source; + m_framesPulled = 0; + m_scheduleOriginFrame = 0; + m_capturedFrames.store (0); + m_maxInternalSilentFrames.store (0); + m_chunkIndex = 0; + m_silentFrames = 0; + m_nonSilentAudioSeen = false; + m_active = true; + m_elapsed.start (); + if (Profile::Ft8Period == m_profile) + { + constexpr qint64 periodMs = 15000; + auto const capturedOffsetMs = periodOffsetMs >= 0 + ? periodOffsetMs : QDateTime::currentMSecsSinceEpoch () % periodMs; + auto const prefixFrames = capturedOffsetMs * sampleRate / 1000; + if (!appendSilence (prefixFrames)) return; + m_framesPulled = prefixFrames; + m_scheduleOriginFrame = prefixFrames; + } + Q_EMIT captureStarted (m_capturePath); + Q_EMIT audioOutputActive (); + m_timer->start (0); +} + +void FixtureSoundOutput::stop () +{ + if (!m_active) + { + return; + } + ++m_stopCount; + finishCapture (); +} + +void FixtureSoundOutput::finishCapture () +{ + if (!m_active) + { + return; + } + + m_active = false; + m_timer->stop (); + m_source.clear (); + if (Profile::Ft8Period == m_profile && m_capture + && m_capturedFrames.load () < ft8PeriodFrames) + { + if (!appendSilence (ft8PeriodFrames - m_capturedFrames.load ())) return; + m_framesPulled = ft8PeriodFrames; + } + if (m_capture) + { + m_capture->close (); + m_capture.reset (); + } + auto const frames = m_capturedFrames.load (); + Q_EMIT audioOutputIdle (); + Q_EMIT captureStopped (m_capturePath, frames); +} + +bool FixtureSoundOutput::appendCapturedPcm (QByteArray const& pcm) +{ + auto const frames = pcm.size () / bytesPerCapturedFrame; + if (pcm.size () % bytesPerCapturedFrame) + { + fail (tr ("Synthetic audio output received a partial captured frame.")); + return false; + } + if (Profile::Ft8Period == m_profile + && m_capturedFrames.load () + frames > ft8PeriodFrames) + { + fail (tr ("Synthetic FT8 audio output exceeded its 15-second capture period.")); + return false; + } + auto const written = m_capture->write (pcm); + if (written != pcm.size ()) + { + fail (tr ("Synthetic audio output wrote %1 of %2 capture bytes: %3") + .arg (written).arg (pcm.size ()).arg (m_capture->errorString ())); + return false; + } + m_capturedFrames.store (m_capturedFrames.load () + frames); + return true; +} + +bool FixtureSoundOutput::appendSilence (qint64 frames) +{ + while (frames > 0) + { + auto const chunkFrames = static_cast<int> (std::min<qint64> (frames, 4096)); + if (!appendCapturedPcm (QByteArray {chunkFrames * bytesPerCapturedFrame, '\0'})) + { + return false; + } + frames -= chunkFrames; + } + return true; +} + +void FixtureSoundOutput::fail (QString const& message) +{ + Q_EMIT captureFailed (message); + Q_EMIT error (message); + finishCapture (); +} + +void FixtureSoundOutput::scheduleNextPull () +{ + auto const targetMs = (m_framesPulled - m_scheduleOriginFrame) * 1000 + / sampleRate; + auto const delayMs = std::max<qint64> (0, targetMs - m_elapsed.elapsed ()); + m_timer->start (static_cast<int> (delayMs)); +} + +void FixtureSoundOutput::pullAudio () +{ + if (!m_active || !m_source || !m_capture) + { + if (m_active) + { + fail (tr ("Synthetic audio output source disappeared during capture.")); + } + return; + } + + if (Profile::Ft8Period == m_profile + && m_capturedFrames.load () == ft8PeriodFrames) + { + fail (tr ("Synthetic FT8 audio output continued beyond its 15-second capture period.")); + return; + } + + auto frames = m_chunkFrames.at (m_chunkIndex % m_chunkFrames.size ()); + if (Profile::Ft8Period == m_profile) + { + frames = static_cast<int> (std::min<qint64> ( + frames, ft8PeriodFrames - m_capturedFrames.load ())); + } + auto const requestedBytes = qint64 (frames) * m_sourceBytesPerFrame; + auto const sourcePcm = m_source->read (requestedBytes); + if (Profile::JttyStrict == m_profile && sourcePcm.size () != requestedBytes) + { + fail (tr ("Synthetic audio output received %1 of %2 source bytes.") + .arg (sourcePcm.size ()).arg (requestedBytes)); + return; + } + if (sourcePcm.size () < 0 || sourcePcm.size () > requestedBytes + || sourcePcm.size () % m_sourceBytesPerFrame) + { + fail (tr ("Synthetic audio output received an invalid source byte count.")); + return; + } + + QByteArray capturedPcm (frames * bytesPerCapturedFrame, '\0'); + auto const sourceFrames = sourcePcm.size () / m_sourceBytesPerFrame; + for (int frame = 0; frame < frames; ++frame) + { + qint16 sample {0}; + if (frame < sourceFrames) + { + std::memcpy (&sample, + sourcePcm.constData () + frame * m_sourceBytesPerFrame + + m_sourceSampleOffset, + sizeof sample); + } + if (!m_nonSilentAudioSeen && sample) + { + m_nonSilentAudioSeen = true; + Q_EMIT nonSilentAudioStarted (m_framesPulled + frame); + } + if (sample) + { + if (m_nonSilentAudioSeen) + { + m_maxInternalSilentFrames.store ( + std::max (m_maxInternalSilentFrames.load (), m_silentFrames)); + } + m_silentFrames = 0; + } + else if (m_nonSilentAudioSeen) + { + ++m_silentFrames; + } + auto const littleEndianSample = qToLittleEndian (sample); + std::memcpy (capturedPcm.data () + frame * bytesPerCapturedFrame, + &littleEndianSample, sizeof littleEndianSample); + } + + if (!appendCapturedPcm (capturedPcm)) return; + + m_framesPulled += frames; + ++m_chunkIndex; + scheduleNextPull (); +} diff --git a/Audio/FixtureSoundOutput.hpp b/Audio/FixtureSoundOutput.hpp new file mode 100644 index 00000000..762502cf --- /dev/null +++ b/Audio/FixtureSoundOutput.hpp @@ -0,0 +1,93 @@ +// -*- Mode: C++ -*- +#ifndef FIXTURE_SOUND_OUTPUT_HPP__ +#define FIXTURE_SOUND_OUTPUT_HPP__ + +#include "Audio/soundout.h" + +#include <atomic> +#include <memory> + +#include <QElapsedTimer> +#include <QPointer> +#include <QString> +#include <QVector> + +class AudioDevice; +class BWFFile; +class QIODevice; +class QTimer; + +class FixtureSoundOutput final + : public SoundOutput +{ + Q_OBJECT + +public: + enum class Profile + { + JttyStrict, + Ft8Period + }; + + explicit FixtureSoundOutput (QString capturePath, + Profile profile = Profile::JttyStrict, + QObject * parent = nullptr); + ~FixtureSoundOutput () override; + + int bufferSize () const override; + qint64 capturedFrames () const {return m_capturedFrames.load ();} + qint64 maxInternalSilentFrames () const + { + return m_maxInternalSilentFrames.load (); + } + int restartCount () const {return m_restartCount.load ();} + int stopCount () const {return m_stopCount.load ();} + QString const& capturePath () const {return m_capturePath;} + +public Q_SLOTS: + void setFormat (QAudioDeviceInfo const&, unsigned, int = 0) override; + void restart (QIODevice * source) override; + void restart (QIODevice * source, qint64 periodOffsetMs) override; + void stop () override; + +Q_SIGNALS: + void captureStarted (QString path) const; + void nonSilentAudioStarted (qint64 frame) const; + void captureStopped (QString path, qint64 frames) const; + void captureFailed (QString message) const; + +private: + bool appendCapturedPcm (QByteArray const& pcm); + bool appendSilence (qint64 frames); + void finishCapture (); + void fail (QString const& message); + void scheduleNextPull (); + Q_SLOT void pullAudio (); + + static constexpr int sampleRate = 48000; + static constexpr qint64 ft8PeriodFrames = 15 * sampleRate; + static constexpr int bytesPerCapturedFrame = 2; + static constexpr int simulatedBufferBytes = 9600; + + QString m_capturePath; + Profile m_profile; + QPointer<QIODevice> m_source; + std::unique_ptr<BWFFile> m_capture; + QTimer * m_timer; + QElapsedTimer m_elapsed; + QVector<int> m_chunkFrames {257, 509, 1021, 2039}; + qint64 m_framesPulled {0}; + qint64 m_scheduleOriginFrame {0}; + std::atomic<qint64> m_capturedFrames {0}; + std::atomic<qint64> m_maxInternalSilentFrames {0}; + std::atomic<int> m_restartCount {0}; + std::atomic<int> m_stopCount {0}; + int m_chunkIndex {0}; + int m_sourceBytesPerFrame {bytesPerCapturedFrame}; + int m_sourceSampleOffset {0}; + qint64 m_silentFrames {0}; + bool m_active {false}; + bool m_nonSilentAudioSeen {false}; +}; + +#endif diff --git a/Audio/TxAudioQueue.cpp b/Audio/TxAudioQueue.cpp new file mode 100644 index 00000000..9217d199 --- /dev/null +++ b/Audio/TxAudioQueue.cpp @@ -0,0 +1,124 @@ +#include "TxAudioQueue.hpp" + +#include <atomic> + +#include "TxAudioQueueEpochSnapshot.hpp" +#include "Modulator/JttyPcmFifo.hpp" + +class TxAudioQueue::Impl +{ +public: + explicit Impl (qint64 capacity_samples) + : fifo {capacity_samples} + { + } + + bool tryEpoch (TxAudioQueueEpoch& result) const noexcept + { + auto const before = epoch_sequence.load (std::memory_order_acquire); + if (before & 1) + { + return false; + } + + auto const current_epoch = epoch.load (std::memory_order_relaxed); + // Keep payload reads ahead of the sequence validation load. + std::atomic_thread_fence (std::memory_order_acquire); + auto const after = epoch_sequence.load (std::memory_order_relaxed); + return TxAudioQueueDetail::tryMakeEpochSnapshot ( + before, current_epoch, after, result); + } + + void clear (TxAudioQueueEpoch value) + { + epoch_sequence.fetch_add (1, std::memory_order_acq_rel); + fifo.clear (value.value ()); + epoch.store (value.value (), std::memory_order_relaxed); + epoch_sequence.fetch_add (1, std::memory_order_release); + } + + JttyPcmFifo fifo; + std::atomic<qint64> epoch {0}; + std::atomic<quint64> epoch_sequence {0}; +}; + +TxAudioQueue::TxAudioQueue () + : TxAudioQueue {defaultCapacity ()} +{ +} + +TxAudioQueue::TxAudioQueue (qint64 capacity_samples) + : impl_ {new Impl {capacity_samples}} +{ +} + +TxAudioQueue::~TxAudioQueue () = default; + +TxAudioQueueEnqueueResult TxAudioQueue::enqueue ( + QVector<qint16> const& samples, TxAudioQueueEpoch epoch) +{ + return enqueue (samples.constData (), samples.size (), epoch); +} + +TxAudioQueueEnqueueResult TxAudioQueue::enqueue ( + qint16 const * samples, qint64 count, TxAudioQueueEpoch epoch) +{ + bool accepted {false}; + TxAudioQueueEpoch current_epoch; + if (impl_->tryEpoch (current_epoch) && epoch == current_epoch) + { + accepted = impl_->fifo.enqueue (samples, count, epoch.value ()); + } + return TxAudioQueueEnqueueResult {accepted, progress ()}; +} + +void TxAudioQueue::clear (TxAudioQueueEpoch epoch) +{ + impl_->clear (epoch); +} + +void TxAudioQueue::applyPendingReset () noexcept +{ + impl_->fifo.applyPendingReset (); +} + +qint16 TxAudioQueue::pullSample (qint64 drain_guard) noexcept +{ + return impl_->fifo.pullSample (drain_guard); +} + +TxAudioQueueDrainState TxAudioQueue::takeDrainReady () noexcept +{ + TxAudioQueueEpoch epoch_before; + if (!impl_->tryEpoch (epoch_before)) + { + return TxAudioQueueDrainState {}; + } + + auto const raw = impl_->fifo.takeDrainReady (); + TxAudioQueueEpoch epoch; + if (!impl_->tryEpoch (epoch) || !raw.ready + || epoch_before != epoch + || raw.epoch != epoch.value ()) + { + return TxAudioQueueDrainState {false, epoch, 0}; + } + return TxAudioQueueDrainState {true, epoch, raw.totalAtDrain}; +} + +TxAudioQueueProgress TxAudioQueue::progress () const noexcept +{ + TxAudioQueueEpoch epoch; + impl_->tryEpoch (epoch); + return TxAudioQueueProgress { + epoch, + impl_->fifo.queuedReal (), + impl_->fifo.servedReal (), + impl_->fifo.totalReal () + }; +} + +qint64 TxAudioQueue::capacity () const noexcept +{ + return impl_->fifo.capacity (); +} diff --git a/Audio/TxAudioQueue.hpp b/Audio/TxAudioQueue.hpp new file mode 100644 index 00000000..8e1a4710 --- /dev/null +++ b/Audio/TxAudioQueue.hpp @@ -0,0 +1,93 @@ +#ifndef TX_AUDIO_QUEUE_HPP_ +#define TX_AUDIO_QUEUE_HPP_ + +#include <memory> + +#include <QMetaType> +#include <QVector> +#include <QtGlobal> + +struct TxAudioQueueEpoch +{ + constexpr TxAudioQueueEpoch () noexcept : value_ {0} {} + explicit constexpr TxAudioQueueEpoch (qint64 value) noexcept : value_ {value} {} + + static constexpr TxAudioQueueEpoch invalid () noexcept {return TxAudioQueueEpoch {};} + constexpr bool isValid () const noexcept {return value_ > 0;} + constexpr qint64 value () const noexcept {return value_;} + +private: + qint64 value_; +}; + +inline constexpr bool operator == (TxAudioQueueEpoch lhs, + TxAudioQueueEpoch rhs) noexcept +{ + return lhs.value () == rhs.value (); +} + +inline constexpr bool operator != (TxAudioQueueEpoch lhs, + TxAudioQueueEpoch rhs) noexcept +{ + return !(lhs == rhs); +} + +struct TxAudioQueueProgress +{ + TxAudioQueueEpoch epoch {}; + qint64 queued_samples {0}; + qint64 served_samples {0}; + qint64 total_samples {0}; +}; + +struct TxAudioQueueDrainState +{ + bool ready {false}; + TxAudioQueueEpoch epoch {}; + qint64 total_at_drain {0}; +}; + +struct TxAudioQueueEnqueueResult +{ + bool accepted {false}; + TxAudioQueueProgress progress {}; +}; + +class TxAudioQueue +{ +public: + // One serialized producer owns clear/enqueue; one consumer owns reset/pull/drain. + static constexpr qint64 defaultCapacity () noexcept {return 60 * 48000;} + + TxAudioQueue (); + explicit TxAudioQueue (qint64 capacity_samples); + ~TxAudioQueue (); + + TxAudioQueue (TxAudioQueue const&) = delete; + TxAudioQueue& operator = (TxAudioQueue const&) = delete; + + TxAudioQueueEnqueueResult enqueue (QVector<qint16> const& samples, + TxAudioQueueEpoch epoch); + TxAudioQueueEnqueueResult enqueue (qint16 const * samples, qint64 count, + TxAudioQueueEpoch epoch); + void clear (TxAudioQueueEpoch epoch); + void applyPendingReset () noexcept; + + qint16 pullSample (qint64 drain_guard) noexcept; + TxAudioQueueDrainState takeDrainReady () noexcept; + + // A concurrent clear may produce progress with an invalid epoch. + TxAudioQueueProgress progress () const noexcept; + qint64 capacity () const noexcept; + +private: + class Impl; + std::unique_ptr<Impl> impl_; +}; + +Q_DECLARE_METATYPE (TxAudioQueueEpoch) +Q_DECLARE_METATYPE (TxAudioQueueProgress) +Q_DECLARE_METATYPE (TxAudioQueueDrainState) +Q_DECLARE_METATYPE (TxAudioQueueEnqueueResult) + +#endif diff --git a/Audio/TxAudioQueueEpochSnapshot.hpp b/Audio/TxAudioQueueEpochSnapshot.hpp new file mode 100644 index 00000000..21b6d052 --- /dev/null +++ b/Audio/TxAudioQueueEpochSnapshot.hpp @@ -0,0 +1,23 @@ +#ifndef TX_AUDIO_QUEUE_EPOCH_SNAPSHOT_HPP_ +#define TX_AUDIO_QUEUE_EPOCH_SNAPSHOT_HPP_ + +#include "TxAudioQueue.hpp" + +namespace TxAudioQueueDetail +{ + inline bool tryMakeEpochSnapshot (quint64 sequence_before, + qint64 epoch, + quint64 sequence_after, + TxAudioQueueEpoch& result) noexcept + { + if ((sequence_before & 1) || sequence_before != sequence_after) + { + return false; + } + + result = TxAudioQueueEpoch {epoch}; + return true; + } +} + +#endif diff --git a/Audio/TxIdentity.hpp b/Audio/TxIdentity.hpp new file mode 100644 index 00000000..b0c00b49 --- /dev/null +++ b/Audio/TxIdentity.hpp @@ -0,0 +1,99 @@ +#ifndef TX_IDENTITY_HPP_ +#define TX_IDENTITY_HPP_ + +#include <QMetaType> +#include <QtGlobal> + +namespace TxEvidence +{ + struct TxSessionId + { + constexpr TxSessionId () noexcept : value_ {0} {} + explicit constexpr TxSessionId (qint64 value) noexcept : value_ {value} {} + + static constexpr TxSessionId invalid () noexcept {return TxSessionId {};} + constexpr bool isValid () const noexcept {return value_ > 0;} + constexpr qint64 value () const noexcept {return value_;} + + private: + qint64 value_; + }; + + struct TxGeneration + { + constexpr TxGeneration () noexcept : value_ {0} {} + explicit constexpr TxGeneration (qint64 value) noexcept : value_ {value} {} + + static constexpr TxGeneration invalid () noexcept {return TxGeneration {};} + constexpr bool isValid () const noexcept {return value_ > 0;} + constexpr qint64 value () const noexcept {return value_;} + + private: + qint64 value_; + }; + + inline constexpr bool operator == (TxSessionId lhs, TxSessionId rhs) noexcept + { + return lhs.value () == rhs.value (); + } + + inline constexpr bool operator != (TxSessionId lhs, TxSessionId rhs) noexcept + { + return !(lhs == rhs); + } + + inline constexpr bool operator < (TxSessionId lhs, TxSessionId rhs) noexcept + { + return lhs.value () < rhs.value (); + } + + inline constexpr bool operator <= (TxSessionId lhs, TxSessionId rhs) noexcept + { + return !(rhs < lhs); + } + + inline constexpr bool operator > (TxSessionId lhs, TxSessionId rhs) noexcept + { + return rhs < lhs; + } + + inline constexpr bool operator >= (TxSessionId lhs, TxSessionId rhs) noexcept + { + return !(lhs < rhs); + } + + inline constexpr bool operator == (TxGeneration lhs, TxGeneration rhs) noexcept + { + return lhs.value () == rhs.value (); + } + + inline constexpr bool operator != (TxGeneration lhs, TxGeneration rhs) noexcept + { + return !(lhs == rhs); + } + + inline constexpr bool operator < (TxGeneration lhs, TxGeneration rhs) noexcept + { + return lhs.value () < rhs.value (); + } + + inline constexpr bool operator <= (TxGeneration lhs, TxGeneration rhs) noexcept + { + return !(rhs < lhs); + } + + inline constexpr bool operator > (TxGeneration lhs, TxGeneration rhs) noexcept + { + return rhs < lhs; + } + + inline constexpr bool operator >= (TxGeneration lhs, TxGeneration rhs) noexcept + { + return !(lhs < rhs); + } +} + +Q_DECLARE_METATYPE (TxEvidence::TxSessionId) +Q_DECLARE_METATYPE (TxEvidence::TxGeneration) + +#endif diff --git a/Audio/TxPlaybackDiagnostics.cpp b/Audio/TxPlaybackDiagnostics.cpp new file mode 100644 index 00000000..5e99b6ca --- /dev/null +++ b/Audio/TxPlaybackDiagnostics.cpp @@ -0,0 +1,443 @@ +#include "Audio/TxPlaybackDiagnostics.hpp" + +#include <atomic> + +#include <QStringList> + +namespace +{ + std::atomic<qint64> next_session_id {1}; + std::atomic<qint64> next_generation {1}; + + qint64 framesFromUsecs (qint64 usecs, int sampleRateHz) + { + if (usecs < 0 || sampleRateHz <= 0) + { + return -1; + } + return usecs * sampleRateHz / 1000000; + } + + QString reasonName (TxEvidence::TxStopReason reason) + { + switch (reason) + { + case TxEvidence::TxStopReason::NormalEnd: return "normal-end"; + case TxEvidence::TxStopReason::UserHalt: return "user-halt"; + case TxEvidence::TxStopReason::Watchdog: return "watchdog"; + case TxEvidence::TxStopReason::Error: return "error"; + case TxEvidence::TxStopReason::ModeChange: return "mode-change"; + } + return "unknown"; + } + + QString tierName (TxEvidence::TxPlayoutTier tier) + { + switch (tier) + { + case TxEvidence::TxPlayoutTier::DeviceClock: return "device-clock"; + case TxEvidence::TxPlayoutTier::DeadReckoning: return "dead-reckoning"; + case TxEvidence::TxPlayoutTier::Unavailable: return "unavailable"; + } + return "unavailable"; + } + + int tierStrength (TxEvidence::TxPlayoutTier tier) + { + switch (tier) + { + case TxEvidence::TxPlayoutTier::Unavailable: return 0; + case TxEvidence::TxPlayoutTier::DeadReckoning: return 1; + case TxEvidence::TxPlayoutTier::DeviceClock: return 2; + } + return 0; + } + + QString combinedDiagnostic (QString const& source, QString const& playout) + { + if (source.isEmpty () || source == playout) return playout; + if (playout.isEmpty ()) return source; + return source + QStringLiteral (" | ") + playout; + } +} + +namespace TxEvidence +{ + TxPlaybackDiagnostics::TxPlaybackDiagnostics () = default; + TxPlaybackDiagnostics::~TxPlaybackDiagnostics () = default; + + TxSessionId TxPlaybackDiagnostics::allocateSessionId () + { + return TxSessionId {next_session_id.fetch_add (1, std::memory_order_relaxed)}; + } + + TxGeneration TxPlaybackDiagnostics::allocateGeneration () + { + return TxGeneration {next_generation.fetch_add (1, std::memory_order_relaxed)}; + } + + TxStopDecision TxPlaybackDiagnostics::decisionFor (TxStopReason reason, + bool zeroTailMode) + { + TxStopDecision decision; + decision.reason = reason; + decision.tail_ms = zeroTailMode ? 0 : 200; + return decision; + } + + TxSessionId TxPlaybackDiagnostics::beginSession (QString const& mode, + int sampleRateHz, + qint64 committedEndSample, + bool targetKnown, + QString const& diagnostic) + { + auto const sessionId = allocateSessionId (); + TxStartSnapshot snapshot; + snapshot.session_id = sessionId; + snapshot.generation = allocateGeneration (); + snapshot.mode = mode; + snapshot.sample_rate_hz = sampleRateHz; + snapshot.committed_end_sample = committedEndSample; + snapshot.target_known = targetKnown; + snapshot.diagnostic = diagnostic; + if (!commitStart (snapshot)) return TxSessionId::invalid (); + findActive (sessionId, snapshot.generation)->claimed = false; + return sessionId; + } + + TxGeneration TxPlaybackDiagnostics::beginGeneration (TxSessionId sessionId) + { + for (auto& active : active_) + { + if (active.start.session_id == sessionId && !active.stopped) + { + if (!active.claimed) + { + active.claimed = true; + return active.start.generation; + } + TxStartSnapshot next = active.start; + next.generation = allocateGeneration (); + commitStart (next); + return next.generation; + } + } + return TxGeneration::invalid (); + } + + bool TxPlaybackDiagnostics::commitStart (TxStartSnapshot const& snapshot) + { + if (!snapshot.session_id.isValid () || !snapshot.generation.isValid () || + snapshot.sample_rate_hz <= 0) + { + return false; + } + if (findActive (snapshot.session_id, snapshot.generation)) + { + return false; + } + ActiveSession active; + active.start = snapshot; + active.playout.session_id = snapshot.session_id; + active.playout.generation = snapshot.generation; + active_.append (active); + return true; + } + + bool TxPlaybackDiagnostics::commitTarget (TxSessionId sessionId, + TxGeneration generation, + qint64 committedEndSample, + bool targetKnown, + QString const& diagnostic) + { + auto * active = findActive (sessionId, generation); + if (!active || committedEndSample < -1 || + (active->start.committed_end_sample >= 0 && + committedEndSample >= 0 && + committedEndSample < active->start.committed_end_sample)) + { + return false; + } + active->start.committed_end_sample = committedEndSample; + active->start.target_known = targetKnown; + if (!diagnostic.isEmpty ()) active->start.diagnostic = diagnostic; + active->playout = normalize (active->start, active->raw); + if (active->stopped) + { + for (auto& item : terminal_) + { + if (item.session_id == sessionId && item.generation == generation) + { + item = terminal (*active); + break; + } + } + } + return true; + } + + bool TxPlaybackDiagnostics::observeSourceProgress (TxSessionId sessionId, + TxGeneration generation, + qint64 servedSamples, + qint64 totalSamples, + QString const& diagnostic) + { + auto * active = findActive (sessionId, generation); + if (!active || servedSamples < 0 || totalSamples < servedSamples || + (active->source_served_frames >= 0 && + servedSamples < active->source_served_frames) || + (active->source_total_frames >= 0 && + totalSamples < active->source_total_frames)) + { + return false; + } + active->source_served_frames = servedSamples; + active->source_total_frames = totalSamples; + if (!diagnostic.isEmpty ()) active->source_progress_diagnostic = diagnostic; + if (active->stopped) + { + for (auto& item : terminal_) + { + if (item.session_id == sessionId && item.generation == generation) + { + item = terminal (*active); + break; + } + } + } + return true; + } + + bool TxPlaybackDiagnostics::observe (TxSessionId sessionId, + TxGeneration generation, + TxRawPlayoutSnapshot const& raw) + { + auto * active = findActive (sessionId, generation); + if (!active) + { + return false; + } + if (raw.start_event) + { + if (raw.backend_start_sequence <= 0 || + (active->bound && raw.backend_start_sequence <= active->backend_start_sequence)) + { + return false; + } + active->bound = true; + active->backend_start_sequence = raw.backend_start_sequence; + } + else if (!active->bound || raw.backend_start_sequence != active->backend_start_sequence) + { + return false; + } + if ((active->raw.processed_usecs >= 0 && raw.processed_usecs >= 0 && + raw.processed_usecs < active->raw.processed_usecs) || + (active->raw.successfully_written_frames >= 0 && + raw.successfully_written_frames >= 0 && + raw.successfully_written_frames < active->raw.successfully_written_frames)) + { + return false; + } + if (!raw.start_event && tierStrength (raw.tier) < tierStrength (active->raw.tier)) + { + return false; + } + if (raw.source_served_frames >= 0 && + raw.source_total_frames >= raw.source_served_frames && + (active->source_served_frames < 0 || + raw.source_served_frames >= active->source_served_frames) && + (active->source_total_frames < 0 || + raw.source_total_frames >= active->source_total_frames)) + { + active->source_served_frames = raw.source_served_frames; + active->source_total_frames = raw.source_total_frames; + } + active->raw = raw; + active->underrun = active->underrun || raw.error == TxBackendError::Underrun; + active->playout = normalize (active->start, raw); + if (active->stopped) + { + for (auto& item : terminal_) + { + if (item.session_id == sessionId && item.generation == generation) + { + item = terminal (*active); + break; + } + } + } + return true; + } + + TxStopDecision TxPlaybackDiagnostics::stop (TxSessionId sessionId, + TxGeneration generation, + TxStopReason reason, + int legacyTailMs) + { + TxStopDecision decision; + decision.reason = reason; + decision.tail_ms = legacyTailMs; + auto * active = findActive (sessionId, generation); + if (!active) + { + return decision; + } + active->stopped = true; + active->stop = decision; + terminal_.append (terminal (*active)); + if (terminal_.size () > 16) + { + int const removeCount = terminal_.size () - 16; + for (int index = 0; index != removeCount; ++index) + { + auto const expired = terminal_.at (index); + for (int activeIndex = 0; activeIndex != active_.size (); ++activeIndex) + { + if (active_[activeIndex].start.session_id == expired.session_id && + active_[activeIndex].start.generation == expired.generation) + { + active_.remove (activeIndex); + break; + } + } + } + terminal_.remove (0, removeCount); + } + return decision; + } + + QVector<TxTerminalSession> TxPlaybackDiagnostics::terminalSessions () const + { + return terminal_; + } + + QString TxPlaybackDiagnostics::diagnosticDump () const + { + QStringList entries; + for (auto const& active : active_) + { + if (active.stopped) + { + continue; + } + auto entry = QString ("active session=%1 generation=%2 mode=%3 tier=%4 " + "target_known=%5 committed_end=%6 consumed=%7 " + "served=%8 underrun=%9 sequence=%10") + .arg (active.start.session_id.value ()) + .arg (active.start.generation.value ()) + .arg (active.start.mode) + .arg (tierName (active.raw.tier)) + .arg (active.start.target_known ? "true" : "false") + .arg (active.start.committed_end_sample) + .arg (active.playout.consumed_samples) + .arg (active.source_served_frames) + .arg (active.underrun ? "true" : "false") + .arg (active.backend_start_sequence); + entry += QString (" source_diagnostic=\"%1\" playout_diagnostic=\"%2\"") + .arg (combinedDiagnostic (active.start.diagnostic, + active.source_progress_diagnostic), + active.raw.diagnostic); + entries.append (entry); + } + for (auto const& item : terminal_) + { + auto entry = QString ("terminal session=%1 generation=%2 mode=%3 tier=%4 " + "reason=%5 tail_ms=%6 target_known=%7 committed_end=%8 " + "consumed=%9 served=%10 underrun=%11 truncated=%12") + .arg (item.session_id.value ()) + .arg (item.generation.value ()) + .arg (item.mode) + .arg (tierName (item.tier)) + .arg (reasonName (item.stop.reason)) + .arg (item.stop.tail_ms) + .arg (item.target_known ? "true" : "false") + .arg (item.committed_end_sample) + .arg (item.consumed_samples) + .arg (item.source_served_samples) + .arg (item.underrun ? "true" : "false") + .arg (item.truncated_known ? (item.truncated ? "true" : "false") : "unknown"); + entry += QString (" diagnostic=\"%1\"").arg (item.diagnostic); + entries.append (entry); + } + return entries.join ('\n'); + } + + TxPlaybackDiagnostics::ActiveSession * TxPlaybackDiagnostics::findActive ( + TxSessionId sessionId, TxGeneration generation) + { + for (auto& active : active_) + { + if (active.start.session_id == sessionId && active.start.generation == generation) + { + return &active; + } + } + return nullptr; + } + + TxPlaybackDiagnostics::ActiveSession const * TxPlaybackDiagnostics::findActive ( + TxSessionId sessionId, TxGeneration generation) const + { + for (auto const& active : active_) + { + if (active.start.session_id == sessionId && active.start.generation == generation) + { + return &active; + } + } + return nullptr; + } + + TxPlayoutSnapshot TxPlaybackDiagnostics::normalize (TxStartSnapshot const& start, + TxRawPlayoutSnapshot const& raw) + { + TxPlayoutSnapshot result; + result.session_id = start.session_id; + result.generation = start.generation; + result.raw = raw; + int const rate = raw.sample_rate_hz > 0 ? raw.sample_rate_hz : start.sample_rate_hz; + if (raw.tier == TxPlayoutTier::DeviceClock) + { + result.consumed_samples = framesFromUsecs (raw.processed_usecs, rate); + } + else if (raw.tier == TxPlayoutTier::DeadReckoning) + { + result.consumed_samples = raw.successfully_written_frames; + } + if (result.consumed_samples >= 0 && raw.report_interval_ms > 0 && rate > 0) + { + result.uncertainty_samples = qint64 (raw.report_interval_ms) * rate / 1000; + } + return result; + } + + TxTerminalSession TxPlaybackDiagnostics::terminal (ActiveSession const& active) + { + TxTerminalSession result; + result.session_id = active.start.session_id; + result.generation = active.start.generation; + result.mode = active.start.mode; + result.tier = active.raw.tier; + result.target_known = active.start.target_known; + result.committed_end_sample = active.start.committed_end_sample; + result.source_served_samples = active.source_served_frames; + result.consumed_samples = active.playout.consumed_samples; + result.uncertainty_samples = active.playout.uncertainty_samples; + result.underrun = active.underrun; + qint64 const observedSamples = result.consumed_samples >= 0 + ? result.consumed_samples : result.source_served_samples; + result.truncated_known = result.target_known && observedSamples >= 0; + result.truncated = result.truncated_known && + observedSamples <= result.committed_end_sample; + result.terminal_playout_observed = active.bound && active.raw.available && + active.raw.tier != TxPlayoutTier::Unavailable; + result.backend_start_sequence = active.backend_start_sequence; + result.stop = active.stop; + result.diagnostic = combinedDiagnostic ( + combinedDiagnostic (active.start.diagnostic, + active.source_progress_diagnostic), + active.raw.diagnostic); + return result; + } +} diff --git a/Audio/TxPlaybackDiagnostics.hpp b/Audio/TxPlaybackDiagnostics.hpp new file mode 100644 index 00000000..d40ab2d8 --- /dev/null +++ b/Audio/TxPlaybackDiagnostics.hpp @@ -0,0 +1,70 @@ +#ifndef TX_PLAYBACK_DIAGNOSTICS_HPP_ +#define TX_PLAYBACK_DIAGNOSTICS_HPP_ + +#include <QVector> + +#include "Audio/TxPlaybackEvidence.hpp" + +namespace TxEvidence +{ + class TxPlaybackDiagnostics + { + public: + TxPlaybackDiagnostics (); + ~TxPlaybackDiagnostics (); + + static TxSessionId allocateSessionId (); + static TxGeneration allocateGeneration (); + static TxStopDecision decisionFor (TxStopReason reason, bool zeroTailMode); + + TxSessionId beginSession (QString const& mode, int sampleRateHz, + qint64 committedEndSample = -1, + bool targetKnown = false, + QString const& diagnostic = QString ()); + TxGeneration beginGeneration (TxSessionId sessionId); + bool commitStart (TxStartSnapshot const& snapshot); + bool commitTarget (TxSessionId sessionId, TxGeneration generation, + qint64 committedEndSample, bool targetKnown = true, + QString const& diagnostic = QString ()); + bool observeSourceProgress (TxSessionId sessionId, TxGeneration generation, + qint64 servedSamples, qint64 totalSamples, + QString const& diagnostic = QString ()); + bool observe (TxSessionId sessionId, TxGeneration generation, + TxRawPlayoutSnapshot const& raw); + TxStopDecision stop (TxSessionId sessionId, TxGeneration generation, + TxStopReason reason, int legacyTailMs = 0); + + QVector<TxTerminalSession> terminalSessions () const; + QString diagnosticDump () const; + + private: + struct ActiveSession + { + TxStartSnapshot start; + TxRawPlayoutSnapshot raw; + TxPlayoutSnapshot playout; + qint64 source_served_frames {-1}; + qint64 source_total_frames {-1}; + QString source_progress_diagnostic; + bool claimed {true}; + bool bound {false}; + bool underrun {false}; + qint64 backend_start_sequence {0}; + bool stopped {false}; + TxStopDecision stop; + }; + + ActiveSession * findActive (TxSessionId sessionId, + TxGeneration generation); + ActiveSession const * findActive (TxSessionId sessionId, + TxGeneration generation) const; + static TxPlayoutSnapshot normalize (TxStartSnapshot const& start, + TxRawPlayoutSnapshot const& raw); + static TxTerminalSession terminal (ActiveSession const& active); + + QVector<ActiveSession> active_; + QVector<TxTerminalSession> terminal_; + }; +} + +#endif diff --git a/Audio/TxPlaybackEvidence.hpp b/Audio/TxPlaybackEvidence.hpp new file mode 100644 index 00000000..568a0c91 --- /dev/null +++ b/Audio/TxPlaybackEvidence.hpp @@ -0,0 +1,144 @@ +#ifndef TX_PLAYBACK_EVIDENCE_HPP_ +#define TX_PLAYBACK_EVIDENCE_HPP_ + +#include <QMetaType> +#include <QString> +#include <QtGlobal> + +#include "Audio/TxIdentity.hpp" + +namespace TxEvidence +{ + inline qint64 boundedCommittedEndSample (qint64 leadingSilentFrames, + qint64 firstSourceSample, + qint64 lastSourceSample) noexcept + { + if (leadingSilentFrames < 0 || firstSourceSample < 0 || + lastSourceSample < firstSourceSample) + { + return -1; + } + return leadingSilentFrames + lastSourceSample - firstSourceSample; + } + + inline qint64 interleavedFrameCount (qint64 scalarCount, + int channelCount) noexcept + { + if (scalarCount < 0 || channelCount <= 0 || scalarCount % channelCount) + { + return -1; + } + return scalarCount / channelCount; + } + + enum class TxPlayoutTier + { + Unavailable, + DeadReckoning, + DeviceClock + }; + + enum class TxBackendState + { + Unavailable, + Active, + Idle, + Suspended, + Stopped, + Interrupted, + Unknown + }; + + enum class TxBackendError + { + None, + Open, + Io, + Underrun, + Fatal, + Unknown + }; + + enum class TxStopReason + { + NormalEnd, + UserHalt, + Watchdog, + Error, + ModeChange + }; + + struct TxStartSnapshot + { + TxSessionId session_id; + TxGeneration generation; + QString mode; + int sample_rate_hz {0}; + qint64 committed_end_sample {-1}; + bool target_known {false}; + QString diagnostic; + }; + + struct TxRawPlayoutSnapshot + { + TxPlayoutTier tier {TxPlayoutTier::Unavailable}; + qint64 backend_start_sequence {0}; + bool start_event {false}; + bool available {false}; + TxBackendState state {TxBackendState::Unavailable}; + TxBackendError error {TxBackendError::None}; + qint64 available_bytes {-1}; + qint64 buffered_bytes {-1}; + qint64 capacity_bytes {-1}; + qint64 processed_usecs {-1}; + qint64 elapsed_usecs {-1}; + qint64 successfully_written_frames {-1}; + qint64 source_served_frames {-1}; + qint64 source_total_frames {-1}; + int channel_count {0}; + int bytes_per_frame {0}; + int sample_rate_hz {0}; + int report_interval_ms {0}; + QString diagnostic; + }; + + struct TxPlayoutSnapshot + { + TxSessionId session_id; + TxGeneration generation; + TxRawPlayoutSnapshot raw; + qint64 consumed_samples {-1}; + qint64 uncertainty_samples {-1}; + }; + + struct TxStopDecision + { + int tail_ms {0}; + TxStopReason reason {TxStopReason::NormalEnd}; + }; + + struct TxTerminalSession + { + TxSessionId session_id; + TxGeneration generation; + QString mode; + TxPlayoutTier tier {TxPlayoutTier::Unavailable}; + bool target_known {false}; + qint64 committed_end_sample {-1}; + qint64 source_served_samples {-1}; + qint64 consumed_samples {-1}; + qint64 uncertainty_samples {-1}; + bool underrun {false}; + bool truncated_known {false}; + bool truncated {false}; + bool terminal_playout_observed {false}; + qint64 backend_start_sequence {0}; + TxStopDecision stop; + QString diagnostic; + }; +} + +Q_DECLARE_METATYPE (TxEvidence::TxStartSnapshot) +Q_DECLARE_METATYPE (TxEvidence::TxRawPlayoutSnapshot) + +#endif diff --git a/Audio/TxRequest.hpp b/Audio/TxRequest.hpp new file mode 100644 index 00000000..ccb736b0 --- /dev/null +++ b/Audio/TxRequest.hpp @@ -0,0 +1,73 @@ +#ifndef TX_REQUEST_HPP_ +#define TX_REQUEST_HPP_ + +#include <QMetaType> +#include <QString> +#include <QVector> +#include <QtGlobal> + +#include "AudioDevice.hpp" +#include "TxAudioQueue.hpp" +#include "TxIdentity.hpp" + +namespace TxEvidence +{ + struct TxRequest + { + QString mode {"FT8"}; + unsigned symbols_length {79}; + double frames_per_symbol {1920.0}; + double frequency_hz {1500.0}; + double tone_spacing {-3.0}; + AudioDevice::Channel channel {AudioDevice::Mono}; + bool synchronize {true}; + bool fast_mode {false}; + double snr_db {99.0}; + double tr_period_s {60.0}; + TxSessionId session_id {}; + TxGeneration generation {}; + TxAudioQueueEpoch queue_epoch {}; + bool tuning {false}; + QVector<int> cw_id; + qint64 start_window_open_ms {-1}; + qint64 start_window_close_ms {-1}; + }; + + inline bool operator == (TxRequest const& lhs, TxRequest const& rhs) + { + return lhs.mode == rhs.mode + && lhs.symbols_length == rhs.symbols_length + && lhs.frames_per_symbol == rhs.frames_per_symbol + && lhs.frequency_hz == rhs.frequency_hz + && lhs.tone_spacing == rhs.tone_spacing + && lhs.channel == rhs.channel + && lhs.synchronize == rhs.synchronize + && lhs.fast_mode == rhs.fast_mode + && lhs.snr_db == rhs.snr_db + && lhs.tr_period_s == rhs.tr_period_s + && lhs.session_id == rhs.session_id + && lhs.generation == rhs.generation + && lhs.queue_epoch == rhs.queue_epoch + && lhs.tuning == rhs.tuning + && lhs.cw_id == rhs.cw_id + && lhs.start_window_open_ms == rhs.start_window_open_ms + && lhs.start_window_close_ms == rhs.start_window_close_ms; + } + + inline bool operator != (TxRequest const& lhs, TxRequest const& rhs) + { + return !(lhs == rhs); + } +} + +Q_DECLARE_METATYPE (TxEvidence::TxRequest) + +namespace TxEvidence +{ + inline int register_tx_request_type () + { + return qRegisterMetaType<TxRequest> ("TxEvidence::TxRequest"); + } +} + +#endif diff --git a/Audio/WavFile.cpp b/Audio/WavFile.cpp new file mode 100644 index 00000000..b1c6bb55 --- /dev/null +++ b/Audio/WavFile.cpp @@ -0,0 +1,147 @@ +#include "WavFile.hpp" +#include <algorithm> +#include <limits> +#include <QAudioFormat> +#include <QDateTime> +#include "Audio/BWFFile.hpp" +#include "revision_utils.hpp" + +namespace +{ +bool has_native_byte_order (QAudioFormat const& format) +{ +#if Q_BYTE_ORDER == Q_LITTLE_ENDIAN + return QAudioFormat::LittleEndian == format.byteOrder (); +#else + return QAudioFormat::BigEndian == format.byteOrder (); +#endif +} + +bool is_supported_decode_format (QAudioFormat const& format) +{ + if ("audio/pcm" != format.codec () || 1 != format.channelCount ()) + { + return false; + } + + if (11025 == format.sampleRate () && 8 == format.sampleSize ()) + { + return QAudioFormat::UnSignedInt == format.sampleType (); + } + + return (11025 == format.sampleRate () || 12000 == format.sampleRate ()) + && 16 == format.sampleSize () + && QAudioFormat::SignedInt == format.sampleType () + && has_native_byte_order (format); +} +} + +namespace Radio +{ + +WavFile::LoadResult WavFile::load (QString const& name, int max_frames) +{ + LoadResult result; + if (max_frames <= 0) + { + result.error = name + ": invalid WAV frame limit"; + return result; + } + + BWFFile file {QAudioFormat {}, name}; + if (!file.open (BWFFile::ReadOnly)) + { + result.error = name + ": " + file.errorString (); + return result; + } + + result.format = file.format (); + auto const bytes_per_frame = result.format.bytesPerFrame (); + if (!is_supported_decode_format (result.format) || bytes_per_frame <= 0) + { + result.error = name + ": unsupported WAV format"; + return result; + } + + auto max_bytes = std::min<qint64> ( + static_cast<qint64> (max_frames) * bytes_per_frame, + (std::numeric_limits<int>::max) ()); + max_bytes -= max_bytes % bytes_per_frame; + auto bytes_to_read = std::min (max_bytes, file.size ()); + bytes_to_read -= bytes_to_read % bytes_per_frame; + + result.samples.resize (static_cast<int> (bytes_to_read)); + qint64 bytes_read {0}; + if (bytes_to_read > 0) + { + bytes_read = file.read (result.samples.data (), bytes_to_read); + if (bytes_read < 0) + { + result.samples.clear (); + result.error = name + ": " + file.errorString (); + return result; + } + } + + bytes_read -= bytes_read % bytes_per_frame; + result.samples.resize (static_cast<int> (bytes_read)); + result.frames = static_cast<int> (bytes_read / bytes_per_frame); + return result; +} + +QString WavFile::save (QString const& name, short const * data, int samples, + QString const& my_callsign, QString const& my_grid, + QString const& mode, qint32 sub_mode, + Frequency frequency, QString const& his_call, + QString const& his_grid, QString const& dgrd) +{ + QAudioFormat format; + format.setCodec ("audio/pcm"); + format.setSampleRate (12000); + format.setChannelCount (1); + format.setSampleSize (16); + format.setSampleType (QAudioFormat::SignedInt); + auto source = QString {"%1; %2"}.arg (my_callsign).arg (my_grid); + auto comment = QString {"Mode=%1%2; Freq=%3%4"} + .arg (mode) + .arg (QString {(mode.contains ('J') && !mode.contains ('+')) + || mode.startsWith ("FST4") || mode.startsWith ('Q') + ? QString {"; Sub Mode="} + QString::number (int (samples / 12000)) + QChar {'A' + sub_mode} + : QString {}}) + .arg (Radio::frequency_MHz_string (frequency)) + .arg (QString {mode!="WSPR" ? QString {"; DXCall=%1; DXGrid=%2"} + .arg (his_call) + .arg (his_grid).toLocal8Bit () : ""}); + BWFFile::InfoDictionary list_info { + {{{'I','S','R','C'}}, source.toLocal8Bit ()}, + {{{'I','S','F','T'}}, program_title (revision ()).simplified ().toLocal8Bit ()}, + {{{'I','C','R','D'}}, QDateTime::currentDateTimeUtc () + .toString ("yyyy-MM-ddTHH:mm:ss.zzzZ").toLocal8Bit ()}, + {{{'I','C','M','T'}}, comment.toLocal8Bit ()}, + {{{'D','G','R','D'}}, dgrd.toLocal8Bit()}, //added for Bob KA1GT + }; + auto file_name = name + ".wav"; + BWFFile wav {format, file_name, list_info}; + if (!wav.open (BWFFile::WriteOnly) + || 0 > wav.write (reinterpret_cast<char const *> (data) + , sizeof (short) * samples)) + { + return file_name + ": " + wav.errorString (); + } + return QString {}; +} + +void WavFile::killWaveFile (QString const& name, bool saveAll, bool saveDecoded, + bool bDecoded, QString const& mode) +{ + if (name.size () && !(saveAll || (saveDecoded && bDecoded))) { + QFile f1 {name + ".wav"}; + if (f1.exists ()) f1.remove (); + if (mode == "WSPR" || mode == "FST4W") { + QFile f2 {name + ".c2"}; + if (f2.exists ()) f2.remove (); + } + } +} + +} diff --git a/Audio/WavFile.hpp b/Audio/WavFile.hpp new file mode 100644 index 00000000..05c82820 --- /dev/null +++ b/Audio/WavFile.hpp @@ -0,0 +1,37 @@ +#ifndef WAVFILE_HPP +#define WAVFILE_HPP + +#include <QAudioFormat> +#include <QByteArray> +#include <QString> +#include "Radio.hpp" + +namespace Radio +{ + +class WavFile +{ +public: + struct LoadResult + { + QByteArray samples; + QAudioFormat format; + QString error; + int frames {0}; + + bool isValid () const {return error.isEmpty ();} + }; + + static LoadResult load (QString const& name, int max_frames); + static QString save (QString const& name, short const * data, int samples, + QString const& my_callsign, QString const& my_grid, + QString const& mode, qint32 sub_mode, + Frequency frequency, QString const& his_call, + QString const& his_grid, QString const& dgrd); + static void killWaveFile (QString const& name, bool saveAll, bool saveDecoded, + bool bDecoded, QString const& mode); +}; + +} + +#endif // WAVFILE_HPP diff --git a/Audio/WavInputLoader.cpp b/Audio/WavInputLoader.cpp new file mode 100644 index 00000000..b28125c5 --- /dev/null +++ b/Audio/WavInputLoader.cpp @@ -0,0 +1,78 @@ +#include "WavInputLoader.hpp" + +#include <algorithm> +#include <cstring> +#include <mutex> + +#include "Audio/WavFile.hpp" + +extern "C" +{ + void wav12_ (short d2[], short d1[], int * frames, short * sample_size); +} + +namespace +{ +int constexpr wav12_output_capacity = 60 * 12000; +std::mutex wav12_mutex; +} + +namespace Radio +{ + +WavInputResult load_wav_input (QString const& name, int sample_limit) +{ + WavInputResult result; + auto const basename = name.mid (name.lastIndexOf ('/') + 1); + auto const wav_position = name.indexOf (".wav", 0, Qt::CaseInsensitive); + auto const case_sensitive_position = name.indexOf (".wav"); + auto const directory_position = name.lastIndexOf ('/'); + if (wav_position > 0) + { + if (case_sensitive_position - directory_position > 13) + { + result.nutc = basename.mid (7, 6).toInt (); + result.fileDateTime = basename.mid (0, 13); + } + else if (wav_position == name.indexOf ('_', -11) + 7) + { + result.nutc = name.mid (wav_position - 6, 6).toInt (); + result.fileDateTime = name.mid (wav_position - 13, 13); + } + else + { + result.nutc = 100 * name.mid (wav_position - 4, 4).toInt (); + result.fileDateTime = name.mid (wav_position - 11, 11); + } + } + + auto const wav = WavFile::load (name, sample_limit); + if (wav.isValid ()) + { + result.samples.assign (sample_limit, 0); + if (!wav.samples.isEmpty ()) + { + std::memcpy (result.samples.data (), wav.samples.constData (), wav.samples.size ()); + } + + auto frames_read = wav.frames; + if (11025 == wav.format.sampleRate ()) + { + result.samples.resize (std::max (sample_limit, wav12_output_capacity), 0); + short sample_size = wav.format.sampleSize (); + { + std::lock_guard<std::mutex> lock {wav12_mutex}; + wav12_ (result.samples.data (), result.samples.data (), &frames_read, &sample_size); + } + frames_read = std::min (frames_read, sample_limit); + result.samples.resize (sample_limit); + } + result.frames = frames_read; + result.valid = true; + } + + result.yymmdd = basename.left (6).toInt (); + return result; +} + +} diff --git a/Audio/WavInputLoader.hpp b/Audio/WavInputLoader.hpp new file mode 100644 index 00000000..8071ea9f --- /dev/null +++ b/Audio/WavInputLoader.hpp @@ -0,0 +1,25 @@ +#ifndef WAV_INPUT_LOADER_HPP +#define WAV_INPUT_LOADER_HPP + +#include <vector> + +#include <QString> + +namespace Radio +{ + +struct WavInputResult +{ + std::vector<short> samples; + QString fileDateTime; + int frames {0}; + int nutc {0}; + int yymmdd {0}; + bool valid {false}; +}; + +WavInputResult load_wav_input (QString const& name, int sample_limit); + +} + +#endif // WAV_INPUT_LOADER_HPP diff --git a/Audio/WavLoadCoordinator.cpp b/Audio/WavLoadCoordinator.cpp new file mode 100644 index 00000000..3069f67e --- /dev/null +++ b/Audio/WavLoadCoordinator.cpp @@ -0,0 +1,82 @@ +#include "WavLoadCoordinator.hpp" + +#include <utility> + +#include <QPointer> +#include <QtConcurrent/QtConcurrentRun> + +#include "DecDataMutex.hpp" + +WavLoadCoordinator::WavLoadCoordinator (QObject * parent) + : QObject {parent} +{ + connect (&watcher_, &QFutureWatcher<Result>::finished, + this, &WavLoadCoordinator::handleFinished); +} + +WavLoadCoordinator::~WavLoadCoordinator () +{ + waitForFinished (); + if (loading_) + { + set_dec_data_input_blocked (false); + loading_ = false; + } +} + +bool WavLoadCoordinator::start (Work work) +{ + if (loading_ || !work) + { + return false; + } + + result_.reset (); + loading_ = true; + set_dec_data_input_blocked (true); + QPointer<WavLoadCoordinator> guard {this}; + Q_EMIT loadingChanged (true); + if (!guard) + { + return false; + } + watcher_.setFuture (QtConcurrent::run (std::move (work))); + return true; +} + +bool WavLoadCoordinator::isLoading () const +{ + return loading_; +} + +WavLoadCoordinator::Result WavLoadCoordinator::result () const +{ + return result_; +} + +void WavLoadCoordinator::waitForFinished () +{ + watcher_.waitForFinished (); +} + +void WavLoadCoordinator::handleFinished () +{ + try + { + result_ = watcher_.result (); + } + catch (...) + { + result_ = std::make_shared<Radio::WavInputResult> (); + } + + QPointer<WavLoadCoordinator> guard {this}; + Q_EMIT resultReady (); + if (!guard) + { + return; + } + set_dec_data_input_blocked (false); + loading_ = false; + Q_EMIT loadingChanged (false); +} diff --git a/Audio/WavLoadCoordinator.hpp b/Audio/WavLoadCoordinator.hpp new file mode 100644 index 00000000..9f4204d7 --- /dev/null +++ b/Audio/WavLoadCoordinator.hpp @@ -0,0 +1,40 @@ +#ifndef WAV_LOAD_COORDINATOR_HPP +#define WAV_LOAD_COORDINATOR_HPP + +#include <functional> +#include <memory> + +#include <QFutureWatcher> +#include <QObject> + +#include "Audio/WavInputLoader.hpp" + +class WavLoadCoordinator : public QObject +{ + Q_OBJECT + +public: + using Result = std::shared_ptr<Radio::WavInputResult>; + using Work = std::function<Result ()>; + + explicit WavLoadCoordinator (QObject * parent = nullptr); + ~WavLoadCoordinator () override; + + bool start (Work work); + bool isLoading () const; + Result result () const; + void waitForFinished (); + +Q_SIGNALS: + void loadingChanged (bool loading); + void resultReady (); + +private: + void handleFinished (); + + bool loading_ {false}; + Result result_; + QFutureWatcher<Result> watcher_; +}; + +#endif // WAV_LOAD_COORDINATOR_HPP diff --git a/Audio/soundin.cpp b/Audio/soundin.cpp index 89d86782..24844864 100644 --- a/Audio/soundin.cpp +++ b/Audio/soundin.cpp @@ -21,10 +21,12 @@ bool SoundInput::checkStream () switch (m_stream->error ()) { case QAudio::OpenError: + if (!m_destroying) clearStreamDescriptor (); Q_EMIT error (tr ("An error opening the audio input device has occurred.")); break; case QAudio::IOError: + if (!m_destroying) clearStreamDescriptor (); Q_EMIT error (tr ("An error occurred during read from the audio input device.")); break; @@ -33,6 +35,7 @@ bool SoundInput::checkStream () // break; case QAudio::FatalError: + if (!m_destroying) clearStreamDescriptor (); Q_EMIT error (tr ("Non-recoverable error, audio input device not usable at this time.")); break; @@ -46,6 +49,29 @@ bool SoundInput::checkStream () return result; } +void SoundInput::publishStreamDescriptor () +{ + if (!m_stream) + { + return; + } + + auto descriptor = audioStreamDescriptorFromQAudioFormat (m_stream->format ()); + if (descriptor.isValid ()) + { + descriptor.clock_domain = + AudioStreamDescriptor::ClockDomain::DeviceClock; + descriptor.timing_evidence = + AudioStreamDescriptor::TimingEvidence::PositionCountable; + descriptor.can_report_discontinuities = false; + setStreamDescriptor (descriptor); + } + else + { + LOG_WARN ("Opened input audio stream has an unrecognized format"); + } +} + void SoundInput::start(QAudioDeviceInfo const& device, int framesPerBuffer, AudioDevice * sink , unsigned downSampleFactor, AudioDevice::Channel channel) { @@ -53,6 +79,11 @@ void SoundInput::start(QAudioDeviceInfo const& device, int framesPerBuffer, Audi stop (); + if (device.isNull ()) + { + return; + } + m_sink = sink; QAudioFormat format (device.preferredFormat()); @@ -95,8 +126,12 @@ void SoundInput::start(QAudioDeviceInfo const& device, int framesPerBuffer, Audi if (m_sink->initialize (QIODevice::WriteOnly, channel)) { m_stream->start (sink); - checkStream (); + auto const stream_ok = checkStream (); cummulative_lost_usec_ = -1; + if (stream_ok) + { + publishStreamDescriptor (); + } // LOG_DEBUG ("Selected buffer size (bytes): " << m_stream->bufferSize () << " period size: " << m_stream->periodSize ()); } else @@ -127,7 +162,10 @@ void SoundInput::resume () { // m_stream->resume (); m_stream->start (m_sink); // better stop and restart audio (fixes issues on Linux and macOS) - checkStream (); + if (checkStream ()) + { + publishStreamDescriptor (); + } } } @@ -208,9 +246,11 @@ void SoundInput::stop() m_stream->stop (); } m_stream.reset (); + if (!m_destroying) clearStreamDescriptor (); } SoundInput::~SoundInput () { + m_destroying = true; stop (); } diff --git a/Audio/soundin.h b/Audio/soundin.h index 823993c6..752338ee 100644 --- a/Audio/soundin.h +++ b/Audio/soundin.h @@ -3,53 +3,51 @@ #define SOUNDIN_H__ #include <limits> -#include <QObject> #include <QString> #include <QDateTime> #include <QScopedPointer> #include <QPointer> #include <QAudioInput> -#include "Audio/AudioDevice.hpp" +#include "Audio/AudioInputSource.hpp" class QAudioDeviceInfo; class QAudioInput; // Gets audio data from sound sample source and passes it to a sink device class SoundInput - : public QObject + final : public AudioInputSource { Q_OBJECT; public: SoundInput (QObject * parent = nullptr) - : QObject {parent} + : AudioInputSource {parent} , cummulative_lost_usec_ {std::numeric_limits<qint64>::min ()} { } - ~SoundInput (); + ~SoundInput () override; // 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; + Q_SLOT void start(QAudioDeviceInfo const&, int framesPerBuffer, AudioDevice * sink, unsigned downSampleFactor, AudioDevice::Channel = AudioDevice::Mono) override; + Q_SLOT void suspend () override; + Q_SLOT void resume () override; + Q_SLOT void stop () override; + Q_SLOT void reset (bool report_dropped_frames) override; private: // used internally Q_SLOT void handleStateChanged (QAudio::State); bool checkStream (); + void publishStreamDescriptor (); QScopedPointer<QAudioInput> m_stream; QPointer<AudioDevice> m_sink; qint64 cummulative_lost_usec_; + bool m_destroying {false}; }; #endif diff --git a/Audio/soundout.cpp b/Audio/soundout.cpp index 8a5d6d30..55a0104a 100644 --- a/Audio/soundout.cpp +++ b/Audio/soundout.cpp @@ -12,6 +12,37 @@ #include "moc_soundout.cpp" +namespace +{ + TxEvidence::TxBackendState txBackendState (QAudio::State state) noexcept + { + switch (state) + { + case QAudio::ActiveState: return TxEvidence::TxBackendState::Active; + case QAudio::IdleState: return TxEvidence::TxBackendState::Idle; + case QAudio::SuspendedState: return TxEvidence::TxBackendState::Suspended; + case QAudio::StoppedState: return TxEvidence::TxBackendState::Stopped; +#if QT_VERSION >= QT_VERSION_CHECK (5, 10, 0) + case QAudio::InterruptedState: return TxEvidence::TxBackendState::Interrupted; +#endif + } + return TxEvidence::TxBackendState::Unknown; + } + + TxEvidence::TxBackendError txBackendError (QAudio::Error error) noexcept + { + switch (error) + { + case QAudio::NoError: return TxEvidence::TxBackendError::None; + case QAudio::OpenError: return TxEvidence::TxBackendError::Open; + case QAudio::IOError: return TxEvidence::TxBackendError::Io; + case QAudio::UnderrunError: return TxEvidence::TxBackendError::Underrun; + case QAudio::FatalError: return TxEvidence::TxBackendError::Fatal; + } + return TxEvidence::TxBackendError::Unknown; + } +} + bool SoundOutput::checkStream () const { bool result {false}; @@ -54,6 +85,8 @@ void SoundOutput::setFormat (QAudioDeviceInfo const& device, unsigned channels, void SoundOutput::restart (QIODevice * source) { + ++m_backendStartSequence; + bool failed {false}; if (!m_device.isNull ()) { QAudioFormat format (m_device.preferredFormat ()); @@ -67,10 +100,12 @@ void SoundOutput::restart (QIODevice * source) if (!format.isValid ()) { Q_EMIT error (tr ("Requested output audio format is not valid.")); + failed = true; } else if (!m_device.isFormatSupported (format)) { Q_EMIT error (tr ("Requested output audio format is not supported on device.")); + failed = true; } else { @@ -82,11 +117,22 @@ void SoundOutput::restart (QIODevice * source) error_ = false; connect (m_stream.data(), &QAudioOutput::stateChanged, this, &SoundOutput::handleStateChanged); - connect (m_stream.data(), &QAudioOutput::notify, [this] () {checkStream ();}); + connect (m_stream.data(), &QAudioOutput::notify, [this] () { + checkStream (); + publishRawTxPlayoutSnapshot (); + }); // qDebug() << "A" << m_volume << m_stream->notifyInterval(); } } + else + { + failed = true; + } + if (failed) + { + publishUnavailableTxPlayoutSnapshot (true, tr ("Audio output restart attempt failed.")); + } if (!m_stream) { if (!error_) @@ -94,6 +140,10 @@ void SoundOutput::restart (QIODevice * source) error_ = true; // only signal error once Q_EMIT error (tr ("No audio output device configured.")); } + if (!failed) + { + publishUnavailableTxPlayoutSnapshot (true, tr ("No audio output device configured.")); + } return; } else @@ -111,6 +161,7 @@ void SoundOutput::restart (QIODevice * source) } m_stream->setCategory ("production"); m_stream->start (source); + publishRawTxPlayoutSnapshot (true); // LOG_DEBUG ("Selected buffer size (bytes): " << m_stream->bufferSize () << " period size: " << m_stream->periodSize ()); } @@ -120,6 +171,7 @@ void SoundOutput::suspend () { m_stream->suspend (); checkStream (); + publishRawTxPlayoutSnapshot (); } } @@ -129,6 +181,7 @@ void SoundOutput::resume () { m_stream->resume (); checkStream (); + publishRawTxPlayoutSnapshot (); } } @@ -136,8 +189,15 @@ void SoundOutput::reset () { if (m_stream) { + auto const beforeReset = makeRawTxPlayoutSnapshot (); m_stream->reset (); checkStream (); + Q_EMIT rawTxPlayoutSnapshot (beforeReset); + publishRawTxPlayoutSnapshot (); + } + else + { + publishRawTxPlayoutSnapshot (); } } @@ -145,8 +205,15 @@ void SoundOutput::stop () { if (m_stream) { + auto const beforeStop = makeRawTxPlayoutSnapshot (); m_stream->reset (); m_stream->stop (); + Q_EMIT rawTxPlayoutSnapshot (beforeStop); + publishRawTxPlayoutSnapshot (); + } + else + { + publishRawTxPlayoutSnapshot (); } #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! @@ -160,6 +227,59 @@ qreal SoundOutput::attenuation () const return -(20. * qLn (m_volume) / qLn (10.)); } +int SoundOutput::bufferSize () const +{ + return m_stream ? m_stream->bufferSize () : 0; +} + +TxEvidence::TxRawPlayoutSnapshot SoundOutput::makeRawTxPlayoutSnapshot (bool startEvent) const +{ + TxEvidence::TxRawPlayoutSnapshot snapshot; + if (!m_stream) return snapshot; + + QAudioFormat const format {m_stream->format ()}; + qint64 const capacity {m_stream->bufferSize ()}; + qint64 const available {m_stream->bytesFree ()}; + snapshot.tier = TxEvidence::TxPlayoutTier::DeviceClock; + snapshot.backend_start_sequence = m_backendStartSequence; + snapshot.start_event = startEvent; + snapshot.available = true; + snapshot.state = txBackendState (m_stream->state ()); + snapshot.error = txBackendError (m_stream->error ()); + snapshot.available_bytes = available; + snapshot.buffered_bytes = capacity >= 0 && available >= 0 ? qMax<qint64> (0, capacity - available) : -1; + snapshot.capacity_bytes = capacity; + snapshot.processed_usecs = m_stream->processedUSecs (); + snapshot.elapsed_usecs = m_stream->elapsedUSecs (); + snapshot.channel_count = format.channelCount (); + snapshot.bytes_per_frame = format.bytesPerFrame (); + snapshot.sample_rate_hz = format.sampleRate (); + snapshot.report_interval_ms = m_stream->notifyInterval (); + return snapshot; +} + +void SoundOutput::publishRawTxPlayoutSnapshot (bool startEvent) const +{ + if (!m_stream) + { + publishUnavailableTxPlayoutSnapshot (startEvent, tr ("No audio output stream is active.")); + return; + } + auto const snapshot = makeRawTxPlayoutSnapshot (startEvent); + Q_EMIT rawTxPlayoutSnapshot (snapshot); +} + +void SoundOutput::publishUnavailableTxPlayoutSnapshot (bool startEvent, QString const& diagnostic) const +{ + TxEvidence::TxRawPlayoutSnapshot snapshot; + snapshot.backend_start_sequence = m_backendStartSequence; + snapshot.start_event = startEvent; + snapshot.state = TxEvidence::TxBackendState::Unavailable; + snapshot.error = TxEvidence::TxBackendError::Open; + snapshot.diagnostic = diagnostic; + Q_EMIT rawTxPlayoutSnapshot (snapshot); +} + void SoundOutput::setAttenuation (qreal a) { Q_ASSERT (0. <= a && a <= 999.); @@ -186,10 +306,12 @@ void SoundOutput::handleStateChanged (QAudio::State newState) { case QAudio::IdleState: Q_EMIT status (tr ("Idle")); + Q_EMIT audioOutputIdle (); break; case QAudio::ActiveState: Q_EMIT status (tr ("Sending")); + Q_EMIT audioOutputActive (); break; case QAudio::SuspendedState: @@ -213,4 +335,5 @@ void SoundOutput::handleStateChanged (QAudio::State newState) } break; } + publishRawTxPlayoutSnapshot (); } diff --git a/Audio/soundout.h b/Audio/soundout.h index 387c1b0f..ad72ea82 100644 --- a/Audio/soundout.h +++ b/Audio/soundout.h @@ -8,6 +8,8 @@ #include <QAudioDeviceInfo> #include <QOperatingSystemVersion> +#include "Audio/TxPlaybackEvidence.hpp" + class QIODevice; class QAudioDeviceInfo; @@ -19,31 +21,49 @@ class SoundOutput Q_OBJECT; public: - SoundOutput () - : m_framesBuffered {0} + explicit SoundOutput (QObject * parent = nullptr) + : QObject {parent} + , m_framesBuffered {0} , m_volume {1.0} , error_ {false} + , m_backendStartSequence {0} { } qreal attenuation () const; + // Device buffer size in bytes, or 0 when no stream is active. Call only on the + // audio thread (this object's thread); QAudioOutput is not cross-thread safe. + virtual int bufferSize () const; + public Q_SLOTS: - void setFormat (QAudioDeviceInfo const& device, unsigned channels, int frames_buffered = 0); - void restart (QIODevice *); + virtual void setFormat (QAudioDeviceInfo const& device, unsigned channels, + int frames_buffered = 0); + virtual void restart (QIODevice *); + virtual void restart (QIODevice * source, qint64 period_offset_ms) + { + Q_UNUSED (period_offset_ms); + restart (source); + } void suspend (); void resume (); void reset (); - void stop (); + virtual void stop (); void setAttenuation (qreal); /* unsigned */ void resetAttenuation (); /* to zero */ Q_SIGNALS: void error (QString message) const; void status (QString message) const; + void audioOutputActive () const; + void audioOutputIdle () const; + void rawTxPlayoutSnapshot (TxEvidence::TxRawPlayoutSnapshot snapshot) const; private: bool checkStream () const; + TxEvidence::TxRawPlayoutSnapshot makeRawTxPlayoutSnapshot (bool startEvent = false) const; + void publishRawTxPlayoutSnapshot (bool startEvent = false) const; + void publishUnavailableTxPlayoutSnapshot (bool startEvent, QString const& diagnostic) const; private Q_SLOTS: void handleStateChanged (QAudio::State); @@ -55,6 +75,7 @@ private: int m_framesBuffered; qreal m_volume; bool error_; + qint64 m_backendStartSequence; }; #endif |
