capture-system-or-process-audio-core 1.4.0

Safe-Rust portable PCM stream contracts, software mixer, resampler, and core backend traits for capture-system-or-process-audio
Documentation
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
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
use crate::{
    measurements::{Stage, Trace},
    ordering::{Failure, Stop},
    reads::{Cancellation, Mode, ReadError, ReadResult, ReadStream},
    schema::Format,
};
use crossbeam_utils::atomic::AtomicCell;
use std::{
    sync::{
        Arc, Mutex, RwLock,
        atomic::{
            AtomicBool, AtomicU64, AtomicUsize,
            Ordering::{Acquire, Relaxed, Release, SeqCst},
        },
    },
    thread::{self, JoinHandle, Thread},
    time::{Duration, Instant},
};

const _: () = assert!(
    std::mem::size_of::<Option<Thread>>() == std::mem::size_of::<usize>(),
    "Option<Thread> must be pointer-sized so AtomicCell<Option<Thread>> is lock-free"
);

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum EndReason {
    Stopped,
    TargetExited,
    Failed(Failure),
}

/// Caller blocking policy for event-driven stream and manager reads.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CallerWait {
    Zero,
    Bounded(Duration),
    Unbounded,
}

impl CallerWait {
    #[inline]
    pub fn from_timeout(timeout: Duration) -> Self {
        if timeout.is_zero() {
            Self::Zero
        } else {
            Self::Bounded(timeout)
        }
    }

    #[inline]
    pub const fn is_blocking(self) -> bool {
        !matches!(self, Self::Zero)
    }
}

/// Unified absolute-deadline set across the four permitted wakeup clocks:
/// caller timeout, bounded peer alignment, target relaunch wait, and opted-in idle silence.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct DeadlineSet {
    pub caller_ns: Option<u64>,
    pub alignment_ns: Option<u64>,
    pub relaunch_ns: Option<u64>,
    pub silence_ns: Option<u64>,
}

impl DeadlineSet {
    #[inline]
    pub fn earliest_ns(&self) -> Option<u64> {
        [
            self.caller_ns,
            self.alignment_ns,
            self.relaunch_ns,
            self.silence_ns,
        ]
        .into_iter()
        .flatten()
        .min()
    }

