summaryrefslogtreecommitdiff
path: root/tests/unit/tci/test_tci_receive_ownership.cpp
blob: 760bf29f1c3fdae8638cbc0108a4e0e95466c18b (plain)
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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
#include <QtTest>
#include <QMutexLocker>
#include <QThread>
#include <boost/log/keywords/channel.hpp>

#include <algorithm>
#include <array>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <cstring>
#include <functional>
#include <memory>
#include <mutex>
#include <vector>

#include "DecDataMutex.hpp"
#include "FastDecode.hpp"
#include "TciSimScript.hpp"
#include "TciSimServer.hpp"
#include "Transceiver/TCITransceiver.hpp"
#include "widgets/itoneAndicw.h"
#include "wsjtx_config.h"

namespace
{
dec_data_t storage {};
constexpr int block = 3456;
constexpr int captureCount = block;

struct ReceiveClock
{
  std::mutex mutex;
  std::condition_variable changed;
  qint64 timestamp = 104000; // 14 s into a 15 s period; 105000 wraps to zero.
  bool armed = false, paused = false, released = false, timedOut = false;

  qint64 now ()
  {
    std::unique_lock<std::mutex> lock {mutex};
    if (armed)
      {
        armed = false;
        paused = true;
        changed.notify_all ();
        timedOut = !changed.wait_for (lock, std::chrono::seconds {5}, [&] { return released; });
      }
    return timestamp;
  }
  void set (qint64 value) { std::lock_guard<std::mutex> lock {mutex}; timestamp = value; }
  void arm () { std::lock_guard<std::mutex> lock {mutex}; armed = true; }
  bool waitPaused ()
  {
    std::unique_lock<std::mutex> lock {mutex};
    return changed.wait_for (lock, std::chrono::seconds {5}, [&] { return paused; });
  }
  void release ()
  {
    std::lock_guard<std::mutex> lock {mutex};
    released = true;
    changed.notify_all ();
  }
};

// The real decoder launcher is linked; only the downstream decoder is a probe.
struct DecodeProbe
{
  std::mutex mutex;
  std::condition_variable changed;
  bool released = false, timedOut = false;
  std::vector<short> samples;
  int frames = 0;
  double period = 0;
  QByteArray myCall, hisCall;
  void release ()
  {
    std::lock_guard<std::mutex> lock {mutex};
    released = true;
    changed.notify_all ();
  }
};
DecodeProbe * activeProbe = nullptr;

struct Job
{
  std::array<int, 15> arguments {};
  std::array<char, 8000> messages {};
  char myCall[12], hisCall[12];
  double period = 15;
  Job ()
  {
    arguments[1] = captureCount;
    arguments[3] = 1;
    arguments[9] = 104;
    std::memcpy (myCall, "K1ABC       ", 12);
    std::memcpy (hisCall, "W9XYZ       ", 12);
  }
  QFuture<FastDecodeResult> submit (short const * samples = storage.d2)
  {
    return startFastDecode (samples, arguments.data (), period,
                            myCall, hisCall);
  }
};

class Harness
{
public:
  Harness () : logger_ {boost::log::keywords::channel = "TCI_RECEIVE_TEST"}
  {
    QObject::connect (&server, &TciSimServer::client_arrived, &server, [this] (int) {
      server.send_text (TciSimScript::greeting_messages (TciSimGreeting::Thetis).join (';'));
    });
    QObject::connect (&server, &TciSimServer::text_received, &server,
                      [this] (QString const& text, int) {
      for (auto const& command : text.split (';', Qt::SkipEmptyParts))
        {
          auto const verb = command.section (':', 0, 0);
          if (verb == "split_enable") server.send_text ("split_enable:0,false");
          else if (verb == "audio_start" || verb == "audio_stop"
                   || verb == "modulation" || verb == "rx_enable"
                   || verb == "trx" || verb == "start" || verb == "stop")
            server.send_text (command);
          else if (verb == "vfo")
            server.send_text (command.count (',') >= 2 ? command : "vfo:0,0,14074000");
        }
    });
    context_ = new QObject;
    context_->moveToThread (&thread_);
    QObject::connect (&thread_, &QThread::finished, context_, &QObject::deleteLater);
    thread_.start ();
  }

