audio-io-bsd 0.3.1

Audio I/O backend abstraction (AudioBackend trait) with a cpal ALSA/OSS backend for FreeBSD-first real-time audio
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
//! [`OssBackend`] — a FreeBSD-native direct OSS [`AudioBackend`].
//!
//! Reaches the kernel audio layer through OSS (`/dev/dsp`, `sound(4)` /
//! `dsp(4)`) via libc raw `ioctl` calls — **no cpal, no ALSA indirection**. On FreeBSD OSS
//! is the native modern audio API; the `alsa-lib` port is only a Linux-software
//! compatibility shim. This backend is gated to `target_os = "freebsd"` and the
//! `oss` feature.
//!
//! # Real-time safety model
//!
//! Identical to the cpal backend: [`OssSink::write`] only **pushes** interleaved
//! `f32` samples into a lock-free [`rtrb`] ring (wait-free, alloc-free). A
//! dedicated audio thread owns the `/dev/dsp` file descriptor, drains the ring,
//! converts `f32` to the negotiated PCM format on a reused scratch buffer, and
//! performs the blocking `write(2)` to the device. The RT thread never touches
//! the file descriptor or performs I/O.
//!
//! # Format negotiation
//!
//! FreeBSD drivers vary in their support for `AFMT_FLOAT`. [`OssBackend`]
//! probes the device with `SNDCTL_DSP_GETFMTS` and negotiates
//! `AFMT_FLOAT → AFMT_S32_LE → AFMT_S16_LE`, confirming each with a readback.
//! The `f32` ↔ integer conversion is performed by [`crate::sample_conv`].
//!
//! > **Hardware note:** the acceptance criteria (sustained playback with xrun 0)
//! > require a `/dev/dsp` device. The pure negotiation/fragment logic is
//! > unit-tested without hardware; live playback is verified on a node with an
//! > audio device.

#![cfg(all(target_os = "freebsd", feature = "oss"))]

use std::ffi::CString;
use std::io;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc;
use std::sync::Arc;
use std::time::Duration;

use audio_core_bsd::AudioFrame;

use crate::backend::{AudioBackend, InputSource, OutputSink};
use crate::device::{DeviceDirection, DeviceInfo, StreamParams};
use crate::error::{IoError, Result};
use crate::sample_conv;

// =============================================================================
// OSS ioctl constants — extracted from FreeBSD `<sys/soundcard.h>` (BSD encoding)
// =============================================================================
// These differ from Linux OSS numbers (FreeBSD uses the BSD _IOC encoding:
// `(inout | (len << 16) | (group << 8) | num)`), which is why this backend uses
// raw constants rather than the oss-sys crate (which targets Linux semantics).
#[allow(dead_code)]
const SNDCTL_DSP_RESET: libc::c_ulong = 0x2000_5000;
const SNDCTL_DSP_SPEED: libc::c_ulong = 0xc004_5002;
const SNDCTL_DSP_SETFMT: libc::c_ulong = 0xc004_5005;
const SNDCTL_DSP_CHANNELS: libc::c_ulong = 0xc004_5006;
const SNDCTL_DSP_GETFMTS: libc::c_ulong = 0x4004_500b;
const SNDCTL_DSP_SETFRAGMENT: libc::c_ulong = 0xc004_500a;
#[allow(dead_code)]
const SNDCTL_DSP_GETOSPACE: libc::c_ulong = 0x4010_500c;

/// `AFMT_FLOAT` — 32-bit IEEE float (preferred; not all drivers support it).
const AFMT_FLOAT: i32 = 0x1000_0000;
/// `AFMT_S32_LE` — signed 32-bit little-endian (first integer fallback).
const AFMT_S32_LE: i32 = 0x0000_1000;
/// `AFMT_S16_LE` — signed 16-bit little-endian (final fallback).
const AFMT_S16_LE: i32 = 0x0000_0010;

/// OSS buffer-space query result (`struct audio_buf_info`, 16 bytes, 4×i32).
///
/// Reserved for the `GETOSPACE`-based backpressure path (a future optimisation
/// over the current blocking-write loop); kept here so the constant and struct
/// stay in lockstep with the extracted FreeBSD ABI.
#[allow(dead_code)]
#[repr(C)]
#[derive(Default, Clone, Copy, Debug)]
struct AudioBufInfo {
    /// Number of free fragments.
    fragments: i32,
    /// Total fragments allocated.
    fragstotal: i32,
    /// Size of one fragment in bytes.
    fragsize: i32,
    /// Free bytes available (≥ fragments × fragsize; includes partial frags).
    bytes: i32,
}