    #[inline]
    pub fn wait_from(&self, now_ns: u64, blocking: bool) -> CallerWait {
        if !blocking {
            return CallerWait::Zero;
        }
        match self.earliest_ns() {
            Some(due_ns) => {
                CallerWait::Bounded(Duration::from_nanos(due_ns.saturating_sub(now_ns)))
            }
            None => CallerWait::Unbounded,
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SubscriptionError {
    ZeroCapacity,
    CapacityExceeded,
    AlreadySubscribed,
    TornDown,
}

pub(crate) struct SignalCore {
    generation: AtomicU64,
    torn_down: AtomicBool,
    waiter_parked: AtomicBool,
    parked_thread: AtomicCell<Option<Thread>>,
    retired_thread: AtomicCell<Option<Thread>>,
    park_wakeups: AtomicU64,
}

impl Default for SignalCore {
    fn default() -> Self {
        Self::new()
    }
}

impl SignalCore {
    pub(crate) fn new() -> Self {
        assert!(
            AtomicCell::<Option<Thread>>::is_lock_free(),
            "AtomicCell<Option<Thread>> must be lock-free for real-time audio callbacks"
        );
        Self {
            generation: AtomicU64::new(0),
            torn_down: AtomicBool::new(false),
            waiter_parked: AtomicBool::new(false),
            parked_thread: AtomicCell::new(None),
            retired_thread: AtomicCell::new(None),
            park_wakeups: AtomicU64::new(0),
        }
    }

    /// Nonblocking, allocation-free notification safe for real-time audio callbacks.
    #[inline]
    pub(crate) fn notify(&self) -> bool {
        self.generation.fetch_add(1, SeqCst);
        if self.waiter_parked.load(SeqCst)
            && let Some(waiter) = self.parked_thread.take()
        {
            waiter.unpark();
            let prev = self.retired_thread.swap(Some(waiter));
            drop(prev);
            return true;
        }
        false
    }

    #[inline]
    pub(crate) fn teardown(&self) {
        self.torn_down.store(true, SeqCst);
        let _ = self.notify();
    }

    #[inline]
    pub(crate) fn is_torn_down(&self) -> bool {
        self.torn_down.load(Acquire)
    }

    #[inline]
    pub(crate) fn generation(&self) -> u64 {
        self.generation.load(SeqCst)
    }

    #[inline]
    pub(crate) fn park_wakeups(&self) -> u64 {
        self.park_wakeups.load(Relaxed)
    }

    #[cfg(any(test, feature = "test-hooks"))]
    pub(crate) fn set_generation_for_test(&self, value: u64) {
        self.generation.store(value, SeqCst);
    }

    #[inline]
    fn drain_retired(&self) {
        drop(self.retired_thread.take());
    }

    fn poll_loop<T>(
        &self,
        is_cancelled: impl Fn() -> bool,
        mut now_ns: impl FnMut() -> u64,
        mut compute_wait: impl FnMut(u64) -> CallerWait,
        mut poll: impl FnMut(u64) -> Option<T>,
    ) -> T {
        self.drain_retired();
        let current_thread = thread::current();
        struct Disarm<'a>(&'a SignalCore);
        impl Drop for Disarm<'_> {
            fn drop(&mut self) {
                self.0.waiter_parked.store(false, SeqCst);
                drop(self.0.parked_thread.take());
                self.0.drain_retired();
            }
        }
        let _disarm = Disarm(self);

        loop {
            // Ready-path fast exit across loop iterations: when data or a due deadline is
            // already available, avoid `Thread::clone` + `parked_thread.swap` atomic traffic.
            let t_fast = now_ns();
            if let Some(result) = poll(t_fast) {
                return result;
            }

            let observed = self.generation.load(SeqCst);
            let _ = self.parked_thread.swap(Some(current_thread.clone()));
            self.waiter_parked.store(true, SeqCst);

            let t_ns = now_ns();
            if let Some(result) = poll(t_ns) {
                return result;
            }
            if self.generation.load(SeqCst) != observed || is_cancelled() {
                self.waiter_parked.store(false, SeqCst);
                drop(self.parked_thread.take());
                self.drain_retired();
                continue;
            }

            let wait = compute_wait(t_ns);
            match wait {
                CallerWait::Zero => {
                    self.waiter_parked.store(false, SeqCst);
                    drop(self.parked_thread.take());
                    self.drain_retired();
                    let t_zero = now_ns();
                    if let Some(result) = poll(t_zero) {
                        return result;
                    }
                    thread::yield_now();
                }
                CallerWait::Bounded(dur) => {
                    if dur.is_zero() {
                        self.waiter_parked.store(false, SeqCst);
                        drop(self.parked_thread.take());
                        self.drain_retired();
                        let t_due = now_ns();
                        if let Some(result) = poll(t_due) {
                            return result;
                        }
                        thread::yield_now();
                    } else {
                        thread::park_timeout(dur);
                        self.park_wakeups.fetch_add(1, Relaxed);
                        self.waiter_parked.store(false, SeqCst);
                        drop(self.parked_thread.take());
                        self.drain_retired();
                    }
                }
                CallerWait::Unbounded => {
                    if !self.torn_down.load(SeqCst) {
                        thread::park();
                        self.park_wakeups.fetch_add(1, Relaxed);
                    }
                    self.waiter_parked.store(false, SeqCst);
                    drop(self.parked_thread.take());
                    self.drain_retired();
                }
            }
        }
    }

    pub(crate) fn poll_without_cancel<T>(
        &self,
        mut now_ns: impl FnMut() -> u64,
        compute_wait: impl FnMut(u64) -> CallerWait,
        mut poll: impl FnMut(u64) -> Option<T>,
    ) -> T {
        let t0 = now_ns();
        if let Some(result) = poll(t0) {
            return result;
        }
        self.poll_loop(|| false, now_ns, compute_wait, poll)
    }

    pub(crate) fn poll_until<T>(
        self_arc: &Arc<Self>,
        cancel: &Cancellation,
        mut now_ns: impl FnMut() -> u64,
        compute_wait: impl FnMut(u64) -> CallerWait,
        mut poll: impl FnMut(u64) -> Option<T>,
    ) -> T {
        // Ready-path fast exit: zero signal writes, zero cancellation listener touches, zero allocations.
        let t0 = now_ns();
        if let Some(result) = poll(t0) {
            return result;
        }

        let _cancel_guard = cancel.attach_wake_signal(self_arc);
        if cancel.is_cancelled() {
            let tc = now_ns();
            if let Some(result) = poll(tc) {
                return result;
            }
        }

        self_arc.poll_loop(|| cancel.is_cancelled(), now_ns, compute_wait, poll)
    }
}

pub struct ReadySignal {
    core: Arc<SignalCore>,
    has_forward: AtomicBool,
    forward: RwLock<Option<Arc<SignalCore>>>,
}

impl Default for ReadySignal {
    fn default() -> Self {
        let sig = Self {
            core: Arc::new(SignalCore::new()),
            has_forward: AtomicBool::new(false),
            forward: RwLock::new(None),
        };
        drop(sig.forward.read());
        sig
    }
}

impl ReadySignal {
    pub fn new() -> Self {
        Self::default()
    }