  ~Harness ()
  {
    clock.release ();
    auto stopped = std::make_shared<std::atomic_bool> (false);
    QMetaObject::invokeMethod (context_, [this, stopped] {
      if (rig) { rig->stop (); delete rig; rig = nullptr; }
      stopped->store (true);
    }, Qt::QueuedConnection);
    server.wait_for ([&] { return stopped->load (); }, 10000);
    // Complete destruction before logger, clock and transport storage expire.
    thread_.quit ();
    thread_.wait ();
    server.close ();
  }

  bool start (ReceivePolicy policy = ReceivePolicy::Timed)
  {
    if (!server.listen ()) return false;
    QString const address = QStringLiteral ("127.0.0.1:%1").arg (server.port ());
    QMetaObject::invokeMethod (context_, [this, address, policy] {
      rig = new TCITransceiver (&logger_, {}, "0", address, true, tci__audio,
                                context_, [this] { return clock.now (); });
      QObject::connect (rig, &Transceiver::failure, rig, [this] (QString const&) {
        failed_.store (true);
      });
      QObject::connect (rig, &Transceiver::tciframeswritten, rig, [this] (qint64) {
        ++notifications_;
      });
      QObject::connect (rig, &Transceiver::receiveAudio, &audioContext_,
                        [this] (ReceiveAudio audio) {
        receiver_.accept (audio, storage);
      }, Qt::QueuedConnection);
      QObject::connect (rig, &Transceiver::continuousAudioAvailable, &audioContext_,
                        [this] (JttyReceiveMailboxPtr mailbox) {
        continuousMailbox = std::move (mailbox);
      }, Qt::QueuedConnection);
      QObject::connect (rig, &Transceiver::continuousReceiveDrained, &audioContext_,
                        [this] (quint64 request, JttyReceiveMailboxPtr mailbox) {
        drainedRequest_ = request;
        drainedMailbox_ = std::move (mailbox);
      }, Qt::QueuedConnection);
      // A ready message is an ordered fence behind preceding binary frames.
      QObject::connect (rig, &TCITransceiver::tci_done7, rig, [this] {
        std::lock_guard<std::mutex> lock {fenceMutex_};
        ++fences_;
        fenceChanged_.notify_all ();
      });
      rig->start (1);
      state_.online (true);
      state_.frequency (14074000);
      state_.mode (Transceiver::USB);
      state_.period (15);
      state_.receive_policy (policy);
      state_.receive_context (77);
      state_.audio (true);
      state_.volume (0);
      rig->set (state_, 2);
      started_.store (true);
    }, Qt::QueuedConnection);
    return server.wait_for ([this] { return started_.load (); }, 10000)
      && !failed_.load () && server.client_connected ();
  }

  bool enableAudio (bool enabled)
  {
    QMetaObject::invokeMethod (context_, [this, enabled] {
      state_.audio (enabled);
      rig->set (state_, ++sequence_);
    }, Qt::BlockingQueuedConnection);
    return !failed_.load ();
  }

  bool setReceivePolicy (ReceivePolicy policy)
  {
    auto done = std::make_shared<std::atomic_bool> (false);
    QMetaObject::invokeMethod (context_, [this, policy, done] {
      state_.receive_policy (policy);
      rig->set (state_, ++sequence_);
      done->store (true);
    }, Qt::QueuedConnection);
    return server.wait_for ([done] { return done->load (); }, 10000) && !failed_.load ();
  }

  bool setReceiveContext (quint64 context)
  {
    auto done = std::make_shared<std::atomic_bool> (false);
    QMetaObject::invokeMethod (context_, [this, context, done] {
      state_.receive_context (context);
      rig->set (state_, ++sequence_);
      done->store (true);
    }, Qt::QueuedConnection);
    return server.wait_for ([done] { return done->load (); }, 10000) && !failed_.load ();
  }

  bool setBlockSize (qint32 size)
  {
    auto done = std::make_shared<std::atomic_bool> (false);
    QMetaObject::invokeMethod (context_, [this, size, done] {
      state_.blocksize (size);
      rig->set (state_, ++sequence_);
      done->store (true);
    }, Qt::QueuedConnection);
    return server.wait_for ([done] { return done->load (); }, 10000) && !failed_.load ();
  }

  bool fence ()
  {
    std::unique_lock<std::mutex> lock {fenceMutex_};
    auto const before = fences_;
    server.send_text ("ready");
    server.flush ();
    // No GUI event dispatch here: queued audio notifications may stay pending.
    return fenceChanged_.wait_for (lock, std::chrono::seconds {5},
                                   [&] { return fences_ > before; });
  }

