Skip to main content

oxideav_core/registry/
codec.rs

1//! In-process codec registry.
2//!
3//! Every codec crate declares itself with one [`CodecInfo`] value —
4//! capabilities, factory functions, the container tags it claims, and
5//! (optionally) a probe function used to disambiguate genuine tag
6//! collisions. The registry stores those registrations and exposes
7//! three orthogonal lookups:
8//!
9//! - **id-keyed** — `make_decoder(params)` / `make_encoder(params)` walk
10//!   the implementations registered under `params.codec_id`, filter by
11//!   capability restrictions, and try them in priority order with init-
12//!   time fallback.
13//! - **tag-keyed** — `resolve_tag(&ProbeContext)` walks every
14//!   registration whose `tags` contains `ctx.tag`, calls each probe
15//!   (treating `None` as "returns 1.0"), and returns the id with the
16//!   highest resulting confidence. Ties go to the lower
17//!   [`CodecInfo::resolution_priority`], then to the earlier
18//!   registration; `resolve_tag_candidates` exposes the ranked list.
19//! - **payload-magic-keyed** — `resolve_payload_magic(first_bytes)`
20//!   prefix-matches the claimed payload magic prefixes against a
21//!   stream's leading bytes; longest matching magic wins, then the
22//!   lower resolution priority, then registration order
23//!   (`resolve_payload_magic_candidates` exposes the ranked list). For
24//!   containers that identify a codec by the payload itself rather
25//!   than a tag (e.g. an Ogg logical stream's first packet, or raw
26//!   elementary streams).
27//! - **diagnostic** — `all_implementations`, `all_tag_registrations`,
28//!   `all_payload_magic_registrations`.
29//!
30//! The tag path explicitly DOES NOT short-circuit on "first claim with
31//! no probe" — every claimant is asked, so a lower-priority probed
32//! claim can out-rank a higher-priority unprobed one when the content
33//! is actually ambiguous (DIV3 XVID-with-real-MSMPEG4 payload etc.).
34
35use std::collections::HashMap;
36
37use crate::arena;
38use crate::{
39    CodecCapabilities, CodecId, CodecOptionsStruct, CodecParameters, CodecResolver, CodecTag,
40    Error, ExecutionContext, Frame, OptionField, Packet, PixelFormat, ProbeContext, ProbeFn,
41    Result,
42};
43
44// ───────────────────────── codec traits ─────────────────────────
45
46/// A packet-to-frame decoder.
47pub trait Decoder: Send {
48    /// Identifier of the codec this decoder handles.
49    fn codec_id(&self) -> &CodecId;
50
51    /// Feed one compressed packet. May or may not produce a frame immediately —
52    /// call `receive_frame` in a loop afterwards.
53    fn send_packet(&mut self, packet: &Packet) -> Result<()>;
54
55    /// Pull the next decoded frame, if any. Returns `Error::NeedMore` when the
56    /// decoder needs another packet.
57    ///
58    /// Besides media frames, a decoder whose output shape can change
59    /// mid-stream returns one [`Frame::StreamParams`] event immediately
60    /// before the first frame of a new shape (never for the first
61    /// shape, which [`output_params`](Self::output_params) announces).
62    /// When the event is returned, `output_params()` already describes
63    /// the new shape and
64    /// [`output_params_generation`](Self::output_params_generation) has
65    /// already moved; the next `Video` / `Audio` frame has the new
66    /// shape. At most one event per change; the same rule holds after
67    /// [`reset`](Self::reset) and while draining after
68    /// [`flush`](Self::flush). Callers that do not care skip it
69    /// ([`Frame::is_stream_params`]) — the counter carries the same
70    /// information.
71    fn receive_frame(&mut self) -> Result<Frame>;
72
73    /// Pull the next decoded frame as an arena-backed [`arena::sync::Frame`].
74    ///
75    /// Decoders that build their output through an
76    /// [`arena::sync::ArenaPool`] override this to return the pooled
77    /// [`arena::sync::Frame`] **directly**, with no per-plane memcpy
78    /// out — the caller gets true zero-copy plane access via
79    /// [`arena::sync::FrameInner::plane`].
80    ///
81    /// The default implementation delegates to [`Self::receive_frame`]
82    /// and copies the video planes into a freshly-leased one-shot
83    /// `arena::sync::ArenaPool`. This makes the method an additive
84    /// change for every existing [`Decoder`] impl: callers using the
85    /// new API still work, but pay one memcpy per plane.
86    ///
87    /// **Audio / subtitle frames:** the [`arena::sync::Frame`] body is
88    /// video-only (planes + [`arena::sync::FrameHeader`] with
89    /// width/height/pixel format). The default implementation returns
90    /// [`Error::Unsupported`] for non-video frames; an audio decoder
91    /// that wants to expose `receive_arena_frame()` must override it
92    /// with its own arena-backed audio-frame type once the framework
93    /// gains one. Until then, audio decoders should keep using
94    /// [`Self::receive_frame`].
95    ///
96    /// **[`Frame::StreamParams`] events** have no arena representation:
97    /// the default implementation consumes them and returns the next
98    /// frame (whose [`arena::sync::FrameHeader`] carries the new shape);
99    /// [`output_params`](Self::output_params) /
100    /// [`output_params_generation`](Self::output_params_generation) have
101    /// moved by then, so a caller watching the counter still sees the
102    /// change.
103    fn receive_arena_frame(&mut self) -> Result<arena::sync::Frame> {
104        let mut frame = self.receive_frame()?;
105        while frame.is_stream_params() {
106            frame = self.receive_frame()?;
107        }
108        match frame {
109            Frame::Video(v) => video_frame_to_arena_sync_frame(&v),
110            Frame::Audio(_) => Err(Error::unsupported(
111                "receive_arena_frame: audio frames not yet supported by default impl",
112            )),
113            Frame::Subtitle(_) => Err(Error::unsupported(
114                "receive_arena_frame: subtitle frames have no arena-backed representation",
115            )),
116            Frame::Vector(_) => Err(Error::unsupported(
117                "receive_arena_frame: vector frames have no arena-backed representation",
118            )),
119            _ => Err(Error::unsupported(
120                "receive_arena_frame: frame kind has no arena-backed representation",
121            )),
122        }
123    }
124
125    /// Signal end-of-stream. After this, `receive_frame` will drain buffered
126    /// frames and eventually return `Error::Eof`.
127    fn flush(&mut self) -> Result<()>;
128
129    /// Discard all carry-over state so the decoder can resume from a new
130    /// bitstream position without producing stale output. Called by the
131    /// player after a container seek.
132    ///
133    /// Unlike [`flush`](Self::flush) (which signals end-of-stream and
134    /// drains buffered frames), `reset` is expected to:
135    /// * drop every buffered input packet and pending output frame;
136    /// * zero any per-stream filter / predictor / overlap memory so the
137    ///   next `send_packet` decodes as if it were the first;
138    /// * leave the codec id and stream parameters untouched.
139    ///
140    /// The default is a conservative "drain-then-forget": call
141    /// [`flush`](Self::flush) and ignore any remaining frames. Stateful
142    /// codecs (LPC predictors, backward-adaptive gain, IMDCT overlap,
143    /// reference pictures, …) should override this to wipe their
144    /// internal state explicitly — otherwise the first ~N output
145    /// samples after a seek will be glitchy until the state re-adapts.
146    fn reset(&mut self) -> Result<()> {
147        self.flush()?;
148        // Drain any remaining output frames so the next send_packet
149        // starts clean. NeedMore / Eof both mean "no more frames"; any
150        // other error is surfaced so the caller can see why.
151        loop {
152            match self.receive_frame() {
153                Ok(_) => {}
154                Err(Error::NeedMore) | Err(Error::Eof) => return Ok(()),
155                Err(e) => return Err(e),
156            }
157        }
158    }
159
160    /// Advisory: announce the runtime environment (today: a thread budget
161    /// for codec-internal parallelism). Called at most once, before the
162    /// first `send_packet`. Default no-op; codecs that want to run
163    /// slice-/GOP-/tile-parallel override this to capture the budget.
164    /// Ignoring the hint is always safe — callers must still work with
165    /// a decoder that runs serial.
166    fn set_execution_context(&mut self, _ctx: &ExecutionContext) {}
167
168    /// Pixel layout of the video frames this decoder emits, stated
169    /// before the first frame — from the codec's configuration record
170    /// in `extradata`, from a negotiated hardware session, or from the
171    /// decoder's fixed output policy. `Some` is a **fact about the
172    /// frames to come** and takes precedence over the container's
173    /// [`CodecParameters::pixel_format`](crate::CodecParameters::pixel_format)
174    /// (a stream label is a claim the container made; the decoder is
175    /// the one producing the planes). `None` — the default — means
176    /// "not known yet: trust the stream parameters", and a decoder
177    /// whose output depends on the first packet (an untagged file that
178    /// decides its layout per picture) answers `None` until it has
179    /// seen one and the real layout afterwards.
180    ///
181    /// Pipelines and gateways read it to label frames from codec-only
182    /// registrations and to pick the conversion into an encoder's
183    /// [`accepted_pixel_formats`](crate::CodecCapabilities::accepted_pixel_formats);
184    /// a frame whose plane shape disagrees with the stated layout is
185    /// the decoder's defect, not the consumer's. The answer may change
186    /// between frames only for a decoder that documents it.
187    ///
188    /// This is the narrow, older form of
189    /// [`output_params`](Self::output_params), whose default derives
190    /// from it. New decoders implement `output_params` (the whole
191    /// output description) and forward this method to it; consumers
192    /// should prefer `output_params`.
193    fn output_pixel_format(&self) -> Option<crate::PixelFormat> {
194        None
195    }
196
197    /// The decoder's resolved description of the frames it emits — the
198    /// **stream-level** home for what [`Frame`]s deliberately do not
199    /// repeat (a [`VideoFrame`](crate::VideoFrame) /
200    /// [`AudioFrame`](crate::AudioFrame) carries no width, height,
201    /// format or rate: the shape does not change 60 times a second, so
202    /// it is stated once, here, and re-stated only when it changes).
203    ///
204    /// Fields a decoder fills when it knows them:
205    ///
206    /// * **video** — [`width`](CodecParameters::width) /
207    ///   [`height`](CodecParameters::height) as the frames have them
208    ///   (the cropped / display size of the emitted planes, not the
209    ///   coded macroblock-aligned size),
210    ///   [`pixel_format`](CodecParameters::pixel_format),
211    ///   [`frame_rate`](CodecParameters::frame_rate) when the bitstream
212    ///   signals one, [`color_signal`](CodecParameters::color_signal)
213    ///   from the bitstream's own signalling, and
214    ///   [`layers`](CodecParameters::layers) for multi-layer output;
215    /// * **audio** — [`sample_rate`](CodecParameters::sample_rate),
216    ///   [`channels`](CodecParameters::channels),
217    ///   [`sample_format`](CodecParameters::sample_format),
218    ///   [`channel_layout`](CodecParameters::channel_layout).
219    ///
220    /// Fields the decoder does not know stay `None` / unspecified;
221    /// container-side fields (`extradata`, `bit_rate`, `tag`,
222    /// `language`, `blobs`, `options`, `limits`) are not the decoder's
223    /// to answer and are ignored by
224    /// [`CodecParameters::merge_output_params`], the helper that folds
225    /// this answer into a stream's parameters.
226    ///
227    /// `Some` is a **fact about the frames** and takes precedence over
228    /// the container's claim for every field it sets. `None` means "not
229    /// known yet: trust the stream parameters". A decoder answers as
230    /// soon as it has parsed what defines the output — its
231    /// configuration record in `extradata` at construction, or the
232    /// first sequence / frame header — ideally before the first frame
233    /// is returned, and at the latest once `receive_frame` has returned
234    /// the first frame. From then on the answer describes the frame
235    /// most recently returned by `receive_frame` (and the ones after
236    /// it, until [`output_params_generation`](Self::output_params_generation)
237    /// changes).
238    ///
239    /// **Mid-stream changes** are announced three ways that always
240    /// agree: this answer changes, the generation counter moves, and —
241    /// for a decoder that emits it — `receive_frame` returns a
242    /// [`Frame::StreamParams`] event carrying this same description,
243    /// immediately before the first frame of the new shape. When that
244    /// event is returned, this method already answers the new shape.
245    /// No event is emitted for the first shape (resolving `None` →
246    /// `Some`, or refining it, up to the first frame).
247    ///
248    /// **Default and the relation to [`output_pixel_format`](Self::output_pixel_format):**
249    /// the default implementation derives from `output_pixel_format()`
250    /// — `Some` of a video [`CodecParameters`] carrying only
251    /// `codec_id` and `pixel_format` when that answers `Some`, `None`
252    /// otherwise — so every decoder that implements the older narrow
253    /// query is described here for free. The direction is one-way:
254    /// `output_params` reads `output_pixel_format`, never the other
255    /// way round (no default recursion). A decoder that implements
256    /// `output_params` itself should also forward
257    /// `output_pixel_format` to it
258    /// (`self.output_params().and_then(|p| p.pixel_format)`) so callers
259    /// of the narrow query keep seeing the same answer. Consumers
260    /// should query `output_params` — it is the complete answer.
261    fn output_params(&self) -> Option<CodecParameters> {
262        self.output_pixel_format().map(|pf| {
263            let mut p = CodecParameters::video(self.codec_id().clone());
264            p.pixel_format = Some(pf);
265            p
266        })
267    }
268
269    /// A cheap change signal for [`output_params`](Self::output_params):
270    /// an integer that changes whenever the output description changes
271    /// **mid-stream** (a resolution switch at a keyframe, a new pixel
272    /// format at a new sequence header, a sample-rate change in a
273    /// chained stream). Consumers keep the last value they saw and
274    /// compare one integer after each successful `receive_frame`;
275    /// only when it differs do they re-read `output_params()`. Frames
276    /// carry nothing extra.
277    ///
278    /// The contract:
279    ///
280    /// * Consumers always read `output_params()` once after the first
281    ///   frame (or before it, if they need the shape up front) —
282    ///   resolving the description from `None` to `Some` before or at
283    ///   the first frame is **not** a change and needs no bump.
284    /// * After the first frame has been returned, a decoder whose
285    ///   output description changes increments the value (wrapping,
286    ///   so it only ever needs `!=` comparison) **at a frame
287    ///   boundary**: the bump and the new `output_params()` answer
288    ///   become visible together, when `receive_frame` returns the
289    ///   first frame with the new shape — or, for a decoder that emits
290    ///   the in-band [`Frame::StreamParams`] event, when it returns that
291    ///   event (immediately before that frame) — not when the decoder
292    ///   parses the header announcing it, because frames of the old
293    ///   shape may still be queued in its reorder buffer. Once
294    ///   `receive_frame` has returned a media frame, `output_params()`
295    ///   describes that frame. One change = one bump = at most one
296    ///   event.
297    /// * It never changes while the description stays the same, and a
298    ///   bump always comes with a changed description.
299    /// * [`reset`](Self::reset) after a seek may change it (the new
300    ///   position can be in a segment of a different shape) under the
301    ///   same rule: visible with the first frame returned afterwards.
302    ///
303    /// The default `0` — "never changes" — is correct for every decoder
304    /// whose output shape is fixed for the stream's lifetime.
305    /// [`OutputParamsWatch`] packages the consumer side in one call.
306    fn output_params_generation(&self) -> u64 {
307        0
308    }
309}
310
311/// Consumer-side helper for the [`Decoder::output_params`] /
312/// [`Decoder::output_params_generation`] contract: folds the decoder's
313/// output description into a stream's [`CodecParameters`] once, and
314/// again only when the decoder signals a mid-stream change — one
315/// integer compare per frame otherwise.
316///
317/// Call [`observe`](Self::observe) after **every** successful
318/// `receive_frame` (the first call always reads the description; later
319/// calls re-read only when the generation moved). Call
320/// [`prime`](Self::prime) before the first frame when the shape is
321/// needed up front (to size a renderer, pick a converter); it merges
322/// whatever the decoder already knows without consuming the
323/// first-frame read, since the description may still be refined up to
324/// the first frame.
325///
326/// A consumer may instead (or additionally) watch the in-band
327/// [`Frame::StreamParams`] event with
328/// [`observe_frame`](Self::observe_frame); the two agree — the
329/// generation has already moved when the event is returned, and
330/// merging the same description twice reports no second change — so a
331/// mid-stream change is reported exactly once either way.
332///
333/// ```
334/// # use oxideav_core::{CodecParameters, Decoder, OutputParamsWatch};
335/// fn pump(dec: &mut dyn Decoder, stream: &mut CodecParameters) -> oxideav_core::Result<()> {
336///     let mut watch = OutputParamsWatch::new();
337///     while let Ok(_frame) = dec.receive_frame() {
338///         if watch.observe(&*dec, stream) {
339///             // shape changed (or was first resolved): reconfigure
340///             // the converter / renderer from `stream` here.
341///         }
342///     }
343///     Ok(())
344/// }
345/// ```
346#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
347pub struct OutputParamsWatch {
348    seen: Option<u64>,
349}
350
351impl OutputParamsWatch {
352    /// A watch that has not read the decoder yet.
353    pub const fn new() -> Self {
354        Self { seen: None }
355    }
356
357    /// Call after a successful `receive_frame`. Re-reads
358    /// [`Decoder::output_params`] on the first call and whenever
359    /// [`Decoder::output_params_generation`] differs from the value of
360    /// the last read, merging it into `stream` through
361    /// [`CodecParameters::merge_output_params`]. Returns `true` when
362    /// that changed an output-describing field of `stream`.
363    ///
364    /// A decoder that still answers `None` leaves `stream` untouched
365    /// and is asked again on the next call.
366    pub fn observe<D: Decoder + ?Sized>(
367        &mut self,
368        decoder: &D,
369        stream: &mut CodecParameters,
370    ) -> bool {
371        let generation = decoder.output_params_generation();
372        if self.seen == Some(generation) {
373            return false;
374        }
375        match decoder.output_params() {
376            Some(p) => {
377                self.seen = Some(generation);
378                stream.merge_output_params(&p)
379            }
380            None => false,
381        }
382    }
383
384    /// Event-side counterpart of [`observe`](Self::observe): when
385    /// `frame` is a [`Frame::StreamParams`] event, merge its parameters
386    /// into `stream` through [`CodecParameters::merge_output_params`]
387    /// and return `true` when that changed an output-describing field;
388    /// for any other frame do nothing and return `false`. Needs no
389    /// decoder, so it also works downstream of a pipeline stage that
390    /// only forwards frames.
391    pub fn observe_frame(&mut self, frame: &Frame, stream: &mut CodecParameters) -> bool {
392        match frame.stream_params() {
393            Some(p) => stream.merge_output_params(p),
394            None => false,
395        }
396    }
397
398    /// Merge what the decoder already knows into `stream` without
399    /// recording a read — for use before the first frame. Returns
400    /// `true` when an output-describing field of `stream` changed.
401    pub fn prime<D: Decoder + ?Sized>(&self, decoder: &D, stream: &mut CodecParameters) -> bool {
402        decoder
403            .output_params()
404            .is_some_and(|p| stream.merge_output_params(&p))
405    }
406
407    /// Forget the last read so the next [`observe`](Self::observe)
408    /// re-reads unconditionally (e.g. after swapping the decoder).
409    pub fn reset(&mut self) {
410        self.seen = None;
411    }
412}
413
414/// A frame-to-packet encoder.
415pub trait Encoder: Send {
416    /// Identifier of the codec this encoder produces.
417    fn codec_id(&self) -> &CodecId;
418
419    /// Parameters describing this encoder's output stream (to feed into a muxer).
420    fn output_params(&self) -> &CodecParameters;
421
422    /// Feed one uncompressed frame. May or may not produce a packet
423    /// immediately — call `receive_packet` in a loop afterwards.
424    ///
425    /// A [`Frame::StreamParams`] event (a mid-stream change of the
426    /// input shape) is rejected with [`Error::Unsupported`] unless the
427    /// encoder can re-configure for the new shape mid-stream; an
428    /// encoder that can, re-configures and keeps
429    /// [`output_params`](Self::output_params) describing its output.
430    fn send_frame(&mut self, frame: &Frame) -> Result<()>;
431
432    /// Pull the next encoded packet, if any. Returns `Error::NeedMore`
433    /// when the encoder needs another frame (or a `flush`).
434    fn receive_packet(&mut self) -> Result<Packet>;
435
436    /// Signal end of input: drain internal lookahead so the remaining
437    /// packets become available via `receive_packet`.
438    fn flush(&mut self) -> Result<()>;
439
440    /// Advisory: announce the runtime environment. Same semantics as
441    /// [`Decoder::set_execution_context`].
442    fn set_execution_context(&mut self, _ctx: &ExecutionContext) {}
443}
444
445/// Default-impl helper for [`Decoder::receive_arena_frame`]: copy a
446/// heap-backed [`crate::VideoFrame`] into a freshly-leased
447/// [`arena::sync::Frame`].
448///
449/// Allocates a single-slot, single-arena `arena::sync::ArenaPool`
450/// sized to fit the planes verbatim. The pool is dropped at the end of
451/// this call; the returned `Frame` keeps its leased buffer alive via
452/// `Arc<FrameInner>` (the `Arena`'s `Weak` handle to the dropped pool
453/// just stops upgrading — the buffer drops normally when the last
454/// `Frame` clone goes away).
455///
456/// Width / height / pixel-format on the returned `FrameHeader` are
457/// derived from the plane shape: `width = plane[0].stride`,
458/// `height = plane[0].data.len() / stride`. Pixel format is left as
459/// [`PixelFormat::Yuv420P`] when there are 3 planes, else the first
460/// per-plane sensible default — this is a best-effort label for the
461/// generic conversion path; decoders that override
462/// `receive_arena_frame` themselves should set the correct pixel
463/// format.
464fn video_frame_to_arena_sync_frame(v: &crate::VideoFrame) -> Result<arena::sync::Frame> {
465    if v.planes.is_empty() {
466        return Err(Error::invalid(
467            "receive_arena_frame: video frame has no planes",
468        ));
469    }
470    let total_bytes: usize = v.planes.iter().map(|p| p.data.len()).sum();
471    if total_bytes == 0 {
472        return Err(Error::invalid(
473            "receive_arena_frame: video frame planes are empty",
474        ));
475    }
476    // One-shot pool sized exactly to the frame. The pool drops at end
477    // of scope; the leased Arena lives on inside the returned Frame
478    // (its Weak<ArenaPool> handle just won't upgrade in Drop, so the
479    // Box<[u8]> falls through to a normal heap free).
480    let pool = arena::sync::ArenaPool::with_alloc_count_cap(
481        1,
482        total_bytes,
483        // One alloc per plane, plus a generous safety margin.
484        (v.planes.len() as u32).saturating_add(4),
485    );
486    let arena = pool.lease()?;
487    let mut plane_offsets: Vec<(usize, usize)> = Vec::with_capacity(v.planes.len());
488    let mut cursor = 0usize;
489    for plane in &v.planes {
490        let dst = arena.alloc::<u8>(plane.data.len())?;
491        dst.copy_from_slice(&plane.data);
492        plane_offsets.push((cursor, plane.data.len()));
493        cursor += plane.data.len();
494    }
495    // Best-effort header: width = stride of plane 0, height inferred
496    // from plane 0's data length. Pixel format defaults to Yuv420P for
497    // the common 3-plane case, Gray8 for single-plane, otherwise
498    // Yuv444P. Decoders that care about exact pixel-format / width /
499    // height should override `receive_arena_frame` themselves so they
500    // can emit a correct `FrameHeader` straight from their arena
501    // build path.
502    let stride0 = v.planes[0].stride.max(1);
503    let width = stride0 as u32;
504    let height = (v.planes[0].data.len() / stride0) as u32;
505    // Count only image planes for the format guess — side-channel
506    // entries (palette, significant bits; copied verbatim above like
507    // any other plane) must not bump e.g. a single-plane palette frame
508    // out of the Gray8 label.
509    let pixel_format = match v.image_plane_count() {
510        1 => PixelFormat::Gray8,
511        3 => PixelFormat::Yuv420P,
512        _ => PixelFormat::Yuv444P,
513    };
514    let header = arena::sync::FrameHeader::new(width, height, pixel_format, v.pts);
515    arena::sync::FrameInner::new(arena, &plane_offsets, header)
516}
517
518/// Factory that builds a decoder for a given codec parameter set.
519pub type DecoderFactory = fn(params: &CodecParameters) -> Result<Box<dyn Decoder>>;
520
521/// Factory that builds an encoder for a given codec parameter set.
522pub type EncoderFactory = fn(params: &CodecParameters) -> Result<Box<dyn Encoder>>;
523
524// ───────────────────────── CodecInfo ─────────────────────────
525
526/// A single registration: capabilities, decoder/encoder factories,
527/// optional probe, and the container tags this codec claims.
528///
529/// Codec crates build one of these per codec id inside their
530/// `register(reg)` function and hand it to
531/// [`CodecRegistry::register`]. The struct is `#[non_exhaustive]` so
532/// additional fields can be added without breaking existing codec
533/// crates — construction is only possible through
534/// [`CodecInfo::new`] plus the builder methods below.
535#[non_exhaustive]
536pub struct CodecInfo {
537    /// Canonical codec identifier this entry registers.
538    pub id: CodecId,
539    /// Capability description (media kind, feature flags, priority).
540    pub capabilities: CodecCapabilities,
541    /// Factory producing a fresh decoder instance, if decode is supported.
542    pub decoder_factory: Option<DecoderFactory>,
543    /// Factory producing a fresh encoder instance, if encode is supported.
544    pub encoder_factory: Option<EncoderFactory>,
545    /// Probe function that returns a confidence in `0.0..=1.0` for a
546    /// given [`ProbeContext`]. `None` means "confidence 1.0 for every
547    /// claimed tag" — the correct default for codecs whose tag claims
548    /// are unambiguous.
549    pub probe: Option<ProbeFn>,
550    /// Tags this codec is willing to be looked up under. One codec may
551    /// claim many tags (an AAC decoder covers several WaveFormat ids,
552    /// a FourCC, an MP4 OTI, and a Matroska CodecID string at once).
553    pub tags: Vec<CodecTag>,
554    /// Payload magic prefixes this codec answers to (`\x01vorbis`,
555    /// `OpusHead`, …). Some carriage formats have no codec tag — the
556    /// codec is announced by a magic byte prefix on the payload itself
557    /// (an Ogg logical stream's first packet is the canonical case;
558    /// raw elementary streams are another). Such claims are
559    /// prefix-matched by
560    /// [`CodecRegistry::resolve_payload_magic_ref`] instead of living in
561    /// the exact-match [`CodecTag`] index. Attached with
562    /// [`Self::payload_magic`] / [`Self::payload_magics`]. Empty prefixes are
563    /// ignored at registration time (a zero-length prefix would match
564    /// every stream while carrying no evidence).
565    pub payload_magics: Vec<Vec<u8>>,
566    /// Schema of the encoder's recognised option keys
567    /// (`CodecParameters::options`). Attached with
568    /// [`Self::encoder_options`]. Used for validation / `oxideav list`
569    /// / pipeline JSON checks.
570    pub encoder_options_schema: Option<&'static [OptionField]>,
571    /// Schema of the decoder's recognised option keys.
572    pub decoder_options_schema: Option<&'static [OptionField]>,
573    /// HW backend identifier, e.g. `"nvidia"`, `"vaapi"`, `"vdpau"`,
574    /// `"vulkan-video"`, `"videotoolbox"`. Set by HW siblings on every
575    /// `CodecInfo` they register; SW codecs leave this `None`.
576    /// Consumers (e.g. the CLI's `info` command) use it to group
577    /// codec entries by backend and to dedupe probe calls — multiple
578    /// `CodecInfo` entries with the same `engine_id` typically share
579    /// an `engine_probe` function, and consumers should call the probe
580    /// at most once per `engine_id` per pass. Attached via
581    /// [`Self::with_engine_id`].
582    pub engine_id: Option<&'static str>,
583    /// Optional engine probe function. When `Some`, calling it returns
584    /// one [`crate::engine::HwDeviceInfo`] entry per device the backend
585    /// sees. Phase-2 HW siblings populate this on every `CodecInfo`
586    /// they register; Phase-3 consumers (CLI) call it on demand.
587    /// Attached via [`Self::with_engine_probe`].
588    pub engine_probe: Option<crate::engine::EngineProbeFn>,
589    /// Tie-break rank for this registration's **claims** (tags and
590    /// payload magics) when another codec id claims the same tag /
591    /// magic with equal evidence. Lower is preferred; defaults to
592    /// [`DEFAULT_PRIORITY`](crate::DEFAULT_PRIORITY). Deliberately
593    /// separate from [`CodecCapabilities::priority`]: that field ranks
594    /// *implementations of one codec id* against each other (HW before
595    /// SW), and a backend's implementation preference must not silently
596    /// out-rank a different codec's identity claim on an ambiguous tag.
597    /// Attached via [`Self::with_resolution_priority`].
598    pub resolution_priority: i32,
599}
600
601impl CodecInfo {
602    /// Start a new registration for `id` with empty capabilities, no
603    /// factories, no probe, and no tags. Chain the builder methods
604    /// below to fill it in, then hand the result to
605    /// [`CodecRegistry::register`].
606    pub fn new(id: CodecId) -> Self {
607        Self {
608            capabilities: CodecCapabilities::audio(id.as_str()),
609            id,
610            decoder_factory: None,
611            encoder_factory: None,
612            probe: None,
613            tags: Vec::new(),
614            payload_magics: Vec::new(),
615            encoder_options_schema: None,
616            decoder_options_schema: None,
617            engine_id: None,
618            engine_probe: None,
619            resolution_priority: crate::DEFAULT_PRIORITY,
620        }
621    }
622
623    /// Set the claim tie-break priority (see
624    /// [`Self::resolution_priority`]). Lower is preferred. Only consulted
625    /// when another codec id claims the same tag with equal probe
626    /// confidence, or the same-length payload magic; evidence always
627    /// out-ranks priority, and equal priorities fall through to
628    /// registration order (earlier wins).
629    pub fn with_resolution_priority(mut self, priority: i32) -> Self {
630        self.resolution_priority = priority;
631        self
632    }
633
634    /// Replace the capability description. The default built by
635    /// [`Self::new`] is a placeholder (audio-flavoured, no flags); every
636    /// real registration should call this.
637    pub fn capabilities(mut self, caps: CodecCapabilities) -> Self {
638        self.capabilities = caps;
639        self
640    }
641
642    /// Builder: attach the decoder factory.
643    pub fn decoder(mut self, factory: DecoderFactory) -> Self {
644        self.decoder_factory = Some(factory);
645        self
646    }
647
648    /// Builder: attach the encoder factory.
649    pub fn encoder(mut self, factory: EncoderFactory) -> Self {
650        self.encoder_factory = Some(factory);
651        self
652    }
653
654    /// Builder: attach a confidence probe (see [`CodecInfo::probe`]).
655    pub fn probe(mut self, probe: ProbeFn) -> Self {
656        self.probe = Some(probe);
657        self
658    }
659
660    /// Claim a single container tag for this codec. Equivalent to
661    /// `.tags([tag])` but avoids the array ceremony for single-tag
662    /// claims.
663    pub fn tag(mut self, tag: CodecTag) -> Self {
664        self.tags.push(tag);
665        self
666    }
667
668    /// Claim a set of container tags for this codec. Takes any
669    /// iterable (arrays, `Vec`, `Option`, …) so the common case of a
670    /// codec with 3-6 tags reads as one clean block.
671    pub fn tags(mut self, tags: impl IntoIterator<Item = CodecTag>) -> Self {
672        self.tags.extend(tags);
673        self
674    }
675
676    /// Claim one payload magic prefix for this codec (see
677    /// [`Self::payload_magics`]). Chain repeatedly for codecs that answer
678    /// to more than one magic:
679    ///
680    /// ```
681    /// # use oxideav_core::registry::CodecInfo;
682    /// # use oxideav_core::CodecId;
683    /// let info = CodecInfo::new(CodecId::new("vorbis")).payload_magic(b"\x01vorbis");
684    /// # let _ = info;
685    /// ```
686    pub fn payload_magic(mut self, magic: impl Into<Vec<u8>>) -> Self {
687        self.payload_magics.push(magic.into());
688        self
689    }
690
691    /// Claim a set of payload magic prefixes for this codec — the
692    /// iterable companion to [`Self::payload_magic`], mirroring the
693    /// [`Self::tag`] / [`Self::tags`] pair.
694    pub fn payload_magics<I>(mut self, magics: I) -> Self
695    where
696        I: IntoIterator,
697        I::Item: Into<Vec<u8>>,
698    {
699        self.payload_magics
700            .extend(magics.into_iter().map(Into::into));
701        self
702    }
703
704    /// Declare the options struct this codec's encoder factory expects.
705    /// Attaches `T::SCHEMA` so the registry can enumerate recognised
706    /// option keys (for `oxideav list`, pipeline JSON validation, etc.).
707    /// The factory itself still has to call
708    /// [`crate::parse_options::<T>()`] against
709    /// `CodecParameters::options` at init time.
710    pub fn encoder_options<T: CodecOptionsStruct>(mut self) -> Self {
711        self.encoder_options_schema = Some(T::SCHEMA);
712        self
713    }
714
715    /// Declare the options struct this codec's decoder factory expects.
716    /// See [`Self::encoder_options`] for the encoder counterpart.
717    pub fn decoder_options<T: CodecOptionsStruct>(mut self) -> Self {
718        self.decoder_options_schema = Some(T::SCHEMA);
719        self
720    }
721
722    /// Tag this codec as belonging to a HW backend identified by
723    /// `engine_id`. Should match the `engine_id` of every other
724    /// `CodecInfo` registered by the same backend, and the corresponding
725    /// `engine_id` field used by the CLI for grouping. SW codecs leave
726    /// this unset.
727    pub fn with_engine_id(mut self, engine_id: &'static str) -> Self {
728        self.engine_id = Some(engine_id);
729        self
730    }
731
732    /// Attach a probe function. Consumers call it to enumerate the
733    /// engines (devices) this backend can dispatch to. Probes are
734    /// expected to be idempotent and side-effect free; consumers may
735    /// call them more than once per process and should dedupe by
736    /// [`Self::engine_id`].
737    pub fn with_engine_probe(mut self, probe: crate::engine::EngineProbeFn) -> Self {
738        self.engine_probe = Some(probe);
739        self
740    }
741}
742
743/// Internal per-impl record held inside the registry's id map. Kept
744/// distinct from [`CodecInfo`] so the id map stays cheap to walk
745/// during `make_decoder` / `make_encoder` lookups.
746#[derive(Clone)]
747pub struct CodecImplementation {
748    /// Capability description copied from the originating [`CodecInfo`].
749    pub caps: CodecCapabilities,
750    /// Decoder factory, if this implementation can decode.
751    pub make_decoder: Option<DecoderFactory>,
752    /// Encoder factory, if this implementation can encode.
753    pub make_encoder: Option<EncoderFactory>,
754    /// Encoder options schema declared via
755    /// [`CodecInfo::encoder_options`]. `None` means the encoder accepts
756    /// no tuning knobs (any non-empty `CodecParameters::options` will
757    /// still be rejected by the factory if the encoder calls
758    /// `parse_options` — this is purely informational for discovery).
759    pub encoder_options_schema: Option<&'static [OptionField]>,
760    /// Decoder options schema declared via
761    /// [`CodecInfo::decoder_options`]; same semantics as the encoder
762    /// schema above.
763    pub decoder_options_schema: Option<&'static [OptionField]>,
764    /// HW backend identifier copied verbatim from the originating
765    /// [`CodecInfo::engine_id`]. `Some("nvidia"/"vaapi"/...)` on HW
766    /// backends; `None` on SW codecs. Consumers (CLI `info` command,
767    /// pipeline dispatcher, bench loop) read this to group entries by
768    /// backend without grepping `caps.implementation`.
769    pub engine_id: Option<&'static str>,
770    /// Engine probe function copied verbatim from the originating
771    /// [`CodecInfo::engine_probe`]. `Some(fn)` on HW backends with a
772    /// probe wired; `None` on SW codecs. Consumers call it on demand
773    /// to enumerate per-device info ([`crate::engine::HwDeviceInfo`]).
774    pub engine_probe: Option<crate::engine::EngineProbeFn>,
775}
776
777/// Registry mapping codec ids and container tags to their registered
778/// implementations; the lookup point behind `make_decoder` /
779/// `make_encoder` / `resolve_tag`.
780#[derive(Default)]
781pub struct CodecRegistry {
782    /// id → list of implementations. Each registered codec appends one
783    /// entry here. `make_decoder` / `make_encoder` walk this list in
784    /// preference order.
785    impls: HashMap<CodecId, Vec<CodecImplementation>>,
786    /// Codec ids in the order their first implementation was
787    /// registered — drives every id-level enumeration so listings are
788    /// stable across processes.
789    impl_order: Vec<CodecId>,
790    /// Append-only list of every registration — the `tag_index` stores
791    /// offsets into this vector.
792    registrations: Vec<RegistrationRecord>,
793    /// Tag → indices into `registrations`. Indices are stored in
794    /// registration order so tie-breaking in `resolve_tag` is
795    /// deterministic (first-registered wins).
796    tag_index: HashMap<CodecTag, Vec<usize>>,
797    /// Payload magic-prefix claims: `(magic, registration index)` in
798    /// registration order. Kept as a flat list rather than a map
799    /// because resolution is prefix matching (see
800    /// [`Self::resolve_payload_magic_ref`]), not exact-key lookup.
801    magic_index: Vec<(Vec<u8>, usize)>,
802}
803
804/// Internal registry record. Mirrors the subset of [`CodecInfo`]
805/// needed at resolve time.
806struct RegistrationRecord {
807    id: CodecId,
808    probe: Option<ProbeFn>,
809    /// Claim tie-break rank copied from [`CodecInfo::resolution_priority`].
810    priority: i32,
811    /// Tags claimed by this registration, in declaration order — the
812    /// source of [`CodecRegistry::all_tag_registrations`]'s ordering.
813    tags: Vec<CodecTag>,
814}
815
816/// One ranked entry from [`CodecRegistry::resolve_tag_candidates`].
817///
818/// Ordered by the registry's resolution rule — `confidence`
819/// descending, then `priority` ascending (lower is preferred), then
820/// `order` ascending (earlier registration wins) — so the first
821/// element is exactly what [`CodecRegistry::resolve_tag_ref`] returns.
822/// `#[non_exhaustive]`: read by field, never constructed by callers.
823#[non_exhaustive]
824#[derive(Clone, Copy, Debug, PartialEq)]
825pub struct TagCandidate<'a> {
826    /// Codec id of the claiming registration.
827    pub id: &'a CodecId,
828    /// Probe confidence for this context (`1.0` for unprobed claims;
829    /// never `<= 0.0` — such claims are not candidates).
830    pub confidence: crate::Confidence,
831    /// Claim tie-break priority (see [`CodecInfo::resolution_priority`]).
832    pub priority: i32,
833    /// 0-based registration sequence number (one per
834    /// [`CodecRegistry::register`] call) — the final tie-break. The
835    /// same id can appear more than once when it registered the claim
836    /// twice; the registry does not fold duplicates.
837    pub order: usize,
838}
839
840/// One ranked entry from [`CodecRegistry::resolve_payload_magic_candidates`].
841///
842/// Ordered by the registry's resolution rule — magic length
843/// descending (most specific prefix), then `priority` ascending, then
844/// `order` ascending — so the first element is exactly what
845/// [`CodecRegistry::resolve_payload_magic_ref`] returns.
846#[non_exhaustive]
847#[derive(Clone, Copy, Debug, PartialEq, Eq)]
848pub struct PayloadMagicCandidate<'a> {
849    /// Codec id of the claiming registration.
850    pub id: &'a CodecId,
851    /// The magic prefix that matched.
852    pub magic: &'a [u8],
853    /// Claim tie-break priority (see [`CodecInfo::resolution_priority`]).
854    pub priority: i32,
855    /// 0-based registration sequence number — the final tie-break.
856    pub order: usize,
857}
858
859impl CodecRegistry {
860    /// An empty registry (same as `Default`).
861    pub fn new() -> Self {
862        Self::default()
863    }
864
865    /// Register one codec. Expands into:
866    ///   * an entry in the id → implementations map (for
867    ///     `make_decoder` / `make_encoder`);
868    ///   * an entry in the tag index for every claimed tag (for
869    ///     `resolve_tag`).
870    ///
871    /// Calling `register` multiple times with the same id is allowed
872    /// and how multi-implementation codecs (software-plus-hardware
873    /// FLAC, for example) are expressed.
874    pub fn register(&mut self, info: CodecInfo) {
875        let CodecInfo {
876            id,
877            capabilities,
878            decoder_factory,
879            encoder_factory,
880            probe,
881            tags,
882            payload_magics,
883            encoder_options_schema,
884            decoder_options_schema,
885            // engine_id / engine_probe are metadata attached to a
886            // CodecInfo for backends that want consumers (CLI `info`,
887            // pipeline bench) to enumerate the underlying devices on
888            // demand. They're surfaced verbatim on the resulting
889            // CodecImplementation so consumers can read them without
890            // grepping `caps.implementation`. Tag-only CodecInfo entries
891            // (no factories) drop the values on the floor — there's no
892            // CodecImplementation built in that branch.
893            engine_id,
894            engine_probe,
895            resolution_priority,
896        } = info;
897
898        let caps = {
899            let mut c = capabilities;
900            if decoder_factory.is_some() {
901                c = c.with_decode();
902            }
903            if encoder_factory.is_some() {
904                c = c.with_encode();
905            }
906            c
907        };
908
909        // Only record an implementation entry when at least one factory
910        // is present. A "tag-only" CodecInfo — used to attach extra tag
911        // claims to a codec that was already registered with factories —
912        // shouldn't pollute the impl list.
913        if decoder_factory.is_some() || encoder_factory.is_some() {
914            let slot = self.impls.entry(id.clone()).or_default();
915            if slot.is_empty() {
916                self.impl_order.push(id.clone());
917            }
918            slot.push(CodecImplementation {
919                caps,
920                make_decoder: decoder_factory,
921                make_encoder: encoder_factory,
922                encoder_options_schema,
923                decoder_options_schema,
924                engine_id,
925                engine_probe,
926            });
927        }
928
929        let record_idx = self.registrations.len();
930        for tag in &tags {
931            self.tag_index
932                .entry(tag.clone())
933                .or_default()
934                .push(record_idx);
935        }
936        self.registrations.push(RegistrationRecord {
937            id: id.clone(),
938            probe,
939            priority: resolution_priority,
940            tags,
941        });
942        for magic in payload_magics {
943            // A zero-length prefix would match every stream while
944            // carrying no evidence — drop it here so resolution never
945            // has to special-case it.
946            if !magic.is_empty() {
947                self.magic_index.push((magic, record_idx));
948            }
949        }
950    }
951
952    /// Whether at least one registered implementation of `id` can decode.
953    pub fn has_decoder(&self, id: &CodecId) -> bool {
954        self.impls
955            .get(id)
956            .map(|v| v.iter().any(|i| i.make_decoder.is_some()))
957            .unwrap_or(false)
958    }
959
960    /// Whether at least one registered implementation of `id` can encode.
961    pub fn has_encoder(&self, id: &CodecId) -> bool {
962        self.impls
963            .get(id)
964            .map(|v| v.iter().any(|i| i.make_encoder.is_some()))
965            .unwrap_or(false)
966    }
967
968    /// First registered decoder factory for `params.codec_id`, invoked
969    /// with `params`. No priority walk, no preference filter, no
970    /// init-time fallback to a lower-priority impl. Errors if no
971    /// decoder is registered for the codec.
972    ///
973    /// Intended for single-impl scenarios — typically a codec crate's
974    /// own self-tests, where exactly one impl has been registered into
975    /// a freshly-constructed registry. Production callers selecting
976    /// among multiple candidates (e.g. h264_sw vs h264_videotoolbox)
977    /// should use `oxideav_pipeline::make_decoder_with` instead, which
978    /// applies `CodecPreferences` and walks priorities.
979    pub fn first_decoder(&self, params: &CodecParameters) -> Result<Box<dyn Decoder>> {
980        let imp = self
981            .implementations(&params.codec_id)
982            .iter()
983            .find(|i| i.make_decoder.is_some())
984            .ok_or_else(|| {
985                Error::CodecNotFound(format!("no decoder for codec {}", params.codec_id))
986            })?;
987        (imp.make_decoder.expect("checked above"))(params)
988    }
989
990    /// First registered encoder factory — see [`first_decoder`].
991    ///
992    /// [`first_decoder`]: Self::first_decoder
993    pub fn first_encoder(&self, params: &CodecParameters) -> Result<Box<dyn Encoder>> {
994        let imp = self
995            .implementations(&params.codec_id)
996            .iter()
997            .find(|i| i.make_encoder.is_some())
998            .ok_or_else(|| {
999                Error::CodecNotFound(format!("no encoder for codec {}", params.codec_id))
1000            })?;
1001        (imp.make_encoder.expect("checked above"))(params)
1002    }
1003
1004    /// Look up a decoder by exact implementation name
1005    /// (`"h264_sw"`, `"aac_audiotoolbox"`, ...). Errors if the impl
1006    /// isn't registered or if it has no decoder factory.
1007    pub fn decoder_by_impl(
1008        &self,
1009        impl_name: &str,
1010        params: &CodecParameters,
1011    ) -> Result<Box<dyn Decoder>> {
1012        let imp = self
1013            .implementations(&params.codec_id)
1014            .iter()
1015            .find(|i| i.caps.implementation == impl_name)
1016            .ok_or_else(|| {
1017                Error::CodecNotFound(format!(
1018                    "no implementation `{impl_name}` for codec {}",
1019                    params.codec_id
1020                ))
1021            })?;
1022        let factory = imp
1023            .make_decoder
1024            .ok_or_else(|| Error::CodecNotFound(format!("`{impl_name}` is encoder-only")))?;
1025        factory(params)
1026    }
1027
1028    /// Look up an encoder by exact implementation name — see
1029    /// [`decoder_by_impl`].
1030    ///
1031    /// [`decoder_by_impl`]: Self::decoder_by_impl
1032    pub fn encoder_by_impl(
1033        &self,
1034        impl_name: &str,
1035        params: &CodecParameters,
1036    ) -> Result<Box<dyn Encoder>> {
1037        let imp = self
1038            .implementations(&params.codec_id)
1039            .iter()
1040            .find(|i| i.caps.implementation == impl_name)
1041            .ok_or_else(|| {
1042                Error::CodecNotFound(format!(
1043                    "no implementation `{impl_name}` for codec {}",
1044                    params.codec_id
1045                ))
1046            })?;
1047        let factory = imp
1048            .make_encoder
1049            .ok_or_else(|| Error::CodecNotFound(format!("`{impl_name}` is decoder-only")))?;
1050        factory(params)
1051    }
1052
1053    /// Iterate codec ids that have at least one decoder implementation,
1054    /// in the order each id's first implementation was registered.
1055    pub fn decoder_ids(&self) -> impl Iterator<Item = &CodecId> {
1056        self.impl_order.iter().filter(|id| self.has_decoder(id))
1057    }
1058
1059    /// Iterate codec ids that have at least one encoder implementation,
1060    /// in the order each id's first implementation was registered.
1061    pub fn encoder_ids(&self) -> impl Iterator<Item = &CodecId> {
1062        self.impl_order.iter().filter(|id| self.has_encoder(id))
1063    }
1064
1065    /// All registered implementations of a given codec id.
1066    pub fn implementations(&self, id: &CodecId) -> &[CodecImplementation] {
1067        self.impls.get(id).map(|v| v.as_slice()).unwrap_or(&[])
1068    }
1069
1070    /// Lookup the encoder options schema for a registered codec. Walks
1071    /// implementations in registration order and returns the first
1072    /// schema found. `None` means either the codec isn't registered or
1073    /// no implementation declared an encoder schema.
1074    pub fn encoder_options_schema(&self, id: &CodecId) -> Option<&'static [OptionField]> {
1075        self.impls
1076            .get(id)?
1077            .iter()
1078            .find_map(|i| i.encoder_options_schema)
1079    }
1080
1081    /// Lookup the decoder options schema — see
1082    /// [`encoder_options_schema`](Self::encoder_options_schema).
1083    pub fn decoder_options_schema(&self, id: &CodecId) -> Option<&'static [OptionField]> {
1084        self.impls
1085            .get(id)?
1086            .iter()
1087            .find_map(|i| i.decoder_options_schema)
1088    }
1089
1090    /// Iterator over every (codec_id, impl) pair — useful for `oxideav list`
1091    /// to show capability flags per implementation. Ids come in the
1092    /// order their first implementation was registered; implementations
1093    /// of one id in their own registration order.
1094    pub fn all_implementations(&self) -> impl Iterator<Item = (&CodecId, &CodecImplementation)> {
1095        self.impl_order
1096            .iter()
1097            .flat_map(move |id| self.implementations(id).iter().map(move |i| (id, i)))
1098    }
1099
1100    /// Iterator over every `(tag, codec_id)` pair currently registered —
1101    /// used by `oxideav tags` debug output and by tests that want to
1102    /// walk the tag surface. Registration order, then each
1103    /// registration's tag declaration order.
1104    pub fn all_tag_registrations(&self) -> impl Iterator<Item = (&CodecTag, &CodecId)> {
1105        self.registrations
1106            .iter()
1107            .flat_map(|rec| rec.tags.iter().map(move |tag| (tag, &rec.id)))
1108    }
1109
1110    /// Inherent form of tag resolution that returns a reference.
1111    /// The owned-value form used by container code lives behind the
1112    /// [`CodecResolver`] trait impl below.
1113    ///
1114    /// Walks every registration that claimed `ctx.tag`, calls its
1115    /// probe with `ctx`, and returns the id of the registration that
1116    /// scored highest. Probes that return `0.0` (or anything not
1117    /// strictly positive, `NaN` included) are discarded; ties on
1118    /// confidence are broken by [`CodecInfo::resolution_priority`]
1119    /// (lower wins), then by registration order (first wins).
1120    /// Registrations with no probe are treated as returning `1.0`.
1121    /// [`resolve_tag_candidates`](Self::resolve_tag_candidates) returns
1122    /// the whole ranked list this picks the head of.
1123    pub fn resolve_tag_ref(&self, ctx: &ProbeContext) -> Option<&CodecId> {
1124        self.resolve_tag_candidates(ctx).first().map(|c| c.id)
1125    }
1126
1127    /// Every registration that claimed `ctx.tag` and whose probe
1128    /// accepts the context, ranked by the resolution rule: confidence
1129    /// descending, then priority ascending, then registration order
1130    /// ascending. Empty when the tag is unclaimed or every claimant's
1131    /// probe refused. The observation hook for collision audits: a
1132    /// list with two heads at equal confidence *and* equal priority is
1133    /// a tie the registry broke by registration order alone.
1134    pub fn resolve_tag_candidates(&self, ctx: &ProbeContext) -> Vec<TagCandidate<'_>> {
1135        let Some(idxs) = self.tag_index.get(ctx.tag) else {
1136            return Vec::new();
1137        };
1138        let mut out: Vec<TagCandidate<'_>> = idxs
1139            .iter()
1140            .filter_map(|&i| {
1141                let rec = &self.registrations[i];
1142                let confidence = match rec.probe {
1143                    Some(f) => f(ctx),
1144                    None => 1.0,
1145                };
1146                // `> 0.0` is false for NaN, so a broken probe is
1147                // dropped rather than ranked unpredictably.
1148                (confidence > 0.0).then_some(TagCandidate {
1149                    id: &rec.id,
1150                    confidence,
1151                    priority: rec.priority,
1152                    order: i,
1153                })
1154            })
1155            .collect();
1156        // `idxs` is already in registration order and `order` is
1157        // unique, so the sort key is total and the result is fixed by
1158        // the registrations alone.
1159        out.sort_by(|a, b| {
1160            b.confidence
1161                .partial_cmp(&a.confidence)
1162                .unwrap_or(std::cmp::Ordering::Equal)
1163                .then(a.priority.cmp(&b.priority))
1164                .then(a.order.cmp(&b.order))
1165        });
1166        out
1167    }
1168
1169    /// Inherent form of payload-magic resolution that returns a
1170    /// reference. The owned-value form used by container code lives
1171    /// behind the [`CodecResolver`] trait impl below.
1172    ///
1173    /// Walks every registered payload magic prefix (declared via
1174    /// [`CodecInfo::payload_magic`] / [`CodecInfo::payload_magics`]) and
1175    /// returns the codec whose magic is a prefix of `first_bytes` —
1176    /// however much of the stream's leading payload the caller has
1177    /// (an Ogg demuxer passes the first packet of a logical stream; a
1178    /// raw-stream prober passes the file head). The **longest**
1179    /// matching magic wins (most specific claim); remaining ties are
1180    /// broken by [`CodecInfo::resolution_priority`] (lower wins), then
1181    /// by registration order (first wins). Unlike the tag path there
1182    /// is no probe step: a payload magic is itself the bitstream
1183    /// evidence a probe would look for, and specificity is expressed
1184    /// by prefix length instead of a confidence value.
1185    /// [`resolve_payload_magic_candidates`](Self::resolve_payload_magic_candidates)
1186    /// returns the whole ranked list this picks the head of.
1187    pub fn resolve_payload_magic_ref(&self, first_bytes: &[u8]) -> Option<&CodecId> {
1188        self.resolve_payload_magic_candidates(first_bytes)
1189            .first()
1190            .map(|c| c.id)
1191    }
1192
1193    /// Every registered payload magic that is a prefix of
1194    /// `first_bytes`, ranked by the resolution rule: magic length
1195    /// descending, then priority ascending, then registration order
1196    /// ascending. The payload-magic companion to
1197    /// [`resolve_tag_candidates`](Self::resolve_tag_candidates).
1198    pub fn resolve_payload_magic_candidates(
1199        &self,
1200        first_bytes: &[u8],
1201    ) -> Vec<PayloadMagicCandidate<'_>> {
1202        let mut out: Vec<PayloadMagicCandidate<'_>> = self
1203            .magic_index
1204            .iter()
1205            .filter(|(magic, _)| first_bytes.starts_with(magic))
1206            .map(|(magic, i)| {
1207                let rec = &self.registrations[*i];
1208                PayloadMagicCandidate {
1209                    id: &rec.id,
1210                    magic: magic.as_slice(),
1211                    priority: rec.priority,
1212                    order: *i,
1213                }
1214            })
1215            .collect();
1216        // One registration may claim several magics that all match
1217        // (`order` then repeats); the stable sort keeps those in their
1218        // declaration order, which is the only remaining distinction
1219        // and is itself fixed by the registration.
1220        out.sort_by(|a, b| {
1221            b.magic
1222                .len()
1223                .cmp(&a.magic.len())
1224                .then(a.priority.cmp(&b.priority))
1225                .then(a.order.cmp(&b.order))
1226        });
1227        out
1228    }
1229
1230    /// Iterator over every `(payload magic, codec_id)` pair currently
1231    /// registered, in registration order — the payload-magic companion
1232    /// to [`all_tag_registrations`](Self::all_tag_registrations).
1233    pub fn all_payload_magic_registrations(&self) -> impl Iterator<Item = (&[u8], &CodecId)> {
1234        self.magic_index
1235            .iter()
1236            .map(move |(magic, i)| (magic.as_slice(), &self.registrations[*i].id))
1237    }
1238}
1239
1240/// Implement the shared [`CodecResolver`] interface so container
1241/// demuxers can accept `&dyn CodecResolver` without depending on
1242/// this crate directly — the trait lives in oxideav-core.
1243impl CodecResolver for CodecRegistry {
1244    fn resolve_tag(&self, ctx: &ProbeContext) -> Option<CodecId> {
1245        self.resolve_tag_ref(ctx).cloned()
1246    }
1247
1248    fn resolve_payload_magic(&self, first_packet: &[u8]) -> Option<CodecId> {
1249        self.resolve_payload_magic_ref(first_packet).cloned()
1250    }
1251}
1252
1253#[cfg(test)]
1254mod tag_tests {
1255    use super::*;
1256    use crate::CodecCapabilities;
1257
1258    /// Probe: return 1.0 iff the peeked bytes look like MS-MPEG4 (no
1259    /// 0x000001 start code in the first few bytes).
1260    fn probe_msmpeg4(ctx: &ProbeContext) -> f32 {
1261        match ctx.packet {
1262            Some(d) if !d.windows(3).take(6).any(|w| w == [0x00, 0x00, 0x01]) => 1.0,
1263            Some(_) => 0.0,
1264            None => 0.5, // no data yet — weak evidence
1265        }
1266    }
1267
1268    /// Probe: return 1.0 iff the peeked bytes look like MPEG-4 Part 2
1269    /// (starts with a 0x000001 start code in the first few bytes).
1270    fn probe_mpeg4_part2(ctx: &ProbeContext) -> f32 {
1271        match ctx.packet {
1272            Some(d) if d.windows(3).take(6).any(|w| w == [0x00, 0x00, 0x01]) => 1.0,
1273            Some(_) => 0.0,
1274            None => 0.5,
1275        }
1276    }
1277
1278    fn info(id: &str) -> CodecInfo {
1279        CodecInfo::new(CodecId::new(id)).capabilities(CodecCapabilities::audio(id))
1280    }
1281
1282    #[test]
1283    fn resolve_single_claim_no_probe() {
1284        let mut reg = CodecRegistry::new();
1285        reg.register(info("flac").tag(CodecTag::fourcc(b"FLAC")));
1286        let t = CodecTag::fourcc(b"FLAC");
1287        assert_eq!(
1288            reg.resolve_tag_ref(&ProbeContext::new(&t))
1289                .map(|c| c.as_str()),
1290            Some("flac"),
1291        );
1292    }
1293
1294    #[test]
1295    fn resolve_missing_tag_returns_none() {
1296        let reg = CodecRegistry::new();
1297        let t = CodecTag::fourcc(b"????");
1298        assert!(reg.resolve_tag_ref(&ProbeContext::new(&t)).is_none());
1299    }
1300
1301    #[test]
1302    fn unprobed_claims_tie_first_registered_wins() {
1303        // Two unprobed claims on the same tag: deterministic order.
1304        let mut reg = CodecRegistry::new();
1305        reg.register(info("first").tag(CodecTag::fourcc(b"TEST")));
1306        reg.register(info("second").tag(CodecTag::fourcc(b"TEST")));
1307        let t = CodecTag::fourcc(b"TEST");
1308        assert_eq!(
1309            reg.resolve_tag_ref(&ProbeContext::new(&t))
1310                .map(|c| c.as_str()),
1311            Some("first"),
1312        );
1313    }
1314
1315    #[test]
1316    fn probe_picks_matching_bitstream() {
1317        // The core bug fix: every probe is asked and the highest
1318        // confidence wins regardless of registration order.
1319        let mut reg = CodecRegistry::new();
1320        reg.register(
1321            info("msmpeg4v3")
1322                .probe(probe_msmpeg4)
1323                .tag(CodecTag::fourcc(b"DIV3")),
1324        );
1325        reg.register(
1326            info("mpeg4video")
1327                .probe(probe_mpeg4_part2)
1328                .tag(CodecTag::fourcc(b"DIV3")),
1329        );
1330
1331        let mpeg4_part2 = [0x00u8, 0x00, 0x01, 0xB0, 0x01, 0x00];
1332        let ms_mpeg4 = [0x85u8, 0x3F, 0xD4, 0x80, 0x00, 0xA2];
1333        let tag = CodecTag::fourcc(b"DIV3");
1334
1335        let ctx_part2 = ProbeContext::new(&tag).packet(&mpeg4_part2);
1336        assert_eq!(
1337            reg.resolve_tag_ref(&ctx_part2).map(|c| c.as_str()),
1338            Some("mpeg4video"),
1339        );
1340        let ctx_ms = ProbeContext::new(&tag).packet(&ms_mpeg4);
1341        assert_eq!(
1342            reg.resolve_tag_ref(&ctx_ms).map(|c| c.as_str()),
1343            Some("msmpeg4v3"),
1344        );
1345    }
1346
1347    #[test]
1348    fn unprobed_claim_wins_against_low_confidence_probe() {
1349        // One codec claims a tag without a probe (→ confidence 1.0)
1350        // and another claims it with a probe returning 0.3. The
1351        // unprobed one wins — a codec that knows it owns the tag
1352        // outright should not lose to a speculative probe.
1353        let mut reg = CodecRegistry::new();
1354        reg.register(info("owner").tag(CodecTag::fourcc(b"OWN_")));
1355        reg.register(
1356            info("speculative")
1357                .probe(|_| 0.3)
1358                .tag(CodecTag::fourcc(b"OWN_")),
1359        );
1360        let t = CodecTag::fourcc(b"OWN_");
1361        assert_eq!(
1362            reg.resolve_tag_ref(&ProbeContext::new(&t))
1363                .map(|c| c.as_str()),
1364            Some("owner"),
1365        );
1366    }
1367
1368    #[test]
1369    fn probe_returning_zero_is_skipped() {
1370        let mut reg = CodecRegistry::new();
1371        reg.register(
1372            info("refuses")
1373                .probe(|_| 0.0)
1374                .tag(CodecTag::fourcc(b"MAYB")),
1375        );
1376        reg.register(info("fallback").tag(CodecTag::fourcc(b"MAYB")));
1377        let t = CodecTag::fourcc(b"MAYB");
1378        let ctx = ProbeContext::new(&t).packet(b"hello");
1379        assert_eq!(
1380            reg.resolve_tag_ref(&ctx).map(|c| c.as_str()),
1381            Some("fallback"),
1382        );
1383    }
1384
1385    #[test]
1386    fn fourcc_case_insensitive_lookup() {
1387        let mut reg = CodecRegistry::new();
1388        reg.register(info("vid").tag(CodecTag::fourcc(b"div3")));
1389        // Registered as "DIV3" (uppercase via ctor); lookup using
1390        // lowercase / mixed case also hits.
1391        let upper = CodecTag::fourcc(b"DIV3");
1392        let lower = CodecTag::fourcc(b"div3");
1393        let mixed = CodecTag::fourcc(b"DiV3");
1394        assert!(reg.resolve_tag_ref(&ProbeContext::new(&upper)).is_some());
1395        assert!(reg.resolve_tag_ref(&ProbeContext::new(&lower)).is_some());
1396        assert!(reg.resolve_tag_ref(&ProbeContext::new(&mixed)).is_some());
1397    }
1398
1399    #[test]
1400    fn wave_format_and_matroska_tags_work() {
1401        let mut reg = CodecRegistry::new();
1402        reg.register(info("mp3").tag(CodecTag::wave_format(0x0055)));
1403        reg.register(info("h264").tag(CodecTag::matroska("V_MPEG4/ISO/AVC")));
1404        let wf = CodecTag::wave_format(0x0055);
1405        let mk = CodecTag::matroska("V_MPEG4/ISO/AVC");
1406        assert_eq!(
1407            reg.resolve_tag_ref(&ProbeContext::new(&wf))
1408                .map(|c| c.as_str()),
1409            Some("mp3"),
1410        );
1411        assert_eq!(
1412            reg.resolve_tag_ref(&ProbeContext::new(&mk))
1413                .map(|c| c.as_str()),
1414            Some("h264"),
1415        );
1416    }
1417
1418    #[test]
1419    fn mp4_object_type_tag_works() {
1420        let mut reg = CodecRegistry::new();
1421        reg.register(info("aac").tag(CodecTag::mp4_object_type(0x40)));
1422        let t = CodecTag::mp4_object_type(0x40);
1423        assert_eq!(
1424            reg.resolve_tag_ref(&ProbeContext::new(&t))
1425                .map(|c| c.as_str()),
1426            Some("aac"),
1427        );
1428    }
1429
1430    #[test]
1431    fn multi_tag_claim_all_resolve() {
1432        let mut reg = CodecRegistry::new();
1433        reg.register(info("aac").tags([
1434            CodecTag::fourcc(b"MP4A"),
1435            CodecTag::wave_format(0x00FF),
1436            CodecTag::mp4_object_type(0x40),
1437            CodecTag::matroska("A_AAC"),
1438        ]));
1439        for t in [
1440            CodecTag::fourcc(b"MP4A"),
1441            CodecTag::wave_format(0x00FF),
1442            CodecTag::mp4_object_type(0x40),
1443            CodecTag::matroska("A_AAC"),
1444        ] {
1445            assert_eq!(
1446                reg.resolve_tag_ref(&ProbeContext::new(&t))
1447                    .map(|c| c.as_str()),
1448                Some("aac"),
1449                "tag {t:?} did not resolve",
1450            );
1451        }
1452    }
1453}
1454
1455#[cfg(test)]
1456mod payload_magic_tests {
1457    use super::*;
1458    use crate::CodecCapabilities;
1459
1460    fn info(id: &str) -> CodecInfo {
1461        CodecInfo::new(CodecId::new(id)).capabilities(CodecCapabilities::audio(id))
1462    }
1463
1464    /// Registry with the classic Ogg family registered, each under its
1465    /// real BOS magic.
1466    fn ogg_family_registry() -> CodecRegistry {
1467        let mut reg = CodecRegistry::new();
1468        reg.register(info("vorbis").payload_magic(b"\x01vorbis"));
1469        reg.register(info("opus").payload_magic(b"OpusHead"));
1470        reg.register(info("theora").payload_magic(b"\x80theora"));
1471        reg.register(info("flac").payload_magic(b"\x7fFLAC"));
1472        reg
1473    }
1474
1475    #[test]
1476    fn resolve_payload_magic_matches_first_packet_prefix() {
1477        let reg = ogg_family_registry();
1478        // A Vorbis identification header: magic + version + channels +
1479        // rate + ... — the resolver only needs the prefix to match.
1480        let vorbis_id_header = b"\x01vorbis\x00\x00\x00\x00\x02\x44\xac\x00\x00";
1481        assert_eq!(
1482            reg.resolve_payload_magic_ref(vorbis_id_header)
1483                .map(|c| c.as_str()),
1484            Some("vorbis"),
1485        );
1486        assert_eq!(
1487            reg.resolve_payload_magic_ref(b"OpusHead\x01\x02\x38\x01")
1488                .map(|c| c.as_str()),
1489            Some("opus"),
1490        );
1491        assert_eq!(
1492            reg.resolve_payload_magic_ref(b"\x80theora\x03\x02\x01")
1493                .map(|c| c.as_str()),
1494            Some("theora"),
1495        );
1496        assert_eq!(
1497            reg.resolve_payload_magic_ref(b"\x7fFLAC\x01\x00")
1498                .map(|c| c.as_str()),
1499            Some("flac"),
1500        );
1501    }
1502
1503    #[test]
1504    fn resolve_payload_magic_exact_length_packet_matches() {
1505        // A packet that is exactly the magic (nothing after it) still
1506        // resolves — starts_with is inclusive of equality.
1507        let reg = ogg_family_registry();
1508        assert_eq!(
1509            reg.resolve_payload_magic_ref(b"OpusHead")
1510                .map(|c| c.as_str()),
1511            Some("opus"),
1512        );
1513    }
1514
1515    #[test]
1516    fn resolve_payload_magic_unknown_or_short_packet_is_none() {
1517        let reg = ogg_family_registry();
1518        // Unknown magic.
1519        assert!(reg.resolve_payload_magic_ref(b"Speex   1.2.0").is_none());
1520        // Packet shorter than every registered magic.
1521        assert!(reg.resolve_payload_magic_ref(b"Opus").is_none());
1522        // Empty packet.
1523        assert!(reg.resolve_payload_magic_ref(b"").is_none());
1524    }
1525
1526    #[test]
1527    fn resolve_payload_magic_longest_prefix_wins_regardless_of_order() {
1528        // A shorter magic that is itself a prefix of a longer one must
1529        // lose to the more specific claim, whichever registered first.
1530        let mut reg = CodecRegistry::new();
1531        reg.register(info("generic").payload_magic(b"Opus"));
1532        reg.register(info("opus").payload_magic(b"OpusHead"));
1533        assert_eq!(
1534            reg.resolve_payload_magic_ref(b"OpusHead\x01")
1535                .map(|c| c.as_str()),
1536            Some("opus"),
1537        );
1538        // ...but the shorter claim still wins packets only it matches.
1539        assert_eq!(
1540            reg.resolve_payload_magic_ref(b"OpusTags")
1541                .map(|c| c.as_str()),
1542            Some("generic"),
1543        );
1544
1545        // Same result with the registration order flipped.
1546        let mut reg = CodecRegistry::new();
1547        reg.register(info("opus").payload_magic(b"OpusHead"));
1548        reg.register(info("generic").payload_magic(b"Opus"));
1549        assert_eq!(
1550            reg.resolve_payload_magic_ref(b"OpusHead\x01")
1551                .map(|c| c.as_str()),
1552            Some("opus"),
1553        );
1554    }
1555
1556    #[test]
1557    fn resolve_payload_magic_equal_length_tie_first_registered_wins() {
1558        let mut reg = CodecRegistry::new();
1559        reg.register(info("first").payload_magic(b"SameMagic"));
1560        reg.register(info("second").payload_magic(b"SameMagic"));
1561        assert_eq!(
1562            reg.resolve_payload_magic_ref(b"SameMagic\x00")
1563                .map(|c| c.as_str()),
1564            Some("first"),
1565        );
1566    }
1567
1568    #[test]
1569    fn empty_payload_magic_is_ignored_at_registration() {
1570        let mut reg = CodecRegistry::new();
1571        reg.register(info("greedy").payload_magic(b""));
1572        assert!(reg.resolve_payload_magic_ref(b"anything at all").is_none());
1573        assert_eq!(reg.all_payload_magic_registrations().count(), 0);
1574    }
1575
1576    #[test]
1577    fn payload_magics_plural_builder_and_diagnostics() {
1578        // One codec answering to several magics via the iterable
1579        // builder; the diagnostic iterator surfaces each claim in
1580        // registration order.
1581        let mut reg = CodecRegistry::new();
1582        reg.register(info("speex").payload_magics([b"Speex   ".to_vec(), b"speex-alt".to_vec()]));
1583        assert_eq!(
1584            reg.resolve_payload_magic_ref(b"Speex   1.2")
1585                .map(|c| c.as_str()),
1586            Some("speex"),
1587        );
1588        assert_eq!(
1589            reg.resolve_payload_magic_ref(b"speex-alt\x00")
1590                .map(|c| c.as_str()),
1591            Some("speex"),
1592        );
1593        let all: Vec<(&[u8], &str)> = reg
1594            .all_payload_magic_registrations()
1595            .map(|(m, id)| (m, id.as_str()))
1596            .collect();
1597        assert_eq!(
1598            all,
1599            vec![
1600                (b"Speex   ".as_slice(), "speex"),
1601                (b"speex-alt".as_slice(), "speex"),
1602            ],
1603        );
1604    }
1605
1606    #[test]
1607    fn magic_claims_compose_with_tag_claims_on_one_registration() {
1608        // A codec that lives in both Ogg and Matroska declares both
1609        // claim kinds on one CodecInfo; each resolution path finds it.
1610        let mut reg = CodecRegistry::new();
1611        reg.register(
1612            info("vorbis")
1613                .tag(CodecTag::matroska("A_VORBIS"))
1614                .payload_magic(b"\x01vorbis"),
1615        );
1616        let mk = CodecTag::matroska("A_VORBIS");
1617        assert_eq!(
1618            reg.resolve_tag_ref(&ProbeContext::new(&mk))
1619                .map(|c| c.as_str()),
1620            Some("vorbis"),
1621        );
1622        assert_eq!(
1623            reg.resolve_payload_magic_ref(b"\x01vorbis\x00")
1624                .map(|c| c.as_str()),
1625            Some("vorbis"),
1626        );
1627    }
1628
1629    #[test]
1630    fn resolver_trait_payload_magic_surface() {
1631        // The owned-value trait form mirrors the inherent form, and
1632        // the default implementation (NullCodecResolver) resolves
1633        // nothing.
1634        let reg = ogg_family_registry();
1635        let resolver: &dyn CodecResolver = &reg;
1636        assert_eq!(
1637            resolver
1638                .resolve_payload_magic(b"OpusHead\x01")
1639                .map(|c| c.0.clone()),
1640            Some("opus".to_owned()),
1641        );
1642        assert!(resolver.resolve_payload_magic(b"unknown").is_none());
1643
1644        let null = crate::NullCodecResolver;
1645        assert!(null.resolve_payload_magic(b"OpusHead\x01").is_none());
1646    }
1647
1648    /// The surface is container-agnostic: a raw elementary stream
1649    /// identified by a file-head magic resolves through the same path
1650    /// as the Ogg family — nothing about the mechanism is Ogg-shaped.
1651    #[test]
1652    fn payload_magic_serves_non_ogg_carriage() {
1653        let mut reg = CodecRegistry::new();
1654        reg.register(info("flac").payload_magic(b"fLaC"));
1655        reg.register(info("shorten").payload_magic(b"ajkg"));
1656
1657        assert_eq!(
1658            reg.resolve_payload_magic_ref(b"fLaC\x00\x00\x00\x22"),
1659            Some(&CodecId::new("flac"))
1660        );
1661        assert_eq!(
1662            reg.resolve_payload_magic_ref(b"ajkg\x02"),
1663            Some(&CodecId::new("shorten"))
1664        );
1665        assert_eq!(reg.resolve_payload_magic_ref(b"RIFF"), None);
1666    }
1667}
1668
1669/// Resolution-order tests. Every id / tag / magic here is invented:
1670/// the rule is format-agnostic and must be provable with synthetic
1671/// registrations only.
1672#[cfg(test)]
1673mod resolution_order_tests {
1674    use super::*;
1675    use crate::CodecCapabilities;
1676
1677    fn info(id: &str) -> CodecInfo {
1678        CodecInfo::new(CodecId::new(id)).capabilities(CodecCapabilities::audio(id))
1679    }
1680
1681    fn tag_ids<'a>(cands: &[TagCandidate<'a>]) -> Vec<&'a str> {
1682        cands.iter().map(|c| c.id.as_str()).collect()
1683    }
1684
1685    fn magic_ids<'a>(cands: &[PayloadMagicCandidate<'a>]) -> Vec<&'a str> {
1686        cands.iter().map(|c| c.id.as_str()).collect()
1687    }
1688
1689    #[test]
1690    fn codec_info_resolution_priority_defaults_and_builder() {
1691        assert_eq!(info("x").resolution_priority, crate::DEFAULT_PRIORITY);
1692        assert_eq!(info("x").with_resolution_priority(7).resolution_priority, 7);
1693    }
1694
1695    #[test]
1696    fn equal_tag_claims_resolve_by_registration_order_across_fresh_contexts() {
1697        const ORDER: [&str; 5] = ["zeta", "alpha", "omicron", "beta", "kappa"];
1698        let tag = CodecTag::fourcc(b"SYNT");
1699        for _ in 0..1000 {
1700            let mut ctx = crate::RuntimeContext::new();
1701            for id in ORDER {
1702                ctx.codecs.register(info(id).tag(tag.clone()));
1703            }
1704            let pc = ProbeContext::new(&tag);
1705            assert_eq!(
1706                ctx.codecs.resolve_tag_ref(&pc).map(|c| c.as_str()),
1707                Some("zeta")
1708            );
1709            let cands = ctx.codecs.resolve_tag_candidates(&pc);
1710            assert_eq!(tag_ids(&cands), ORDER.to_vec());
1711            assert_eq!(
1712                cands.iter().map(|c| c.order).collect::<Vec<_>>(),
1713                vec![0, 1, 2, 3, 4]
1714            );
1715        }
1716    }
1717
1718    #[test]
1719    fn equal_magic_claims_resolve_by_registration_order_across_fresh_contexts() {
1720        const ORDER: [&str; 4] = ["zeta", "alpha", "omicron", "beta"];
1721        for _ in 0..1000 {
1722            let mut ctx = crate::RuntimeContext::new();
1723            for id in ORDER {
1724                ctx.codecs.register(info(id).payload_magic(b"SYNTHMAGIC"));
1725            }
1726            assert_eq!(
1727                ctx.codecs
1728                    .resolve_payload_magic_ref(b"SYNTHMAGIC\x00")
1729                    .map(|c| c.as_str()),
1730                Some("zeta")
1731            );
1732            let cands = ctx
1733                .codecs
1734                .resolve_payload_magic_candidates(b"SYNTHMAGIC\x00");
1735            assert_eq!(magic_ids(&cands), ORDER.to_vec());
1736        }
1737    }
1738
1739    #[test]
1740    fn tag_priority_beats_registration_order() {
1741        let tag = CodecTag::wave_format(0x7777);
1742        let mut reg = CodecRegistry::new();
1743        reg.register(info("earlier").tag(tag.clone()));
1744        reg.register(
1745            info("later-preferred")
1746                .with_resolution_priority(10)
1747                .tag(tag.clone()),
1748        );
1749        let pc = ProbeContext::new(&tag);
1750        assert_eq!(
1751            reg.resolve_tag_ref(&pc).map(|c| c.as_str()),
1752            Some("later-preferred")
1753        );
1754        let cands = reg.resolve_tag_candidates(&pc);
1755        assert_eq!(tag_ids(&cands), vec!["later-preferred", "earlier"]);
1756        assert_eq!(cands[0].priority, 10);
1757        assert_eq!(cands[0].order, 1);
1758        assert_eq!(cands[1].priority, crate::DEFAULT_PRIORITY);
1759        assert_eq!(cands[1].order, 0);
1760        assert_eq!(cands[0].confidence, 1.0);
1761    }
1762
1763    #[test]
1764    fn tag_confidence_beats_priority() {
1765        // A probe that positively identifies the payload wins against
1766        // an unprobed-but-top-priority claim only when its confidence
1767        // is higher; at 1.0 vs 1.0 the priority decides.
1768        let tag = CodecTag::fourcc(b"AMBI");
1769        let mut reg = CodecRegistry::new();
1770        reg.register(
1771            info("prioritised")
1772                .with_resolution_priority(i32::MIN)
1773                .probe(|_| 0.6)
1774                .tag(tag.clone()),
1775        );
1776        reg.register(info("certain").tag(tag.clone()));
1777        let pc = ProbeContext::new(&tag);
1778        assert_eq!(
1779            reg.resolve_tag_ref(&pc).map(|c| c.as_str()),
1780            Some("certain")
1781        );
1782        let cands = reg.resolve_tag_candidates(&pc);
1783        assert_eq!(tag_ids(&cands), vec!["certain", "prioritised"]);
1784    }
1785
1786    #[test]
1787    fn tag_candidates_drop_refusing_and_non_finite_probes() {
1788        let tag = CodecTag::fourcc(b"NANP");
1789        let mut reg = CodecRegistry::new();
1790        reg.register(info("refuses").probe(|_| 0.0).tag(tag.clone()));
1791        reg.register(info("broken").probe(|_| f32::NAN).tag(tag.clone()));
1792        reg.register(info("negative").probe(|_| -1.0).tag(tag.clone()));
1793        reg.register(info("accepts").probe(|_| 0.2).tag(tag.clone()));
1794        let pc = ProbeContext::new(&tag);
1795        assert_eq!(tag_ids(&reg.resolve_tag_candidates(&pc)), vec!["accepts"]);
1796        assert_eq!(
1797            reg.resolve_tag_ref(&pc).map(|c| c.as_str()),
1798            Some("accepts")
1799        );
1800        // An unclaimed tag yields an empty list, not an error.
1801        let other = CodecTag::fourcc(b"NONE");
1802        assert!(
1803            reg.resolve_tag_candidates(&ProbeContext::new(&other))
1804                .is_empty()
1805        );
1806    }
1807
1808    #[test]
1809    fn duplicate_tag_claim_by_one_id_is_visible_not_folded() {
1810        // The registry contract allows registering one id several
1811        // times (multi-implementation codecs). A tag claimed twice by
1812        // the same id resolves to that id either way; the candidate
1813        // list shows both claims so an audit can flag the redundancy.
1814        let tag = CodecTag::fourcc(b"TWIC");
1815        let mut reg = CodecRegistry::new();
1816        reg.register(info("dup").tag(tag.clone()));
1817        reg.register(info("other").tag(tag.clone()));
1818        reg.register(info("dup").tag(tag.clone()));
1819        let pc = ProbeContext::new(&tag);
1820        let cands = reg.resolve_tag_candidates(&pc);
1821        assert_eq!(tag_ids(&cands), vec!["dup", "other", "dup"]);
1822        assert_eq!(
1823            cands.iter().map(|c| c.order).collect::<Vec<_>>(),
1824            vec![0, 1, 2]
1825        );
1826        assert_eq!(reg.resolve_tag_ref(&pc).map(|c| c.as_str()), Some("dup"));
1827    }
1828
1829    #[test]
1830    fn magic_priority_beats_registration_order_but_not_length() {
1831        let mut reg = CodecRegistry::new();
1832        reg.register(info("earlier").payload_magic(b"MAGIC"));
1833        reg.register(
1834            info("later-preferred")
1835                .with_resolution_priority(1)
1836                .payload_magic(b"MAGIC"),
1837        );
1838        reg.register(info("longer").payload_magic(b"MAGICAL"));
1839        // Equal-length tie: priority decides.
1840        let cands = reg.resolve_payload_magic_candidates(b"MAGIC\x00");
1841        assert_eq!(magic_ids(&cands), vec!["later-preferred", "earlier"]);
1842        assert_eq!(cands[0].order, 1);
1843        assert_eq!(cands[0].magic, b"MAGIC");
1844        // A longer matching magic beats both regardless of priority.
1845        let cands = reg.resolve_payload_magic_candidates(b"MAGICAL\x00");
1846        assert_eq!(
1847            magic_ids(&cands),
1848            vec!["longer", "later-preferred", "earlier"]
1849        );
1850        assert_eq!(
1851            reg.resolve_payload_magic_ref(b"MAGICAL\x00")
1852                .map(|c| c.as_str()),
1853            Some("longer")
1854        );
1855        // Nothing matches: empty list, None.
1856        assert!(reg.resolve_payload_magic_candidates(b"other").is_empty());
1857        assert!(reg.resolve_payload_magic_ref(b"other").is_none());
1858    }
1859
1860    fn dec(_p: &crate::CodecParameters) -> crate::Result<Box<dyn Decoder>> {
1861        Err(Error::unsupported("dummy"))
1862    }
1863    fn enc(_p: &crate::CodecParameters) -> crate::Result<Box<dyn Encoder>> {
1864        Err(Error::unsupported("dummy"))
1865    }
1866
1867    #[test]
1868    fn enumerations_follow_registration_order() {
1869        for _ in 0..200 {
1870            let mut reg = CodecRegistry::new();
1871            reg.register(
1872                info("zeta")
1873                    .decoder(dec)
1874                    .tags([CodecTag::fourcc(b"ZET1"), CodecTag::fourcc(b"ZET2")]),
1875            );
1876            reg.register(info("alpha").encoder(enc).tag(CodecTag::fourcc(b"ALPH")));
1877            reg.register(info("omicron").decoder(dec).encoder(enc));
1878            // Second impl of an existing id does not move it.
1879            reg.register(info("zeta").encoder(enc).tag(CodecTag::fourcc(b"ZET3")));
1880            // Tag-only registration: no impl, but its tags are listed.
1881            reg.register(info("beta").tag(CodecTag::fourcc(b"BETA")));
1882
1883            let ids: Vec<&str> = reg
1884                .all_implementations()
1885                .map(|(id, _)| id.as_str())
1886                .collect();
1887            assert_eq!(ids, vec!["zeta", "zeta", "alpha", "omicron"]);
1888            let dec_ids: Vec<&str> = reg.decoder_ids().map(|i| i.as_str()).collect();
1889            assert_eq!(dec_ids, vec!["zeta", "omicron"]);
1890            let enc_ids: Vec<&str> = reg.encoder_ids().map(|i| i.as_str()).collect();
1891            assert_eq!(enc_ids, vec!["zeta", "alpha", "omicron"]);
1892            let tags: Vec<(String, &str)> = reg
1893                .all_tag_registrations()
1894                .map(|(t, id)| (format!("{t:?}"), id.as_str()))
1895                .collect();
1896            let want: Vec<(String, &str)> = [
1897                (CodecTag::fourcc(b"ZET1"), "zeta"),
1898                (CodecTag::fourcc(b"ZET2"), "zeta"),
1899                (CodecTag::fourcc(b"ALPH"), "alpha"),
1900                (CodecTag::fourcc(b"ZET3"), "zeta"),
1901                (CodecTag::fourcc(b"BETA"), "beta"),
1902            ]
1903            .into_iter()
1904            .map(|(t, id)| (format!("{t:?}"), id))
1905            .collect();
1906            assert_eq!(tags, want);
1907        }
1908    }
1909
1910    #[test]
1911    fn resolution_priority_is_independent_of_capabilities_priority() {
1912        // A registration that ranks itself first as an *implementation*
1913        // (HW-style capabilities priority) does not thereby win a tag
1914        // tie against a different codec id registered earlier.
1915        let tag = CodecTag::fourcc(b"SHRD");
1916        let mut reg = CodecRegistry::new();
1917        reg.register(info("sw-id").tag(tag.clone()));
1918        reg.register(
1919            CodecInfo::new(CodecId::new("hw-id"))
1920                .capabilities(CodecCapabilities::video("hw-id").with_priority(10))
1921                .tag(tag.clone()),
1922        );
1923        let pc = ProbeContext::new(&tag);
1924        assert_eq!(reg.resolve_tag_ref(&pc).map(|c| c.as_str()), Some("sw-id"));
1925        let cands = reg.resolve_tag_candidates(&pc);
1926        assert!(cands.iter().all(|c| c.priority == crate::DEFAULT_PRIORITY));
1927    }
1928}
1929
1930#[cfg(test)]
1931mod engine_tests {
1932    use super::*;
1933    use crate::engine::HwDeviceInfo;
1934
1935    #[test]
1936    fn codec_info_engine_id_and_probe_default_to_none() {
1937        let ci = CodecInfo::new(CodecId::new("h264"));
1938        assert!(ci.engine_id.is_none());
1939        assert!(ci.engine_probe.is_none());
1940    }
1941
1942    #[test]
1943    fn codec_info_engine_builder_methods_set_fields() {
1944        fn dummy_probe() -> Vec<HwDeviceInfo> {
1945            vec![]
1946        }
1947        let ci = CodecInfo::new(CodecId::new("h264"))
1948            .with_engine_id("nvidia")
1949            .with_engine_probe(dummy_probe);
1950        assert_eq!(ci.engine_id, Some("nvidia"));
1951        assert!(ci.engine_probe.is_some());
1952        let probe = ci.engine_probe.unwrap();
1953        let result = probe();
1954        assert!(result.is_empty());
1955    }
1956
1957    #[test]
1958    fn registering_codec_with_engine_metadata_does_not_panic() {
1959        // The new fields are passthrough metadata — register() should
1960        // accept them without affecting existing id/tag bookkeeping.
1961        fn dummy_probe() -> Vec<HwDeviceInfo> {
1962            vec![]
1963        }
1964        let mut reg = CodecRegistry::new();
1965        reg.register(
1966            CodecInfo::new(CodecId::new("h264"))
1967                .capabilities(CodecCapabilities::audio("h264_nvdec"))
1968                .tag(CodecTag::fourcc(b"H264"))
1969                .with_engine_id("nvidia")
1970                .with_engine_probe(dummy_probe),
1971        );
1972        let t = CodecTag::fourcc(b"H264");
1973        assert_eq!(
1974            reg.resolve_tag_ref(&ProbeContext::new(&t))
1975                .map(|c| c.as_str()),
1976            Some("h264"),
1977        );
1978    }
1979
1980    /// No-op decoder factory so the registration produces a real
1981    /// CodecImplementation (the registry skips tag-only entries —
1982    /// without a factory there'd be nothing in `implementations()`
1983    /// to assert against).
1984    fn dummy_decoder_factory(
1985        _params: &crate::CodecParameters,
1986    ) -> crate::Result<Box<dyn super::Decoder>> {
1987        Err(crate::Error::unsupported("dummy decoder"))
1988    }
1989
1990    #[test]
1991    fn engine_metadata_propagates_through_register() {
1992        fn dummy_probe() -> Vec<HwDeviceInfo> {
1993            vec![]
1994        }
1995        let mut reg = CodecRegistry::default();
1996        reg.register(
1997            CodecInfo::new(CodecId::new("h264"))
1998                .capabilities(CodecCapabilities::video("h264_test"))
1999                .decoder(dummy_decoder_factory)
2000                .with_engine_id("test-backend")
2001                .with_engine_probe(dummy_probe),
2002        );
2003        let impls = reg.implementations(&CodecId::new("h264"));
2004        assert_eq!(impls.len(), 1);
2005        assert_eq!(impls[0].engine_id, Some("test-backend"));
2006        assert!(impls[0].engine_probe.is_some());
2007    }
2008
2009    #[test]
2010    fn engine_metadata_absent_for_sw_codecs() {
2011        // SW codecs don't call the engine builders — both fields
2012        // should land as None on the resulting CodecImplementation.
2013        let mut reg = CodecRegistry::default();
2014        reg.register(
2015            CodecInfo::new(CodecId::new("flac"))
2016                .capabilities(CodecCapabilities::audio("flac_sw"))
2017                .decoder(dummy_decoder_factory),
2018        );
2019        let impls = reg.implementations(&CodecId::new("flac"));
2020        assert_eq!(impls.len(), 1);
2021        assert!(impls[0].engine_id.is_none());
2022        assert!(impls[0].engine_probe.is_none());
2023    }
2024}
2025
2026#[cfg(test)]
2027mod output_params_tests {
2028    use super::*;
2029    use crate::{
2030        ChannelLayout, ColorRange, ColorSignal, MediaType, Rational, SampleFormat, VideoFrame,
2031    };
2032
2033    /// Shared plumbing for the mocks: the codec id they report.
2034    struct Base {
2035        id: CodecId,
2036    }
2037
2038    impl Base {
2039        fn new(id: &str) -> Self {
2040            Self {
2041                id: CodecId::new(id),
2042            }
2043        }
2044    }
2045
2046    /// Implements nothing of the output-description surface.
2047    struct Neither(Base);
2048
2049    impl Decoder for Neither {
2050        fn codec_id(&self) -> &CodecId {
2051            &self.0.id
2052        }
2053        fn send_packet(&mut self, _: &Packet) -> Result<()> {
2054            Ok(())
2055        }
2056        fn receive_frame(&mut self) -> Result<Frame> {
2057            Err(Error::NeedMore)
2058        }
2059        fn flush(&mut self) -> Result<()> {
2060            Ok(())
2061        }
2062    }
2063
2064    /// Implements only the older narrow query.
2065    struct PixOnly(Base);
2066
2067    impl Decoder for PixOnly {
2068        fn codec_id(&self) -> &CodecId {
2069            &self.0.id
2070        }
2071        fn send_packet(&mut self, _: &Packet) -> Result<()> {
2072            Ok(())
2073        }
2074        fn receive_frame(&mut self) -> Result<Frame> {
2075            Err(Error::NeedMore)
2076        }
2077        fn flush(&mut self) -> Result<()> {
2078            Ok(())
2079        }
2080        fn output_pixel_format(&self) -> Option<PixelFormat> {
2081            Some(PixelFormat::Yuv420P10Le)
2082        }
2083    }
2084
2085    /// A decoder that changes resolution mid-stream: every packet whose
2086    /// first byte is non-zero is a "keyframe" announcing that byte as
2087    /// the new height; the shape becomes visible with the first frame
2088    /// decoded from it, following the trait contract.
2089    struct Switching {
2090        base: Base,
2091        queued: std::collections::VecDeque<u32>,
2092        current: Option<u32>,
2093        generation: u64,
2094    }
2095
2096    impl Switching {
2097        fn new() -> Self {
2098            Self {
2099                base: Base::new("mock-switch"),
2100                queued: Default::default(),
2101                current: None,
2102                generation: 0,
2103            }
2104        }
2105    }
2106
2107    impl Decoder for Switching {
2108        fn codec_id(&self) -> &CodecId {
2109            &self.base.id
2110        }
2111        fn send_packet(&mut self, packet: &Packet) -> Result<()> {
2112            let h = packet.data.first().copied().unwrap_or(0) as u32;
2113            let h = if h == 0 {
2114                *self.queued.back().or(self.current.as_ref()).unwrap_or(&16)
2115            } else {
2116                h
2117            };
2118            self.queued.push_back(h);
2119            Ok(())
2120        }
2121        fn receive_frame(&mut self) -> Result<Frame> {
2122            let h = self.queued.pop_front().ok_or(Error::NeedMore)?;
2123            if let Some(cur) = self.current
2124                && cur != h
2125            {
2126                self.generation = self.generation.wrapping_add(1);
2127            }
2128            self.current = Some(h);
2129            Ok(Frame::Video(VideoFrame {
2130                pts: None,
2131                planes: Vec::new(),
2132            }))
2133        }
2134        fn flush(&mut self) -> Result<()> {
2135            Ok(())
2136        }
2137        fn output_params(&self) -> Option<CodecParameters> {
2138            let h = self.current?;
2139            let mut p = CodecParameters::video(self.base.id.clone());
2140            p.width = Some(32);
2141            p.height = Some(h);
2142            p.pixel_format = Some(PixelFormat::Yuv420P);
2143            Some(p)
2144        }
2145        fn output_pixel_format(&self) -> Option<PixelFormat> {
2146            self.output_params().and_then(|p| p.pixel_format)
2147        }
2148        fn output_params_generation(&self) -> u64 {
2149            self.generation
2150        }
2151    }
2152
2153    fn pkt(b: u8) -> Packet {
2154        Packet::new(0, crate::TimeBase::new(1, 1), vec![b])
2155    }
2156
2157    #[test]
2158    fn default_without_any_answer_is_none_and_generation_zero() {
2159        let d = Neither(Base::new("mock"));
2160        assert!(d.output_params().is_none());
2161        assert_eq!(d.output_params_generation(), 0);
2162    }
2163
2164    #[test]
2165    fn default_derives_from_output_pixel_format() {
2166        let d = PixOnly(Base::new("mock-pix"));
2167        let p = d.output_params().expect("derived from output_pixel_format");
2168        assert_eq!(p.codec_id, CodecId::new("mock-pix"));
2169        assert_eq!(p.media_type, MediaType::Video);
2170        assert_eq!(p.pixel_format, Some(PixelFormat::Yuv420P10Le));
2171        assert_eq!(p.width, None);
2172        assert_eq!(p.height, None);
2173        assert_eq!(d.output_params_generation(), 0);
2174    }
2175
2176    #[test]
2177    fn merge_decoder_wins_for_output_fields_container_keeps_the_rest() {
2178        let mut stream = CodecParameters::video(CodecId::new("h264"));
2179        stream.width = Some(1920);
2180        stream.height = Some(1088);
2181        stream.frame_rate = Some(Rational::new(25, 1));
2182        stream.extradata = vec![1, 2, 3];
2183        stream.bit_rate = Some(5_000_000);
2184        stream.language = Some("en".into());
2185        stream.color_signal = ColorSignal::from_code_points(1, 1, 1, false);
2186
2187        let mut out = CodecParameters::video(CodecId::new("h264"));
2188        out.height = Some(1080);
2189        out.pixel_format = Some(PixelFormat::Yuv420P);
2190        out.color_signal = ColorSignal::default().with_range(ColorRange::Full);
2191
2192        assert!(stream.merge_output_params(&out));
2193        assert_eq!(stream.width, Some(1920), "decoder None keeps container");
2194        assert_eq!(stream.height, Some(1080), "decoder Some wins");
2195        assert_eq!(stream.pixel_format, Some(PixelFormat::Yuv420P));
2196        assert_eq!(stream.frame_rate, Some(Rational::new(25, 1)));
2197        assert_eq!(stream.extradata, vec![1, 2, 3]);
2198        assert_eq!(stream.bit_rate, Some(5_000_000));
2199        assert_eq!(stream.language.as_deref(), Some("en"));
2200        assert_eq!(stream.color_signal.range, ColorRange::Full);
2201        assert_eq!(
2202            stream.color_signal.primaries,
2203            ColorSignal::from_code_points(1, 1, 1, false).primaries,
2204            "unspecified decoder parts keep the container's"
2205        );
2206        assert!(!stream.merge_output_params(&out), "second merge is a no-op");
2207    }
2208
2209    #[test]
2210    fn merge_audio_keeps_count_and_layout_consistent() {
2211        let mut stream = CodecParameters::audio(CodecId::new("mp3"))
2212            .channels(2)
2213            .channel_layout(ChannelLayout::Stereo);
2214        stream.sample_rate = Some(44_100);
2215        let mut out = CodecParameters::audio(CodecId::new("mp3")).channels(1);
2216        out.sample_format = Some(SampleFormat::S16);
2217        out.sample_rate = Some(48_000);
2218        assert!(stream.merge_output_params(&out));
2219        assert_eq!(stream.channels, Some(1));
2220        assert_eq!(stream.channel_layout, None, "stale stereo layout dropped");
2221        assert_eq!(stream.resolved_layout(), Some(ChannelLayout::Mono));
2222        assert_eq!(stream.sample_rate, Some(48_000));
2223        assert_eq!(stream.sample_format, Some(SampleFormat::S16));
2224
2225        // Layout-only answer re-derives a disagreeing count.
2226        let mut stream = CodecParameters::audio(CodecId::new("aac")).channels(2);
2227        let out = CodecParameters::audio(CodecId::new("aac")).channel_layout(ChannelLayout::Mono);
2228        assert!(stream.merge_output_params(&out));
2229        assert_eq!(stream.channels, Some(1));
2230        assert_eq!(stream.channel_layout, Some(ChannelLayout::Mono));
2231    }
2232
2233    #[test]
2234    fn merge_of_empty_answer_changes_nothing() {
2235        let mut stream = CodecParameters::video(CodecId::new("vp9"));
2236        stream.width = Some(640);
2237        let out = CodecParameters::video(CodecId::new("vp9"));
2238        assert!(!stream.merge_output_params(&out));
2239        assert_eq!(stream.width, Some(640));
2240    }
2241
2242    #[test]
2243    fn generation_bumps_with_the_first_frame_of_the_new_shape() {
2244        let mut d = Switching::new();
2245        assert!(d.output_params().is_none(), "nothing parsed yet");
2246        d.send_packet(&pkt(16)).unwrap();
2247        d.send_packet(&pkt(0)).unwrap();
2248        // New shape announced while old-shape frames are still queued.
2249        d.send_packet(&pkt(24)).unwrap();
2250
2251        d.receive_frame().unwrap();
2252        assert_eq!(d.output_params().unwrap().height, Some(16));
2253        assert_eq!(d.output_params_generation(), 0, "first resolve is no bump");
2254        d.receive_frame().unwrap();
2255        assert_eq!(d.output_params_generation(), 0, "same shape, no bump");
2256        assert_eq!(d.output_params().unwrap().height, Some(16));
2257        d.receive_frame().unwrap();
2258        assert_eq!(d.output_params_generation(), 1);
2259        assert_eq!(d.output_params().unwrap().height, Some(24));
2260        assert_eq!(d.output_pixel_format(), Some(PixelFormat::Yuv420P));
2261    }
2262
2263    #[test]
2264    fn watch_merges_once_and_again_only_on_change() {
2265        let mut d = Switching::new();
2266        let mut stream = CodecParameters::video(CodecId::new("mock-switch"));
2267        stream.bit_rate = Some(1234);
2268        let mut watch = OutputParamsWatch::new();
2269
2270        // Nothing known yet: prime and observe leave the stream alone.
2271        assert!(!watch.prime(&d, &mut stream));
2272        assert!(!watch.observe(&d, &mut stream));
2273
2274        for b in [16, 0, 0, 24, 0] {
2275            d.send_packet(&pkt(b)).unwrap();
2276        }
2277        let mut changes = Vec::new();
2278        let dyn_dec: &mut dyn Decoder = &mut d;
2279        while dyn_dec.receive_frame().is_ok() {
2280            changes.push(watch.observe(&*dyn_dec, &mut stream));
2281        }
2282        assert_eq!(changes, vec![true, false, false, true, false]);
2283        assert_eq!(stream.height, Some(24));
2284        assert_eq!(stream.width, Some(32));
2285        assert_eq!(stream.bit_rate, Some(1234));
2286
2287        // reset forces a re-read; same answer → no field change.
2288        watch.reset();
2289        assert!(!watch.observe(&d, &mut stream));
2290        assert_eq!(watch, {
2291            let mut w = OutputParamsWatch::new();
2292            w.observe(&d, &mut stream.clone());
2293            w
2294        });
2295    }
2296
2297    #[test]
2298    fn watch_picks_up_the_derived_default() {
2299        let d = PixOnly(Base::new("mock-pix"));
2300        let mut stream = CodecParameters::video(CodecId::new("mock-pix"));
2301        stream.width = Some(64);
2302        let mut watch = OutputParamsWatch::new();
2303        assert!(watch.observe(&d, &mut stream));
2304        assert_eq!(stream.pixel_format, Some(PixelFormat::Yuv420P10Le));
2305        assert_eq!(stream.width, Some(64));
2306        assert!(!watch.observe(&d, &mut stream));
2307    }
2308
2309    /// Like [`Switching`] but also emits the in-band
2310    /// [`Frame::StreamParams`] event immediately before the first frame
2311    /// of a new mid-stream shape. Frames carry one real plane
2312    /// (`32 × height` bytes) so the arena path can be exercised.
2313    struct Eventing {
2314        base: Base,
2315        queued: std::collections::VecDeque<u32>,
2316        current: Option<u32>,
2317        generation: u64,
2318        flushed: bool,
2319    }
2320
2321    impl Eventing {
2322        fn new() -> Self {
2323            Self {
2324                base: Base::new("mock-event"),
2325                queued: Default::default(),
2326                current: None,
2327                generation: 0,
2328                flushed: false,
2329            }
2330        }
2331    }
2332
2333    impl Decoder for Eventing {
2334        fn codec_id(&self) -> &CodecId {
2335            &self.base.id
2336        }
2337        fn send_packet(&mut self, packet: &Packet) -> Result<()> {
2338            let h = packet.data.first().copied().unwrap_or(0) as u32;
2339            let h = if h == 0 {
2340                *self.queued.back().or(self.current.as_ref()).unwrap_or(&16)
2341            } else {
2342                h
2343            };
2344            self.queued.push_back(h);
2345            Ok(())
2346        }
2347        fn receive_frame(&mut self) -> Result<Frame> {
2348            let Some(&h) = self.queued.front() else {
2349                return Err(if self.flushed {
2350                    Error::Eof
2351                } else {
2352                    Error::NeedMore
2353                });
2354            };
2355            if let Some(cur) = self.current
2356                && cur != h
2357            {
2358                // Mid-stream change: publish the new shape (answer +
2359                // bump) together with the event, then the frame.
2360                self.current = Some(h);
2361                self.generation = self.generation.wrapping_add(1);
2362                return Ok(Frame::StreamParams(Box::new(
2363                    self.output_params().expect("shape known"),
2364                )));
2365            }
2366            self.queued.pop_front();
2367            self.current = Some(h);
2368            Ok(Frame::Video(VideoFrame {
2369                pts: None,
2370                planes: vec![crate::VideoPlane {
2371                    stride: 32,
2372                    data: vec![0; 32 * h as usize],
2373                }],
2374            }))
2375        }
2376        fn flush(&mut self) -> Result<()> {
2377            self.flushed = true;
2378            Ok(())
2379        }
2380        fn reset(&mut self) -> Result<()> {
2381            // Drop pending output; keep the shape of the last frame
2382            // returned so a different shape after the seek is
2383            // announced under the same rule.
2384            self.queued.clear();
2385            self.flushed = false;
2386            Ok(())
2387        }
2388        fn output_params(&self) -> Option<CodecParameters> {
2389            let h = self.current?;
2390            let mut p = CodecParameters::video(self.base.id.clone());
2391            p.width = Some(32);
2392            p.height = Some(h);
2393            p.pixel_format = Some(PixelFormat::Gray8);
2394            Some(p)
2395        }
2396        fn output_pixel_format(&self) -> Option<PixelFormat> {
2397            self.output_params().and_then(|p| p.pixel_format)
2398        }
2399        fn output_params_generation(&self) -> u64 {
2400            self.generation
2401        }
2402    }
2403
2404    /// One received item, as a consumer sees it.
2405    #[derive(Debug, PartialEq)]
2406    enum Seen {
2407        Video(u32),
2408        Event(u32, u64),
2409    }
2410
2411    fn shape(p: &CodecParameters) -> (Option<u32>, Option<u32>, Option<PixelFormat>) {
2412        (p.width, p.height, p.pixel_format)
2413    }
2414
2415    fn drain(d: &mut Eventing) -> Vec<Seen> {
2416        let mut out = Vec::new();
2417        while let Ok(f) = d.receive_frame() {
2418            match f {
2419                Frame::Video(v) => {
2420                    let h = (v.planes[0].data.len() / v.planes[0].stride) as u32;
2421                    assert_eq!(
2422                        d.output_params().unwrap().height,
2423                        Some(h),
2424                        "output_params describes the frame just returned"
2425                    );
2426                    out.push(Seen::Video(h));
2427                }
2428                Frame::StreamParams(p) => {
2429                    assert_eq!(
2430                        d.output_params().as_ref().map(shape),
2431                        Some(shape(&p)),
2432                        "output_params already answers the new shape"
2433                    );
2434                    out.push(Seen::Event(p.height.unwrap(), d.output_params_generation()));
2435                }
2436                other => panic!("unexpected {other:?}"),
2437            }
2438        }
2439        out
2440    }
2441
2442    #[test]
2443    fn stream_params_frame_helpers() {
2444        let mut p = CodecParameters::video(CodecId::new("x"));
2445        p.width = Some(8);
2446        let ev = Frame::StreamParams(Box::new(p.clone()));
2447        assert_eq!(ev.pts(), None);
2448        assert!(ev.is_stream_params());
2449        assert_eq!(ev.stream_params().map(shape), Some(shape(&p)));
2450        let media = Frame::Video(VideoFrame {
2451            pts: Some(7),
2452            planes: Vec::new(),
2453        });
2454        assert_eq!(media.pts(), Some(7));
2455        assert!(!media.is_stream_params());
2456        assert!(media.stream_params().is_none());
2457        // Boxed: the event does not grow `Frame`.
2458        assert!(std::mem::size_of::<Frame>() < std::mem::size_of::<CodecParameters>());
2459        assert!(
2460            std::mem::size_of::<Frame>()
2461                <= std::mem::size_of::<crate::VectorFrame>()
2462                    .max(std::mem::size_of::<crate::SubtitleCue>())
2463                    + std::mem::size_of::<usize>()
2464        );
2465    }
2466
2467    #[test]
2468    fn event_precedes_the_first_frame_of_the_new_shape_only() {
2469        let mut d = Eventing::new();
2470        for b in [16, 0, 24, 0, 0] {
2471            d.send_packet(&pkt(b)).unwrap();
2472        }
2473        d.flush().unwrap();
2474        assert_eq!(
2475            drain(&mut d),
2476            vec![
2477                Seen::Video(16),
2478                Seen::Video(16),
2479                Seen::Event(24, 1),
2480                Seen::Video(24),
2481                Seen::Video(24),
2482                Seen::Video(24),
2483            ],
2484            "no event for the first shape, one for the change, flush keeps order"
2485        );
2486        assert!(matches!(d.receive_frame(), Err(Error::Eof)));
2487    }
2488
2489    #[test]
2490    fn event_after_reset_follows_the_same_rule() {
2491        let mut d = Eventing::new();
2492        d.send_packet(&pkt(16)).unwrap();
2493        assert_eq!(drain(&mut d), vec![Seen::Video(16)]);
2494        // Pending output is dropped by the seek; it lands in a 24-high
2495        // segment while 16 was the last shape out.
2496        d.send_packet(&pkt(16)).unwrap();
2497        d.reset().unwrap();
2498        d.send_packet(&pkt(24)).unwrap();
2499        d.send_packet(&pkt(0)).unwrap();
2500        assert_eq!(
2501            drain(&mut d),
2502            vec![Seen::Event(24, 1), Seen::Video(24), Seen::Video(24)]
2503        );
2504        // Seek back to the original shape: another single event.
2505        d.reset().unwrap();
2506        d.send_packet(&pkt(16)).unwrap();
2507        assert_eq!(drain(&mut d), vec![Seen::Event(16, 2), Seen::Video(16)]);
2508        // Seek within the same shape: no event.
2509        d.reset().unwrap();
2510        d.send_packet(&pkt(16)).unwrap();
2511        assert_eq!(drain(&mut d), vec![Seen::Video(16)]);
2512    }
2513
2514    /// Feed the same switching stream and count reported changes after
2515    /// the first frame for each consumer style.
2516    fn changes_after_first(mode: &str) -> (usize, CodecParameters) {
2517        let mut d = Eventing::new();
2518        for b in [16, 0, 24, 0, 40, 0] {
2519            d.send_packet(&pkt(b)).unwrap();
2520        }
2521        let mut stream = CodecParameters::video(CodecId::new("mock-event"));
2522        stream.bit_rate = Some(99);
2523        let mut watch = OutputParamsWatch::new();
2524        let mut reports = Vec::new();
2525        let dec: &mut dyn Decoder = &mut d;
2526        while let Ok(f) = dec.receive_frame() {
2527            let changed = match mode {
2528                // Counter only, observed after every receive_frame.
2529                "counter" => watch.observe(&*dec, &mut stream),
2530                // Counter only, events skipped.
2531                "counter-skip" => !f.is_stream_params() && watch.observe(&*dec, &mut stream),
2532                // Event only (first shape via the first-frame read).
2533                "event" => {
2534                    if reports.is_empty() {
2535                        watch.observe(&*dec, &mut stream)
2536                    } else {
2537                        watch.observe_frame(&f, &mut stream)
2538                    }
2539                }
2540                // Both on every item.
2541                _ => {
2542                    let a = watch.observe_frame(&f, &mut stream);
2543                    let b = watch.observe(&*dec, &mut stream);
2544                    a | b
2545                }
2546            };
2547            reports.push(changed);
2548        }
2549        assert!(reports[0], "{mode}: first frame resolves the shape");
2550        (reports[1..].iter().filter(|c| **c).count(), stream)
2551    }
2552
2553    #[test]
2554    fn counter_and_event_report_each_change_exactly_once() {
2555        for mode in ["counter", "counter-skip", "event", "both"] {
2556            let (n, stream) = changes_after_first(mode);
2557            assert_eq!(n, 2, "{mode}: two mid-stream changes, each once");
2558            assert_eq!(stream.height, Some(40), "{mode}");
2559            assert_eq!(stream.width, Some(32), "{mode}");
2560            assert_eq!(stream.bit_rate, Some(99), "{mode}: container field kept");
2561        }
2562    }
2563
2564    #[test]
2565    fn observe_frame_ignores_media_frames() {
2566        let mut watch = OutputParamsWatch::new();
2567        let mut stream = CodecParameters::video(CodecId::new("x"));
2568        let before = stream.clone();
2569        let f = Frame::Video(VideoFrame {
2570            pts: None,
2571            planes: Vec::new(),
2572        });
2573        assert!(!watch.observe_frame(&f, &mut stream));
2574        assert_eq!(shape(&stream), shape(&before));
2575    }
2576
2577    #[test]
2578    fn arena_default_consumes_the_event() {
2579        let mut d = Eventing::new();
2580        for b in [16, 24] {
2581            d.send_packet(&pkt(b)).unwrap();
2582        }
2583        let a = d.receive_arena_frame().unwrap();
2584        assert_eq!(a.header().height, 16);
2585        let gen_before = d.output_params_generation();
2586        let b = d.receive_arena_frame().unwrap();
2587        assert_eq!(
2588            b.header().height,
2589            24,
2590            "event skipped, new-shape frame returned"
2591        );
2592        assert_eq!(d.output_params_generation(), gen_before + 1);
2593        assert!(matches!(d.receive_arena_frame(), Err(Error::NeedMore)));
2594    }
2595}