// -----------------------------------------------------------------------------
// Capture-side ioctl constants — verified from FreeBSD `<sys/soundcard.h>`
// (BSD encoding). These differ from the output variants only in the ioctl
// number and direction. `PCM_ENABLE_INPUT` is 0x1 (0x2 is OUTPUT — the design
// doc's 0x2 estimate was wrong; verified on FreeBSD 15.1).
// -----------------------------------------------------------------------------
#[allow(dead_code)]
const SNDCTL_DSP_GETISPACE: libc::c_ulong = 0x4010_500d;
#[allow(dead_code)]
const SNDCTL_DSP_GETIPTR: libc::c_ulong = 0x400c_5011;
#[allow(dead_code)]
const SNDCTL_DSP_GETTRIGGER: libc::c_ulong = 0x4004_5010;
#[allow(dead_code)]
const SNDCTL_DSP_SETTRIGGER: libc::c_ulong = 0x8004_5010;
#[allow(dead_code)]
const PCM_ENABLE_INPUT: i32 = 0x1;

/// OSS capture-pointer query result (`struct count_info`, 12 bytes, 3×i32) for
/// `SNDCTL_DSP_GETIPTR`. Distinct from `AudioBufInfo` (16 bytes) — reusing the
/// wrong struct would corrupt the ioctl.
#[allow(dead_code)]
#[repr(C)]
#[derive(Default, Clone, Copy, Debug)]
struct CountInfo {
    /// Sample counter since the last reset.
    samples: i32,
    /// Free byte count.
    fifo_depth: i32,
    /// Block (fragment) counter.
    blocks: i32,
}

/// The negotiated device sample format, paired with its byte width.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum OssFormat {
    /// Native float (no conversion needed).
    Float,
    /// Signed 32-bit little-endian (4 bytes/sample).
    S32Le,
    /// Signed 16-bit little-endian (2 bytes/sample).
    S16Le,
}

impl OssFormat {
    /// The OSS `AFMT_*` constant the driver was told to use.
    const fn afmt(self) -> i32 {
        match self {
            OssFormat::Float => AFMT_FLOAT,
            OssFormat::S32Le => AFMT_S32_LE,
            OssFormat::S16Le => AFMT_S16_LE,
        }
    }

    /// Bytes per sample in the negotiated device format.
    const fn bytes_per_sample(self) -> usize {
        match self {
            OssFormat::Float | OssFormat::S32Le => 4,
            OssFormat::S16Le => 2,
        }
    }
}

// =============================================================================
// Pure logic (unit-testable without /dev/dsp)
// =============================================================================

/// Picks the best device format from a `GETFMTS` support mask, preferring
/// float, then s32le, then s16le. Returns `None` if none are supported.
#[must_use]
fn negotiate_format(supported_mask: i32) -> Option<OssFormat> {
    for (bit, fmt) in [
        (AFMT_FLOAT, OssFormat::Float),
        (AFMT_S32_LE, OssFormat::S32Le),
        (AFMT_S16_LE, OssFormat::S16Le),
    ] {
        if supported_mask & bit == bit {
            return Some(fmt);
        }
    }
    None
}

/// Encodes a `SNDCTL_DSP_SETFRAGMENT` argument: high 16 bits = fragment count,
/// low 16 bits = fragment size as log2(bytes). `frag_log2` must be ≥ 4.
#[must_use]
fn encode_fragment(num_frags: i32, frag_log2: i32) -> i32 {
    let n = num_frags.clamp(1, 0x7FFF);
    let s = frag_log2.clamp(4, 0xFFFF);
    (n << 0x10) | (s & 0xFFFF)
}

/// Estimates the round-trip buffer latency in milliseconds for a fragment
/// configuration. `bytes_per_sample` is the negotiated device format width.
///
/// Useful for mapping a requested `StreamParams.buffer_size` to the OSS fragment
/// parameters (ROADMAP §4.6).
// The `as f64` casts on `usize` are sound: channel/byte counts are tiny.
#[allow(clippy::cast_precision_loss)]
#[must_use]
pub fn fragment_latency_ms(
    num_frags: i32,
    frag_log2: i32,
    channels: u16,
    bytes_per_sample: usize,
    sample_rate: u32,
) -> f64 {
    let ch = channels.max(1) as usize;
    let bps = bytes_per_sample.max(1);
    let bytes_per_frag = f64::from(1_u32 << u32::try_from(frag_log2.max(0)).unwrap_or(0));
    let frames_per_frag = bytes_per_frag / (ch * bps) as f64;
    let total_frames = f64::from(num_frags) * frames_per_frag;
    total_frames / f64::from(sample_rate) * 1000.0
}

/// Issue an ioctl with a pointer argument, mapping OS errors to [`IoError`].
unsafe fn dsp_ioctl_ptr<T>(fd: libc::c_int, req: libc::c_ulong, arg: *mut T) -> Result<()> {
    let rc = libc::ioctl(fd, req, arg.cast::<libc::c_void>());
    if rc < 0 {
        Err(io::Error::last_os_error().into())
    } else {
        Ok(())
    }
}