  bool packet (std::vector<float> const& pcm, int offset, int count, int receiver = 0)
  {
    QByteArray bytes;
    if (!TciStream::prepare_float_frame (&bytes, 2 * count)) return false;
    auto * header = TciStream::header (&bytes);
    header->receiver = receiver;
    header->sampleRate = 48000;
    header->format = TciStream::Float32Format;
    header->type = TciStream::RxAudioStream;
    header->length = 2 * count;
    header->channels = 2;
    auto * payload = TciStream::float_payload (&bytes);
    for (int i = 0; i < count; ++i)
      {
        payload[2 * i] = pcm[offset + i];
        payload[2 * i + 1] = -pcm[offset + i]; // Distinct unused right channel.
      }
    bool const sent = server.send_binary (bytes);
    return sent;
  }

  bool incompleteAudioPacket ()
  {
    QByteArray bytes;
    if (!TciStream::prepare_float_frame (&bytes, 2)) return false;
    auto * header = TciStream::header (&bytes);
    header->receiver = 0;
    header->sampleRate = 48000;
    header->format = TciStream::Float32Format;
    header->type = TciStream::RxAudioStream;
    header->length = 2;
    header->channels = 2;
    bytes.chop (sizeof (float));
    bool const sent = server.send_binary (bytes);
    server.flush ();
    return sent && fence ();
  }

  bool feed (std::vector<float> const& pcm, std::vector<int> const& chunks = {4096},
             int receiver = 0)
  {
    int offset = 0, index = 0;
    while (offset < int (pcm.size ()))
      {
        int count = std::min (chunks[index++ % chunks.size ()], int (pcm.size ()) - offset);
        if (!packet (pcm, offset, count, receiver)) return false;
        offset += count;
      }
    return fence ();
  }

  std::vector<short> snapshot ()
  {
    QCoreApplication::sendPostedEvents (&audioContext_, QEvent::MetaCall);
    QMutexLocker lock {&dec_data_mutex ()};
    return {storage.d2, storage.d2 + storage.params.kin};
  }
  int notifications () const { return notifications_.load (); }
  void deliverContinuous () { QCoreApplication::sendPostedEvents (&audioContext_, QEvent::MetaCall); }
  bool drainContinuous (quint64 request)
  {
    QMetaObject::invokeMethod (context_, [this, request] {
      static_cast<Transceiver *> (rig)->requestContinuousReceiveDrain (request);
    }, Qt::QueuedConnection);
    return server.wait_for ([this, request] { return drainedRequest_ == request; }, 10000)
      && drainedMailbox_ == continuousMailbox;
  }
  JttyReceiveMailboxPtr continuousMailbox;

  TciSimServer server;
  ReceiveClock clock;
  TCITransceiver * rig = nullptr;
private:
  Transceiver::logger_type logger_;
  QThread thread_;
  QObject * context_ = nullptr;
  QObject audioContext_;
  ReceiveAudioConsumer receiver_;
  quint64 drainedRequest_ = 0;
  JttyReceiveMailboxPtr drainedMailbox_;
  Transceiver::TransceiverState state_;
  unsigned sequence_ = 2;
  std::atomic_bool started_ {false}, failed_ {false};
  std::atomic_int notifications_ {0};
  std::mutex fenceMutex_;
  std::condition_variable fenceChanged_;
  int fences_ = 0;
};

std::vector<float> signal (int outputFrames, float value)
{
  return std::vector<float> (4 * outputFrames, value);
}
}

dec_data_t& dec_data = storage;
int volatile itone[MAX_NUM_SYMBOLS] {};
int volatile icw[NUM_CW_SYMBOLS] {};
float gran () { return 0; }

extern "C" void fast_decode_ (short samples[], int arguments[], double * period,
                               char[], char myCall[], char hisCall[],
                               fortran_charlen_t, fortran_charlen_t, fortran_charlen_t)
{
  auto& probe = *activeProbe;
  std::unique_lock<std::mutex> lock {probe.mutex};
  probe.timedOut = !probe.changed.wait_for (lock, std::chrono::seconds {5},
                                           [&] { return probe.released; });
  if (probe.timedOut) return;
  probe.frames = arguments[1];
  if (probe.frames >= 0 && probe.frames <= 360000)
    probe.samples.assign (samples, samples + probe.frames);
  probe.period = *period;
  probe.myCall = QByteArray (myCall, 12);
  probe.hisCall = QByteArray (hisCall, 12);
}

