1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
|
#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,
unsigned pacingSpeed,
QObject * parent)
: AudioInputSource {parent}
, m_path {std::move (path)}
, m_profile {profile}
, m_pacingSpeed {profile == Profile::Jtty ? pacingSpeed : 1}
, 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 ();
if (m_sink) m_sink->finishInput ();
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_pacingStartMs = QDateTime::currentMSecsSinceEpoch ()
- (m_framesEmitted * 1000 / m_inputSampleRate);
if (Profile::Jtty != m_profile) m_periodStartMs = m_pacingStartMs;
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;
}
qint64 FixtureAudioInput::pacingTimestamp (qint64 frameIndex) const
{
return m_pacingStartMs + 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 ();
if (m_sink) m_sink->finishInput ();
m_sink.clear ();
m_pcm.clear ();
m_leadInFrames = 0;
m_tailFrames = 0;
m_framesEmitted = 0;
m_periodStartMs = 0;
m_pacingStartMs = 0;
m_jttyAcknowledgedInputFrames = 0;
m_emissionTimer.invalidate ();
m_nextChunkMs = 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 || !m_started
|| !m_emitting || m_suspended || !m_sink
|| m_framesEmitted >= totalFrames ()) 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
|| m_framesEmitted >= totalFrames ())
{
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
{
m_periodStartMs = (now / 180000) * 180000 + jttyCaptureOffsetMs ();
}
m_pacingStartMs = Profile::Jtty == m_profile ? now : m_periodStartMs;
m_emissionTimer.start ();
m_emitting = true;
publishCaptureAnchor (m_framesEmitted);
if (Profile::ReceiveHandoff == m_profile) return;
auto const delay = Profile::Jtty == m_profile && m_pacingSpeed > 1
? qint64 {1} : std::max<qint64> (0, m_pacingStartMs - now);
m_timer->start (static_cast<int> (delay));
}
void FixtureAudioInput::scheduleNextChunk ()
{
if (!m_started || !m_armed || !m_emitting || m_suspended || !m_sink
|| m_framesEmitted >= totalFrames ()) return;
if (Profile::Jtty == m_profile && m_pacingSpeed > 1)
{
auto const delay = std::max<qint64> (1, m_nextChunkMs - m_emissionTimer.elapsed ());
m_timer->start (static_cast<int> (delay));
return;
}
if (Profile::ReceiveHandoff == m_profile)
{
m_timer->start (0);
return;
}
auto const target = pacingTimestamp (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 = pacingTimestamp (m_framesEmitted);
auto const now = QDateTime::currentMSecsSinceEpoch ();
if (Profile::ReceiveHandoff != m_profile
&& !(Profile::Jtty == m_profile && m_pacingSpeed > 1) && now < target)
{
m_timer->start (static_cast<int> (target - now));
return;
}
if (!m_framesEmitted)
{
Q_EMIT emissionStarted (m_periodStartMs);
}
auto const remainingFrames = totalFrames () - m_framesEmitted;
auto chunkFrames = std::min<qint64> (
remainingFrames, m_chunkFrames.at (m_chunkIndex % m_chunkFrames.size ()));
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;
if (chunkFrames > allowedFrames - m_framesEmitted)
{
m_waitingForJttyDecoder = true;
return;
}
m_waitingForJttyDecoder = false;
}
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 (Profile::Jtty == m_profile)
{
auto const scaledRate = qint64 {m_inputSampleRate} * m_pacingSpeed;
// Decoder backpressure must not accumulate a burst of overdue chunks.
m_nextChunkMs = m_emissionTimer.elapsed ()
+ (chunkFrames * 1000 + scaledRate - 1) / scaledRate;
}
if (m_framesEmitted == totalFrames ())
{
m_emitting = false;
if (Profile::Jtty == m_profile) m_sink->finishInput ();
Q_EMIT status (tr ("Synthetic audio fixture exhausted"));
Q_EMIT emissionFinished (m_framesEmitted);
return;
}
scheduleNextChunk ();
}
|