/// Issue an ioctl with an `int` argument (read-write), returning the readback
/// value the driver wrote (used to confirm format/rate acceptance).
unsafe fn dsp_ioctl_int(fd: libc::c_int, req: libc::c_ulong, mut value: i32) -> Result<i32> {
    let rc = libc::ioctl(fd, req, core::ptr::addr_of_mut!(value));
    if rc < 0 {
        Err(io::Error::last_os_error().into())
    } else {
        Ok(value)
    }
}

// =============================================================================
// OssBackend
// =============================================================================

/// A FreeBSD-native [`AudioBackend`] that talks to OSS `/dev/dsp` directly.
///
/// Construct with [`OssBackend::new`]. Device enumeration scans `/dev/dsp` and
/// any `/dev/dspN` units; `/dev/dsp` (unit 0) is the default output.
pub struct OssBackend;

impl OssBackend {
    /// Creates a new OSS backend.
    #[must_use]
    pub const fn new() -> Self {
        Self
    }

    /// The default OSS device path.
    const DEFAULT_DEV: &'static str = "/dev/dsp";
}

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

impl AudioBackend for OssBackend {
    fn enumerate_devices(&self) -> Vec<DeviceInfo> {
        let mut devs = Vec::new();
        // The default device.
        devs.push(DeviceInfo::new(
            Self::DEFAULT_DEV,
            DeviceDirection::Duplex,
            2,
            vec![44_100, 48_000, 96_000],
            true,
        ));
        // Additional units /dev/dsp1..N (best-effort scan; absent units skipped).
        for unit in 1..=8 {
            let path = format!("/dev/dsp{unit}");
            if std::path::Path::new(&path).exists() {
                devs.push(DeviceInfo::new(
                    path,
                    DeviceDirection::Duplex,
                    2,
                    vec![44_100, 48_000, 96_000],
                    false,
                ));
            }
        }
        devs
    }

    fn default_output(&self) -> Option<DeviceInfo> {
        Some(DeviceInfo::new(
            Self::DEFAULT_DEV,
            DeviceDirection::Output,
            2,
            vec![44_100, 48_000, 96_000],
            true,
        ))
    }

    fn default_input(&self) -> Option<DeviceInfo> {
        Some(DeviceInfo::new(
            Self::DEFAULT_DEV,
            DeviceDirection::Input,
            2,
            vec![44_100, 48_000, 96_000],
            true,
        ))
    }

    fn open_output(&self, dev: &str, params: StreamParams) -> Result<Box<dyn OutputSink>> {
        params.validate()?;

        // Open /dev/dsp for writing.
        let cdev = CString::new(dev).map_err(|e| IoError::DeviceNotFound(format!("{dev}: {e}")))?;
        // SAFETY: cdev is a valid NUL-terminated C string; O_WRONLY | O_CLOEXEC.
        let fd = unsafe { libc::open(cdev.as_ptr(), libc::O_WRONLY | libc::O_CLOEXEC) };
        if fd < 0 {
            let e = io::Error::last_os_error();
            // ENOENT/ENXIO → DeviceNotFound; EBUSY → Backend (busy).
            return match e.raw_os_error() {
                Some(libc::ENOENT | libc::ENXIO) => Err(IoError::DeviceNotFound(dev.into())),
                _ => Err(IoError::Backend(format!("open {dev}: {e}"))),
            };
        }

        // Negotiate the device format: probe GETFMTS, then SETFMT readback.
        let fmt = configure_output(fd, params)?;

        // SPSC ring of interleaved f32 samples shared with the audio thread.
        let (producer, consumer) = rtrb::RingBuffer::<f32>::new(RING_CAPACITY);
        let (drop_tx, drop_rx) = mpsc::channel::<()>();
        let (ready_tx, ready_rx) = mpsc::channel::<Result<()>>();

        let channels = params.channels;
        let sample_rate = params.sample_rate;

        std::thread::Builder::new()
            .name("audio-io-oss-output".into())
            .spawn(move || {
                run_output_thread(fd, consumer, channels, sample_rate, fmt, ready_tx, drop_rx);
            })
            .map_err(|e| IoError::Backend(format!("spawn oss output thread: {e}")))?;

        ready_rx
            .recv()
            .map_err(|e| IoError::StreamSetup(format!("oss output thread panicked: {e}")))??;

        Ok(Box::new(OssSink {
            producer,
            scratch: Vec::with_capacity(4 * channels as usize),
            channels,
            drop_tx: Some(drop_tx),
        }))
    }