class TestTciReceiveOwnership : public QObject
{
  Q_OBJECT
private Q_SLOTS:
  void block_size_changes_preserve_captured_partial_audio ()
  {
    Harness h;
    QVERIFY (h.start (ReceivePolicy::ContinuousJtty));
    QVERIFY (h.feed (signal (100, 0.125f)));
    h.deliverContinuous ();
    QVERIFY (h.continuousMailbox);
    QVERIFY (h.setBlockSize (-1));
    QVERIFY (h.setBlockSize (0));
    QVERIFY (h.setBlockSize (7 * 512 + 1));
    QVERIFY (h.setBlockSize (block));
    JttyReceiveEvent event;
    QVERIFY (h.continuousMailbox->take (event));
    QCOMPARE (event.kind, JttyReceiveEvent::Kind::Begin);
    auto const firstSession = event.session;
    QVERIFY (!h.continuousMailbox->take (event));
    QVERIFY (h.setBlockSize (256));
    QVERIFY (h.continuousMailbox->take (event));
    QCOMPARE (event.kind, JttyReceiveEvent::Kind::Samples);
    QCOMPARE (event.session, firstSession);
    QCOMPARE (event.samples.size (), std::size_t {100});
    QVERIFY (std::any_of (event.samples.begin (), event.samples.end (),
                         [] (short sample) { return sample != 0; }));
    QVERIFY (h.continuousMailbox->take (event));
    QCOMPARE (event.kind, JttyReceiveEvent::Kind::End);
    QCOMPARE (event.firstSample, qint64 {100});
    QVERIFY (!h.continuousMailbox->take (event));
    QVERIFY (h.feed (signal (256, 0.25f)));
    QVERIFY (h.continuousMailbox->take (event));
    QCOMPARE (event.kind, JttyReceiveEvent::Kind::Begin);
    QVERIFY (event.session != firstSession);
    QVERIFY (h.continuousMailbox->take (event));
    QCOMPARE (event.kind, JttyReceiveEvent::Kind::Samples);
    QCOMPARE (event.firstSample, qint64 {0});
    QCOMPARE (event.samples.size (), std::size_t {256});
    QVERIFY (!h.continuousMailbox->take (event));
  }

  void continuous_audio_retains_partial_packet_across_clock_wrap ()
  {
    Harness h;
    QVERIFY (h.start (ReceivePolicy::ContinuousJtty));
    QVERIFY (h.feed (signal (block + 100, 0.125f), {511, 1701, 2047}));
    h.clock.set (105000);
    QVERIFY (h.feed (signal (block, 0.25f), {777, 512}));
    QVERIFY (h.enableAudio (false));
    h.deliverContinuous ();
    QVERIFY (h.continuousMailbox);
    JttyReceiveEvent event;
    quint64 session = 0;
    qint64 frames = 0;
    bool ended = false;
    while (h.continuousMailbox->take (event))
      {
        if (event.kind == JttyReceiveEvent::Kind::Begin)
          {
            QCOMPARE (session, quint64 {0});
            session = event.session;
          }
        QCOMPARE (event.session, session);
        QCOMPARE (event.context, quint64 {77});
        if (event.kind == JttyReceiveEvent::Kind::Samples)
          {
            QCOMPARE (event.firstSample, frames);
            frames = event.endSample ();
          }
        if (event.kind == JttyReceiveEvent::Kind::End)
          {
            QCOMPARE (event.firstSample, frames);
            ended = true;
          }
      }
    QCOMPARE (frames, qint64 (2 * block + 100));
    QVERIFY (ended);
    QCOMPARE (h.notifications (), 0);
    QVERIFY (h.setReceiveContext (88));
    QVERIFY (h.enableAudio (true));
    QVERIFY (h.feed (signal (block, 0.125f)));
    h.deliverContinuous ();
    QVERIFY (h.continuousMailbox->take (event));
    QCOMPARE (event.kind, JttyReceiveEvent::Kind::Begin);
    QCOMPARE (event.context, quint64 {88});
    QVERIFY (event.session != session);
    auto const interruptedSession = event.session;
    QVERIFY (h.continuousMailbox->take (event));
    QCOMPARE (event.kind, JttyReceiveEvent::Kind::Samples);
    QVERIFY (!h.continuousMailbox->take (event));
    QVERIFY (h.feed (signal (25, 0.125f)));
    QVERIFY (h.incompleteAudioPacket ());
    QVERIFY (h.continuousMailbox->take (event));
    QCOMPARE (event.kind, JttyReceiveEvent::Kind::Samples);
    QCOMPARE (event.samples.size (), std::size_t {25});
    QVERIFY (h.continuousMailbox->take (event));
    QCOMPARE (event.kind, JttyReceiveEvent::Kind::End);
    QCOMPARE (event.reason, JttyReceiveReason::InputError);
    QVERIFY (!h.continuousMailbox->take (event));
    QVERIFY (h.feed (signal (block, 0.125f)));
    QVERIFY (h.continuousMailbox->take (event));
    QCOMPARE (event.kind, JttyReceiveEvent::Kind::Begin);
    QVERIFY (event.session != interruptedSession);
    QCOMPARE (event.firstSample, qint64 {0});
    QVERIFY (h.enableAudio (false));
    QVERIFY (h.setReceivePolicy (ReceivePolicy::Timed));
    QVERIFY (h.drainContinuous (55));
    QVERIFY (h.enableAudio (true));
    QVERIFY (h.feed (signal (block, 0.125f)));
    QCOMPARE (h.snapshot ().size (), std::size_t (block));
    QCOMPARE (h.notifications (), 1);
  }