    #[inline]
    pub fn notify(&self) {
        let _ = self.core.notify();
        if self.has_forward.load(Acquire)
            && let Ok(guard) = self.forward.try_read()
            && let Some(ref session_core) = *guard
        {
            let _ = session_core.notify();
        }
    }

    #[inline]
    pub fn generation(&self) -> u64 {
        self.core.generation()
    }

    #[inline]
    pub fn park_wakeups(&self) -> u64 {
        self.core.park_wakeups()
    }

    pub fn poll_until<T>(
        &self,
        started: Instant,
        timeout: Duration,
        cancel: &Cancellation,
        poll: impl FnMut(u64) -> Option<T>,
    ) -> T {
        let blocking = !timeout.is_zero();
        let timeout_ns = timeout.as_nanos().min(u128::from(u64::MAX)) as u64;
        SignalCore::poll_until(
            &self.core,
            cancel,
            || started.elapsed().as_nanos().min(u128::from(u64::MAX)) as u64,
            |elapsed_ns| {
                if !blocking {
                    CallerWait::Zero
                } else {
                    CallerWait::Bounded(Duration::from_nanos(timeout_ns.saturating_sub(elapsed_ns)))
                }
            },
            poll,
        )
    }
}

/// RAII subscription forwarding an admitted input's `ReadySignal` to a parent `SessionNotifier`.
/// Dropping or calling `deregister` fences in-flight callbacks on the control thread so no callback
/// references `SessionNotifier` after deregistration.
pub struct SessionSubscription {
    ready: Arc<ReadySignal>,
    active_subscriptions: Arc<AtomicUsize>,
    detached: bool,
}

impl SessionSubscription {
    pub fn deregister(&mut self) {
        if self.detached {
            return;
        }
        self.detached = true;
        self.ready.has_forward.store(false, Release);
        let prev = self
            .ready
            .forward
            .write()
            .unwrap_or_else(|e| e.into_inner())
            .take();
        if let Some(ref session_core) = prev {
            let _ = session_core.notify();
        }
        drop(prev);
        self.active_subscriptions.fetch_sub(1, SeqCst);
    }
}

impl Drop for SessionSubscription {
    fn drop(&mut self) {
        self.deregister();
    }
}

pub const MAX_SESSION_SUBSCRIPTIONS: usize = 256;

/// Bounded session-level event notifier observing admitted inputs, topology,
/// stop/EOF/failure transitions, and per-read cancellation without carrying PCM.
pub struct SessionNotifier {
    core: Arc<SignalCore>,
    max_subscriptions: usize,
    active_subscriptions: Arc<AtomicUsize>,
}

impl SessionNotifier {
    pub fn new(max_subscriptions: usize) -> Result<Self, SubscriptionError> {
        if max_subscriptions == 0 {
            return Err(SubscriptionError::ZeroCapacity);
        }
        if max_subscriptions > MAX_SESSION_SUBSCRIPTIONS {
            return Err(SubscriptionError::CapacityExceeded);
        }
        Ok(Self {
            core: Arc::new(SignalCore::new()),
            max_subscriptions,
            active_subscriptions: Arc::new(AtomicUsize::new(0)),
        })
    }

    #[inline]
    pub fn max_subscriptions(&self) -> usize {
        self.max_subscriptions
    }

    #[inline]
    pub fn active_subscriptions(&self) -> usize {
        self.active_subscriptions.load(SeqCst)
    }

    #[inline]
    pub fn generation(&self) -> u64 {
        self.core.generation()
    }

    #[inline]
    pub fn park_wakeups(&self) -> u64 {
        self.core.park_wakeups()
    }

    #[inline]
    pub fn is_torn_down(&self) -> bool {
        self.core.is_torn_down()
    }