    fn open_input(
        &self,
        dev: &str,
        params: StreamParams,
    ) -> Result<Box<dyn crate::backend::InputSource>> {
        params.validate()?;

        // Open /dev/dsp for reading (capture-only MVP; full duplex is post-MVP).
        let cdev = CString::new(dev).map_err(|e| IoError::DeviceNotFound(format!("{dev}: {e}")))?;
        // SAFETY: cdev is a valid NUL-terminated C string; O_RDONLY | O_NONBLOCK
        // (non-blocking so the capture worker can poll shutdown) | O_CLOEXEC.
        let fd = unsafe {
            libc::open(
                cdev.as_ptr(),
                libc::O_RDONLY | libc::O_NONBLOCK | libc::O_CLOEXEC,
            )
        };
        if fd < 0 {
            let e = io::Error::last_os_error();
            return match e.raw_os_error() {
                Some(libc::ENOENT | libc::ENXIO) => Err(IoError::DeviceNotFound(dev.into())),
                _ => Err(IoError::Backend(format!("open {dev}: {e}"))),
            };
        }

        // Configure the device (mirror of configure_output).
        let fmt = configure_input(fd, params)?;

        // SPSC ring of interleaved f32: worker pushes, caller (OssSource) pops.
        let (producer, consumer) = rtrb::RingBuffer::<f32>::new(RING_CAPACITY);
        let (drop_tx, drop_rx) = mpsc::channel::<()>();
        let (ready_tx, ready_rx) = mpsc::channel::<Result<()>>();
        let fatal = Arc::new(AtomicBool::new(false));

        let channels = params.channels;
        let sample_rate = params.sample_rate;
        let fatal_worker = Arc::clone(&fatal);

        std::thread::Builder::new()
            .name("audio-io-oss-input".into())
            .spawn(move || {
                run_input_thread(
                    fd,
                    producer,
                    channels,
                    sample_rate,
                    fmt,
                    ready_tx,
                    drop_rx,
                    fatal_worker,
                );
            })
            .map_err(|e| IoError::Backend(format!("spawn oss input thread: {e}")))?;

        ready_rx
            .recv()
            .map_err(|e| IoError::StreamSetup(format!("oss input thread panicked: {e}")))??;

        Ok(Box::new(OssSource {
            consumer,
            channels,
            sample_rate,
            drop_tx: Some(drop_tx),
            fatal,
        }))
    }
}

/// Ring capacity (interleaved f32 samples) — ~0.68 s @ 48 kHz stereo.
const RING_CAPACITY: usize = 1 << 16;

/// Probe and configure the device: format negotiation, channels, sample rate,
/// and fragment size. Returns the negotiated [`OssFormat`].
fn configure_output(fd: libc::c_int, params: StreamParams) -> Result<OssFormat> {
    // 1. Query supported formats.
    let mut fmts = 0_i32;
    // SAFETY: GETFMTS writes one int into &fmts.
    unsafe { dsp_ioctl_ptr(fd, SNDCTL_DSP_GETFMTS, core::ptr::addr_of_mut!(fmts)) }?;

    let chosen = negotiate_format(fmts)
        .ok_or_else(|| IoError::UnsupportedConfig("no supported OSS sample format".into()))?;

    // 2. SETFMT with readback confirmation.
    // SAFETY: SETFMT reads/writes one int.
    let readback = unsafe { dsp_ioctl_int(fd, SNDCTL_DSP_SETFMT, chosen.afmt()) }?;
    if readback != chosen.afmt() {
        return Err(IoError::UnsupportedConfig(format!(
            "driver rejected format {chosen:?} (readback 0x{readback:x})"
        )));
    }

    // 3. Channels.
    let mut chans = i32::from(params.channels);
    // SAFETY: CHANNELS reads/writes one int.
    let got_chans = unsafe { dsp_ioctl_int(fd, SNDCTL_DSP_CHANNELS, chans) }?;
    if got_chans != chans {
        // Some drivers round; accept if it matches a sane value.
        if !(1..=8).contains(&got_chans) {
            return Err(IoError::UnsupportedConfig(format!(
                "driver returned {got_chans} channels (requested {chans})"
            )));
        }
        chans = got_chans;
    }

    // 4. Sample rate.
    let rate = i32::try_from(params.sample_rate).unwrap_or(i32::MAX);
    // SAFETY: SPEED reads/writes one int.
    let got_rate = unsafe { dsp_ioctl_int(fd, SNDCTL_DSP_SPEED, rate) }?;
    if got_rate > 0 && (got_rate - rate).abs() > rate / 100 {
        return Err(IoError::UnsupportedConfig(format!(
            "driver returned {got_rate} Hz (requested {rate})"
        )));
    }

    // 5. Fragment size — target ~10 ms latency (§4.6).
    let ch_us = usize::try_from(chans).unwrap_or(0);
    let frag_log2 = compute_fragment_log2(ch_us, chosen.bytes_per_sample(), &params);
    let frag_arg = encode_fragment(4, frag_log2);
    // SAFETY: SETFRAGMENT reads/writes one int.
    let _ = unsafe { dsp_ioctl_int(fd, SNDCTL_DSP_SETFRAGMENT, frag_arg) };

    Ok(chosen)
}