  void continuous_anchor_uses_first_packet_sample_time ()
  {
    Harness h;
    h.clock.set (200000);
    QVERIFY (h.start (ReceivePolicy::ContinuousJtty));
    std::vector<float> pcm (4096, 0.125f);
    QVERIFY (h.feed (pcm));
    h.deliverContinuous ();
    QVERIFY (h.continuousMailbox);
    JttyReceiveEvent event;
    QVERIFY (h.continuousMailbox->take (event));
    QCOMPARE (event.kind, JttyReceiveEvent::Kind::Begin);
    QCOMPARE (event.anchorUtcMs, qint64 {199915});
  }

  void packetization_preserves_audio ()
  {
    Harness h;
    QVERIFY (h.start ());
    auto pcm = signal (captureCount, 0.0f);
    for (std::size_t i = 0; i < pcm.size (); ++i)
      pcm[i] = (int (i % 31) - 15) / 32.0f;
    // fil4 has persistent FIR history. Feed the same silent pre-roll for each
    // run; do not reset it through test-only access to Fortran saved state.
    QVERIFY (h.feed (signal (block, 0.0f)));
    QVERIFY (h.feed (pcm));
    auto first = h.snapshot ();
    QVERIFY (h.enableAudio (false));
    QVERIFY (h.enableAudio (true));
    QVERIFY (h.feed (signal (block, 0.0f), {4095}));
    QVERIFY (h.feed (pcm, {4095}));
    auto second = h.snapshot ();
    QCOMPARE (first.size (), std::size_t (2 * block));
    QCOMPARE (second.size (), first.size ());
    QVERIFY (std::any_of (first.begin () + block, first.end (), [] (short x) { return x != 0; }));
    // Discard pre-roll output: its first taps legitimately contain history
    // from the preceding stream. Compare only identically conditioned audio.
    QVERIFY (std::equal (first.begin () + block, first.end (), second.begin () + block));
  }

  void ignored_audio_does_not_change_reception ()
  {
    Harness h;
    QVERIFY (h.start ());
    QVERIFY (h.feed (signal (captureCount, 0.125f)));
    auto before = h.snapshot ();
    int const notifications = h.notifications ();

    QVERIFY (h.feed (signal (block, -0.25f), {4096}, 1));
    QVERIFY (before == h.snapshot ());
    QCOMPARE (h.notifications (), notifications);

    QVERIFY (h.enableAudio (false));
    QVERIFY (h.feed (signal (block, -0.25f)));
    QVERIFY (before == h.snapshot ());
    QCOMPARE (h.notifications (), notifications);
    // An accepted block is a positive control proving the transport and gate
    // work, rather than mistaking an idle or disconnected receiver for success.
    QVERIFY (h.enableAudio (true));
    QVERIFY (h.feed (signal (block, -0.25f)));
    QCOMPARE (h.snapshot ().size (), std::size_t (block));
  }