    #[inline]
    pub fn notify(&self) -> bool {
        self.core.notify()
    }

    #[inline]
    pub fn teardown(&self) {
        self.core.teardown();
    }

    #[cfg(any(test, feature = "test-hooks"))]
    pub fn set_generation_for_test(&self, value: u64) {
        self.core.set_generation_for_test(value);
    }

    #[allow(deprecated, reason = "fetch_update supports the minimum Rust version")]
    pub fn subscribe(
        &self,
        input_ready: &Arc<ReadySignal>,
    ) -> Result<SessionSubscription, SubscriptionError> {
        if self.core.is_torn_down() {
            return Err(SubscriptionError::TornDown);
        }
        let max_subs = self.max_subscriptions;
        self.active_subscriptions
            .fetch_update(SeqCst, SeqCst, |cur| {
                cur.checked_add(1).filter(|next| *next <= max_subs)
            })
            .map_err(|_| SubscriptionError::CapacityExceeded)?;

        {
            let mut guard = input_ready
                .forward
                .write()
                .unwrap_or_else(|e| e.into_inner());
            if guard.is_some() {
                self.active_subscriptions.fetch_sub(1, SeqCst);
                return Err(SubscriptionError::AlreadySubscribed);
            }
            if self.core.is_torn_down() {
                self.active_subscriptions.fetch_sub(1, SeqCst);
                return Err(SubscriptionError::TornDown);
            }
            *guard = Some(Arc::clone(&self.core));
            input_ready.has_forward.store(true, Release);
        }
        // Wake the session after releasing the write lock so any publication during subscribe is rescanned.
        let _ = self.core.notify();
        Ok(SessionSubscription {
            ready: Arc::clone(input_ready),
            active_subscriptions: Arc::clone(&self.active_subscriptions),
            detached: false,
        })
    }

    pub fn poll_until<T>(
        &self,
        cancel: &Cancellation,
        now_ns: impl FnMut() -> u64,
        compute_wait: impl FnMut(u64) -> CallerWait,
        poll: impl FnMut(u64) -> Option<T>,
    ) -> T {
        SignalCore::poll_until(&self.core, cancel, now_ns, compute_wait, poll)
    }
}

/// RAII guard held at the outermost scope of a spawned worker thread; notifies `WorkerLifecycle`
/// immediately on normal return or unwind (`0` `1 ms` sleep polling).
pub struct WorkerExitGuard {
    exited: Arc<AtomicBool>,
    done: Arc<SignalCore>,
}

impl Drop for WorkerExitGuard {
    fn drop(&mut self) {
        self.exited.store(true, SeqCst);
        let _ = self.done.notify();
    }
}

pub struct WorkerSpawner {
    stop: Arc<AtomicBool>,
    exited: Arc<AtomicBool>,
    done: Arc<SignalCore>,
}

impl WorkerSpawner {
    pub fn bind(self, worker: JoinHandle<()>) -> WorkerLifecycle {
        WorkerLifecycle {
            stop: self.stop,
            exited: self.exited,
            done: self.done,
            panicked: Arc::new(AtomicBool::new(false)),
            worker: Arc::new(Mutex::new(Some(worker))),
        }
    }

    pub fn bind_completed(self) -> WorkerLifecycle {
        self.exited.store(true, SeqCst);
        let _ = self.done.notify();
        WorkerLifecycle {
            stop: self.stop,
            exited: self.exited,
            done: self.done,
            panicked: Arc::new(AtomicBool::new(false)),
            worker: Arc::new(Mutex::new(None)),
        }
    }
}

/// Event-driven worker lifecycle handle for bounded startup cancellation and teardown waiting.
#[derive(Clone)]
pub struct WorkerLifecycle {
    stop: Arc<AtomicBool>,
    exited: Arc<AtomicBool>,
    done: Arc<SignalCore>,
    panicked: Arc<AtomicBool>,
    worker: Arc<Mutex<Option<JoinHandle<()>>>>,
}

impl WorkerLifecycle {
    pub fn prepare(stop: Arc<AtomicBool>) -> (WorkerSpawner, WorkerExitGuard) {
        let exited = Arc::new(AtomicBool::new(false));
        let done = Arc::new(SignalCore::new());
        (
            WorkerSpawner {
                stop,
                exited: Arc::clone(&exited),
                done: Arc::clone(&done),
            },
            WorkerExitGuard { exited, done },
        )
    }