/// Picks a fragment size (log2 bytes) targeting a small latency window.
#[allow(clippy::needless_pass_by_value)]
fn compute_fragment_log2(channels: usize, bytes_per_sample: usize, params: &StreamParams) -> i32 {
    // Target one fragment ≈ 256 frames: bytes = 256 * channels * bps.
    let target_frames = match params.buffer_size {
        crate::device::BufferSize::Fixed(n) => n.max(64),
        crate::device::BufferSize::Default => 256,
    };
    let target_bytes = target_frames * channels.max(1) * bytes_per_sample.max(1);
    let mut log2 = 4_i32;
    while (1 << log2) < target_bytes && log2 < 16 {
        log2 += 1;
    }
    log2
}

/// The dedicated audio-thread loop: drain the ring, convert f32→PCM, write.
// `ready_tx`/`drop_rx` are owned for the thread's lifetime (used by reference).
#[allow(clippy::needless_pass_by_value)]
fn run_output_thread(
    fd: libc::c_int,
    mut consumer: rtrb::Consumer<f32>,
    channels: u16,
    _sample_rate: u32,
    fmt: OssFormat,
    ready_tx: mpsc::Sender<Result<()>>,
    drop_rx: mpsc::Receiver<()>,
) {
    // Signal readiness (the device is configured and the loop is about to run).
    let _ = ready_tx.send(Ok(()));

    let ch = channels.max(1) as usize;
    let bps = fmt.bytes_per_sample();
    // Reused scratch buffers (allocated once on the audio thread).
    let mut f32_buf: Vec<f32> = Vec::with_capacity(1024);
    let mut pcm_bytes: Vec<u8> = Vec::with_capacity(4096);

    // Run while the sink is alive: `try_recv` is `Empty` while the sink holds
    // its sender, and `Disconnected` once `Drop for OssSink` drops it → the
    // `while let` exits and the thread closes the fd. (An explicit `Ok` signal,
    // currently unused, also exits.)
    while let Err(mpsc::TryRecvError::Empty) = drop_rx.try_recv() {
        // Drain whatever is available in whole-frame chunks.
        f32_buf.clear();
        while let Ok(s) = consumer.pop() {
            f32_buf.push(s);
        }
        if f32_buf.is_empty() {
            // No data yet — brief yield to avoid a busy spin.
            std::thread::sleep(Duration::from_millis(1));
            continue;
        }
        // Truncate to a whole number of frames.
        let n = (f32_buf.len() / ch) * ch;
        if n == 0 {
            continue;
        }

        // Convert f32 → PCM bytes according to the negotiated format.
        let needed = n * bps;
        if pcm_bytes.len() < needed {
            pcm_bytes.resize(needed, 0);
        }
        match fmt {
            OssFormat::Float => {
                // f32 → little-endian bytes directly.
                for (i, &v) in f32_buf.iter().take(n).enumerate() {
                    pcm_bytes[i * 4..i * 4 + 4].copy_from_slice(&v.to_le_bytes());
                }
            }
            OssFormat::S32Le => {
                let mut tmp = vec![0_i32; n];
                sample_conv::f32_interleaved_to_s32(&f32_buf[..n], &mut tmp);
                sample_conv::s32_interleaved_to_le_bytes(&tmp, &mut pcm_bytes[..needed]);
            }
            OssFormat::S16Le => {
                let mut tmp = vec![0_i16; n];
                sample_conv::f32_interleaved_to_s16(&f32_buf[..n], &mut tmp);
                sample_conv::s16_interleaved_to_le_bytes(&tmp, &mut pcm_bytes[..needed]);
            }
        }

        // Blocking write to the device (audio thread — not RT).
        let mut off = 0;
        while off < needed {
            // SAFETY: writing pcm_bytes[off..] to a valid fd.
            let wr = unsafe {
                libc::write(
                    fd,
                    pcm_bytes[off..].as_ptr().cast::<libc::c_void>(),
                    needed - off,
                )
            };
            if wr < 0 {
                let e = io::Error::last_os_error();
                if e.kind() == io::ErrorKind::WouldBlock {
                    break;
                }
                // Transient errors: stop this chunk but keep the loop alive.
                break;
            }
            off += usize::try_from(wr).unwrap_or(0);
            if wr == 0 {
                break;
            }
        }
    }
    // Thread exit: close the fd.
    // SAFETY: fd is a valid open descriptor owned solely by this thread.
    unsafe { libc::close(fd) };
}

/// Output sink backed by a `/dev/dsp` descriptor (owned on a dedicated thread)
/// and a lock-free ring — structurally identical to the cpal backend's sink.
pub struct OssSink {
    producer: rtrb::Producer<f32>,
    scratch: Vec<f32>,
    channels: u16,
    drop_tx: Option<mpsc::Sender<()>>,
}

