Skip to main content

usbdac_core/
playback.rs

1//! Explicit source-domain playback resolution and streaming.
2//! Existing strict negotiation and direct stream APIs remain unchanged.
3use crate::convert::{
4    ConversionKind, ConversionPlan, ConvertOptions, Converter, PcmFormat, SampleFormat,
5};
6use crate::dsd_pcm::DsdPcmConverter;
7use crate::{
8    AltFormat, Dac, DacListener, DacStream, Encoding, Error, RatePolicy, Result, StreamFormat,
9    StreamRequest, StreamStats,
10};
11use parking_lot::Mutex;
12use std::sync::Arc;
13use std::time::{Duration, Instant};
14
15#[derive(Debug, Clone, PartialEq)]
16pub struct PlaybackPolicy {
17    pub allow_lossless: bool,
18    pub allow_widening: bool,
19    pub allow_lossy: bool,
20    pub allow_native_dsd: bool,
21    pub dop_confirmed: bool,
22    pub allow_dop_pcm: bool,
23    pub max_pcm_rate: Option<u32>,
24    pub allowed_pcm_depths: Option<Vec<u8>>,
25    pub conversion_options: ConvertOptions,
26}
27impl Default for PlaybackPolicy {
28    fn default() -> Self {
29        Self {
30            allow_lossless: true,
31            allow_widening: true,
32            allow_lossy: true,
33            allow_native_dsd: true,
34            dop_confirmed: false,
35            allow_dop_pcm: true,
36            max_pcm_rate: None,
37            allowed_pcm_depths: None,
38            conversion_options: ConvertOptions::default(),
39        }
40    }
41}
42#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
43pub enum PlaybackFidelity {
44    Exact,
45    BitExact,
46    Lossless,
47    Lossy,
48}
49#[derive(Debug, Clone, PartialEq)]
50pub enum PlaybackTransform {
51    Direct,
52    Pcm {
53        plan: ConversionPlan,
54        unsigned_input: bool,
55    },
56    DsdToPcm {
57        bit_rate: u32,
58        dop_input: bool,
59        options: ConvertOptions,
60    },
61    DopToNative {
62        target_channels: u16,
63    },
64    DopRepack {
65        target_channels: u16,
66    },
67    NativeToDop {
68        target_channels: u16,
69    },
70    DsdChannelExpansion {
71        target_channels: u16,
72    },
73}
74/// Auditable ranking inputs for an individual planned request. Bandwidth is
75/// the conservative passband edge of the production conversion path.
76#[derive(Debug, Clone)]
77pub struct PlaybackCandidateQuality {
78    pub request: StreamRequest,
79    pub fidelity: PlaybackFidelity,
80    pub retained_bandwidth_hz: Option<f64>,
81    pub meaningful_depth_bits: Option<u8>,
82    pub resampling: bool,
83    pub resampler_passband_hz: Option<f64>,
84    pub resampler_attenuation_db: Option<f64>,
85    pub dsd_first_stage_passband_hz: Option<f64>,
86    pub dsd_first_stage_attenuation_db: Option<f64>,
87    pub reason: String,
88}
89#[derive(Debug, Clone)]
90pub struct PlaybackDecision {
91    pub source: StreamRequest,
92    pub format: StreamFormat,
93    /// Ordered planned requests; a success may stop before all were attempted.
94    pub candidates: Vec<StreamRequest>,
95    /// Quality records aligned to `candidates`; planned, not necessarily attempted.
96    pub candidate_quality: Vec<PlaybackCandidateQuality>,
97    pub selected_quality: PlaybackCandidateQuality,
98    pub attempted_candidates: usize,
99    /// Typed, clean refusals for the attempted prefix before the selected request.
100    pub candidate_refusals: Vec<Error>,
101    pub exact_refusal: Option<Error>,
102    /// Descriptor-backed source exclusion before any candidate USB mutation.
103    pub source_preflight_refusal: Option<String>,
104    pub transform: PlaybackTransform,
105    pub fidelity: PlaybackFidelity,
106    /// Input framing at `PlaybackStream::write`. Native DSD is one byte/channel.
107    pub source_frame_bytes: usize,
108}
109#[derive(Debug, Clone, Default)]
110pub struct PlaybackConversionStats {
111    pub source_bytes: u64,
112    pub target_bytes: u64,
113    pub clipped_samples: u64,
114}
115
116fn conversion_error(e: crate::convert::ConvertError) -> Error {
117    match e {
118        crate::convert::ConvertError::Unsupported(reason) => Error::Unsupported {
119            reason,
120            offered: vec![],
121        },
122        crate::convert::ConvertError::InvalidArgument(reason) => Error::InvalidArgument(reason),
123        crate::convert::ConvertError::InvalidState(reason) => Error::InvalidState(reason),
124    }
125}
126fn input_sample(source: &StreamRequest, options: &ConvertOptions) -> Result<SampleFormat> {
127    match source.encoding {
128        Encoding::PcmU8 => {
129            if options.source_sample.is_some() {
130                return Err(Error::InvalidArgument(
131                    "U8 source does not accept a source_sample override".into(),
132                ));
133            }
134            Ok(SampleFormat::I16)
135        }
136        Encoding::PcmFloat32 => {
137            if options
138                .source_sample
139                .is_some_and(|s| s != SampleFormat::Float32)
140            {
141                return Err(Error::InvalidArgument(
142                    "float input requires Float32 source layout".into(),
143                ));
144            }
145            Ok(SampleFormat::Float32)
146        }
147        Encoding::Pcm => Ok(options.source_sample.unwrap_or(match source.bit_depth {
148            16 => SampleFormat::I16,
149            24 => SampleFormat::I24,
150            32 => SampleFormat::I32,
151            _ => return Err(Error::InvalidArgument("unsupported PCM depth".into())),
152        })),
153        _ => Err(Error::InvalidArgument("not PCM".into())),
154    }
155}
156fn input_frame(source: &StreamRequest, options: &ConvertOptions) -> Result<usize> {
157    let slot = match source.encoding {
158        Encoding::PcmU8 => 1,
159        Encoding::Pcm | Encoding::PcmFloat32 => input_sample(source, options)?.bytes_per_sample(),
160        Encoding::DoP => match source.bit_depth {
161            24 => 3,
162            32 => 4,
163            _ => {
164                return Err(Error::InvalidArgument(
165                    "DoP requires 24 or 32-bit slots".into(),
166                ))
167            }
168        },
169        Encoding::DsdNative { .. } => 1,
170    };
171    Ok(slot * usize::from(source.channels))
172}
173fn exact_matches(request: &StreamRequest, f: &StreamFormat) -> bool {
174    f.encoding == request.encoding
175        && f.channels == request.channels
176        && (matches!(request.encoding, Encoding::DsdNative { .. })
177            || (f.sample_rate == request.sample_rate && f.valid_bits == request.bit_depth))
178}
179fn permitted(policy: &PlaybackPolicy, f: &StreamFormat) -> bool {
180    !matches!(
181        f.encoding,
182        Encoding::Pcm | Encoding::PcmU8 | Encoding::PcmFloat32
183    ) || (policy.max_pcm_rate.map_or(true, |max| f.sample_rate <= max)
184        && policy
185            .allowed_pcm_depths
186            .as_ref()
187            .map_or(true, |depths| depths.contains(&f.valid_bits)))
188}
189fn dsd_rate(source: &StreamRequest) -> Option<u32> {
190    match source.encoding {
191        Encoding::DsdNative { bit_rate } => Some(bit_rate),
192        Encoding::DoP => source.sample_rate.checked_mul(16),
193        _ => None,
194    }
195}
196fn supported_dsd(rate: u32) -> bool {
197    matches!(
198        rate,
199        2_822_400
200            | 3_072_000
201            | 5_644_800
202            | 6_144_000
203            | 11_289_600
204            | 12_288_000
205            | 22_579_200
206            | 24_576_000
207    )
208}
209fn fidelity(kind: ConversionKind, unsigned: bool) -> PlaybackFidelity {
210    match kind {
211        ConversionKind::None if !unsigned => PlaybackFidelity::Exact,
212        ConversionKind::None | ConversionKind::BitExact if !unsigned => PlaybackFidelity::BitExact,
213        ConversionKind::None | ConversionKind::BitExact | ConversionKind::Lossless => {
214            PlaybackFidelity::Lossless
215        }
216        ConversionKind::Lossy => PlaybackFidelity::Lossy,
217    }
218}
219fn enabled(policy: &PlaybackPolicy, f: PlaybackFidelity) -> bool {
220    match f {
221        PlaybackFidelity::Exact => true,
222        PlaybackFidelity::BitExact | PlaybackFidelity::Lossless => policy.allow_lossless,
223        PlaybackFidelity::Lossy => policy.allow_lossy,
224    }
225}
226#[derive(Clone)]
227struct Candidate {
228    request: StreamRequest,
229    fidelity: PlaybackFidelity,
230    rate_rank: usize,
231    channels_rank: u8,
232    depth_rank: (u8, u8),
233    quality: PlaybackCandidateQuality,
234    upsample_excess: u32,
235}
236fn supported_rate(alt: &crate::AltSetting, rate: u32) -> bool {
237    alt.sample_rates.contains(&rate)
238        || alt.rate_ranges.iter().any(|r| {
239            rate >= r.min_hz
240                && rate <= r.max_hz
241                && if r.step_hz == 0 {
242                    // A zero-resolution range yields only its minimum, as ALSA's
243                    // parse_uac2_sample_rate_range adds `min` and then stops on
244                    // `res == 0` (format.c:448, 478).
245                    rate == r.min_hz
246                } else {
247                    (rate - r.min_hz).checked_rem(r.step_hz) == Some(0)
248                }
249        })
250}
251fn candidates(
252    caps: &crate::Capabilities,
253    source: &StreamRequest,
254    policy: &PlaybackPolicy,
255) -> Result<Vec<Candidate>> {
256    let dsd = dsd_rate(source);
257    if let Some(rate) = dsd {
258        if !supported_dsd(rate) || !(1..=8).contains(&source.channels) {
259            return Ok(vec![]);
260        }
261    }
262    let source_rate = dsd.map_or(source.sample_rate, |r| r / 16);
263    let sample = if dsd.is_some() {
264        SampleFormat::Float32
265    } else {
266        input_sample(source, &policy.conversion_options)?
267    };
268    let source_depth = if dsd.is_some() { 24 } else { source.bit_depth };
269    let mut found = Vec::<(StreamRequest, PlaybackFidelity)>::new();
270    const STANDARD: [u32; 19] = [
271        8_000, 11_025, 12_000, 16_000, 22_050, 24_000, 32_000, 44_100, 48_000, 88_200, 96_000,
272        176_400, 192_000, 352_800, 384_000, 705_600, 768_000, 1_411_200, 1_536_000,
273    ];
274    for alt in caps.alt_settings.iter().filter(|a| {
275        matches!(a.format, AltFormat::Pcm | AltFormat::PcmFloat32)
276            && (a.channels == source.channels || (source.channels == 1 && a.channels == 2))
277            && [16, 24, 32].contains(&a.valid_bits)
278            && a.pacing.is_some()
279            && a.service_interval_us > 0
280            && (1..=4).contains(&a.subslot_bytes)
281            && u16::from(a.valid_bits) <= u16::from(a.subslot_bytes) * 8
282    }) {
283        if policy
284            .allowed_pcm_depths
285            .as_ref()
286            .is_some_and(|d| !d.contains(&alt.valid_bits))
287        {
288            continue;
289        }
290        let mut rates = alt.sample_rates.clone();
291        for range in &alt.rate_ranges {
292            for rate in STANDARD
293                .into_iter()
294                .chain([range.min_hz, range.max_hz, source_rate])
295            {
296                if supported_rate(alt, rate) {
297                    rates.push(rate);
298                }
299            }
300            if range.step_hz > 0 {
301                if let Some(maximum) = policy.max_pcm_rate {
302                    let ceiling = maximum.min(range.max_hz);
303                    if ceiling >= range.min_hz {
304                        let index = (ceiling - range.min_hz) / range.step_hz;
305                        if let Some(rate) = index
306                            .checked_mul(range.step_hz)
307                            .and_then(|v| range.min_hz.checked_add(v))
308                        {
309                            if supported_rate(alt, rate) {
310                                rates.push(rate);
311                            }
312                        }
313                    }
314                }
315            }
316            if range.step_hz > 0 && source_rate >= range.min_hz {
317                let n = (source_rate - range.min_hz) / range.step_hz;
318                for i in [n, n.saturating_add(1)] {
319                    if let Some(rate) = i
320                        .checked_mul(range.step_hz)
321                        .and_then(|v| range.min_hz.checked_add(v))
322                    {
323                        if supported_rate(alt, rate) {
324                            rates.push(rate)
325                        }
326                    }
327                }
328            }
329        }
330        rates.sort_unstable();
331        rates.dedup();
332        for rate in rates {
333            if !(crate::convert::MIN_RATE..=crate::convert::MAX_RATE).contains(&rate)
334                || policy.max_pcm_rate.is_some_and(|max| rate > max)
335            {
336                continue;
337            }
338            let packet = (u64::from(rate) * u64::from(alt.service_interval_us)).div_ceil(1_000_000)
339                * u64::from(alt.channels)
340                * u64::from(alt.subslot_bytes);
341            if packet > alt.max_packet_bytes as u64 {
342                continue;
343            }
344            if source_rate != rate
345                && crate::convert::filter_info(source_rate, rate, policy.conversion_options.quality)
346                    .is_err()
347            {
348                continue;
349            }
350            let target_sample = if alt.format == AltFormat::PcmFloat32 {
351                if alt.valid_bits != 32 || alt.subslot_bytes != 4 {
352                    continue;
353                }
354                SampleFormat::Float32
355            } else {
356                match SampleFormat::int(alt.valid_bits, alt.subslot_bytes) {
357                    Ok(v) => v,
358                    Err(_) => continue,
359                }
360            };
361            let mut opts = policy.conversion_options;
362            if dsd.is_some() {
363                opts.source_sample = None;
364            }
365            let plan = match ConversionPlan::pcm(
366                PcmFormat::new(source_rate, source.channels, sample),
367                PcmFormat::new(rate, alt.channels, target_sample),
368                &opts,
369            ) {
370                Ok(v) => v,
371                Err(_) => continue,
372            };
373            if source.encoding == Encoding::PcmU8 && !policy.allow_widening {
374                continue;
375            }
376            if !policy.allow_widening
377                && plan
378                    .steps()
379                    .iter()
380                    .any(|step| matches!(step, crate::convert::Step::Widen { .. }))
381            {
382                continue;
383            }
384            if dsd.is_some()
385                && (!policy.allow_lossy
386                    || policy.conversion_options.source_sample.is_some()
387                    || (matches!(source.encoding, Encoding::DoP) && !policy.allow_dop_pcm))
388            {
389                continue;
390            }
391            let kind = if dsd.is_some() {
392                PlaybackFidelity::Lossy
393            } else {
394                fidelity(plan.kind(), source.encoding == Encoding::PcmU8)
395            };
396            if !enabled(policy, kind) {
397                continue;
398            }
399            let req = if alt.format == AltFormat::PcmFloat32 {
400                StreamRequest::pcm_float32(rate, alt.channels)
401            } else {
402                StreamRequest::pcm(rate, alt.channels, alt.valid_bits)
403            };
404            if req == *source {
405                continue;
406            }
407            if !found.iter().any(|(r, _)| *r == req) {
408                found.push((req, kind));
409            }
410        }
411    }
412    if let Some(bit_rate) = dsd {
413        if policy.allow_lossless {
414            for alt in &caps.alt_settings {
415                if alt.channels != source.channels && !(source.channels == 1 && alt.channels == 2) {
416                    continue;
417                }
418                if alt.pacing.is_none() || alt.service_interval_us == 0 {
419                    continue;
420                }
421                let channel_fidelity = if alt.channels == source.channels {
422                    PlaybackFidelity::BitExact
423                } else {
424                    PlaybackFidelity::Lossless
425                };
426                let request = if policy.allow_native_dsd
427                    && alt.format == AltFormat::Dsd
428                    && alt.subslot_bytes > 0
429                {
430                    let bits = u32::from(alt.subslot_bytes) * 8;
431                    if bit_rate % bits != 0 {
432                        continue;
433                    }
434                    let wire_rate = bit_rate / bits;
435                    if !supported_rate(alt, wire_rate) {
436                        continue;
437                    }
438                    let required = (u64::from(wire_rate) * u64::from(alt.service_interval_us))
439                        .div_ceil(1_000_000)
440                        * u64::from(alt.channels)
441                        * u64::from(alt.subslot_bytes);
442                    if required > alt.max_packet_bytes as u64 {
443                        continue;
444                    }
445                    StreamRequest::dsd_native(bit_rate, alt.channels)
446                } else if policy.dop_confirmed
447                    && matches!(source.encoding, Encoding::DsdNative { .. } | Encoding::DoP)
448                    && matches!(alt.format, AltFormat::Pcm | AltFormat::Dop)
449                    && [24, 32].contains(&alt.valid_bits)
450                {
451                    let carrier = bit_rate / 16;
452                    if bit_rate % 16 != 0
453                        || !supported_rate(alt, carrier)
454                        || policy.max_pcm_rate.is_some_and(|max| carrier > max)
455                        || policy
456                            .allowed_pcm_depths
457                            .as_ref()
458                            .is_some_and(|depths| !depths.contains(&alt.valid_bits))
459                    {
460                        continue;
461                    }
462                    let required = (u64::from(carrier) * u64::from(alt.service_interval_us))
463                        .div_ceil(1_000_000)
464                        * u64::from(alt.channels)
465                        * u64::from(alt.subslot_bytes);
466                    if required > alt.max_packet_bytes as u64 {
467                        continue;
468                    }
469                    let mut req = StreamRequest::dop(bit_rate, alt.channels);
470                    req.bit_depth = alt.valid_bits;
471                    req
472                } else {
473                    continue;
474                };
475                if request == *source || found.iter().any(|(r, _)| *r == request) {
476                    continue;
477                }
478                found.push((request, channel_fidelity));
479            }
480        }
481    }
482    let mut rates: Vec<u32> = found.iter().map(|(r, _)| r.sample_rate).collect();
483    crate::rank_sample_rates(&mut rates, source_rate);
484    let mut out: Vec<_> = found
485        .into_iter()
486        .map(|(request, fidelity)| Candidate {
487            quality: candidate_quality(source, &request, fidelity, &policy.conversion_options),
488            upsample_excess: request.sample_rate.saturating_sub(source_rate),
489            rate_rank: if matches!(request.encoding, Encoding::DsdNative { .. }) {
490                0
491            } else {
492                rates
493                    .iter()
494                    .position(|r| *r == request.sample_rate)
495                    .unwrap_or(usize::MAX)
496            },
497            channels_rank: u8::from(request.channels != source.channels),
498            depth_rank: (
499                u8::from(request.bit_depth < source_depth),
500                request.bit_depth.abs_diff(source_depth),
501            ),
502            request,
503            fidelity,
504        })
505        .collect();
506    sort_candidates(&mut out);
507    Ok(out)
508}
509fn sort_candidates(candidates: &mut [Candidate]) {
510    candidates.sort_by(|a, b| {
511        a.fidelity
512            .cmp(&b.fidelity)
513            .then_with(|| {
514                if a.fidelity == PlaybackFidelity::Lossy {
515                    b.quality
516                        .retained_bandwidth_hz
517                        .unwrap_or(0.0)
518                        .total_cmp(&a.quality.retained_bandwidth_hz.unwrap_or(0.0))
519                        .then_with(|| {
520                            b.quality
521                                .meaningful_depth_bits
522                                .cmp(&a.quality.meaningful_depth_bits)
523                        })
524                        .then_with(|| a.upsample_excess.cmp(&b.upsample_excess))
525                } else {
526                    std::cmp::Ordering::Equal
527                }
528            })
529            .then_with(|| {
530                (a.rate_rank, a.channels_rank, a.depth_rank).cmp(&(
531                    b.rate_rank,
532                    b.channels_rank,
533                    b.depth_rank,
534                ))
535            })
536    });
537}
538fn candidate_quality(
539    source: &StreamRequest,
540    target: &StreamRequest,
541    fidelity: PlaybackFidelity,
542    options: &ConvertOptions,
543) -> PlaybackCandidateQuality {
544    let dsd = dsd_rate(source);
545    let source_rate = dsd.map_or(source.sample_rate, |rate| rate / 16);
546    let target_pcm = matches!(
547        target.encoding,
548        Encoding::Pcm | Encoding::PcmU8 | Encoding::PcmFloat32
549    );
550    let resampling = target_pcm && target.sample_rate != source_rate;
551    let filter = if resampling {
552        crate::convert::filter_info(source_rate, target.sample_rate, options.quality).ok()
553    } else {
554        None
555    };
556    let first_stage = if target_pcm {
557        dsd.map(|rate| f64::from(rate) * 0.020)
558    } else {
559        None
560    };
561    let retained_bandwidth_hz = if target_pcm {
562        let bandwidth = if resampling {
563            filter.as_ref().map(|f| f.passband_hz)
564        } else {
565            Some(f64::from(source_rate) / 2.0)
566        };
567        bandwidth.map(|bandwidth| first_stage.map_or(bandwidth, |first| first.min(bandwidth)))
568    } else {
569        None
570    };
571    let source_bits = match source.encoding {
572        Encoding::PcmU8 => 8,
573        Encoding::PcmFloat32 | Encoding::DoP | Encoding::DsdNative { .. } => 24,
574        Encoding::Pcm => match options.source_sample {
575            Some(SampleFormat::Float32) => 24,
576            Some(SampleFormat::Int { bits, .. }) => bits,
577            None => source.bit_depth,
578        },
579    };
580    let target_bits = match target.encoding {
581        Encoding::PcmFloat32 => 24,
582        Encoding::PcmU8 => 8,
583        Encoding::Pcm => target.bit_depth,
584        _ => 0,
585    };
586    let meaningful_depth_bits = target_pcm.then_some(if resampling {
587        target_bits
588    } else {
589        source_bits.min(target_bits)
590    });
591    PlaybackCandidateQuality {
592        request: *target,
593        fidelity,
594        retained_bandwidth_hz,
595        meaningful_depth_bits,
596        resampling,
597        resampler_passband_hz: filter.as_ref().map(|f| f.passband_hz),
598        resampler_attenuation_db: filter.as_ref().map(|f| f.design_attenuation_db),
599        dsd_first_stage_passband_hz: first_stage,
600        dsd_first_stage_attenuation_db: first_stage.map(|_| 120.0),
601        reason: if target_pcm {
602            "Ranked by fidelity, retained conversion passband, meaningful depth, and excess upsampling; rate-family preference breaks ties".into()
603        } else {
604            "Bitstream-preserving transport; no PCM conversion passband applies".into()
605        },
606    }
607}
608/// Returns a conservative source exclusion only for a complete claimed descriptor scan.
609/// Unknown/opaque alternatives and unknown rates remain eligible for real negotiation.
610fn descriptor_exclusion(
611    complete: bool,
612    alts: &[crate::AltSetting],
613    native_only_aliases: &[(u8, u8, u8)],
614    complete_uac1_rate_alternates: &[(u8, u8, u8)],
615    source: &StreamRequest,
616) -> Option<String> {
617    if !complete || alts.is_empty() {
618        return None;
619    }
620    // DoP rides a Type I PCM alternate of the same channel count and depth at
621    // bit_rate / 16 Hz (DoP v1.1 §2; ALSA carries it on a 24/32-bit PCM format,
622    // pcm.c fill_playback_urb_dsd_dop), so its exact shape is checked like PCM.
623    // ALSA never tries a format absent from the parsed table (pcm.c
624    // hw_rule_rate/hw_check_valid_format), so a snapshot that cannot carry the
625    // exact DoP shape skips straight to the DoP and PCM fallbacks.
626    let dop = matches!(source.encoding, Encoding::DoP);
627    let desired = match source.encoding {
628        Encoding::Pcm | Encoding::DoP => AltFormat::Pcm,
629        Encoding::PcmU8 => AltFormat::PcmU8,
630        Encoding::PcmFloat32 => AltFormat::PcmFloat32,
631        Encoding::DsdNative { .. } => AltFormat::Dsd,
632    };
633    if alts.iter().any(|a| {
634        a.channels == source.channels
635            && a.format == AltFormat::Other
636            && !native_only_aliases.contains(&(
637                a.interface_number,
638                a.alt_setting,
639                a.endpoint_address,
640            ))
641    }) {
642        return None;
643    }
644    // Exact depth: the transport admits a Type I alternate only when its
645    // bBitResolution equals the requested depth (negotiate.rs
646    // transport_compatibility_penalty), for DoP carriers as for PCM.
647    let matching: Vec<_> = alts
648        .iter()
649        .filter(|a| {
650            a.channels == source.channels
651                && (a.format == desired || (dop && a.format == AltFormat::Dop))
652                && (desired == AltFormat::Dsd || a.valid_bits == source.bit_depth)
653        })
654        .collect();
655    if matching.is_empty() {
656        return Some(
657            "complete descriptor snapshot has no matching encoding/channel/depth shape".into(),
658        );
659    }
660    let possibly_supported = matching.iter().any(|alt| {
661        // UAC1 rates are trusted only with the strict raw Type-I completeness witness.
662        let uac1_proven = alt.uac_version == crate::UacVersion::V1
663            && !matches!(source.encoding, Encoding::DsdNative { .. })
664            && complete_uac1_rate_alternates.contains(&(
665                alt.interface_number,
666                alt.alt_setting,
667                alt.endpoint_address,
668            ));
669        if (alt.uac_version != crate::UacVersion::V2 && !uac1_proven)
670            || alt.rate_ranges.is_empty()
671            || alt
672                .rate_ranges
673                .iter()
674                .any(|r| r.min_hz == 0 || r.min_hz > r.max_hz)
675        {
676            return true;
677        }
678        let rate = match source.encoding {
679            Encoding::DsdNative { bit_rate } => {
680                let divisor = u32::from(alt.subslot_bytes) * 8;
681                if divisor == 0 || bit_rate.checked_rem(divisor) != Some(0) {
682                    return true;
683                }
684                bit_rate / divisor
685            }
686            _ => source.sample_rate,
687        };
688        // Same rate rule as transport model_excludes (negotiate.rs): a
689        // zero-resolution range yields only its minimum (ALSA format.c:448-478).
690        supported_rate(alt, rate)
691    });
692    if possibly_supported {
693        None
694    } else {
695        Some(
696            if matching.iter().all(|alt| alt.uac_version == crate::UacVersion::V1) {
697                "complete UAC1 Type-I descriptor rate list/range excludes the exact source rate"
698            } else {
699                "complete UAC1 Type-I/UAC2 descriptor snapshot and rate ranges exclude the exact source rate"
700            }.into(),
701        )
702    }
703}
704fn exact_policy_allows(source: &StreamRequest, policy: &PlaybackPolicy) -> bool {
705    let pcm_limit_ok = !matches!(
706        source.encoding,
707        Encoding::Pcm | Encoding::PcmU8 | Encoding::PcmFloat32 | Encoding::DoP
708    ) || (policy
709        .max_pcm_rate
710        .map_or(true, |max| source.sample_rate <= max)
711        && policy
712            .allowed_pcm_depths
713            .as_ref()
714            .map_or(true, |depths| depths.contains(&source.bit_depth)));
715    let native_allowed =
716        !matches!(source.encoding, Encoding::DsdNative { .. }) || policy.allow_native_dsd;
717    pcm_limit_ok
718        && native_allowed
719        && (!matches!(source.encoding, Encoding::DoP) || policy.dop_confirmed)
720}
721/// Validates the source independently of descriptor or policy filtering and
722/// returns its input frame size.
723fn validate_source(source: &StreamRequest, policy: &PlaybackPolicy) -> Result<usize> {
724    if source.rate_policy != RatePolicy::Exact {
725        return Err(Error::InvalidArgument(
726            "playback source requires exact rate policy".into(),
727        ));
728    }
729    if !(1..=32).contains(&source.channels) {
730        return Err(Error::InvalidArgument(
731            "source channels must be between one and 32".into(),
732        ));
733    }
734    crate::transport::api::playback_format_from_request(source)?;
735    input_frame(source, &policy.conversion_options)
736}
737/// The negotiated wire must carry what the transform produces. A DSD-to-PCM
738/// decimation on a DoP or native DSD wire would hand PCM bits to a DSD decoder
739/// (the ring stamps valid DoP markers over them), so it is never admitted.
740fn ensure_transform_fits_wire(transform: &PlaybackTransform, format: &StreamFormat) -> Result<()> {
741    let fits = match transform {
742        PlaybackTransform::Direct => true,
743        PlaybackTransform::Pcm { .. } | PlaybackTransform::DsdToPcm { .. } => matches!(
744            format.encoding,
745            Encoding::Pcm | Encoding::PcmU8 | Encoding::PcmFloat32
746        ),
747        PlaybackTransform::DopToNative { .. } | PlaybackTransform::DsdChannelExpansion { .. } => {
748            matches!(format.encoding, Encoding::DsdNative { .. })
749        }
750        PlaybackTransform::DopRepack { .. } | PlaybackTransform::NativeToDop { .. } => {
751            format.encoding == Encoding::DoP
752        }
753    };
754    if fits {
755        Ok(())
756    } else {
757        Err(Error::InvalidState(format!(
758            "playback transform {transform:?} cannot feed a {:?} wire",
759            format.encoding
760        )))
761    }
762}
763type CandidateNegotiation = (StreamFormat, usize, Option<Error>, Vec<Error>);
764impl Dac {
765    pub fn resolve_playback(
766        &self,
767        source: &StreamRequest,
768        policy: &PlaybackPolicy,
769    ) -> Result<PlaybackDecision> {
770        let frame = validate_source(source, policy)?;
771        let caps = self.capabilities()?;
772        let decision = resolve_with(&caps, source, policy, frame, |selected| {
773            self.negotiate_playback_candidates(selected)
774        })?;
775        ensure_transform_fits_wire(&decision.transform, &decision.format)?;
776        Ok(decision)
777    }
778}
779/// Plans, negotiates through `negotiate` and maps the result to a transform.
780/// `resolve_playback` supplies the real transport; tests supply a model of it.
781fn resolve_with(
782    caps: &crate::Capabilities,
783    source: &StreamRequest,
784    policy: &PlaybackPolicy,
785    frame: usize,
786    negotiate: impl FnOnce(&[StreamRequest]) -> Result<CandidateNegotiation>,
787) -> Result<PlaybackDecision> {
788    let policy_allows_exact = exact_policy_allows(source, policy);
789    let policy_refusal = (!policy_allows_exact).then(|| Error::Unsupported {
790        reason: if matches!(source.encoding, Encoding::DoP) && !policy.dop_confirmed {
791            "DoP decoder has not been confirmed"
792        } else {
793            "exact source is disallowed by downstream policy"
794        }
795        .into(),
796        offered: vec![],
797    });
798    let source_preflight_refusal = if policy_allows_exact {
799        descriptor_exclusion(
800            caps.exclusion_snapshot_complete,
801            &caps.alt_settings,
802            &caps.native_only_aliases,
803            &caps.complete_uac1_rate_alternates,
804            source,
805        )
806    } else {
807        None
808    };
809    let allow_exact = policy_allows_exact && source_preflight_refusal.is_none();
810    let all = candidates(caps, source, policy)?;
811    // A strict prefix preserves the global fidelity/rate/channel/depth ranking.
812    // The transport may attempt only a bounded prefix under one owner reservation.
813    let capacity = if allow_exact { 7 } else { 8 };
814    let chosen: Vec<_> = all
815        .iter()
816        .take(capacity)
817        .map(|candidate| candidate.request)
818        .collect();
819    let mut selected = Vec::new();
820    if allow_exact {
821        selected.push(*source);
822    }
823    selected.extend(chosen);
824    if selected.is_empty() {
825        return Err(policy_refusal.unwrap_or(Error::Unsupported {
826            reason: source_preflight_refusal
827                .clone()
828                .unwrap_or_else(|| "no permitted playback format".into()),
829            offered: vec![],
830        }));
831    }
832    let (format, attempted_candidates, first_refusal, candidate_refusals) = negotiate(&selected)?;
833    if !selected.iter().any(|r| exact_matches(r, &format)) || !permitted(policy, &format) {
834        return Err(Error::InvalidState(
835            "candidate negotiation returned an unplanned format".into(),
836        ));
837    }
838    let mut candidate_quality: Vec<_> = selected
839        .iter()
840        .map(|request| {
841            all.iter()
842                .find(|candidate| candidate.request == *request)
843                .map(|candidate| candidate.quality.clone())
844                .unwrap_or_else(|| {
845                    candidate_quality(
846                        source,
847                        request,
848                        PlaybackFidelity::Exact,
849                        &policy.conversion_options,
850                    )
851                })
852        })
853        .collect();
854    let mut selected_quality = candidate_quality
855        .iter()
856        .find(|quality| quality.request == format.request)
857        .cloned()
858        .ok_or_else(|| Error::InvalidState("selected candidate has no quality record".into()))?;
859    let exact_selected = allow_exact && exact_matches(source, &format);
860    let refusal = if exact_selected {
861        None
862    } else {
863        policy_refusal.or_else(|| source_preflight_refusal.as_ref().map(|reason| Error::Unsupported { reason: format!("source descriptor preflight: {reason}; no source USB negotiation was attempted"), offered: vec![] })).or(first_refusal)
864    };
865    if exact_selected {
866        if source.encoding == Encoding::Pcm {
867            let source_sample = input_sample(source, &policy.conversion_options)?;
868            let wire_sample = SampleFormat::int(format.valid_bits, format.subslot_bytes)
869                .map_err(conversion_error)?;
870            if source_sample == wire_sample {
871                return Ok(PlaybackDecision {
872                    source: *source,
873                    format,
874                    candidates: selected,
875                    candidate_quality,
876                    selected_quality,
877                    attempted_candidates,
878                    candidate_refusals,
879                    exact_refusal: None,
880                    source_preflight_refusal: None,
881                    transform: PlaybackTransform::Direct,
882                    fidelity: PlaybackFidelity::Exact,
883                    source_frame_bytes: frame,
884                });
885            }
886            let plan = ConversionPlan::between(source, &format, &policy.conversion_options)
887                .map_err(conversion_error)?;
888            let f = fidelity(plan.kind(), false);
889            selected_quality.fidelity = f;
890            if let Some(q) = candidate_quality
891                .iter_mut()
892                .find(|q| q.request == format.request)
893            {
894                q.fidelity = f;
895            }
896            if !enabled(policy, f)
897                || (!policy.allow_widening
898                    && plan
899                        .steps()
900                        .iter()
901                        .any(|step| matches!(step, crate::convert::Step::Widen { .. })))
902            {
903                return Err(Error::Unsupported {
904                    reason: "source layout conversion is disallowed by policy".into(),
905                    offered: vec![],
906                });
907            }
908            let transform = if plan.kind() == ConversionKind::None {
909                PlaybackTransform::Direct
910            } else {
911                PlaybackTransform::Pcm {
912                    plan,
913                    unsigned_input: false,
914                }
915            };
916            return Ok(PlaybackDecision {
917                source: *source,
918                format,
919                candidates: selected,
920                candidate_quality,
921                selected_quality,
922                attempted_candidates,
923                candidate_refusals,
924                exact_refusal: None,
925                source_preflight_refusal: None,
926                transform,
927                fidelity: f,
928                source_frame_bytes: frame,
929            });
930        }
931        let repack = source.encoding == Encoding::DoP
932            && usize::from(format.subslot_bytes) != frame / usize::from(source.channels);
933        if repack && !policy.allow_lossless {
934            return Err(Error::Unsupported {
935                reason: "DoP slot repacking is disallowed by policy".into(),
936                offered: vec![],
937            });
938        }
939        let channels = format.channels;
940        if repack {
941            selected_quality.fidelity = PlaybackFidelity::BitExact;
942            if let Some(q) = candidate_quality
943                .iter_mut()
944                .find(|q| q.request == format.request)
945            {
946                q.fidelity = PlaybackFidelity::BitExact;
947            }
948        }
949        return Ok(PlaybackDecision {
950            source: *source,
951            format,
952            candidates: selected,
953            candidate_quality,
954            selected_quality,
955            attempted_candidates,
956            candidate_refusals,
957            exact_refusal: None,
958            source_preflight_refusal: None,
959            transform: if repack {
960                PlaybackTransform::DopRepack {
961                    target_channels: channels,
962                }
963            } else {
964                PlaybackTransform::Direct
965            },
966            fidelity: if repack {
967                PlaybackFidelity::BitExact
968            } else {
969                PlaybackFidelity::Exact
970            },
971            source_frame_bytes: frame,
972        });
973    }
974    let (transform, fidelity) = if matches!(source.encoding, Encoding::DoP)
975        && matches!(format.encoding, Encoding::DsdNative { .. })
976    {
977        (
978            PlaybackTransform::DopToNative {
979                target_channels: format.channels,
980            },
981            if source.channels == format.channels {
982                PlaybackFidelity::BitExact
983            } else {
984                PlaybackFidelity::Lossless
985            },
986        )
987    } else if matches!(source.encoding, Encoding::DsdNative { .. })
988        && matches!(format.encoding, Encoding::DoP)
989    {
990        (
991            PlaybackTransform::NativeToDop {
992                target_channels: format.channels,
993            },
994            if source.channels == format.channels {
995                PlaybackFidelity::BitExact
996            } else {
997                PlaybackFidelity::Lossless
998            },
999        )
1000    } else if matches!(source.encoding, Encoding::DoP) && matches!(format.encoding, Encoding::DoP) {
1001        // Each DoP v1.1 carrier frame holds 16 DSD bits per channel under an
1002        // alternating 0x05/0xFA marker (dop.txt §2), so moving DoP to another
1003        // carrier is a lossless unpack/repack, the way ALSA's
1004        // fill_playback_urb_dsd_dop (pcm.c) packs DSD_U16 payload. A 24-bit
1005        // carrier in a 32-bit subslot is MSB-justified with zero padding
1006        // (Frmts20 §2.3.1.7.1), so the DSD bits are unchanged.
1007        if !policy.allow_lossless {
1008            return Err(Error::Unsupported {
1009                reason: "DoP slot repacking is disallowed by policy".into(),
1010                offered: vec![],
1011            });
1012        }
1013        (
1014            PlaybackTransform::DopRepack {
1015                target_channels: format.channels,
1016            },
1017            if source.channels == format.channels {
1018                PlaybackFidelity::BitExact
1019            } else {
1020                PlaybackFidelity::Lossless
1021            },
1022        )
1023    } else if matches!(source.encoding, Encoding::DsdNative { .. })
1024        && matches!(format.encoding, Encoding::DsdNative { .. })
1025    {
1026        (
1027            PlaybackTransform::DsdChannelExpansion {
1028                target_channels: format.channels,
1029            },
1030            PlaybackFidelity::Lossless,
1031        )
1032    } else if let Some(bit_rate) = dsd_rate(source) {
1033        let mut options = policy.conversion_options;
1034        if format.sample_rate == bit_rate / 16 {
1035            options.headroom_db = 0.0;
1036        }
1037        (
1038            PlaybackTransform::DsdToPcm {
1039                bit_rate,
1040                dop_input: matches!(source.encoding, Encoding::DoP),
1041                options,
1042            },
1043            PlaybackFidelity::Lossy,
1044        )
1045    } else {
1046        let mut pcm_source = *source;
1047        let unsigned = source.encoding == Encoding::PcmU8;
1048        if unsigned {
1049            pcm_source = StreamRequest::pcm(source.sample_rate, source.channels, 16);
1050        }
1051        let plan = ConversionPlan::between(&pcm_source, &format, &policy.conversion_options)
1052            .map_err(conversion_error)?;
1053        let fidelity = fidelity(plan.kind(), unsigned);
1054        if !enabled(policy, fidelity) {
1055            return Err(Error::InvalidState(
1056                "negotiated conversion violates playback policy".into(),
1057            ));
1058        }
1059        (
1060            PlaybackTransform::Pcm {
1061                plan,
1062                unsigned_input: unsigned,
1063            },
1064            fidelity,
1065        )
1066    };
1067    Ok(PlaybackDecision {
1068        source: *source,
1069        format,
1070        candidates: selected,
1071        candidate_quality,
1072        selected_quality,
1073        attempted_candidates,
1074        candidate_refusals,
1075        exact_refusal: refusal,
1076        source_preflight_refusal,
1077        transform,
1078        fidelity,
1079        source_frame_bytes: frame,
1080    })
1081}
1082impl Dac {
1083    pub fn open_playback(
1084        &self,
1085        decision: &PlaybackDecision,
1086        listener: Arc<dyn DacListener>,
1087    ) -> Result<PlaybackStream> {
1088        let engine = engine_for(decision)?;
1089        let stream = self.open_stream(&decision.format, listener)?;
1090        if !matches!(&decision.transform, PlaybackTransform::Direct) {
1091            stream.set_host_processing(true);
1092        }
1093        Ok(PlaybackStream::with_sink(
1094            Sink::Usb(stream),
1095            decision,
1096            engine,
1097        ))
1098    }
1099}
1100fn engine_for(decision: &PlaybackDecision) -> Result<Engine> {
1101    Ok(match &decision.transform {
1102        PlaybackTransform::Direct
1103            if matches!(decision.source.encoding, Encoding::DsdNative { .. })
1104                && decision.source_frame_bytes < decision.format.bytes_per_frame() =>
1105        {
1106            Engine::DsdRepack
1107        }
1108        PlaybackTransform::Direct => Engine::Direct,
1109        PlaybackTransform::Pcm {
1110            plan,
1111            unsigned_input,
1112        } => Engine::Pcm {
1113            converter: Converter::new(plan).map_err(conversion_error)?,
1114            unsigned: *unsigned_input,
1115        },
1116        PlaybackTransform::DopToNative { .. }
1117        | PlaybackTransform::DopRepack { .. }
1118        | PlaybackTransform::NativeToDop { .. }
1119        | PlaybackTransform::DsdChannelExpansion { .. } => Engine::DsdRepack,
1120        PlaybackTransform::DsdToPcm {
1121            bit_rate,
1122            dop_input,
1123            options,
1124        } => {
1125            let sample = if decision.format.encoding == Encoding::PcmFloat32 {
1126                SampleFormat::Float32
1127            } else {
1128                SampleFormat::int(decision.format.valid_bits, decision.format.subslot_bytes)
1129                    .map_err(conversion_error)?
1130            };
1131            let target = PcmFormat::new(
1132                decision.format.sample_rate,
1133                decision.format.channels,
1134                sample,
1135            );
1136            let mut opts = *options;
1137            opts.source_sample = None;
1138            Engine::Dsd {
1139                converter: Box::new(
1140                    DsdPcmConverter::with_options(
1141                        *bit_rate,
1142                        decision.source.channels,
1143                        target,
1144                        &opts,
1145                    )
1146                    .map_err(conversion_error)?,
1147                ),
1148                dop: *dop_input,
1149            }
1150        }
1151    })
1152}
1153
1154enum Engine {
1155    Direct,
1156    DsdRepack,
1157    Pcm {
1158        converter: Converter,
1159        unsigned: bool,
1160    },
1161    Dsd {
1162        converter: Box<DsdPcmConverter>,
1163        dop: bool,
1164    },
1165}
1166fn emit_producer_timing(
1167    observer: Option<&ProducerTimingObserver>,
1168    started: Option<Instant>,
1169    phase: ProducerTimingPhase,
1170    input_bytes: usize,
1171    output_bytes: usize,
1172    blocked: bool,
1173) {
1174    if let (Some(started), Some(observer)) = (started, observer) {
1175        observer(ProducerTiming {
1176            phase,
1177            started,
1178            elapsed: started.elapsed(),
1179            input_bytes,
1180            output_bytes,
1181            blocked,
1182        });
1183    }
1184}
1185type Observer = Arc<dyn Fn(&[u8]) + Send + Sync>;
1186/// Independently timed source-side operation. No wall-clock time is inferred.
1187#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1188pub enum ProducerTimingPhase {
1189    SourceFormat,
1190    ConverterProcess,
1191    ConverterFinish,
1192    RingEnqueue,
1193    Observer,
1194}
1195#[derive(Debug, Clone, Copy)]
1196pub struct ProducerTiming {
1197    pub phase: ProducerTimingPhase,
1198    pub started: Instant,
1199    pub elapsed: Duration,
1200    pub input_bytes: usize,
1201    pub output_bytes: usize,
1202    /// True when an enqueue accepts fewer bytes than requested.
1203    pub blocked: bool,
1204}
1205pub type ProducerTimingObserver = Arc<dyn Fn(ProducerTiming) + Send + Sync>;
1206
1207/// Source frames one converter or repack step takes. `write` loops over steps,
1208/// so this bounds only the staging buffers, never what one call accepts.
1209const WRITE_CHUNK_FRAMES: usize = 256;
1210/// DSD idle pattern: ALSA's silence byte for DSD_U8/U16/U32 (sound/core/pcm_misc.c
1211/// pcm_formats[].silence = 0x69), and what the ring sends for DSD while paused.
1212const DSD_IDLE: u8 = 0x69;
1213
1214/// The ring a playback stream feeds: the USB stream, or a model of its ring in tests.
1215enum Sink {
1216    Usb(DacStream),
1217    #[cfg(test)]
1218    Model(tests::RingModel),
1219}
1220macro_rules! on_sink {
1221    ($sink:expr, $stream:ident => $body:expr) => {
1222        match $sink {
1223            Sink::Usb($stream) => $body,
1224            #[cfg(test)]
1225            Sink::Model($stream) => $body,
1226        }
1227    };
1228}
1229impl Sink {
1230    fn write(&self, data: &[u8]) -> Result<usize> {
1231        on_sink!(self, s => s.write(data))
1232    }
1233    fn writable_bytes(&self) -> usize {
1234        on_sink!(self, s => s.writable_bytes())
1235    }
1236    fn play(&self) -> Result<()> {
1237        on_sink!(self, s => s.play())
1238    }
1239    fn pause(&self) -> Result<()> {
1240        on_sink!(self, s => s.pause())
1241    }
1242    fn flush(&self) -> Result<()> {
1243        on_sink!(self, s => s.flush())
1244    }
1245    fn drain(&self) -> Result<()> {
1246        on_sink!(self, s => s.drain())
1247    }
1248    fn is_drained(&self) -> bool {
1249        on_sink!(self, s => s.is_drained())
1250    }
1251    fn played_frames(&self) -> u64 {
1252        on_sink!(self, s => s.played_frames())
1253    }
1254    fn close(self) -> Result<()> {
1255        on_sink!(self, s => s.close())
1256    }
1257    fn stats(&self) -> StreamStats {
1258        match self {
1259            Sink::Usb(stream) => stream.stats(),
1260            #[cfg(test)]
1261            Sink::Model(_) => unreachable!("the ring model keeps no transport statistics"),
1262        }
1263    }
1264}
1265/// Wire bytes made but not yet taken by the ring. Kept behind a lock so
1266/// `writable_bytes(&self)` can move them into the ring before it reports room.
1267#[derive(Default)]
1268struct Staged {
1269    bytes: Vec<u8>,
1270    offset: usize,
1271    target_bytes: u64,
1272    /// An error met after input was accepted, returned by the next call.
1273    error: Option<Error>,
1274}
1275/// Rate of one `PlaybackStream::write` source frame. Native DSD is one byte per channel.
1276fn source_frame_rate(source: &StreamRequest) -> u32 {
1277    match source.encoding {
1278        Encoding::DsdNative { bit_rate } => bit_rate / 8,
1279        _ => source.sample_rate,
1280    }
1281}
1282/// Wire bytes per second the ring drains at the format's nominal rate.
1283fn wire_bytes_per_second(format: &StreamFormat) -> u64 {
1284    let per_tick = if matches!(format.encoding, Encoding::DsdNative { .. }) {
1285        usize::from(format.channels)
1286    } else {
1287        format.bytes_per_frame()
1288    };
1289    u64::from(format.counter_rate_hz()) * per_tick as u64
1290}
1291/// Source frames whose output fills `room` wire bytes, rounded up so any room
1292/// of a whole wire frame admits at least one source frame (the ring can then
1293/// always reach its start threshold, which never exceeds its target).
1294fn source_frames_for_room(room: usize, source_rate: u32, wire_bytes_per_second: u64) -> usize {
1295    if room == 0 || source_rate == 0 || wire_bytes_per_second == 0 {
1296        return 0;
1297    }
1298    (room as u128 * u128::from(source_rate))
1299        .div_ceil(u128::from(wire_bytes_per_second))
1300        .min(usize::MAX as u128) as usize
1301}
1302
1303/// One source-domain stream. Conversion and USB writes are nonblocking; a short
1304/// input count means the caller must retry the remainder. Observers see bytes
1305/// accepted by the core stream, before any native DSD wire packing/DoP marker rewrite.
1306pub struct PlaybackStream {
1307    stream: Sink,
1308    decision: PlaybackDecision,
1309    engine: Engine,
1310    input: Vec<u8>,
1311    input_offset: usize,
1312    staged: Mutex<Staged>,
1313    marker: Option<bool>,
1314    finishing: bool,
1315    drain_called: bool,
1316    source_bytes: u64,
1317    observer: Option<Observer>,
1318    timing_observer: Option<ProducerTimingObserver>,
1319}
1320impl PlaybackStream {
1321    fn with_sink(stream: Sink, decision: &PlaybackDecision, engine: Engine) -> Self {
1322        Self {
1323            stream,
1324            decision: decision.clone(),
1325            engine,
1326            input: Vec::with_capacity(65536),
1327            input_offset: 0,
1328            staged: Mutex::new(Staged {
1329                bytes: Vec::with_capacity(65536),
1330                ..Staged::default()
1331            }),
1332            marker: None,
1333            finishing: false,
1334            drain_called: false,
1335            source_bytes: 0,
1336            observer: None,
1337            timing_observer: None,
1338        }
1339    }
1340    pub fn decision(&self) -> &PlaybackDecision {
1341        &self.decision
1342    }
1343    pub fn format(&self) -> &StreamFormat {
1344        &self.decision.format
1345    }
1346    pub fn set_observer(&mut self, observer: Option<Observer>) {
1347        self.observer = observer;
1348    }
1349    /// Install an optional synchronous, nonblocking instrumentation callback.
1350    /// `started` uses the process monotonic clock and can be aligned with the
1351    /// transport feedback trace's `started_at`. Callbacks must not block.
1352    pub fn set_timing_observer(&mut self, observer: Option<ProducerTimingObserver>) {
1353        self.timing_observer = observer;
1354    }
1355    fn timing_start(&self) -> Option<Instant> {
1356        self.timing_observer.as_ref().map(|_| Instant::now())
1357    }
1358    fn timing_end(
1359        &self,
1360        started: Option<Instant>,
1361        phase: ProducerTimingPhase,
1362        input_bytes: usize,
1363        output_bytes: usize,
1364        blocked: bool,
1365    ) {
1366        emit_producer_timing(
1367            self.timing_observer.as_ref(),
1368            started,
1369            phase,
1370            input_bytes,
1371            output_bytes,
1372            blocked,
1373        );
1374    }
1375    fn notify_observer(&self, bytes: &[u8]) {
1376        if let Some(observer) = &self.observer {
1377            let start = self.timing_start();
1378            observer(bytes);
1379            self.timing_end(
1380                start,
1381                ProducerTimingPhase::Observer,
1382                bytes.len(),
1383                bytes.len(),
1384                false,
1385            );
1386        }
1387    }
1388    fn latch(&mut self, error: Error) {
1389        self.staged.get_mut().error = Some(error);
1390    }
1391    fn take_latched(&mut self) -> Result<()> {
1392        match self.staged.get_mut().error.take() {
1393            Some(error) => Err(error),
1394            None => Ok(()),
1395        }
1396    }
1397    /// Moves at most `limit` staged wire bytes into the ring. True once nothing is staged.
1398    fn flush_staged(&self, limit: usize) -> Result<bool> {
1399        let mut staged = self.staged.lock();
1400        let mut budget = limit;
1401        while staged.offset < staged.bytes.len() {
1402            let at = staged.offset;
1403            let wanted = (staged.bytes.len() - at).min(budget);
1404            if wanted == 0 {
1405                return Ok(false);
1406            }
1407            let start = self.timing_start();
1408            let write = self.stream.write(&staged.bytes[at..at + wanted]);
1409            self.timing_end(
1410                start,
1411                ProducerTimingPhase::RingEnqueue,
1412                wanted,
1413                write.as_ref().copied().unwrap_or(0),
1414                write.as_ref().is_ok_and(|n| *n < wanted),
1415            );
1416            let n = write?;
1417            if n == 0 {
1418                return Ok(false);
1419            }
1420            self.notify_observer(&staged.bytes[at..at + n]);
1421            staged.offset += n;
1422            staged.target_bytes += n as u64;
1423            budget -= n;
1424        }
1425        staged.bytes.clear();
1426        staged.offset = 0;
1427        Ok(true)
1428    }
1429    fn flush_output(&self) -> Result<bool> {
1430        self.flush_staged(usize::MAX)
1431    }
1432    fn pump(&mut self) -> Result<bool> {
1433        if !self.flush_output()? {
1434            return Ok(false);
1435        }
1436        while self.input_offset < self.input.len() {
1437            let start = self.timing_start();
1438            let output = &mut self.staged.get_mut().bytes;
1439            output.resize(65536, 0);
1440            let processed = match &mut self.engine {
1441                Engine::Pcm { converter, .. } => {
1442                    converter.process(&self.input[self.input_offset..], output)
1443                }
1444                Engine::Dsd { converter, .. } => {
1445                    converter.process(&self.input[self.input_offset..], output)
1446                }
1447                Engine::Direct | Engine::DsdRepack => {
1448                    return Err(Error::InvalidState("direct stream has staged input".into()))
1449                }
1450            };
1451            self.timing_end(
1452                start,
1453                ProducerTimingPhase::ConverterProcess,
1454                processed.as_ref().map_or(0, |p| p.consumed),
1455                processed.as_ref().map_or(0, |p| p.produced),
1456                false,
1457            );
1458            let p = processed.map_err(conversion_error)?;
1459            self.input_offset += p.consumed;
1460            self.staged.get_mut().bytes.truncate(p.produced);
1461            if p.consumed == 0 && p.produced == 0 {
1462                return Err(Error::InvalidState("converter made no progress".into()));
1463            }
1464            if !self.flush_output()? {
1465                return Ok(false);
1466            }
1467        }
1468        self.input.clear();
1469        self.input_offset = 0;
1470        Ok(true)
1471    }
1472    /// Accepts whole source frames and returns bytes accepted, never target bytes.
1473    /// Takes as much as the ring can hold (up to its capacity, like
1474    /// `DacStream::write`); converted streams work through it in internal steps
1475    /// of `WRITE_CHUNK_FRAMES` source frames. An error met after input was
1476    /// accepted is returned by the next `write` or `drain`, so an accepted
1477    /// count is never lost.
1478    pub fn write(&mut self, data: &[u8]) -> Result<usize> {
1479        self.take_latched()?;
1480        if self.finishing {
1481            return Err(Error::InvalidState("write after drain".into()));
1482        }
1483        let frame = self.decision.source_frame_bytes;
1484        if frame == 0 {
1485            return Err(Error::InvalidState("zero source frame".into()));
1486        }
1487        let whole = data.len() / frame * frame;
1488        if whole == 0 {
1489            return Ok(0);
1490        }
1491        if matches!(self.engine, Engine::Direct) {
1492            return self.write_direct(&data[..whole]);
1493        }
1494        let mut accepted = 0;
1495        while accepted < whole {
1496            let end = whole.min(accepted + WRITE_CHUNK_FRAMES * frame);
1497            let step = if matches!(self.engine, Engine::DsdRepack) {
1498                self.write_dsd_repack(&data[accepted..end])
1499            } else {
1500                self.write_converted(&data[accepted..end])
1501            };
1502            match step {
1503                Ok(0) => break,
1504                Ok(n) => accepted += n,
1505                Err(error) if accepted == 0 => return Err(error),
1506                Err(error) => {
1507                    self.latch(error);
1508                    break;
1509                }
1510            }
1511            if self.staged.get_mut().error.is_some() {
1512                break;
1513            }
1514        }
1515        Ok(accepted)
1516    }
1517    fn write_direct(&mut self, data: &[u8]) -> Result<usize> {
1518        let frame = self.decision.source_frame_bytes;
1519        let n = data.len();
1520        let mut phase = self.marker;
1521        if self.decision.source.encoding == Encoding::DoP {
1522            let start = self.timing_start();
1523            let checked = validate_dop(
1524                data,
1525                usize::from(self.decision.source.channels),
1526                frame / usize::from(self.decision.source.channels),
1527                &mut phase,
1528            );
1529            self.timing_end(start, ProducerTimingPhase::SourceFormat, n, n, false);
1530            checked?;
1531        }
1532        let start = self.timing_start();
1533        let write = self.stream.write(data);
1534        self.timing_end(
1535            start,
1536            ProducerTimingPhase::RingEnqueue,
1537            n,
1538            write.as_ref().copied().unwrap_or(0),
1539            write.as_ref().is_ok_and(|taken| *taken < n),
1540        );
1541        let taken = write?;
1542        if self.decision.source.encoding == Encoding::DoP {
1543            let mut accepted = self.marker;
1544            let start = self.timing_start();
1545            let checked = validate_dop(
1546                &data[..taken],
1547                usize::from(self.decision.source.channels),
1548                frame / usize::from(self.decision.source.channels),
1549                &mut accepted,
1550            );
1551            self.timing_end(
1552                start,
1553                ProducerTimingPhase::SourceFormat,
1554                taken,
1555                taken,
1556                false,
1557            );
1558            checked?;
1559            self.marker = accepted;
1560        }
1561        if taken > 0 {
1562            self.notify_observer(&data[..taken]);
1563        }
1564        self.source_bytes += taken as u64;
1565        self.staged.get_mut().target_bytes += taken as u64;
1566        Ok(taken)
1567    }
1568    /// One converter step of at most `WRITE_CHUNK_FRAMES` whole source frames.
1569    fn write_converted(&mut self, data: &[u8]) -> Result<usize> {
1570        if !self.pump()? {
1571            return Ok(0);
1572        }
1573        let frame = self.decision.source_frame_bytes;
1574        let n = data.len();
1575        let start = self.timing_start();
1576        self.input.clear();
1577        let formatted: Result<()> = (|| {
1578            match &self.engine {
1579                Engine::Pcm { unsigned: true, .. } => {
1580                    self.input.resize(n * 2, 0);
1581                    pcm_u8_to_i16(data, &mut self.input);
1582                }
1583                Engine::Pcm { .. } | Engine::Dsd { dop: false, .. } => {
1584                    self.input.extend_from_slice(data)
1585                }
1586                Engine::Dsd { dop: true, .. } => unpack_dop_into(
1587                    data,
1588                    usize::from(self.decision.source.channels),
1589                    frame / usize::from(self.decision.source.channels),
1590                    &mut self.marker,
1591                    &mut self.input,
1592                )?,
1593                Engine::Direct | Engine::DsdRepack => unreachable!(),
1594            };
1595            Ok(())
1596        })();
1597        self.timing_end(
1598            start,
1599            ProducerTimingPhase::SourceFormat,
1600            n,
1601            self.input.len(),
1602            false,
1603        );
1604        formatted?;
1605        self.input_offset = 0;
1606        self.source_bytes += n as u64;
1607        if let Err(error) = self.pump() {
1608            self.latch(error);
1609        }
1610        Ok(n)
1611    }
1612    /// One repack step of at most `WRITE_CHUNK_FRAMES` whole source frames.
1613    fn write_dsd_repack(&mut self, data: &[u8]) -> Result<usize> {
1614        if !self.flush_output()? {
1615            return Ok(0);
1616        }
1617        let start = self.timing_start();
1618        let staged = self.staged.get_mut();
1619        staged.offset = 0;
1620        let taken = repack_dsd_input(
1621            &self.decision.source,
1622            &self.decision.format,
1623            self.decision.source_frame_bytes,
1624            data,
1625            &mut self.marker,
1626            &mut self.input,
1627            &mut staged.bytes,
1628        )?;
1629        let produced = staged.bytes.len();
1630        self.timing_end(
1631            start,
1632            ProducerTimingPhase::SourceFormat,
1633            taken,
1634            produced,
1635            false,
1636        );
1637        self.source_bytes += taken as u64;
1638        if let Err(error) = self.flush_output() {
1639            self.latch(error);
1640        }
1641        Ok(taken)
1642    }
1643    /// Begin or progress drain. Returns false when the caller must retry after
1644    /// the USB ring makes space; `is_drained` reports actual USB completion.
1645    /// A final partial native DSD word or DoP pair is completed with DSD idle
1646    /// (0x69), so every accepted DSD byte is played.
1647    pub fn drain(&mut self) -> Result<bool> {
1648        self.take_latched()?;
1649        self.finishing = true;
1650        if self.drain_called {
1651            return Ok(true);
1652        }
1653        if matches!(self.engine, Engine::DsdRepack) {
1654            if !self.flush_output()? {
1655                return Ok(false);
1656            }
1657            if !self.input.is_empty() {
1658                let staged = self.staged.get_mut();
1659                staged.offset = 0;
1660                pad_dsd_tail(
1661                    &self.decision.source,
1662                    &self.decision.format,
1663                    &mut self.input,
1664                    &mut staged.bytes,
1665                )?;
1666                if !self.flush_output()? {
1667                    return Ok(false);
1668                }
1669            }
1670        } else if !self.pump()? {
1671            return Ok(false);
1672        }
1673        if !matches!(self.engine, Engine::Direct | Engine::DsdRepack) {
1674            loop {
1675                let start = self.timing_start();
1676                let output = &mut self.staged.get_mut().bytes;
1677                output.resize(65536, 0);
1678                let finished = match &mut self.engine {
1679                    Engine::Pcm { converter, .. } => converter.finish(output),
1680                    Engine::Dsd { converter, .. } => converter.finish(output),
1681                    Engine::Direct | Engine::DsdRepack => unreachable!(),
1682                };
1683                self.timing_end(
1684                    start,
1685                    ProducerTimingPhase::ConverterFinish,
1686                    0,
1687                    finished.as_ref().copied().unwrap_or(0),
1688                    false,
1689                );
1690                let n = finished.map_err(conversion_error)?;
1691                self.staged.get_mut().bytes.truncate(n);
1692                if n == 0 {
1693                    break;
1694                }
1695                if !self.flush_output()? {
1696                    return Ok(false);
1697                }
1698            }
1699        }
1700        self.stream.drain()?;
1701        self.drain_called = true;
1702        Ok(true)
1703    }
1704    pub fn play(&self) -> Result<()> {
1705        self.stream.play()
1706    }
1707    pub fn pause(&self) -> Result<()> {
1708        self.stream.pause()
1709    }
1710    pub fn flush(&mut self) -> Result<()> {
1711        self.stream.flush()?;
1712        match &mut self.engine {
1713            Engine::Pcm { converter, .. } => converter.reset(),
1714            Engine::Dsd { converter, .. } => converter.reset(),
1715            Engine::Direct | Engine::DsdRepack => {}
1716        }
1717        self.input.clear();
1718        let staged = self.staged.get_mut();
1719        staged.bytes.clear();
1720        staged.offset = 0;
1721        staged.target_bytes = 0;
1722        staged.error = None;
1723        self.input_offset = 0;
1724        self.marker = None;
1725        self.finishing = false;
1726        self.drain_called = false;
1727        self.source_bytes = 0;
1728        Ok(())
1729    }
1730    /// Source bytes to write now to bring the ring to its active target, in
1731    /// whole source frames, mirroring `DacStream::writable_bytes`: the ring's
1732    /// room converted to source frames through the source/wire rate ratio,
1733    /// minus source frames still waiting in the converter. Staged wire output
1734    /// is first moved into that room (observers see it here), so it never pins
1735    /// the capacity. 0 after `drain` or once the stream has failed; while an
1736    /// error is pending it is one source frame, so the next `write` reports it.
1737    /// `write` still accepts more, up to the ring's capacity.
1738    pub fn writable_bytes(&self) -> usize {
1739        if self.finishing {
1740            return 0;
1741        }
1742        let frame = self.decision.source_frame_bytes;
1743        if self.staged.lock().error.is_some() {
1744            return frame;
1745        }
1746        match self.flush_staged(self.stream.writable_bytes()) {
1747            Ok(true) => {}
1748            Ok(false) => return 0,
1749            Err(error) => {
1750                self.staged.lock().error = Some(error);
1751                return frame;
1752            }
1753        }
1754        source_frames_for_room(
1755            self.stream.writable_bytes(),
1756            source_frame_rate(&self.decision.source),
1757            wire_bytes_per_second(&self.decision.format),
1758        )
1759        .saturating_sub(self.pending_source_frames())
1760            * frame
1761    }
1762    /// Accepted source frames still held as converter or repack input.
1763    fn pending_source_frames(&self) -> usize {
1764        let channels = usize::from(self.decision.source.channels);
1765        let per_frame = match &self.engine {
1766            Engine::Direct => return 0,
1767            Engine::Pcm { unsigned: true, .. } => 2 * channels,
1768            Engine::Pcm { .. } => self.decision.source_frame_bytes,
1769            // DoP unpacks to two DSD bytes per channel; native DSD is one.
1770            Engine::Dsd { .. } | Engine::DsdRepack => {
1771                if self.decision.source.encoding == Encoding::DoP {
1772                    2 * channels
1773                } else {
1774                    channels
1775                }
1776            }
1777        };
1778        (self.input.len() - self.input_offset).div_ceil(per_frame.max(1))
1779    }
1780    pub fn is_drained(&self) -> bool {
1781        self.drain_called && self.stream.is_drained()
1782    }
1783    /// Source-relative statistics. A lossy or channel-expanding transform can
1784    /// never report source bit-perfect even if its target USB payload is intact.
1785    pub fn stats(&self) -> StreamStats {
1786        let mut stats = self.stream.stats();
1787        if matches!(
1788            self.decision.fidelity,
1789            PlaybackFidelity::Lossless | PlaybackFidelity::Lossy
1790        ) {
1791            stats.bit_perfect = false;
1792            if stats.bit_perfect_blocker.is_none() {
1793                stats.bit_perfect_blocker = Some(crate::BitPerfectBlocker::FormatChanged);
1794            }
1795        }
1796        stats
1797    }
1798    /// Raw target transport statistics; not a claim of source fidelity.
1799    pub fn target_stats(&self) -> StreamStats {
1800        self.stream.stats()
1801    }
1802    pub fn conversion_stats(&self) -> PlaybackConversionStats {
1803        let clipped_samples = match &self.engine {
1804            Engine::Pcm { converter, .. } => converter.clipped_samples(),
1805            Engine::Dsd { converter, .. } => converter.clipped_samples(),
1806            Engine::Direct | Engine::DsdRepack => 0,
1807        };
1808        PlaybackConversionStats {
1809            source_bytes: self.source_bytes,
1810            target_bytes: self.staged.lock().target_bytes,
1811            clipped_samples,
1812        }
1813    }
1814    pub fn played_frames(&self) -> u64 {
1815        let wire = self.stream.played_frames();
1816        let source_rate = source_frame_rate(&self.decision.source);
1817        let target_rate = self.decision.format.counter_rate_hz();
1818        if target_rate == 0 {
1819            return 0;
1820        }
1821        ((u128::from(wire) * u128::from(source_rate) / u128::from(target_rate)) as u64)
1822            .min(self.source_bytes / self.decision.source_frame_bytes as u64)
1823    }
1824    pub fn latency_frames(&self) -> u64 {
1825        (self.source_bytes / self.decision.source_frame_bytes as u64)
1826            .saturating_sub(self.played_frames())
1827    }
1828    pub fn close(self) -> Result<()> {
1829        self.stream.close()
1830    }
1831}
1832/// Bytes of one complete target group per source channel: a DoP pair or one
1833/// native DSD subslot word.
1834fn dsd_group_bytes(format: &StreamFormat) -> Result<usize> {
1835    let slot = usize::from(format.subslot_bytes);
1836    let target_dop = format.encoding == Encoding::DoP;
1837    if slot == 0 || (target_dop && !matches!(slot, 3 | 4)) {
1838        return Err(Error::InvalidArgument(
1839            "invalid target DSD word layout".into(),
1840        ));
1841    }
1842    Ok(if target_dop { 2 } else { slot })
1843}
1844/// Completes a final partial group with DSD idle and packs it.
1845fn pad_dsd_tail(
1846    source: &StreamRequest,
1847    format: &StreamFormat,
1848    pending: &mut Vec<u8>,
1849    output: &mut Vec<u8>,
1850) -> Result<()> {
1851    let unit = usize::from(source.channels) * dsd_group_bytes(format)?;
1852    pending.resize(pending.len().div_ceil(unit) * unit, DSD_IDLE);
1853    pack_dsd_groups(source, format, pending, output)
1854}
1855
1856/// Accept complete source frames, buffering incomplete target groups for the next write.
1857fn repack_dsd_input(
1858    source: &StreamRequest,
1859    format: &StreamFormat,
1860    source_frame: usize,
1861    data: &[u8],
1862    marker: &mut Option<bool>,
1863    pending: &mut Vec<u8>,
1864    output: &mut Vec<u8>,
1865) -> Result<usize> {
1866    let src_ch = usize::from(source.channels);
1867    let dst_ch = usize::from(format.channels);
1868    if src_ch == 0 || (src_ch != dst_ch && !(src_ch == 1 && dst_ch == 2)) || source_frame == 0 {
1869        return Err(Error::InvalidArgument("invalid DSD channel layout".into()));
1870    }
1871    dsd_group_bytes(format)?;
1872    let taken = (data.len() / source_frame).min(WRITE_CHUNK_FRAMES) * source_frame;
1873    if taken == 0 {
1874        return Ok(0);
1875    }
1876    if source.encoding == Encoding::DoP {
1877        unpack_dop_into(
1878            &data[..taken],
1879            src_ch,
1880            source_frame / src_ch,
1881            marker,
1882            pending,
1883        )?;
1884    } else {
1885        pending.extend_from_slice(&data[..taken]);
1886    }
1887    pack_dsd_groups(source, format, pending, output)?;
1888    Ok(taken)
1889}
1890/// Packs the complete target groups of chronological DSD bytes into `output`.
1891fn pack_dsd_groups(
1892    source: &StreamRequest,
1893    format: &StreamFormat,
1894    pending: &mut Vec<u8>,
1895    output: &mut Vec<u8>,
1896) -> Result<()> {
1897    let src_ch = usize::from(source.channels);
1898    let dst_ch = usize::from(format.channels);
1899    let target_dop = format.encoding == Encoding::DoP;
1900    let slot = usize::from(format.subslot_bytes);
1901    let group = dsd_group_bytes(format)?;
1902    let complete = pending.len() / (src_ch * group) * src_ch * group;
1903    output.clear();
1904    if target_dop {
1905        for pair in pending[..complete].chunks_exact(src_ch * 2) {
1906            for ch in 0..dst_ch {
1907                let input_ch = if src_ch == 1 { 0 } else { ch };
1908                if slot == 4 {
1909                    output.push(0);
1910                }
1911                output.push(pair[src_ch + input_ch]);
1912                output.push(pair[input_ch]);
1913                output.push(0);
1914            }
1915        }
1916    } else if src_ch == 1 && dst_ch == 2 {
1917        output.resize(complete * 2, 0);
1918        duplicate_mono_dsd(&pending[..complete], output);
1919    } else {
1920        output.extend_from_slice(&pending[..complete]);
1921    }
1922    pending.drain(..complete);
1923    Ok(())
1924}
1925/// Duplicate chronological mono DSD bytes into stereo channel-interleaved bytes.
1926/// Returns the source bytes consumed, bounded by output capacity.
1927pub fn duplicate_mono_dsd(input: &[u8], output: &mut [u8]) -> usize {
1928    let count = input.len().min(output.len() / 2);
1929    for (sample, pair) in input[..count].iter().zip(output.chunks_exact_mut(2)) {
1930        pair[0] = *sample;
1931        pair[1] = *sample;
1932    }
1933    count
1934}
1935
1936/// Convert unsigned 8-bit PCM to signed 16-bit PCM, with silence at 0x80.
1937/// Returns input samples consumed, bounded by output capacity.
1938pub fn pcm_u8_to_i16(input: &[u8], output: &mut [u8]) -> usize {
1939    let count = input.len().min(output.len() / 2);
1940    for (sample, slot) in input[..count].iter().zip(output.chunks_exact_mut(2)) {
1941        slot.copy_from_slice(&((i16::from(*sample) - 128) << 8).to_le_bytes());
1942    }
1943    count
1944}
1945fn validate_dop(data: &[u8], channels: usize, slot: usize, phase: &mut Option<bool>) -> Result<()> {
1946    if channels == 0 || !matches!(slot, 3 | 4) || data.len() % (channels * slot) != 0 {
1947        return Err(Error::InvalidArgument("invalid DoP frame layout".into()));
1948    }
1949    let mut next = *phase;
1950    for frame in data.chunks_exact(channels * slot) {
1951        let marker = frame[slot - 1];
1952        if !matches!(marker, 0x05 | 0xfa)
1953            || next.is_some_and(|expected| marker != if expected { 0xfa } else { 0x05 })
1954            || frame
1955                .chunks_exact(slot)
1956                .any(|word| word[slot - 1] != marker || (slot == 4 && word[0] != 0))
1957        {
1958            return Err(Error::InvalidArgument(
1959                "invalid DoP markers or padding".into(),
1960            ));
1961        }
1962        next = Some(marker == 0x05);
1963    }
1964    *phase = next;
1965    Ok(())
1966}
1967/// Unpack from a caller-specified expected marker phase. On error, phase is unchanged.
1968pub fn unpack_dop(data: &[u8], channels: usize, slot: usize, phase: &mut bool) -> Result<Vec<u8>> {
1969    let mut out = Vec::with_capacity(data.len());
1970    let mut next = Some(*phase);
1971    unpack_dop_into(data, channels, slot, &mut next, &mut out)?;
1972    *phase = next.unwrap_or(*phase);
1973    Ok(out)
1974}
1975fn unpack_dop_into(
1976    data: &[u8],
1977    channels: usize,
1978    slot: usize,
1979    phase: &mut Option<bool>,
1980    out: &mut Vec<u8>,
1981) -> Result<()> {
1982    let mut next = *phase;
1983    validate_dop(data, channels, slot, &mut next)?;
1984    for frame in data.chunks_exact(channels * slot) {
1985        for word in frame.chunks_exact(slot) {
1986            out.push(word[slot - 2]);
1987        }
1988        for word in frame.chunks_exact(slot) {
1989            out.push(word[slot - 3]);
1990        }
1991    }
1992    *phase = next;
1993    Ok(())
1994}
1995
1996#[cfg(test)]
1997mod tests {
1998    use super::*;
1999    fn descriptor_alt(format: AltFormat, channels: u16, bits: u8) -> crate::AltSetting {
2000        crate::AltSetting {
2001            interface_number: 1,
2002            alt_setting: 1,
2003            endpoint_address: 1,
2004            format,
2005            channels,
2006            subslot_bytes: 4,
2007            valid_bits: bits,
2008            rate_ranges: vec![crate::RateRange {
2009                min_hz: 44_100,
2010                max_hz: 48_000,
2011                step_hz: 3_900,
2012            }],
2013            sample_rates: vec![44_100, 48_000],
2014            sync_type: crate::SyncKind::Asynchronous,
2015            feedback_endpoint: Some(0x81),
2016            max_packet_bytes: 776,
2017            service_interval_us: 125,
2018            uac_version: crate::UacVersion::V2,
2019            endpoint_interval: 1,
2020            usage: crate::EndpointUsage::Data,
2021            refresh: 0,
2022            synch_address: 0,
2023            pacing: Some(crate::Pacing::ExplicitFeedback { endpoint: 0x81 }),
2024        }
2025    }
2026    fn capabilities_for(alts: Vec<crate::AltSetting>) -> crate::Capabilities {
2027        crate::Capabilities {
2028            exclusion_snapshot_complete: true,
2029            native_only_aliases: vec![],
2030            complete_uac1_rate_alternates: vec![],
2031            uac_version: crate::UacVersion::V2,
2032            link_speed: crate::LinkSpeed::High,
2033            alt_settings: alts,
2034            pcm_sample_rates: vec![],
2035            pcm_bit_depths: vec![],
2036            channel_counts: vec![1, 2],
2037            supports_pcm: true,
2038            supports_dop: true,
2039            dop_max_dsd_bit_rate: None,
2040            supports_native_dsd: false,
2041            native_dsd_bit_rates: vec![],
2042            has_explicit_feedback: true,
2043            volume: None,
2044            has_hardware_volume: false,
2045            has_mute: false,
2046        }
2047    }
2048    fn wire_format(request: StreamRequest, subslot: u8) -> StreamFormat {
2049        StreamFormat {
2050            request,
2051            encoding: request.encoding,
2052            sample_rate: request.sample_rate,
2053            channels: request.channels,
2054            channel_map: crate::capture::ChannelMap::uac2(request.channels, 0).unwrap(),
2055            valid_bits: request.bit_depth,
2056            subslot_bytes: subslot,
2057            interface_number: 1,
2058            alt_setting: 1,
2059            endpoint_address: 1,
2060            sync_type: crate::SyncKind::Synchronous,
2061            explicit_feedback: false,
2062            link_speed: crate::LinkSpeed::High,
2063            service_interval_us: 125,
2064            pacing: crate::Pacing::Synchronous,
2065            clock: None,
2066            native_dsd_signature: None,
2067        }
2068    }
2069    #[test]
2070    fn exact_float_request_is_not_duplicated_in_fallback_candidates() {
2071        let mut alt = descriptor_alt(AltFormat::PcmFloat32, 2, 32);
2072        alt.sample_rates = vec![48_000];
2073        alt.rate_ranges.clear();
2074        let source = StreamRequest::pcm_float32(48_000, 2);
2075        let found = candidates(
2076            &capabilities_for(vec![alt]),
2077            &source,
2078            &PlaybackPolicy::default(),
2079        )
2080        .unwrap();
2081        assert!(found.iter().all(|candidate| candidate.request != source));
2082    }
2083    #[test]
2084    fn stepped_candidate_includes_largest_rate_within_policy_ceiling() {
2085        let mut alt = descriptor_alt(AltFormat::Pcm, 2, 16);
2086        alt.subslot_bytes = 2;
2087        alt.sample_rates.clear();
2088        alt.rate_ranges = vec![crate::RateRange {
2089            min_hz: 8_000,
2090            max_hz: 96_000,
2091            step_hz: 1_000,
2092        }];
2093        let policy = PlaybackPolicy {
2094            max_pcm_rate: Some(47_000),
2095            ..PlaybackPolicy::default()
2096        };
2097        let source = StreamRequest::pcm(96_000, 2, 16);
2098        let found = candidates(&capabilities_for(vec![alt]), &source, &policy).unwrap();
2099        assert!(found
2100            .iter()
2101            .any(|candidate| candidate.request.sample_rate == 47_000));
2102        assert!(found
2103            .iter()
2104            .all(|candidate| candidate.request.sample_rate <= 47_000));
2105    }
2106    #[test]
2107    fn confirmed_dop_can_repack_to_stereo_but_unconfirmed_never_forwards() {
2108        let mut alt = descriptor_alt(AltFormat::Pcm, 2, 24);
2109        alt.sample_rates = vec![176_400];
2110        alt.rate_ranges.clear();
2111        let source = StreamRequest::dop(2_822_400, 1);
2112        let confirmed = PlaybackPolicy {
2113            dop_confirmed: true,
2114            ..PlaybackPolicy::default()
2115        };
2116        let caps = capabilities_for(vec![alt]);
2117        let found = candidates(&caps, &source, &confirmed).unwrap();
2118        assert!(found
2119            .iter()
2120            .any(|candidate| candidate.request.encoding == Encoding::DoP
2121                && candidate.request.channels == 2));
2122        let unconfirmed = candidates(&caps, &source, &PlaybackPolicy::default()).unwrap();
2123        assert!(unconfirmed
2124            .iter()
2125            .all(|candidate| candidate.request.encoding != Encoding::DoP));
2126    }
2127    #[test]
2128    fn partial_dsd_byte_frames_are_retained_until_complete_wire_word() {
2129        let source = StreamRequest::dsd_native(2_822_400, 1);
2130        let format = wire_format(StreamRequest::dsd_native(2_822_400, 2), 4);
2131        let (mut phase, mut pending, mut output) = (None, Vec::new(), Vec::new());
2132        for byte in [0x11, 0x22, 0x33] {
2133            assert_eq!(
2134                repack_dsd_input(
2135                    &source,
2136                    &format,
2137                    1,
2138                    &[byte],
2139                    &mut phase,
2140                    &mut pending,
2141                    &mut output
2142                )
2143                .unwrap(),
2144                1
2145            );
2146            assert!(output.is_empty());
2147        }
2148        assert_eq!(pending.len(), 3);
2149        assert_eq!(
2150            repack_dsd_input(
2151                &source,
2152                &format,
2153                1,
2154                &[0x44],
2155                &mut phase,
2156                &mut pending,
2157                &mut output
2158            )
2159            .unwrap(),
2160            1
2161        );
2162        assert_eq!(output, [0x11, 0x11, 0x22, 0x22, 0x33, 0x33, 0x44, 0x44]);
2163        assert!(pending.is_empty());
2164    }
2165    #[test]
2166    fn dop_start_phase_is_inferred_and_failed_batch_does_not_advance() {
2167        let source = StreamRequest::dop(2_822_400, 1);
2168        let format = wire_format(StreamRequest::dsd_native(2_822_400, 2), 4);
2169        let (mut phase, mut pending, mut output) = (None, Vec::new(), Vec::new());
2170        assert_eq!(
2171            repack_dsd_input(
2172                &source,
2173                &format,
2174                3,
2175                &[0x11, 0x22, 0xfa],
2176                &mut phase,
2177                &mut pending,
2178                &mut output
2179            )
2180            .unwrap(),
2181            3
2182        );
2183        assert_eq!(phase, Some(false));
2184        assert_eq!(pending, [0x22, 0x11]);
2185        assert!(repack_dsd_input(
2186            &source,
2187            &format,
2188            3,
2189            &[0x33, 0x44, 0xfa],
2190            &mut phase,
2191            &mut pending,
2192            &mut output
2193        )
2194        .is_err());
2195        assert_eq!(phase, Some(false));
2196        assert_eq!(pending, [0x22, 0x11]);
2197        assert_eq!(
2198            repack_dsd_input(
2199                &source,
2200                &format,
2201                3,
2202                &[0x33, 0x44, 0x05],
2203                &mut phase,
2204                &mut pending,
2205                &mut output
2206            )
2207            .unwrap(),
2208            3
2209        );
2210        assert_eq!(output, [0x22, 0x22, 0x11, 0x11, 0x44, 0x44, 0x33, 0x33]);
2211        phase = None;
2212        assert!(validate_dop(&[0x11, 0x22, 0xfa], 1, 3, &mut phase).is_ok());
2213        assert_eq!(phase, Some(false));
2214    }
2215    #[test]
2216    fn descriptor_preflight_only_excludes_proven_shapes_and_rates() {
2217        let pcm = descriptor_alt(AltFormat::Pcm, 2, 32);
2218        let native = descriptor_alt(AltFormat::Dsd, 2, 1);
2219        let alts = vec![pcm.clone(), native.clone()];
2220        assert!(
2221            descriptor_exclusion(false, &alts, &[], &[], &StreamRequest::pcm(8_000, 1, 16))
2222                .is_none()
2223        );
2224        assert!(
2225            descriptor_exclusion(true, &alts, &[], &[], &StreamRequest::pcm(8_000, 1, 16))
2226                .is_some()
2227        );
2228        assert!(
2229            descriptor_exclusion(true, &alts, &[], &[], &StreamRequest::pcm(8_000, 2, 32))
2230                .is_some()
2231        );
2232        assert!(
2233            descriptor_exclusion(true, &alts, &[], &[], &StreamRequest::pcm(44_100, 2, 32))
2234                .is_none()
2235        );
2236        assert!(descriptor_exclusion(
2237            true,
2238            &alts,
2239            &[],
2240            &[],
2241            &StreamRequest::dsd_native(2_822_400, 1)
2242        )
2243        .is_some());
2244        assert!(descriptor_exclusion(
2245            true,
2246            &alts,
2247            &[],
2248            &[],
2249            &StreamRequest::dsd_native(2_822_400, 2)
2250        )
2251        .is_some());
2252        let mut unknown = native.clone();
2253        unknown.rate_ranges.clear();
2254        assert!(descriptor_exclusion(
2255            true,
2256            &[pcm.clone(), unknown],
2257            &[],
2258            &[],
2259            &StreamRequest::dsd_native(2_822_400, 2)
2260        )
2261        .is_none());
2262        let mut opaque = pcm.clone();
2263        opaque.format = AltFormat::Other;
2264        assert!(descriptor_exclusion(
2265            true,
2266            &[pcm.clone(), opaque.clone()],
2267            &[],
2268            &[],
2269            &StreamRequest::pcm_u8(44_100, 2)
2270        )
2271        .is_none());
2272        assert!(descriptor_exclusion(
2273            true,
2274            &[pcm, opaque],
2275            &[(1, 1, 1)],
2276            &[],
2277            &StreamRequest::pcm_u8(44_100, 2)
2278        )
2279        .is_some());
2280    }
2281    #[test]
2282    fn uac1_exact_rate_exclusion_requires_complete_descriptor_witness() {
2283        let mut alt = descriptor_alt(AltFormat::Pcm, 2, 16);
2284        alt.uac_version = crate::UacVersion::V1;
2285        alt.subslot_bytes = 2;
2286        alt.rate_ranges = vec![
2287            crate::RateRange {
2288                min_hz: 44_100,
2289                max_hz: 44_100,
2290                step_hz: 0,
2291            },
2292            crate::RateRange {
2293                min_hz: 48_000,
2294                max_hz: 48_000,
2295                step_hz: 0,
2296            },
2297        ];
2298        alt.sample_rates = vec![44_100, 48_000];
2299        let source = StreamRequest::pcm(8_000, 2, 16);
2300        assert!(
2301            descriptor_exclusion(true, std::slice::from_ref(&alt), &[], &[], &source).is_none()
2302        );
2303        let excluded =
2304            descriptor_exclusion(true, std::slice::from_ref(&alt), &[], &[(1, 1, 1)], &source)
2305                .unwrap();
2306        assert!(excluded.contains("UAC1 Type-I"));
2307        assert!(descriptor_exclusion(
2308            true,
2309            std::slice::from_ref(&alt),
2310            &[],
2311            &[(1, 1, 1)],
2312            &StreamRequest::pcm(44_100, 2, 16)
2313        )
2314        .is_none());
2315        alt.rate_ranges.clear();
2316        alt.sample_rates.clear();
2317        assert!(descriptor_exclusion(true, &[alt], &[], &[(1, 1, 1)], &source).is_none());
2318    }
2319    #[test]
2320    fn policy_blocks_exact_before_negotiation() {
2321        let policy = PlaybackPolicy {
2322            max_pcm_rate: Some(48_000),
2323            ..PlaybackPolicy::default()
2324        };
2325        assert!(!exact_policy_allows(
2326            &StreamRequest::pcm(96_000, 2, 24),
2327            &policy
2328        ));
2329        assert!(exact_policy_allows(
2330            &StreamRequest::pcm(48_000, 2, 24),
2331            &policy
2332        ));
2333        assert!(!exact_policy_allows(
2334            &StreamRequest::dop(2_822_400, 2),
2335            &policy
2336        ));
2337        let native_disabled = PlaybackPolicy {
2338            allow_native_dsd: false,
2339            ..policy
2340        };
2341        assert!(!exact_policy_allows(
2342            &StreamRequest::dsd_native(2_822_400, 2),
2343            &native_disabled
2344        ));
2345    }
2346    #[test]
2347    fn rank_prefers_fidelity_over_rate() {
2348        let candidate = |fidelity, rate_rank| Candidate {
2349            request: StreamRequest::pcm(48_000, 2, 16),
2350            fidelity,
2351            rate_rank,
2352            channels_rank: 0,
2353            depth_rank: (0, 0),
2354            quality: candidate_quality(
2355                &StreamRequest::pcm(48_000, 2, 16),
2356                &StreamRequest::pcm(48_000, 2, 16),
2357                fidelity,
2358                &ConvertOptions::default(),
2359            ),
2360            upsample_excess: 0,
2361        };
2362        let mut items = vec![
2363            candidate(PlaybackFidelity::Lossy, 0),
2364            candidate(PlaybackFidelity::Lossless, 1),
2365            candidate(PlaybackFidelity::BitExact, 3),
2366        ];
2367        sort_candidates(&mut items);
2368        assert_eq!(
2369            items.iter().map(|v| v.fidelity).collect::<Vec<_>>(),
2370            [
2371                PlaybackFidelity::BitExact,
2372                PlaybackFidelity::Lossless,
2373                PlaybackFidelity::Lossy
2374            ]
2375        );
2376    }
2377    #[test]
2378    fn lossy_rank_maximizes_bandwidth_before_rate_family_and_avoids_extra_upsampling() {
2379        for source_rate in [88_200, 176_400, 352_800, 705_600] {
2380            let source = StreamRequest::pcm(source_rate, 2, 16);
2381            let candidate = |rate, rank| {
2382                let request = StreamRequest::pcm(rate, 2, 16);
2383                Candidate {
2384                    request,
2385                    fidelity: PlaybackFidelity::Lossy,
2386                    rate_rank: rank,
2387                    channels_rank: 0,
2388                    depth_rank: (0, 0),
2389                    quality: candidate_quality(
2390                        &source,
2391                        &request,
2392                        PlaybackFidelity::Lossy,
2393                        &ConvertOptions::default(),
2394                    ),
2395                    upsample_excess: rate.saturating_sub(source.sample_rate),
2396                }
2397            };
2398            let mut list = vec![candidate(44_100, 0), candidate(48_000, 1)];
2399            sort_candidates(&mut list);
2400            assert_eq!(list[0].request.sample_rate, 48_000);
2401        }
2402        let dsd = StreamRequest::dsd_native(2_822_400, 2);
2403        let a = candidate_quality(
2404            &dsd,
2405            &StreamRequest::pcm(44_100, 2, 16),
2406            PlaybackFidelity::Lossy,
2407            &ConvertOptions::default(),
2408        );
2409        let b = candidate_quality(
2410            &dsd,
2411            &StreamRequest::pcm(48_000, 2, 16),
2412            PlaybackFidelity::Lossy,
2413            &ConvertOptions::default(),
2414        );
2415        assert!(b.retained_bandwidth_hz.unwrap() > a.retained_bandwidth_hz.unwrap());
2416        let small = StreamRequest::pcm(8_000, 2, 16);
2417        let q1 = candidate_quality(
2418            &small,
2419            &StreamRequest::pcm(44_100, 2, 16),
2420            PlaybackFidelity::Lossy,
2421            &ConvertOptions::default(),
2422        );
2423        let q2 = candidate_quality(
2424            &small,
2425            &StreamRequest::pcm(48_000, 2, 16),
2426            PlaybackFidelity::Lossy,
2427            &ConvertOptions::default(),
2428        );
2429        assert_eq!(q1.retained_bandwidth_hz, q2.retained_bandwidth_hz);
2430        let make = |request, quality, rate_rank| Candidate {
2431            request,
2432            fidelity: PlaybackFidelity::Lossy,
2433            rate_rank,
2434            channels_rank: 0,
2435            depth_rank: (0, 0),
2436            upsample_excess: request.sample_rate - small.sample_rate,
2437            quality,
2438        };
2439        let mut same = vec![
2440            make(StreamRequest::pcm(48_000, 2, 16), q2, 0),
2441            make(StreamRequest::pcm(44_100, 2, 16), q1, 1),
2442        ];
2443        sort_candidates(&mut same);
2444        assert_eq!(same[0].request.sample_rate, 44_100);
2445    }
2446    #[test]
2447    fn producer_timing_records_observer_and_conversion_separately() {
2448        let records = Arc::new(std::sync::Mutex::new(Vec::new()));
2449        let sink = records.clone();
2450        let callback: ProducerTimingObserver =
2451            Arc::new(move |event| sink.lock().unwrap().push(event));
2452        let t = Instant::now();
2453        emit_producer_timing(
2454            Some(&callback),
2455            Some(t),
2456            ProducerTimingPhase::ConverterProcess,
2457            16,
2458            32,
2459            false,
2460        );
2461        let t = Instant::now();
2462        emit_producer_timing(
2463            Some(&callback),
2464            Some(t),
2465            ProducerTimingPhase::Observer,
2466            32,
2467            32,
2468            false,
2469        );
2470        let t = Instant::now();
2471        emit_producer_timing(
2472            Some(&callback),
2473            Some(t),
2474            ProducerTimingPhase::RingEnqueue,
2475            32,
2476            0,
2477            true,
2478        );
2479        let records = records.lock().unwrap();
2480        assert_eq!(
2481            records.iter().map(|v| v.phase).collect::<Vec<_>>(),
2482            [
2483                ProducerTimingPhase::ConverterProcess,
2484                ProducerTimingPhase::Observer,
2485                ProducerTimingPhase::RingEnqueue
2486            ]
2487        );
2488        assert!(records[2].blocked);
2489        assert_eq!(records[0].output_bytes, 32);
2490    }
2491    #[test]
2492    fn converter_supports_high_rate_and_dsd_512_families() {
2493        let options = ConvertOptions::default();
2494        let plan = ConversionPlan::pcm(
2495            PcmFormat::new(1_536_000, 2, SampleFormat::I16),
2496            PcmFormat::new(768_000, 2, SampleFormat::I24),
2497            &options,
2498        )
2499        .unwrap();
2500        assert_eq!(plan.kind(), ConversionKind::Lossy);
2501        for bit_rate in [22_579_200, 24_576_000] {
2502            let target = PcmFormat::new(bit_rate / 16, 2, SampleFormat::I24);
2503            assert!(DsdPcmConverter::with_options(bit_rate, 2, target, &options).is_ok());
2504        }
2505    }
2506    #[test]
2507    fn source_byte_transforms_are_exact_and_bounded() {
2508        let mut output = [0u8; 6];
2509        assert_eq!(pcm_u8_to_i16(&[0, 128, 255, 1], &mut output), 3);
2510        assert_eq!(output, [0, 128, 0, 0, 0, 127]);
2511        let mut stereo = [0u8; 4];
2512        assert_eq!(duplicate_mono_dsd(&[0x69, 0x96, 0xff], &mut stereo), 2);
2513        assert_eq!(stereo, [0x69, 0x69, 0x96, 0x96]);
2514        let mut phase = false;
2515        assert_eq!(
2516            unpack_dop(&[0x12, 0x34, 0x05, 0x56, 0x78, 0x05], 2, 3, &mut phase).unwrap(),
2517            [0x34, 0x78, 0x12, 0x56]
2518        );
2519        assert!(phase);
2520        assert!(unpack_dop(&[0x12, 0x34, 0x05, 0x56, 0x78, 0x05], 2, 3, &mut phase).is_err());
2521        assert!(phase);
2522        let mut phase = false;
2523        assert_eq!(
2524            unpack_dop(
2525                &[0, 0x12, 0x34, 0x05, 0, 0x56, 0x78, 0x05],
2526                2,
2527                4,
2528                &mut phase
2529            )
2530            .unwrap(),
2531            [0x34, 0x78, 0x12, 0x56]
2532        );
2533        let mut bad_phase = false;
2534        assert!(unpack_dop(&[1, 0x12, 0x34, 0x05], 1, 4, &mut bad_phase).is_err());
2535        assert!(!bad_phase);
2536    }
2537
2538    /// One alternate at fixed `rates`, for the transport model below.
2539    fn fixed_alt(
2540        format: AltFormat,
2541        channels: u16,
2542        subslot: u8,
2543        bits: u8,
2544        rates: &[u32],
2545    ) -> crate::AltSetting {
2546        let mut alt = descriptor_alt(format, channels, bits);
2547        alt.subslot_bytes = subslot;
2548        alt.sample_rates = rates.to_vec();
2549        alt.rate_ranges = rates
2550            .iter()
2551            .map(|&rate| crate::RateRange {
2552                min_hz: rate,
2553                max_hz: rate,
2554                step_hz: 0,
2555            })
2556            .collect();
2557        alt
2558    }
2559    /// The transport's admission rule in miniature: a request opens an alternate
2560    /// of its channel count whose Type I depth equals the requested depth
2561    /// (negotiate.rs transport_compatibility_penalty) at a descriptor rate.
2562    fn model_admit(caps: &crate::Capabilities, request: &StreamRequest) -> Option<StreamFormat> {
2563        caps.alt_settings.iter().find_map(|alt| {
2564            if alt.channels != request.channels {
2565                return None;
2566            }
2567            let rate = match request.encoding {
2568                Encoding::DsdNative { bit_rate } if alt.format == AltFormat::Dsd => {
2569                    bit_rate / (u32::from(alt.subslot_bytes) * 8)
2570                }
2571                Encoding::Pcm | Encoding::DoP
2572                    if matches!(alt.format, AltFormat::Pcm | AltFormat::Dop)
2573                        && alt.valid_bits == request.bit_depth =>
2574                {
2575                    request.sample_rate
2576                }
2577                Encoding::PcmFloat32 if alt.format == AltFormat::PcmFloat32 => request.sample_rate,
2578                _ => return None,
2579            };
2580            supported_rate(alt, rate).then(|| {
2581                let mut format = wire_format(*request, alt.subslot_bytes);
2582                format.sample_rate = rate;
2583                format.valid_bits = if alt.format == AltFormat::Dsd {
2584                    1
2585                } else {
2586                    alt.valid_bits
2587                };
2588                format
2589            })
2590        })
2591    }
2592    /// Attempts candidates in order like transport::api's batch. DoP and
2593    /// native DSD refusals are never certified clean (negotiate.rs
2594    /// descriptor_shape_absent), so one ends the batch, as on the device.
2595    fn model_negotiate<'a>(
2596        caps: &crate::Capabilities,
2597        attempts: &'a std::cell::RefCell<Vec<StreamRequest>>,
2598    ) -> impl FnOnce(&[StreamRequest]) -> Result<CandidateNegotiation> + 'a {
2599        let caps = caps.clone();
2600        move |requests| {
2601            let mut refusals = Vec::new();
2602            for (index, request) in requests.iter().enumerate() {
2603                attempts.borrow_mut().push(*request);
2604                if let Some(format) = model_admit(&caps, request) {
2605                    return Ok((format, index + 1, refusals.first().cloned(), refusals));
2606                }
2607                let refusal = Error::Unsupported {
2608                    reason: format!("model refused {request:?}"),
2609                    offered: vec![],
2610                };
2611                if matches!(request.encoding, Encoding::DoP | Encoding::DsdNative { .. }) {
2612                    return Err(refusal);
2613                }
2614                refusals.push(refusal);
2615            }
2616            Err(Error::Unsupported {
2617                reason: "model candidates exhausted".into(),
2618                offered: vec![],
2619            })
2620        }
2621    }
2622    fn resolve_model(
2623        caps: &crate::Capabilities,
2624        source: &StreamRequest,
2625        policy: &PlaybackPolicy,
2626    ) -> (Result<PlaybackDecision>, Vec<StreamRequest>) {
2627        let attempts = std::cell::RefCell::new(Vec::new());
2628        let frame = validate_source(source, policy).unwrap();
2629        let decision = resolve_with(
2630            caps,
2631            source,
2632            policy,
2633            frame,
2634            model_negotiate(caps, &attempts),
2635        )
2636        .and_then(|decision| {
2637            ensure_transform_fits_wire(&decision.transform, &decision.format)?;
2638            Ok(decision)
2639        });
2640        (decision, attempts.into_inner())
2641    }
2642    #[test]
2643    fn dop_fallback_onto_a_dop_carrier_repacks_and_never_decimates() {
2644        // H1: 24-bit DoP64 on a DAC with one 32-bit 176.4 kHz alternate.
2645        let caps = capabilities_for(vec![fixed_alt(AltFormat::Pcm, 2, 4, 32, &[176_400])]);
2646        let policy = PlaybackPolicy {
2647            dop_confirmed: true,
2648            allowed_pcm_depths: Some(vec![32]),
2649            ..PlaybackPolicy::default()
2650        };
2651        let (decision, _) = resolve_model(&caps, &StreamRequest::dop(2_822_400, 2), &policy);
2652        let decision = decision.unwrap();
2653        assert_eq!(decision.format.encoding, Encoding::DoP);
2654        assert_eq!(decision.format.valid_bits, 32);
2655        assert_eq!(
2656            decision.transform,
2657            PlaybackTransform::DopRepack { target_channels: 2 }
2658        );
2659        assert_eq!(decision.fidelity, PlaybackFidelity::BitExact);
2660    }
2661    #[test]
2662    fn mono_dop_fallback_onto_a_stereo_dop_carrier_is_lossless_repack() {
2663        let caps = capabilities_for(vec![fixed_alt(AltFormat::Pcm, 2, 3, 24, &[176_400])]);
2664        let policy = PlaybackPolicy {
2665            dop_confirmed: true,
2666            ..PlaybackPolicy::default()
2667        };
2668        let (decision, attempts) = resolve_model(&caps, &StreamRequest::dop(2_822_400, 1), &policy);
2669        let decision = decision.unwrap();
2670        assert_eq!(decision.format.encoding, Encoding::DoP);
2671        assert_eq!(decision.format.channels, 2);
2672        assert_eq!(
2673            decision.transform,
2674            PlaybackTransform::DopRepack { target_channels: 2 }
2675        );
2676        assert_eq!(decision.fidelity, PlaybackFidelity::Lossless);
2677        // H2: the mono exact shape is absent, so it is never attempted.
2678        assert!(attempts.iter().all(|r| r.channels == 2));
2679        assert!(decision.source_preflight_refusal.is_some());
2680    }
2681    #[test]
2682    fn raw_data_alias_lets_stereo_sources_fall_back_on_a_topping_d10() {
2683        // D10 Balanced (152a:8750): 32- and 24-bit PCM plus a RAW_DATA-only
2684        // native DSD alternate that scans as Other and, with the vendor-wide
2685        // DSD_RAW quirk reference-only, as a PCM-incapable alias.
2686        const RATES: &[u32] = &[
2687            44_100, 48_000, 88_200, 96_000, 176_400, 192_000, 352_800, 384_000,
2688        ];
2689        let mut alt1 = fixed_alt(AltFormat::Pcm, 2, 4, 32, RATES);
2690        alt1.alt_setting = 1;
2691        let mut alt2 = fixed_alt(AltFormat::Pcm, 2, 4, 24, RATES);
2692        alt2.alt_setting = 2;
2693        let mut alt3 = fixed_alt(AltFormat::Other, 2, 4, 32, RATES);
2694        alt3.alt_setting = 3;
2695        let mut caps = capabilities_for(vec![alt1, alt2, alt3]);
2696        caps.native_only_aliases = vec![(1, 3, 1)];
2697        let alts = caps.alt_settings.clone();
2698        let aliases = caps.native_only_aliases.clone();
2699        for source in [
2700            StreamRequest::pcm(44_100, 2, 16),
2701            StreamRequest::pcm(8_000, 2, 16),
2702            StreamRequest::pcm(705_600, 2, 24),
2703            StreamRequest::pcm_u8(44_100, 2),
2704            StreamRequest::pcm_float32(176_400, 2),
2705            StreamRequest::dsd_native(2_822_400, 2),
2706        ] {
2707            assert!(
2708                descriptor_exclusion(true, &alts, &aliases, &[], &source).is_some(),
2709                "{source:?} should be excluded by the descriptors"
2710            );
2711            let (decision, attempts) = resolve_model(&caps, &source, &PlaybackPolicy::default());
2712            let decision = decision.unwrap_or_else(|e| panic!("{source:?}: {e}"));
2713            assert!(!attempts.contains(&source), "{source:?} attempted exactly");
2714            assert!(decision.source_preflight_refusal.is_some());
2715        }
2716        // Shapes the PCM alternates carry are still attempted exactly.
2717        assert!(descriptor_exclusion(
2718            true,
2719            &alts,
2720            &aliases,
2721            &[],
2722            &StreamRequest::pcm(44_100, 2, 32)
2723        )
2724        .is_none());
2725        // Without the alias the opaque alternate keeps the preflight open.
2726        assert!(
2727            descriptor_exclusion(true, &alts, &[], &[], &StreamRequest::pcm(44_100, 2, 16))
2728                .is_none()
2729        );
2730    }
2731    #[test]
2732    fn dsd_to_pcm_is_refused_on_a_dsd_wire() {
2733        let dop_wire = wire_format(StreamRequest::dop(2_822_400, 2), 4);
2734        let native_wire = wire_format(StreamRequest::dsd_native(2_822_400, 2), 4);
2735        let decimate = PlaybackTransform::DsdToPcm {
2736            bit_rate: 2_822_400,
2737            dop_input: true,
2738            options: ConvertOptions::default(),
2739        };
2740        assert!(ensure_transform_fits_wire(&decimate, &dop_wire).is_err());
2741        assert!(ensure_transform_fits_wire(&decimate, &native_wire).is_err());
2742        let pcm_wire = wire_format(StreamRequest::pcm(176_400, 2, 24), 3);
2743        assert!(ensure_transform_fits_wire(&decimate, &pcm_wire).is_ok());
2744        assert!(ensure_transform_fits_wire(
2745            &PlaybackTransform::DopRepack { target_channels: 2 },
2746            &pcm_wire
2747        )
2748        .is_err());
2749    }
2750    #[test]
2751    fn exact_dop_on_a_wider_only_dac_falls_back_to_the_wider_carrier() {
2752        // H2: 24-bit DoP on a 32-bit-only DAC; exact 24-bit cannot open.
2753        let caps = capabilities_for(vec![fixed_alt(AltFormat::Pcm, 2, 4, 32, &[176_400])]);
2754        let policy = PlaybackPolicy {
2755            dop_confirmed: true,
2756            ..PlaybackPolicy::default()
2757        };
2758        let source = StreamRequest::dop(2_822_400, 2);
2759        let (decision, attempts) = resolve_model(&caps, &source, &policy);
2760        let decision = decision.unwrap();
2761        assert!(!attempts.contains(&source));
2762        assert_eq!(decision.format.encoding, Encoding::DoP);
2763        assert_eq!(decision.format.valid_bits, 32);
2764        assert_eq!(decision.fidelity, PlaybackFidelity::BitExact);
2765        assert!(decision
2766            .exact_refusal
2767            .as_ref()
2768            .is_some_and(|e| e.to_string().contains("source descriptor preflight")));
2769    }
2770    #[test]
2771    fn confirmed_dop_on_a_dac_without_a_carrier_falls_back_like_unconfirmed() {
2772        // H2: the only PCM alternate is 24-bit at 44.1/48/96 kHz, no 176.4 kHz.
2773        let caps = capabilities_for(vec![fixed_alt(
2774            AltFormat::Pcm,
2775            2,
2776            3,
2777            24,
2778            &[44_100, 48_000, 96_000],
2779        )]);
2780        let source = StreamRequest::dop(2_822_400, 2);
2781        let confirmed = PlaybackPolicy {
2782            dop_confirmed: true,
2783            ..PlaybackPolicy::default()
2784        };
2785        let (confirmed, attempts) = resolve_model(&caps, &source, &confirmed);
2786        let (unconfirmed, _) = resolve_model(&caps, &source, &PlaybackPolicy::default());
2787        let (confirmed, unconfirmed) = (confirmed.unwrap(), unconfirmed.unwrap());
2788        assert!(!attempts.contains(&source));
2789        assert_eq!(confirmed.format, unconfirmed.format);
2790        assert_eq!(confirmed.format.encoding, Encoding::Pcm);
2791        assert!(matches!(
2792            confirmed.transform,
2793            PlaybackTransform::DsdToPcm {
2794                dop_input: true,
2795                ..
2796            }
2797        ));
2798        // A carrier at the exact rate and depth is still attempted first.
2799        let carrier = capabilities_for(vec![fixed_alt(AltFormat::Pcm, 2, 3, 24, &[176_400])]);
2800        let (exact, attempts) = resolve_model(
2801            &carrier,
2802            &source,
2803            &PlaybackPolicy {
2804                dop_confirmed: true,
2805                ..PlaybackPolicy::default()
2806            },
2807        );
2808        assert_eq!(attempts.first(), Some(&source));
2809        assert_eq!(exact.unwrap().transform, PlaybackTransform::Direct);
2810    }
2811    #[test]
2812    fn preflight_reads_a_zero_resolution_range_as_its_minimum() {
2813        let mut alt = descriptor_alt(AltFormat::Pcm, 2, 24);
2814        alt.sample_rates.clear();
2815        alt.rate_ranges = vec![crate::RateRange {
2816            min_hz: 44_100,
2817            max_hz: 96_000,
2818            step_hz: 0,
2819        }];
2820        let alts = std::slice::from_ref(&alt);
2821        assert!(
2822            descriptor_exclusion(true, alts, &[], &[], &StreamRequest::pcm(44_100, 2, 24))
2823                .is_none()
2824        );
2825        assert!(
2826            descriptor_exclusion(true, alts, &[], &[], &StreamRequest::pcm(48_000, 2, 24))
2827                .is_some()
2828        );
2829    }
2830    #[test]
2831    fn zero_resolution_range_admits_only_its_minimum() {
2832        let mut alt = descriptor_alt(AltFormat::Pcm, 2, 24);
2833        alt.sample_rates.clear();
2834        alt.rate_ranges = vec![crate::RateRange {
2835            min_hz: 44_100,
2836            max_hz: 96_000,
2837            step_hz: 0,
2838        }];
2839        assert!(supported_rate(&alt, 44_100));
2840        assert!(!supported_rate(&alt, 48_000));
2841        assert!(!supported_rate(&alt, 96_000));
2842    }
2843
2844    #[derive(Default)]
2845    struct RingState {
2846        frame: usize,
2847        capacity: usize,
2848        target: usize,
2849        queued: usize,
2850        played: u64,
2851        paused: bool,
2852        draining: bool,
2853        fail_writes: bool,
2854        written: Vec<u8>,
2855    }
2856    /// The transport ring in miniature (transport/shared.rs): `writable_bytes`
2857    /// is the room up to the active target in whole wire frames and `write`
2858    /// takes whole wire frames up to the capacity.
2859    #[derive(Clone, Default)]
2860    pub(super) struct RingModel(Arc<parking_lot::Mutex<RingState>>);
2861    impl RingModel {
2862        fn new(format: &StreamFormat, target: usize, capacity: usize) -> Self {
2863            Self(Arc::new(parking_lot::Mutex::new(RingState {
2864                frame: format.bytes_per_frame(),
2865                capacity,
2866                target,
2867                ..RingState::default()
2868            })))
2869        }
2870        pub(super) fn write(&self, data: &[u8]) -> Result<usize> {
2871            let mut ring = self.0.lock();
2872            if ring.fail_writes {
2873                return Err(Error::InvalidState("model ring failed".into()));
2874            }
2875            if ring.draining {
2876                return Err(Error::InvalidState("model ring is draining".into()));
2877            }
2878            let frames = (data.len() / ring.frame).min(ring.capacity - ring.queued);
2879            ring.queued += frames;
2880            let bytes = frames * ring.frame;
2881            ring.written.extend_from_slice(&data[..bytes]);
2882            Ok(bytes)
2883        }
2884        pub(super) fn writable_bytes(&self) -> usize {
2885            let ring = self.0.lock();
2886            if ring.draining || ring.fail_writes {
2887                0
2888            } else {
2889                ring.target.saturating_sub(ring.queued) * ring.frame
2890            }
2891        }
2892        pub(super) fn play(&self) -> Result<()> {
2893            self.0.lock().paused = false;
2894            Ok(())
2895        }
2896        pub(super) fn pause(&self) -> Result<()> {
2897            self.0.lock().paused = true;
2898            Ok(())
2899        }
2900        pub(super) fn flush(&self) -> Result<()> {
2901            self.0.lock().queued = 0;
2902            Ok(())
2903        }
2904        pub(super) fn drain(&self) -> Result<()> {
2905            self.0.lock().draining = true;
2906            Ok(())
2907        }
2908        pub(super) fn is_drained(&self) -> bool {
2909            let ring = self.0.lock();
2910            ring.draining && ring.queued == 0
2911        }
2912        pub(super) fn played_frames(&self) -> u64 {
2913            self.0.lock().played
2914        }
2915        pub(super) fn close(self) -> Result<()> {
2916            Ok(())
2917        }
2918        /// Plays up to `frames` wire frames unless paused.
2919        fn consume(&self, frames: usize) {
2920            let mut ring = self.0.lock();
2921            if !ring.paused {
2922                let n = frames.min(ring.queued);
2923                ring.queued -= n;
2924                ring.played += n as u64;
2925            }
2926        }
2927        fn queued(&self) -> usize {
2928            self.0.lock().queued
2929        }
2930    }
2931    /// Resolves `source` against one alternate and opens it on a ring model with
2932    /// the given target and capacity in wire frames.
2933    fn model_stream(
2934        alt: crate::AltSetting,
2935        source: StreamRequest,
2936        policy: &PlaybackPolicy,
2937        target: usize,
2938        capacity: usize,
2939    ) -> (PlaybackStream, RingModel) {
2940        let (decision, _) = resolve_model(&capabilities_for(vec![alt]), &source, policy);
2941        let decision = decision.unwrap();
2942        let ring = RingModel::new(&decision.format, target, capacity);
2943        let engine = engine_for(&decision).unwrap();
2944        (
2945            PlaybackStream::with_sink(Sink::Model(ring.clone()), &decision, engine),
2946            ring,
2947        )
2948    }
2949    /// 44.1 kHz source on a 48 kHz-only DAC: a resampling stream.
2950    fn converted_stream(target: usize, capacity: usize) -> (PlaybackStream, RingModel) {
2951        let (stream, ring) = model_stream(
2952            fixed_alt(AltFormat::Pcm, 2, 2, 16, &[48_000]),
2953            StreamRequest::pcm(44_100, 2, 16),
2954            &PlaybackPolicy::default(),
2955            target,
2956            capacity,
2957        );
2958        assert!(matches!(
2959            stream.decision().transform,
2960            PlaybackTransform::Pcm { .. }
2961        ));
2962        (stream, ring)
2963    }
2964    fn direct_stream(target: usize, capacity: usize) -> (PlaybackStream, RingModel) {
2965        let (stream, ring) = model_stream(
2966            fixed_alt(AltFormat::Pcm, 2, 2, 16, &[48_000]),
2967            StreamRequest::pcm(48_000, 2, 16),
2968            &PlaybackPolicy::default(),
2969            target,
2970            capacity,
2971        );
2972        assert_eq!(stream.decision().transform, PlaybackTransform::Direct);
2973        (stream, ring)
2974    }
2975    /// Mono DoP64 onto a stereo 24-bit DoP carrier: a repacking stream.
2976    fn repack_stream(target: usize, capacity: usize) -> (PlaybackStream, RingModel) {
2977        let (stream, ring) = model_stream(
2978            fixed_alt(AltFormat::Pcm, 2, 3, 24, &[176_400]),
2979            StreamRequest::dop(2_822_400, 1),
2980            &PlaybackPolicy {
2981                dop_confirmed: true,
2982                ..PlaybackPolicy::default()
2983            },
2984            target,
2985            capacity,
2986        );
2987        assert_eq!(
2988            stream.decision().transform,
2989            PlaybackTransform::DopRepack { target_channels: 2 }
2990        );
2991        (stream, ring)
2992    }
2993    /// Mono DoP source frames with alternating markers, starting at `first`.
2994    fn dop_frames(count: usize, first: usize) -> Vec<u8> {
2995        (first..first + count)
2996            .flat_map(|i| [0x11, 0x22, if i % 2 == 0 { 0x05 } else { 0xfa }])
2997            .collect()
2998    }
2999    #[test]
3000    fn a_writer_that_waits_for_whole_chunks_progresses() {
3001        // M1: the guide's render gate with a 1,024-frame buffer.
3002        const CHUNK: usize = 1024;
3003        for (name, (mut stream, ring)) in [
3004            ("direct", direct_stream(12_000, 24_000)),
3005            ("converted", converted_stream(12_000, 24_000)),
3006            ("repack", repack_stream(44_100, 88_200)),
3007        ] {
3008            let frame = stream.decision().source_frame_bytes;
3009            assert!(
3010                stream.writable_bytes() >= CHUNK * frame,
3011                "{name}: an empty ring reports {} bytes",
3012                stream.writable_bytes()
3013            );
3014            let mut chunks = 0;
3015            for round in 0..400 {
3016                if stream.writable_bytes() >= CHUNK * frame {
3017                    let data = if stream.decision().source.encoding == Encoding::DoP {
3018                        dop_frames(CHUNK, chunks * CHUNK)
3019                    } else {
3020                        vec![0; CHUNK * frame]
3021                    };
3022                    assert_eq!(stream.write(&data).unwrap(), data.len(), "{name}");
3023                    chunks += 1;
3024                } else {
3025                    ring.consume(1 + round % 700);
3026                }
3027            }
3028            assert!(chunks >= 20, "{name}: only {chunks} chunks were written");
3029        }
3030    }
3031    #[test]
3032    fn paused_streams_stop_near_the_active_target() {
3033        // M2: a paused stream fed by writable_bytes stops at its target, not its capacity.
3034        for (name, (mut stream, ring), target) in [
3035            ("direct", direct_stream(4_800, 24_000), 4_800),
3036            ("converted", converted_stream(4_800, 24_000), 4_800),
3037            ("repack", repack_stream(17_640, 88_200), 17_640),
3038        ] {
3039            stream.pause().unwrap();
3040            let frame = stream.decision().source_frame_bytes;
3041            let mut written = 0;
3042            for _ in 0..1_000 {
3043                let n = stream.writable_bytes();
3044                if n == 0 {
3045                    break;
3046                }
3047                let data = if stream.decision().source.encoding == Encoding::DoP {
3048                    dop_frames(n / frame, written)
3049                } else {
3050                    vec![0; n]
3051                };
3052                written += stream.write(&data).unwrap() / frame;
3053            }
3054            assert_eq!(stream.writable_bytes(), 0, "{name}");
3055            let queued = ring.queued();
3056            assert!(
3057                queued >= target && queued <= target + 32,
3058                "{name}: paused ring holds {queued} frames for a target of {target}"
3059            );
3060        }
3061    }
3062    #[test]
3063    fn staged_output_does_not_pin_the_reported_capacity() {
3064        let (mut stream, ring) = converted_stream(4_800, 4_800);
3065        // Overfill past capacity so converted output is left staged.
3066        let data = vec![0; 8_000 * 4];
3067        let accepted = stream.write(&data).unwrap();
3068        assert!(accepted > 0 && accepted < data.len());
3069        {
3070            let staged = stream.staged.lock();
3071            assert!(staged.offset < staged.bytes.len());
3072        }
3073        assert_eq!(stream.writable_bytes(), 0);
3074        // Once the ring plays out, the report covers the room, not one frame.
3075        ring.consume(4_800);
3076        assert!(stream.writable_bytes() >= 1024 * 4);
3077        assert!(stream.staged.lock().bytes.is_empty());
3078    }
3079    #[test]
3080    fn an_error_after_acceptance_keeps_the_count_and_reports_next() {
3081        for (name, (mut stream, ring)) in [
3082            ("converted", converted_stream(4_800, 4_800)),
3083            ("repack", repack_stream(4_800, 4_800)),
3084        ] {
3085            let frame = stream.decision().source_frame_bytes;
3086            let data = if stream.decision().source.encoding == Encoding::DoP {
3087                dop_frames(1024, 0)
3088            } else {
3089                vec![0; 1024 * frame]
3090            };
3091            ring.0.lock().fail_writes = true;
3092            // The ring fails once output reaches it; the accepted step still counts.
3093            let accepted = stream.write(&data).unwrap();
3094            assert!(accepted > 0 && accepted % frame == 0, "{name}");
3095            assert_eq!(stream.conversion_stats().source_bytes, accepted as u64);
3096            assert!(stream.writable_bytes() > 0, "{name}");
3097            assert!(stream.write(&data).is_err(), "{name}");
3098        }
3099    }
3100    #[test]
3101    fn drain_pads_a_final_partial_dsd_group_with_idle() {
3102        // Native mono DSD on a 4-byte native stereo wire: three bytes are short of a word.
3103        let (mut stream, ring) = model_stream(
3104            fixed_alt(AltFormat::Dsd, 2, 4, 1, &[88_200]),
3105            StreamRequest::dsd_native(2_822_400, 1),
3106            &PlaybackPolicy::default(),
3107            8_820,
3108            17_640,
3109        );
3110        assert!(matches!(
3111            stream.decision().transform,
3112            PlaybackTransform::DsdChannelExpansion { .. }
3113        ));
3114        assert_eq!(stream.write(&[0x11, 0x22, 0x33]).unwrap(), 3);
3115        assert!(stream.drain().unwrap());
3116        assert_eq!(
3117            ring.0.lock().written,
3118            [0x11, 0x11, 0x22, 0x22, 0x33, 0x33, DSD_IDLE, DSD_IDLE]
3119        );
3120        // Native mono onto a stereo DoP wire: one byte is short of a DoP pair.
3121        let format = wire_format(StreamRequest::dop(2_822_400, 2), 3);
3122        let source = StreamRequest::dsd_native(2_822_400, 1);
3123        let (mut pending, mut output) = (vec![0xab], Vec::new());
3124        pad_dsd_tail(&source, &format, &mut pending, &mut output).unwrap();
3125        assert!(pending.is_empty());
3126        assert_eq!(output, [DSD_IDLE, 0xab, 0, DSD_IDLE, 0xab, 0]);
3127    }
3128    #[test]
3129    fn room_converts_to_source_frames_through_the_rate_ratio() {
3130        // 48 kHz wire, 4-byte frames: 4,800 bytes is 1,200 wire frames, 1,103 source frames at 44.1 kHz.
3131        assert_eq!(source_frames_for_room(4_800, 44_100, 48_000 * 4), 1_103);
3132        assert_eq!(source_frames_for_room(4, 44_100, 48_000 * 4), 1);
3133        assert_eq!(source_frames_for_room(0, 44_100, 48_000 * 4), 0);
3134        let native = wire_format(StreamRequest::dsd_native(2_822_400, 2), 4);
3135        // One 8-byte native stereo word is four mono DSD bytes.
3136        assert_eq!(
3137            source_frames_for_room(8, 352_800, wire_bytes_per_second(&native)),
3138            4
3139        );
3140    }
3141}