    #[inline]
    pub fn request_stop(&self) {
        self.stop.store(true, SeqCst);
        if let Some(handle) = self
            .worker
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .as_ref()
        {
            handle.thread().unpark();
        }
    }

    #[inline]
    pub fn panicked(&self) -> bool {
        self.panicked.load(Acquire)
    }

    #[inline]
    pub fn park_wakeups(&self) -> u64 {
        self.done.park_wakeups()
    }

    fn join_taken(&self, handle: JoinHandle<()>) {
        if handle.join().is_err() {
            self.panicked.store(true, Release);
        }
    }

    pub fn is_complete(&self) -> bool {
        let mut guard = self.worker.lock().unwrap_or_else(|e| e.into_inner());
        if guard.as_ref().is_some_and(JoinHandle::is_finished)
            && let Some(handle) = guard.take()
        {
            drop(guard);
            self.join_taken(handle);
            return true;
        }
        guard.is_none()
    }

    pub fn wait(&self, timeout: Duration) -> bool {
        self.request_stop();
        if self.is_complete() {
            return true;
        }
        if timeout.is_zero() {
            return false;
        }
        let started = Instant::now();
        let deadline_ns = timeout.as_nanos().min(u128::from(u64::MAX)) as u64;
        self.done.poll_without_cancel(
            || started.elapsed().as_nanos().min(u128::from(u64::MAX)) as u64,
            |elapsed_ns| {
                CallerWait::Bounded(Duration::from_nanos(deadline_ns.saturating_sub(elapsed_ns)))
            },
            |elapsed_ns| {
                if self.is_complete() {
                    return Some(true);
                }
                if self.exited.load(Acquire) {
                    let handle_opt = self.worker.lock().unwrap_or_else(|e| e.into_inner()).take();
                    if let Some(handle) = handle_opt {
                        self.join_taken(handle);
                    }
                    return Some(true);
                }
                if elapsed_ns >= deadline_ns {
                    return Some(self.is_complete());
                }
                None
            },
        )
    }
}

/// Deterministic FNV-1a endpoint clock-domain hash (`>= min_domain`, with `min_domain >= 2`
/// so hardware input/endpoint domains never collide with default output/process domain `1`).
pub fn endpoint_clock_domain(tag: &str, min_domain: u64) -> u64 {
    let floor = min_domain.max(2);
    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
    for byte in tag.as_bytes() {
        hash ^= u64::from(*byte);
        hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
    }
    hash.max(floor)
}

/// Borrowed runtime context for backend `AudioStream` read loops (`0` allocations).
#[derive(Clone, Copy)]
pub struct StreamReadContext<'a> {
    pub reads: &'a ReadStream,
    pub ready: &'a ReadySignal,
    pub trace: Option<&'a Arc<Trace>>,
}

/// Polls queued packets before a zero-duration timeout and records `Stage::ReadReturned`
/// when tracing is active.
pub fn poll_read_stream(
    ctx: StreamReadContext<'_>,
    frames: usize,
    timeout: Duration,
    cancel: Cancellation,
) -> Result<ReadResult, ReadError> {
    let started = Instant::now();
    let blocking = !timeout.is_zero();
    let deadline = blocking.then(|| timeout.as_nanos().min(u64::MAX as u128) as u64);
    let mut operation =
        ctx.reads
            .begin(Mode::Variable, frames, blocking, deadline, cancel.clone())?;
    let result = ctx
        .ready
        .poll_until(started, timeout, &cancel, |elapsed| operation.poll(elapsed));
    if let Some(tr) = ctx.trace
        && let Some(anchor) = result.last_packet
    {
        tr.record(Stage::ReadReturned, anchor.header.sequence);
    }
    Ok(result)
}

/// Shared blocking/non-blocking caller-destination `read_into` poll helper (`0` steady-state
/// heap allocations when paired with a cached `Cancellation` token).
pub fn poll_read_stream_into(
    ctx: StreamReadContext<'_>,
    format: Arc<Format>,
    destination: &mut [u8],
    frames: usize,
    timeout: Duration,
    cancel: Cancellation,
) -> Result<ReadResult, ReadError> {
    let started = Instant::now();
    let blocking = !timeout.is_zero();
    let deadline = blocking.then(|| timeout.as_nanos().min(u64::MAX as u128) as u64);
    let mut operation = ctx.reads.begin_into(
        destination,
        format,
        frames,
        blocking,
        deadline,
        cancel.clone(),
    )?;
    let result = ctx
        .ready
        .poll_until(started, timeout, &cancel, |elapsed| operation.poll(elapsed));
    if let Some(tr) = ctx.trace
        && let Some(anchor) = result.last_packet
    {
        tr.record(Stage::ReadReturned, anchor.header.sequence);
    }
    Ok(result)
}