impl OutputSink for OssSink {
    fn write(&mut self, frame: &AudioFrame) -> Result<()> {
        let n = frame.num_frames();
        let ch = (self.channels.min(frame.channels)) as usize;
        if ch == 0 {
            return Ok(());
        }
        // Interleave planar → interleaved f32 (RT-safe: bounded loop, reused buf).
        self.scratch.clear();
        self.scratch.reserve(n * ch);
        for i in 0..n {
            for c in 0..ch {
                let v = frame.channel_slice(c).get(i).copied().unwrap_or(0.0);
                self.scratch.push(v);
            }
        }
        for &s in &self.scratch {
            if self.producer.push(s).is_err() {
                return Err(IoError::StreamSetup("oss ring full (back-pressure)".into()));
            }
        }
        Ok(())
    }
}

impl Drop for OssSink {
    fn drop(&mut self) {
        // Signal the audio thread to drain and exit (closes the fd).
        self.drop_tx.take();
    }
}

// =============================================================================
// Input (capture) — the mirror of the output path, direction reversed.
// =============================================================================

/// Configures the OSS device for capture. OSS device configuration is
/// direction-agnostic (`GETFMTS`/`SETFMT`/`CHANNELS`/`SPEED`/`SETFRAGMENT` are
/// identical for capture and playback), so this delegates to the output
/// configuration. Capture-specific steps (`SETTRIGGER` for precise record
/// start/stop) are post-MVP; this release auto-starts capture on the first
/// `read(2)`.
fn configure_input(fd: libc::c_int, params: StreamParams) -> Result<OssFormat> {
    configure_output(fd, params)
}

/// The capture worker thread: blocking-ish `read(2)` (opened `O_NONBLOCK`) →
/// PCM→`f32` conversion → deinterleave-inside-ring → `Producer::push` (non-RT).
///
/// Mirrors [`run_output_thread`] with the direction reversed: the worker
/// *produces* samples (output worker *consumes* them). The caller's
/// [`OssSource::read`] performs the wait-free `Consumer::pop` + deinterleave.
///
// `ready_tx`/`drop_rx` are owned for the thread's lifetime (used by reference).
#[allow(clippy::needless_pass_by_value, clippy::too_many_arguments)]
fn run_input_thread(
    fd: libc::c_int,
    mut producer: rtrb::Producer<f32>,
    channels: u16,
    _sample_rate: u32,
    fmt: OssFormat,
    ready_tx: mpsc::Sender<Result<()>>,
    drop_rx: mpsc::Receiver<()>,
    fatal: Arc<AtomicBool>,
) {
    // Handshake: the device is configured and the loop is about to run.
    let _ = ready_tx.send(Ok(()));

    let ch = channels.max(1) as usize;
    let bps = fmt.bytes_per_sample();
    let frame_bytes = ch * bps;
    // Reused buffers (allocated once on the worker thread).
    let mut pcm_buf: Vec<u8> = Vec::with_capacity(frame_bytes * 256);
    let mut scratch = [0_u8; 4096];

    // Run while the source is alive: `Empty` = keep running; `Disconnected`
    // (source dropped, sender gone) = shutdown.
    while let Err(mpsc::TryRecvError::Empty) = drop_rx.try_recv() {
        // Non-blocking read (opened O_NONBLOCK so this returns EAGAIN when idle,
        // letting the worker poll shutdown).
        // SAFETY: reading into scratch from a valid fd.
        let n = unsafe {
            libc::read(
                fd,
                scratch.as_mut_ptr().cast::<libc::c_void>(),
                scratch.len(),
            )
        };
        if n < 0 {
            let e = io::Error::last_os_error();
            match e.raw_os_error() {
                // EAGAIN and EWOULDBLOCK are the same errno on FreeBSD.
                Some(libc::EAGAIN) => {
                    std::thread::sleep(Duration::from_micros(100));
                    continue;
                }
                Some(libc::EINTR) => continue,
                _ => {
                    // Fatal capture error: signal the caller and back off.
                    fatal.store(true, Ordering::Relaxed);
                    std::thread::sleep(Duration::from_millis(10));
                    continue;
                }
            }
        }
        let n = usize::try_from(n).unwrap_or(0);
        if n == 0 {
            // EOF — the device closed/stopped. Fatal.
            fatal.store(true, Ordering::Relaxed);
            std::thread::sleep(Duration::from_millis(10));
            continue;
        }
        // Accumulate and convert only whole frames (carry the partial tail).
        pcm_buf.extend_from_slice(&scratch[..n]);
        let n_frames = pcm_buf.len() / frame_bytes;
        if n_frames == 0 {
            continue;
        }
        let usable = n_frames * frame_bytes;

        // Convert the whole-frame PCM prefix → interleaved f32 samples.
        let count = n_frames * ch;
        for i in 0..count {
            let off = i * bps;
            let v = match fmt {
                OssFormat::Float => f32::from_le_bytes([
                    pcm_buf[off],
                    pcm_buf[off + 1],
                    pcm_buf[off + 2],
                    pcm_buf[off + 3],
                ]),
                OssFormat::S32Le => {
                    let s = i32::from_le_bytes([
                        pcm_buf[off],
                        pcm_buf[off + 1],
                        pcm_buf[off + 2],
                        pcm_buf[off + 3],
                    ]);
                    sample_conv::s32_to_f32(s)
                }
                OssFormat::S16Le => {
                    let s = i16::from_le_bytes([pcm_buf[off], pcm_buf[off + 1]]);
                    sample_conv::s16_to_f32(s)
                }
            };
            // Push each interleaved sample; a full ring is a benign overrun drop.
            let _ = producer.push(v);
        }
        // Drain the processed prefix, keep the partial tail for the next read.
        pcm_buf.drain(..usable);
    }
    // Thread exit: close the fd.
    // SAFETY: fd is a valid open descriptor owned solely by this thread.
    unsafe { libc::close(fd) };
}