  void submitted_job_survives_period_reuse ()
  {
    Harness h;
    QVERIFY (h.start ());
    QVERIFY (h.feed (signal (captureCount, 0.125f)));
    auto const expected = h.snapshot ();
    Job job;
    DecodeProbe probe;
    activeProbe = &probe;
    auto future = job.submit ();
    h.clock.set (105000);
    bool const fed = h.feed (signal (captureCount, -0.25f));
    auto const replacement = h.snapshot ();
    probe.release ();
    future.waitForFinished ();
    activeProbe = nullptr;
    QVERIFY (fed);
    QVERIFY (!probe.timedOut);
    QCOMPARE (replacement.size (), expected.size ());
    QVERIFY (replacement != expected);
    QCOMPARE (probe.samples.size (), expected.size ());
    QCOMPARE (probe.samples.back (), expected.back ());
    QVERIFY (probe.samples == expected);
    QCOMPARE (probe.frames, captureCount);
    QCOMPARE (probe.period, 15.0);
    QCOMPARE (probe.myCall, QByteArray ("K1ABC       ", 12));
    QCOMPARE (probe.hisCall, QByteArray ("W9XYZ       ", 12));
  }

  void capture_vs_transport_append ()
  {
    Harness h;
    QVERIFY (h.start ());
    QVERIFY (h.feed (signal (captureCount, 0.125f)));
    auto const expected = h.snapshot ();
    // Leave one stereo frame before the next real downsampler output block.
    auto next = signal (block, -0.25f);
    next.pop_back ();
    QVERIFY (h.feed (next));
    h.clock.arm ();
    QVERIFY (h.packet (std::vector<float> { -0.25f }, 0, 1));
    h.server.flush ();
    bool const paused = h.clock.waitPaused ();
    Job job;
    DecodeProbe probe;
    probe.released = true;
    activeProbe = &probe;
    h.clock.release ();
    // Both real sample accesses follow release, with no completion ordering.
    auto future = job.submit ();
    bool const finished = h.fence ();
    future.waitForFinished ();
    activeProbe = nullptr;
    QVERIFY (paused);
    QVERIFY (finished);
    QVERIFY (!h.clock.timedOut);
    QVERIFY (!probe.timedOut);
    QCOMPARE (h.snapshot ().size (), std::size_t (captureCount + block));
    QVERIFY (probe.samples == expected);
  }

  void delayed_notification_retains_period_identity ()
  {
    Harness h;
    QVERIFY (h.start ());
    Job job;
    DecodeProbe probe;
    probe.released = true;
    activeProbe = &probe;
    QObject consumer;
    bool handled = false;
    int rejected = 0;
    auto received = std::make_unique<dec_data_t> ();
    ReceiveAudioConsumer receiver;
    QFuture<FastDecodeResult> future;
    QObject::connect (h.rig, &Transceiver::receiveAudio, &consumer, [&] (ReceiveAudio audio) {
      if (!receiver.accept (audio, *received)) { ++rejected; return; }
      if (handled || audio->end () != captureCount) return;
      handled = true;
      future = job.submit (received->d2);
    }, Qt::QueuedConnection);
    // Transport fences do not dispatch the main thread's queued callbacks.
    bool const fedA = h.feed (signal (captureCount, 0.125f));
    auto const expected = h.snapshot ();
    h.clock.set (105000);
    bool const fedB = h.feed (signal (captureCount, -0.25f));
    auto const replacement = h.snapshot ();
    QCoreApplication::sendPostedEvents (&consumer, QEvent::MetaCall);
    future.waitForFinished ();
    activeProbe = nullptr;
    QVERIFY (fedA);
    QVERIFY (fedB);
    QVERIFY (handled);
    QVERIFY (rejected > 0);
    QVERIFY (!probe.timedOut);
    QCOMPARE (expected.size (), std::size_t (captureCount));
    QCOMPARE (replacement.size (), expected.size ());
    QVERIFY (replacement != expected);
    QCOMPARE (probe.samples.size (), expected.size ());
    QCOMPARE (probe.samples.back (), replacement.back ());
    QVERIFY (probe.samples == replacement);
    // Stale A is rejected; B still reaches the production decode boundary.
  }
};

QTEST_GUILESS_MAIN (TestTciReceiveOwnership)
#include "test_tci_receive_ownership.moc"