pub fn signal_stream_stop(
    control: &crate::ordering::ControlHandle,
    stop_flag: &AtomicBool,
    ready: &ReadySignal,
    mode: Stop,
) {
    control.stop(mode);
    stop_flag.store(true, SeqCst);
    ready.notify();
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        StorageLimits,
        ordering::{Overflow, channel},
        reads::PartialReason,
        schema::{ByteOrder, Channel, Header, Layout, SampleType},
        storage::Pool,
    };

    #[test]
    fn stream_runtime_nonblocking_zero_timeout_and_clock_domain_invariants() {
        let d_a = endpoint_clock_domain("usb-mic-0", 2);
        let d_b = endpoint_clock_domain("usb-mic-1", 2);
        let d_mac = endpoint_clock_domain("", 3);
        assert!(d_a >= 2);
        assert!(d_b >= 2);
        assert_ne!(d_a, d_b);
        assert!(d_mac >= 3);
        assert_eq!(endpoint_clock_domain("usb-mic-0", 2), d_a);

        let fmt = Arc::new(
            Format::new(
                SampleType::F32,
                ByteOrder::Little,
                48_000,
                2,
                Layout::Known(Arc::from([Channel::FrontLeft, Channel::FrontRight])),
            )
            .unwrap(),
        );
        let pool = Pool::new(
            StorageLimits::new(4, 64, 8, 4 * 64 * 8).unwrap(),
            64,
            fmt.clone(),
        )
        .unwrap();
        let (mut producer, reader) = channel(pool, 4).unwrap();
        let reads = ReadStream::new(reader);
        let ready = ReadySignal::new();
        let cancel = Cancellation::default();
        let ctx = StreamReadContext {
            reads: &reads,
            ready: &ready,
            trace: None,
        };

        let empty_res = poll_read_stream(ctx, 16, Duration::ZERO, cancel.clone()).unwrap();
        assert_eq!(empty_res.frames, 0);
        assert_eq!(empty_res.reason, PartialReason::WouldBlock);

        let payload = [0u8; 16 * 8];
        producer.offer(
            &payload,
            Header {
                sequence: 1,
                segment: 1,
                generation: 1,
                frames: 16,
                sample_position: Some(0),
                timestamp: None,
            },
            Overflow::DropOldest,
        );
        let mut dst = [0u8; 16 * 8];
        let allocs = allocation_counter::measure(|| {
            let into_res = poll_read_stream_into(
                ctx,
                fmt.clone(),
                &mut dst,
                16,
                Duration::ZERO,
                cancel.clone(),
            )
            .unwrap();
            assert_eq!(into_res.frames, 16);
            assert_eq!(into_res.reason, PartialReason::Complete);
        });
        assert_eq!(allocs.count_total, 0);

        // Warmed 10,000-packet steady-state read_into allocation check
        let mut seq = 2u64;
        let warmed = allocation_counter::measure(|| {
            for _ in 0..10_000 {
                producer.offer(
                    &payload,
                    Header {
                        sequence: seq,
                        segment: 1,
                        generation: 1,
                        frames: 16,
                        sample_position: None,
                        timestamp: None,
                    },
                    Overflow::DropOldest,
                );
                seq += 1;
                ready.notify();
                let res = poll_read_stream_into(
                    ctx,
                    fmt.clone(),
                    &mut dst,
                    16,
                    Duration::from_millis(50),
                    cancel.clone(),
                )
                .unwrap();
                assert_eq!(res.frames, 16);
            }
        });
        assert_eq!(warmed.count_total, 0);

        let stop = Arc::new(AtomicBool::new(false));
        let stop_bg = stop.clone();
        let wake_worker = Arc::new(SignalCore::new());
        let wake_worker_bg = Arc::clone(&wake_worker);
        let (spawner, exit_guard) = WorkerLifecycle::prepare(stop);
        let handle = thread::spawn(move || {
            let _exit = exit_guard;
            wake_worker_bg.poll_without_cancel(
                || 0,
                |_| CallerWait::Unbounded,
                |_| stop_bg.load(SeqCst).then_some(()),
            );
        });
        let lifecycle = spawner.bind(handle);
        lifecycle.request_stop();
        let _ = wake_worker.notify();
        assert!(lifecycle.wait(Duration::from_millis(500)));
        assert!(lifecycle.is_complete());
        assert!(!lifecycle.panicked());
    }

    #[test]
    fn signal_core_forced_race_p95_retired_drain_and_unbounded_zero_wakeups() {
        let ready = Arc::new(ReadySignal::new());
        let cancel = Cancellation::default();

        // 1. Forced poll-to-wait race across 1,000 reads (`p95 <= 50 us`, wrap-around across u64::MAX)
        ready.core.set_generation_for_test(u64::MAX - 4);
        let mut race_latencies_ns = Vec::with_capacity(1_000);
        for _ in 0..1_000 {
            let mut step = 0usize;
            let mut notified_at = Instant::now();
            ready.poll_until(Instant::now(), Duration::from_millis(100), &cancel, |_| {
                step += 1;
                match step {
                    1 => None, // initial fast-path sees empty
                    2 => {
                        // Producer notifies right between waiter arming and park decision!
                        notified_at = Instant::now();
                        ready.notify();
                        None
                    }
                    _ => Some(()),
                }
            });
            race_latencies_ns.push(notified_at.elapsed().as_nanos() as u64);
        }
        race_latencies_ns.sort_unstable();
        let p95_ns = race_latencies_ns[950];
        assert!(
            p95_ns <= 50_000,
            "forced poll-to-wait race p95 {} ns exceeded 50 us gate",
            p95_ns
        );

        // 2. 100 wakeups inside one `poll_until` call: 0 RT allocations/deallocations (`retired_thread` drained per iteration)
        let notifier = Arc::new(SessionNotifier::new(16).unwrap());
        let notifier_bg = Arc::clone(&notifier);
        let _sub = notifier.subscribe(&ready).unwrap();
        let rt_ready = Arc::clone(&ready);
        let woken_steps = Arc::new(AtomicUsize::new(0));
        let woken_bg = Arc::clone(&woken_steps);
        let seen_steps = Arc::new(AtomicUsize::new(0));
        let seen_bg = Arc::clone(&seen_steps);
        let rt_allocs = Arc::new(AtomicUsize::new(0));
        let rt_allocs_bg = Arc::clone(&rt_allocs);

        let producer_th = thread::spawn(move || {
            for target in 1..=100usize {
                while seen_bg.load(SeqCst) < target - 1
                    || !notifier_bg.core.waiter_parked.load(SeqCst)
                {
                    thread::yield_now();
                }
                woken_bg.store(target, SeqCst);
                let m = allocation_counter::measure(|| {
                    rt_ready.notify();
                });
                rt_allocs_bg.fetch_add(m.count_total as usize, SeqCst);
            }
        });

        notifier.poll_until(
            &cancel,
            || 0,
            |_| CallerWait::Unbounded,
            |_| {
                let cur = woken_steps.load(SeqCst);
                seen_steps.store(cur, SeqCst);
                (cur >= 100).then_some(())
            },
        );
        producer_th.join().unwrap();
        assert_eq!(rt_allocs.load(SeqCst), 0);

        // 3. Unbounded idle wait records `park_wakeups == 0` while idle and wakes immediately on `cancel()`
        let idle_notifier = Arc::new(SessionNotifier::new(8).unwrap());
        let idle_cancel = Cancellation::new();
        let cancel_bg = idle_cancel.clone();
        let armed = Arc::new(AtomicBool::new(false));
        let armed_bg = Arc::clone(&armed);
        let wakeups_while_idle = Arc::new(AtomicU64::new(u64::MAX));
        let wakeups_bg = Arc::clone(&wakeups_while_idle);
        let idle_obs = Arc::clone(&idle_notifier);

        let canceller = thread::spawn(move || {
            while !armed_bg.load(SeqCst) {
                thread::yield_now();
            }
            // Wait until reader is genuinely parked on the unbounded wait
            while !idle_obs.core.waiter_parked.load(SeqCst) {
                thread::yield_now();
            }
            wakeups_bg.store(idle_obs.park_wakeups(), SeqCst);
            cancel_bg.cancel();
        });

        let reader_notifier = Arc::clone(&idle_notifier);
        let cancelled = thread::spawn(move || {
            let mut polls = 0usize;
            reader_notifier.poll_until(
                &idle_cancel,
                || 0,
                |_| CallerWait::Unbounded,
                |_| {
                    polls += 1;
                    if polls >= 2 {
                        armed.store(true, SeqCst);
                    }
                    idle_cancel.is_cancelled().then_some(true)
                },
            )
        })
        .join()
        .unwrap();
        canceller.join().unwrap();
        assert!(cancelled);
        assert_eq!(wakeups_while_idle.load(SeqCst), 0);
        assert_eq!(idle_notifier.park_wakeups(), 1);
    }

    #[test]
    fn multi_listener_cancellation_and_session_subscription_stress() {
        // 1. 8 concurrent waiters sharing clones of one `Cancellation`; 2 finish early & drop guards
        let shared_cancel = Cancellation::new();
        let early_exit = Arc::new(AtomicBool::new(false));
        let parked_count = Arc::new(AtomicUsize::new(0));
        let mut handles = Vec::with_capacity(8);

        for idx in 0..8usize {
            let c = shared_cancel.clone();
            let early = Arc::clone(&early_exit);
            let parked = Arc::clone(&parked_count);
            handles.push(thread::spawn(move || {
                let notifier = SessionNotifier::new(4).unwrap();
                let mut local_polls = 0usize;
                notifier.poll_until(
                    &c,
                    || 0,
                    |_| {
                        if idx < 2 {
                            CallerWait::Bounded(Duration::from_millis(2))
                        } else {
                            CallerWait::Unbounded
                        }
                    },
                    |_| {
                        local_polls += 1;
                        if local_polls == 2 {
                            parked.fetch_add(1, SeqCst);
                        }
                        if idx < 2 && early.load(SeqCst) {
                            return Some("early");
                        }
                        c.is_cancelled().then_some("cancelled")
                    },
                )
            }));
        }

        while parked_count.load(SeqCst) < 8 {
            thread::yield_now();
        }
        // Let waiters 0 and 1 exit early and drop their `CancelWakeGuard`s first!
        early_exit.store(true, SeqCst);
        assert_eq!(handles.remove(0).join().unwrap(), "early");
        assert_eq!(handles.remove(0).join().unwrap(), "early");

        // Now cancel `shared_cancel`: all remaining 6 unbounded waiters (inline + overflow) must wake immediately!
        let cancel_started = Instant::now();
        shared_cancel.cancel();
        for h in handles {
            assert_eq!(h.join().unwrap(), "cancelled");
        }
        assert!(cancel_started.elapsed() < Duration::from_millis(250));

        // 2. `forward_to` child cancellation propagation
        let parent_c = Cancellation::new();
        let child_c = Cancellation::new();
        let _fwd_guard = parent_c.forward_to(&child_c);
        assert!(!child_c.is_cancelled());
        parent_c.cancel();
        assert!(child_c.is_cancelled());

        // 3. 1,000 concurrent `notify()` vs `SessionSubscription::drop` cycles (`0` panics / `0` leaked subs)
        let session = Arc::new(SessionNotifier::new(8).unwrap());
        let input_sig = Arc::new(ReadySignal::new());
        let stop_rt = Arc::new(AtomicBool::new(false));
        let stop_rt_bg = Arc::clone(&stop_rt);
        let sig_bg = Arc::clone(&input_sig);
        let rt_thread = thread::spawn(move || {
            while !stop_rt_bg.load(Relaxed) {
                sig_bg.notify();
            }
        });
        for _ in 0..1_000 {
            let sub = session.subscribe(&input_sig).unwrap();
            assert_eq!(session.active_subscriptions(), 1);
            assert_eq!(
                session.subscribe(&input_sig).err(),
                Some(SubscriptionError::AlreadySubscribed)
            );
            drop(sub);
            assert_eq!(session.active_subscriptions(), 0);
        }
        stop_rt.store(true, Relaxed);
        rt_thread.join().unwrap();

        // 4. `WorkerLifecycle` records worker panic cleanly and wakes immediately
        let stop_p = Arc::new(AtomicBool::new(false));
        let (spawner, exit_guard) = WorkerLifecycle::prepare(stop_p);
        let panicking = thread::spawn(move || {
            let _exit = exit_guard;
            panic!("deliberate worker panic test");
        });
        let lc = spawner.bind(panicking);
        assert!(lc.wait(Duration::from_millis(500)));
        assert!(lc.is_complete());
        assert!(lc.panicked());
    }
}