/// Capture source backed by a `/dev/dsp` descriptor (owned on a dedicated
/// worker thread) and a lock-free ring — the input mirror of [`OssSink`].
///
/// `read` performs a wait-free `Consumer::pop` and deinterleaves into a planar
/// [`AudioFrame`]; it allocates the returned frame (like the cpal input source)
/// but performs no syscall, lock, or block. An underrun (empty ring) yields
/// silence; a fatal capture error (worker flagged) yields [`IoError::StreamSetup`].
pub struct OssSource {
    consumer: rtrb::Consumer<f32>,
    channels: u16,
    sample_rate: u32,
    drop_tx: Option<mpsc::Sender<()>>,
    fatal: Arc<AtomicBool>,
}

impl InputSource for OssSource {
    fn read(&mut self) -> Result<AudioFrame> {
        // A fatal capture error (worker flagged) takes precedence.
        if self.fatal.load(Ordering::Relaxed) {
            return Err(IoError::StreamSetup("oss capture stream stopped".into()));
        }

        let ch = self.channels.max(1) as usize;
        // Drain available interleaved f32 samples.
        let mut inter: Vec<f32> = Vec::new();
        while let Ok(s) = self.consumer.pop() {
            inter.push(s);
        }
        // Truncate to a whole number of frames.
        let n_frames = inter.len() / ch;
        if n_frames == 0 {
            // Underrun — benign silence dropout (ADR-0010).
            return Ok(AudioFrame::silence(self.channels, 0, self.sample_rate));
        }

        // Deinterleave [s0c0, s0c1, s1c0, s1c1, …] → planar [c0: …, c1: …].
        let mut planar = vec![0.0_f32; ch * n_frames];
        for frame in 0..n_frames {
            for c in 0..ch {
                planar[c * n_frames + frame] = inter[frame * ch + c];
            }
        }
        Ok(AudioFrame::from_planar(
            self.channels,
            self.sample_rate,
            planar,
        ))
    }

    fn latency_ms(&self) -> Result<f64> {
        // rtrb 0.3's Consumer does not expose a pending-item count, so a precise
        // latency estimate is unavailable for MVP. (post-MVP: GETIPTR-based.)
        Err(IoError::Backend("oss capture latency unavailable".into()))
    }
}

impl Drop for OssSource {
    fn drop(&mut self) {
        // Signal the worker to exit (closes the fd). The worker is opened
        // O_NONBLOCK, so its read(2) returns promptly (EAGAIN) and it observes
        // the Disconnected state within one poll cycle.
        self.drop_tx.take();
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn negotiate_prefers_float_then_s32_then_s16() {
        assert_eq!(
            negotiate_format(AFMT_FLOAT | AFMT_S32_LE | AFMT_S16_LE),
            Some(OssFormat::Float)
        );
        assert_eq!(
            negotiate_format(AFMT_S32_LE | AFMT_S16_LE),
            Some(OssFormat::S32Le)
        );
        assert_eq!(negotiate_format(AFMT_S16_LE), Some(OssFormat::S16Le));
        assert_eq!(negotiate_format(0), None);
    }

    #[test]
    fn format_afmt_and_width() {
        assert_eq!(OssFormat::Float.afmt(), AFMT_FLOAT);
        assert_eq!(OssFormat::S32Le.afmt(), AFMT_S32_LE);
        assert_eq!(OssFormat::S16Le.afmt(), AFMT_S16_LE);
        assert_eq!(OssFormat::S16Le.bytes_per_sample(), 2);
        assert_eq!(OssFormat::S32Le.bytes_per_sample(), 4);
    }

    #[test]
    fn encode_fragment_packs_count_and_log2() {
        // 4 fragments × 2^10 bytes.
        let arg = encode_fragment(4, 10);
        assert_eq!(arg, (4 << 0x10) | 0xA);
    }

    #[test]
    fn encode_fragment_clamps_extremes() {
        let arg = encode_fragment(0, 2);
        // num clamped to 1, log2 clamped to 4.
        assert_eq!(arg, (1 << 0x10) | 0x4);
    }

    #[test]
    fn fragment_latency_matches_known_case() {
        // Stereo s16le @ 48 kHz: S=10 (1024 B = 256 frame/frag), N=4 → 1024
        // frames ≈ 21.3 ms (ROADMAP §4.6 example).
        let ms = fragment_latency_ms(4, 10, 2, 2, 48_000);
        assert!((ms - 21.33).abs() < 0.1, "got {ms} ms");
    }

    #[test]
    fn fragment_latency_doubles_with_fragment_count() {
        let one = fragment_latency_ms(2, 10, 2, 2, 48_000);
        let two = fragment_latency_ms(4, 10, 2, 2, 48_000);
        assert!((two - 2.0 * one).abs() < 0.01);
    }

    #[test]
    fn oss_backend_enumerates_default_device() {
        let b = OssBackend::new();
        let devs = b.enumerate_devices();
        assert!(devs.iter().any(|d| d.name == "/dev/dsp" && d.is_default));
    }

    #[test]
    fn oss_backend_has_default_output() {
        let b = OssBackend::new();
        let dev = b.default_output().unwrap();
        assert_eq!(dev.name, "/dev/dsp");
    }

    #[test]
    fn oss_backend_open_output_unknown_device_is_not_found() {
        let b = OssBackend::new();
        // A path that cannot contain a NUL and does not exist.
        let err = b
            .open_output("/dev/dsp_nonexistent_unit", StreamParams::pcm_48k_stereo())
            .err()
            .unwrap();
        assert!(err.to_string().contains("device not found") || err.to_string().contains("open"));
    }

    #[test]
    fn default_input_returns_dsp() {
        let b = OssBackend::new();
        let dev = b
            .default_input()
            .expect("OSS backend advertises a default input");
        assert_eq!(dev.name, "/dev/dsp");
        assert_eq!(dev.direction, DeviceDirection::Input);
    }

    #[test]
    fn open_input_unknown_device_is_not_found() {
        // Mirrors the open_output_unknown_device test for the capture path.
        // /dev/dsp_nonexistent_unit does not exist → DeviceNotFound (no /dev/dsp
        // on the test VM either, so this also covers the "no audio device" case).
        let b = OssBackend::new();
        let err = b
            .open_input("/dev/dsp_nonexistent_unit", StreamParams::pcm_48k_mono())
            .err()
            .unwrap();
        assert!(
            err.to_string().contains("device not found") || err.to_string().contains("open"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn open_input_validates_params() {
        let b = OssBackend::new();
        let err = b
            .open_input("/dev/dsp", StreamParams::pcm_48k_mono().with_channels(0))
            .err()
            .unwrap();
        assert!(err.to_string().contains("invalid channel count"));
    }

    #[test]
    fn count_info_is_twelve_bytes() {
        // GETIPTR returns a 12-byte count_info; it must NOT be confused with the
        // 16-byte AudioBufInfo (a struct-size mismatch corrupts the ioctl).
        assert_eq!(std::mem::size_of::<CountInfo>(), 12);
    }

    #[test]
    fn pcm_enable_input_is_one_not_two() {
        // Verified on FreeBSD 15.1: PCM_ENABLE_INPUT = 0x1 (0x2 is OUTPUT).
        // The design doc estimated 0x2 (wrong); this guards against regression.
        assert_eq!(PCM_ENABLE_INPUT, 0x1);
    }

    #[test]
    fn open_output_validates_params() {
        let b = OssBackend::new();
        let err = b
            .open_output("/dev/dsp", StreamParams::pcm_48k_stereo().with_channels(0))
            .err()
            .unwrap();
        assert!(err.to_string().contains("invalid channel count"));
    }

    /// Verifies the audio-thread shutdown contract: while the sink is alive
    /// `try_recv` is `Empty`; after the sink's `drop_tx` is dropped (mirroring
    /// `Drop for OssSink`), `try_recv` becomes `Disconnected`, which the loop
    /// treats as shutdown. This is the lifecycle the `run_output_thread` loop
    /// depends on (the sink's `drop_tx` is dropped, never sent — so the loop
    /// keys off `Disconnected`, not a message).
    #[test]
    fn shutdown_signal_disconnects_on_drop() {
        let (drop_tx, drop_rx) = mpsc::channel::<()>();
        // Alive: Empty (loop continues).
        assert_eq!(drop_rx.try_recv(), Err(mpsc::TryRecvError::Empty));
        // Sink dropped → sender taken and dropped (never sends).
        drop(drop_tx);
        // Now Disconnected → loop breaks, thread exits, fd closes.
        assert_eq!(drop_rx.try_recv(), Err(mpsc::TryRecvError::Disconnected));
    }
}