Skip to main content

rff_format/
lib.rs

1//! `rff-format` — the container (muxer/demuxer) abstraction layer (FFmpeg's
2//! `libavformat` core, minus the formats themselves).
3//!
4//! A container is the file wrapper (AVI, MP4, Matroska, ...) that interleaves
5//! one or more elementary streams. This crate defines:
6//! * [`Stream`] — the description of one elementary stream inside a container,
7//! * [`Demuxer`] — reads a container, exposing streams and [`Packet`]s,
8//! * [`Muxer`] — writes streams + packets back into a container,
9//! * [`FormatRegistry`] — what individual format crates register into.
10//!
11//! Concrete formats live in their own crates (`rff-format-avi`, ...).
12
13pub mod aac;
14pub mod av1;
15pub mod avc;
16pub mod hvc;
17pub mod time;
18
19use std::collections::HashMap;
20use std::io::{Read, Seek, Write};
21
22use rff_core::{
23    CleanAperture, CodecId, ColorInfo, ColorRange, ContentLightLevel, Dictionary, Error,
24    MasteringDisplay, MediaType, Packet, PixelFormat, Rational, Result, SampleFormat, Timecode,
25};
26
27/// Description of one elementary stream within a container.
28#[derive(Debug, Clone)]
29pub struct Stream {
30    /// Position of this stream within its container.
31    pub index: usize,
32    pub codec_id: CodecId,
33    pub media_type: MediaType,
34    /// Unit of all timestamps on packets of this stream.
35    pub time_base: Rational,
36    // --- Video parameters (zero/ignored for non-video) ---
37    pub width: u32,
38    pub height: u32,
39    /// Raw pixel layout, when known (raw video). Self-describing codecs leave this `None`.
40    pub pixel_format: Option<PixelFormat>,
41    /// Luma/chroma value range. JPEG and PNG sources are always
42    /// [`ColorRange::Full`]; leaving it [`Unspecified`](ColorRange::Unspecified)
43    /// makes containers label the data limited-range, which silently corrupts it.
44    pub color_range: ColorRange,
45    // --- Audio parameters (zero/ignored for non-audio) ---
46    pub sample_rate: u32,
47    pub channels: u16,
48    /// Raw sample layout, when known (PCM). Self-describing codecs leave this `None`.
49    pub sample_format: Option<SampleFormat>,
50    /// Codec-private initialization data (e.g. H.264 SPS/PPS, OpusHead). Empty
51    /// for codecs whose bitstream is fully self-describing.
52    pub extradata: Vec<u8>,
53    /// Total stream duration in [`time_base`](Stream::time_base) units, when
54    /// the container declares it (MP4 `mdhd`, Matroska `Duration`). `None` when
55    /// unknown (live streams, TS).
56    pub duration: Option<i64>,
57    /// Total packet count (frames for video), when the container's index
58    /// declares it. `None` when unknown — never a guess.
59    pub nb_frames: Option<u64>,
60    /// The container's own code for this codec, when it has one worth
61    /// keeping: the MP4/QuickTime sample-entry fourcc (`apch` vs `apcn` names
62    /// the ProRes profile, `twos` vs `sowt` the PCM byte order on disk). A
63    /// muxer of the same family writes it back when it is valid for the
64    /// codec, so a remux keeps the original entry; `None` lets the muxer pick.
65    pub codec_tag: Option<[u8; 4]>,
66    // --- Video description (containers label; they do not convert) ---
67    /// Colour primaries / transfer / matrix (MP4 `colr`, Matroska `Colour`).
68    pub color: ColorInfo,
69    /// HDR mastering display (MP4 `mdcv`, Matroska `MasteringMetadata`).
70    pub mastering_display: Option<MasteringDisplay>,
71    /// HDR content light level (MP4 `clli`, Matroska `MaxCLL`/`MaxFALL`).
72    pub content_light: Option<ContentLightLevel>,
73    /// Pixel aspect ratio as `(horizontal, vertical)` spacing (MP4 `pasp`).
74    /// `None` when not recorded, which means square.
75    pub pixel_aspect: Option<(u32, u32)>,
76    /// Clean aperture (MP4 `clap`).
77    pub clean_aperture: Option<CleanAperture>,
78    /// Start timecode (a QuickTime `tmcd` track referenced by this video track).
79    pub timecode: Option<Timecode>,
80    /// The frames carry an alpha plane as a block addition (Matroska
81    /// `AlphaMode`; WebM VP8/VP9 alpha).
82    pub alpha_mode: bool,
83    // --- Audio timing the container records beside the packets ---
84    /// Samples the decoder must drop from the start, in nanoseconds
85    /// (Matroska `CodecDelay`; Opus pre-skip). The demuxer has already taken
86    /// it off packet timestamps; it is here so a remux can write it back.
87    pub codec_delay_ns: u64,
88    /// How far before a seek target decoding must start to converge, in
89    /// nanoseconds (Matroska `SeekPreRoll`; 80 ms for Opus).
90    pub seek_preroll_ns: u64,
91    // --- Presentation (#114) ---
92    /// How the decoded picture is transformed for display: the 3×3 matrix of
93    /// an MP4 `tkhd` (`a b u / c d v / x y w`, with `a b c d x y` in 16.16
94    /// and `u v w` in 2.30 fixed point), kept verbatim so a remux writes it
95    /// back unchanged. `None` means identity. Matroska carries a pure rotation
96    /// of it as `Projection` / `ProjectionPoseRoll`. See [`Stream::rotation`]
97    /// and [`Stream::set_rotation`].
98    pub display_matrix: Option<[i32; 9]>,
99    /// The track language: an ISO 639-2 code (`eng`, `und`) from MP4 `mdhd`
100    /// or Matroska `Language`, or a BCP 47 tag from Matroska
101    /// `LanguageBCP47`. `None` when the container says nothing.
102    pub language: Option<String>,
103    /// The track's human-readable name (Matroska `Name`).
104    pub name: Option<String>,
105    /// Track flags (Matroska `FlagDefault`, `FlagForced`, ...).
106    pub disposition: Disposition,
107    /// Interlacing, as the QuickTime `fiel` detail / Matroska `FieldOrder`
108    /// code (the two share their values): 0 progressive, 1 top field first,
109    /// 6 bottom field first, 9 bottom field first stored first, 14 top field
110    /// first stored first, 2 interlaced but undetermined. `None` when the
111    /// container says nothing.
112    pub field_order: Option<u8>,
113    /// Matroska `StereoMode` (0 mono, 1 side by side left first, ...), when
114    /// the container records it.
115    pub stereo_mode: Option<u8>,
116}
117
118/// A stream's track flags, as Matroska records them (`FlagDefault`,
119/// `FlagEnabled`, `FlagForced`, `FlagHearingImpaired`, `FlagVisualImpaired`,
120/// `FlagOriginal`, `FlagCommentary`). `default` and `enabled` are `None` when
121/// the container leaves them at its default (in Matroska both default to
122/// set), so a fresh stream changes nothing in the output.
123#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
124pub struct Disposition {
125    pub default: Option<bool>,
126    pub enabled: Option<bool>,
127    pub forced: bool,
128    pub hearing_impaired: bool,
129    pub visual_impaired: bool,
130    pub original: bool,
131    pub commentary: bool,
132}
133
134/// The display matrix that rotates a `width`×`height` picture clockwise by
135/// `degrees` (any angle; quarter turns are exact). Quarter turns carry the
136/// translation QuickTime writers put in `tkhd` so the picture lands at the
137/// origin (`0 1 0 / -1 0 0 / h 0 1` for 90°, as an iPhone writes it).
138pub fn rotation_matrix(degrees: f64, width: u32, height: u32) -> [i32; 9] {
139    const ONE: i32 = 1 << 16;
140    const W: i32 = 1 << 30;
141    let fixed = |v: u32| i32::try_from(i64::from(v) << 16).unwrap_or(i32::MAX);
142    let (w, h) = (fixed(width), fixed(height));
143    let turn = degrees.rem_euclid(360.0);
144    match turn {
145        0.0 => [ONE, 0, 0, 0, ONE, 0, 0, 0, W],
146        90.0 => [0, ONE, 0, -ONE, 0, 0, h, 0, W],
147        180.0 => [-ONE, 0, 0, 0, -ONE, 0, w, h, W],
148        270.0 => [0, -ONE, 0, ONE, 0, 0, 0, w, W],
149        t => {
150            let (s, c) = t.to_radians().sin_cos();
151            let q = |v: f64| (v * f64::from(ONE)).round() as i32;
152            [q(c), q(s), 0, q(-s), q(c), 0, 0, 0, W]
153        }
154    }
155}
156
157/// The clockwise rotation (degrees in `[0, 360)`) a display matrix applies,
158/// or `None` when it is not a pure rotation (a flip, a scale, a shear).
159pub fn matrix_rotation(m: &[i32; 9]) -> Option<f64> {
160    let f = |v: i32| f64::from(v) / 65536.0;
161    let (a, b, c, d) = (f(m[0]), f(m[1]), f(m[3]), f(m[4]));
162    let tol = 1e-3;
163    if (a - d).abs() > tol || (b + c).abs() > tol || (a * a + b * b - 1.0).abs() > 2.0 * tol {
164        return None;
165    }
166    let deg = b.atan2(a).to_degrees().rem_euclid(360.0);
167    // Snap what is within rounding of a whole degree (16.16 cos/sin).
168    let snapped = deg.round();
169    let deg = if (deg - snapped).abs() < 1e-2 {
170        snapped.rem_euclid(360.0)
171    } else {
172        deg
173    };
174    Some(deg)
175}
176
177impl Stream {
178    /// The clockwise rotation to apply for display, in degrees: 0 without a
179    /// display matrix, `None` when the matrix is not a pure rotation.
180    pub fn rotation(&self) -> Option<f64> {
181        match &self.display_matrix {
182            None => Some(0.0),
183            Some(m) => matrix_rotation(m),
184        }
185    }
186
187    /// Ask for the picture to be shown rotated `degrees` clockwise (set
188    /// [`width`](Stream::width)/[`height`](Stream::height) first: quarter
189    /// turns record a translation by them). 0 clears the matrix.
190    pub fn set_rotation(&mut self, degrees: f64) {
191        self.display_matrix = if degrees.rem_euclid(360.0) == 0.0 {
192            None
193        } else {
194            Some(rotation_matrix(degrees, self.width, self.height))
195        };
196    }
197}
198
199impl Stream {
200    /// Create a stream with sane defaults for the given codec.
201    pub fn new(index: usize, codec_id: CodecId) -> Stream {
202        Stream {
203            index,
204            codec_id,
205            media_type: codec_id.media_type(),
206            time_base: Rational::new(1, 1000),
207            width: 0,
208            height: 0,
209            pixel_format: None,
210            color_range: ColorRange::Unspecified,
211            sample_rate: 0,
212            channels: 0,
213            sample_format: None,
214            extradata: Vec::new(),
215            duration: None,
216            nb_frames: None,
217            codec_tag: None,
218            color: ColorInfo::UNSPECIFIED,
219            mastering_display: None,
220            content_light: None,
221            pixel_aspect: None,
222            clean_aperture: None,
223            timecode: None,
224            alpha_mode: false,
225            codec_delay_ns: 0,
226            seek_preroll_ns: 0,
227            display_matrix: None,
228            language: None,
229            name: None,
230            disposition: Disposition::default(),
231            field_order: None,
232            stereo_mode: None,
233        }
234    }
235}
236
237/// A byte source a demuxer reads from. (`Box<dyn Read + Send>` keeps the trait
238/// object-safe and lets inputs be files, network streams, or in-memory buffers.)
239pub type Input = Box<dyn Read + Send>;
240
241/// A byte source that can also seek — what a local file or an in-memory buffer
242/// offers and a pipe or socket does not. Blanket-implemented for every
243/// `Read + Seek` type.
244pub trait ReadSeek: Read + Seek {}
245impl<T: Read + Seek> ReadSeek for T {}
246
247/// A seekable [`Input`]. Formats whose index can sit anywhere in the file (MP4's
248/// `moov`) use it to read only that index and fetch each payload on demand,
249/// instead of buffering the whole file. It upcasts to [`Input`] for formats
250/// that only stream.
251pub type SeekInput = Box<dyn ReadSeek + Send>;
252/// A byte sink a muxer writes to.
253pub type Output = Box<dyn Write + Send>;
254
255/// A byte sink that can also seek -- a local file, an in-memory buffer; not a
256/// pipe or socket. Blanket-implemented for every `Write + Seek` type.
257pub trait WriteSeek: Write + Seek {}
258impl<T: Write + Seek> WriteSeek for T {}
259
260/// A seekable [`Output`]. Containers whose header records sizes or an index
261/// that is only known at the end (MP4 `mdat`/`moov`, Matroska Segment/Cues,
262/// AVI `movi`/`idx1`, WAV `RIFF`/`data`) use it to stream the payload as it
263/// arrives and patch the header afterwards, instead of holding the whole
264/// output in memory until the trailer (#28). It upcasts to [`Output`] for
265/// muxers that only stream.
266pub type SeekOutput = Box<dyn WriteSeek + Send>;
267
268/// Reads a container format: parses the header into [`Stream`]s, then yields
269/// [`Packet`]s until the input is exhausted.
270pub trait Demuxer: Send {
271    /// Parse the container header and return its streams.
272    fn read_header(&mut self) -> Result<Vec<Stream>>;
273
274    /// Read the next packet. Returns [`Error::Eof`] at end of input.
275    fn read_packet(&mut self) -> Result<Packet>;
276
277    /// Name the streams the caller will drop: `discard[i]` is stream `i`.
278    /// Called after [`read_header`](Demuxer::read_header); a demuxer may then
279    /// skip those streams' packets without reading or converting them. It is
280    /// a hint: a demuxer that ignores it (the default) still returns them and
281    /// the caller drops them, so either way the kept packets are identical.
282    fn set_discard(&mut self, _discard: &[bool]) {}
283
284    /// Random access to the container's index, for an editor that jumps to a
285    /// frame instead of reading the file in order: per-stream sample tables,
286    /// reading a sample by number, and the sync sample at or before a time.
287    /// Available after [`read_header`](Demuxer::read_header) from demuxers
288    /// whose container has an index (MP4 sample tables, Matroska clusters and
289    /// Cues); `None` from the rest (the default). Reading through the index
290    /// does not move [`read_packet`](Demuxer::read_packet)'s position.
291    fn sample_index(&mut self) -> Option<&mut dyn SampleIndex> {
292        None
293    }
294
295    /// Hand out samples as the container stores them instead of in the form
296    /// rff's decoders take: H.264 / HEVC length-prefixed (AVCC / HVCC)
297    /// rather than Annex-B with the parameter sets put in front of each
298    /// keyframe, PCM in the stored byte order, ASS events in Matroska as
299    /// stored. Storage transforms of the container itself (Matroska
300    /// ContentEncodings and header stripping, the ProRes frame header MKV
301    /// drops) are still undone, so a sample is always a whole codec frame.
302    /// Call it after
303    /// [`read_header`](Demuxer::read_header); it applies to
304    /// [`read_packet`](Demuxer::read_packet) and to [`SampleIndex::read_sample`].
305    /// Returns whether the demuxer honours it (the default does not: its
306    /// samples are already stored as they are handed out).
307    fn set_raw_samples(&mut self, _raw: bool) -> bool {
308        false
309    }
310
311    /// The file's global metadata, in FFmpeg's key names (`title`,
312    /// `artist`, `comment`, `encoder`, `creation_time`, ...): MP4 `udta`
313    /// (`meta/ilst` and QuickTime `©xxx` atoms), Matroska `Info` and global
314    /// `Tags`. Available after [`read_header`](Demuxer::read_header); `None`
315    /// from demuxers that read none (the default).
316    fn metadata(&self) -> Option<&Dictionary> {
317        None
318    }
319}
320
321/// One sample (packet) of a stream as the container's index records it.
322///
323/// The timestamps are the ones [`Demuxer::read_packet`] gives the sample, in
324/// the stream's time base, with the edit list applied; the edit list itself is
325/// [`SampleIndex::edit_list`]. `offset` and `size` locate the stored bytes, so
326/// a caller can also read them itself.
327#[derive(Debug, Clone, Copy, PartialEq, Eq)]
328pub struct SampleInfo {
329    /// File offset of the stored sample.
330    pub offset: u64,
331    /// Stored size in bytes.
332    pub size: u32,
333    /// Decode timestamp.
334    pub dts: i64,
335    /// Presentation timestamp.
336    pub pts: i64,
337    /// Duration (0 when the container does not say).
338    pub duration: i64,
339    /// A sync sample (keyframe): decoding can start here.
340    pub sync: bool,
341}
342
343/// One entry of a stream's edit list (MP4 `elst`): `segment_duration` of
344/// presentation, in the movie time scale, showing the media from
345/// `media_time` (stream time base); `media_time` -1 is an empty edit (a
346/// delay). `media_rate` is 16.16 fixed point (0x10000 = normal speed).
347#[derive(Debug, Clone, Copy, PartialEq, Eq)]
348pub struct EditEntry {
349    pub segment_duration: i64,
350    pub media_time: i64,
351    pub media_rate: i32,
352}
353
354/// Random access over a demuxer's index; see [`Demuxer::sample_index`].
355pub trait SampleIndex {
356    /// Samples in stream `stream` (0 for an unknown stream).
357    fn sample_count(&self, stream: usize) -> u64;
358
359    /// The index entry of sample `index` of `stream`, in decode order.
360    fn sample_info(&self, stream: usize, index: u64) -> Option<SampleInfo>;
361
362    /// Read sample `index` of `stream` as a packet, in the same form as
363    /// [`Demuxer::read_packet`] would give it (see
364    /// [`Demuxer::set_raw_samples`]).
365    fn read_sample(&mut self, stream: usize, index: u64) -> Result<Packet>;
366
367    /// The last sync sample of `stream` whose presentation time is at or
368    /// before `pts`: where decoding starts to show the frame at `pts`.
369    /// `None` if no sync sample is that early.
370    fn sync_at_or_before(&self, stream: usize, pts: i64) -> Option<u64>;
371
372    /// The stream's edit list (empty when it has none, or the container has
373    /// no such thing).
374    fn edit_list(&self, _stream: usize) -> &[EditEntry] {
375        &[]
376    }
377
378    /// The movie time scale [`EditEntry::segment_duration`] counts in (MP4
379    /// `mvhd`), when the container has one.
380    fn movie_timescale(&self) -> Option<u32> {
381        None
382    }
383
384    /// Samples in the stream's stored sample table: what
385    /// [`raw_sample_info`](SampleIndex::raw_sample_info) numbers. Without an
386    /// edit list this is [`sample_count`](SampleIndex::sample_count); an MP4
387    /// edit list can replay samples or leave some out of the edited index.
388    fn raw_sample_count(&self, stream: usize) -> u64 {
389        self.sample_count(stream)
390    }
391
392    /// Sample `index` of the stored sample table, in decode order, with the
393    /// edit list **not** applied: for MP4 the `stbl` row verbatim, `dts` the
394    /// sum of the `stts` deltas before it (0 for the first sample), `pts` =
395    /// `dts` + its `ctts` offset, `duration` its `stts` delta, all in the
396    /// media time scale (the stream's time base). An editor applies
397    /// [`edit_list`](SampleIndex::edit_list) itself on this — for example
398    /// AAC encoder priming (the first edit's `media_time`) and padding (where
399    /// its `segment_duration` ends) — and a muxer given these samples and the
400    /// same edit list ([`Muxer::set_edit_list`]) writes the same table back.
401    /// Defaults to [`sample_info`](SampleIndex::sample_info) for containers
402    /// without edit lists.
403    fn raw_sample_info(&self, stream: usize, index: u64) -> Option<SampleInfo> {
404        self.sample_info(stream, index)
405    }
406
407    /// Read stored sample `index` (numbered as
408    /// [`raw_sample_info`](SampleIndex::raw_sample_info) numbers them) as a
409    /// packet timed by that entry, shaped as
410    /// [`read_sample`](SampleIndex::read_sample) shapes it.
411    fn read_raw_sample(&mut self, stream: usize, index: u64) -> Result<Packet> {
412        self.read_sample(stream, index)
413    }
414}
415
416/// Writes a container format: declare streams, write packets, finalize.
417pub trait Muxer: Send {
418    /// Hand the muxer output metadata (`-metadata title=...`). Called before
419    /// [`write_header`](Muxer::write_header); formats without a metadata slot
420    /// simply ignore it (the default).
421    fn set_metadata(&mut self, _metadata: &Dictionary) {}
422
423    /// A muxer option, FFmpeg-style (`movflags`, `+faststart`). Called before
424    /// [`write_header`](Muxer::write_header). Returns whether the muxer knows
425    /// the option; the default knows none.
426    fn set_option(&mut self, _key: &str, _value: &str) -> bool {
427        false
428    }
429
430    /// Write `edits` as stream `stream`'s edit list instead of the one the
431    /// muxer would derive (encoder delay, trims, a start delay). Segment
432    /// durations are in the muxer's movie time scale (1/1000 s for MP4 unless
433    /// `set_option("movie_timescale", ..)` picks another), media
434    /// times in the stream's time base, -1 for an empty edit. Called before
435    /// [`write_trailer`](Muxer::write_trailer). Returns whether the container
436    /// has edit lists; the default has none.
437    fn set_edit_list(&mut self, _stream: usize, _edits: &[EditEntry]) -> bool {
438        false
439    }
440
441    /// Write the container header for the given set of streams.
442    fn write_header(&mut self, streams: &[Stream]) -> Result<()>;
443
444    /// Write one packet (its `stream_index` selects the target stream).
445    fn write_packet(&mut self, packet: &Packet) -> Result<()>;
446
447    /// Finalize the container (indexes, trailers, fixups).
448    fn write_trailer(&mut self) -> Result<()>;
449}
450
451/// Factory opening a demuxer over an input byte source.
452pub type DemuxerFactory = fn(Input) -> Box<dyn Demuxer>;
453/// Factory opening a demuxer over a [`SeekInput`] — registered alongside the
454/// format's [`DemuxerFactory`] by formats that read less when they can seek.
455pub type SeekableDemuxerFactory = fn(SeekInput) -> Box<dyn Demuxer>;
456/// Factory opening a muxer over an output byte sink.
457pub type MuxerFactory = fn(Output) -> Box<dyn Muxer>;
458/// Factory opening a muxer over a [`SeekOutput`] -- registered alongside the
459/// format's [`MuxerFactory`] by formats that can stream when they can seek.
460pub type SeekableMuxerFactory = fn(SeekOutput) -> Box<dyn Muxer>;
461/// Factory opening a muxer that owns its own file set (HLS/DASH write a
462/// playlist/manifest plus many segment files, so a single byte sink cannot
463/// model them). Receives the output path and the format options
464/// (`-hls_time 6` → `{"hls_time": "6"}`).
465pub type PathMuxerFactory = fn(&std::path::Path, &Dictionary) -> Result<Box<dyn Muxer>>;
466/// Content sniffer: scores how strongly a byte prefix looks like this format,
467/// `0` (no match) to `100` (certain) — mirrors FFmpeg's `AVInputFormat::read_probe`.
468pub type ProbeFn = fn(&[u8]) -> i32;
469
470/// What a container's **muxer** will accept: the machine-readable half of the
471/// rules each muxer already enforces when it writes a header.
472///
473/// Muxers validate at run time, and a few historically wrote a zero codec tag
474/// rather than refusing an unmappable codec. Declaring the same rules here lets
475/// a caller answer "what can this file become?" *before* opening an encoder —
476/// which is what `rff-targets` is built on.
477#[derive(Debug, Clone, Copy, PartialEq, Eq)]
478pub struct MuxCaps {
479    /// Every codec this muxer can write. Empty for demux-only formats.
480    pub codecs: &'static [CodecId],
481    /// Most streams the container holds; `None` when there is no fixed limit.
482    pub max_streams: Option<usize>,
483    /// True when the container holds exactly ONE picture, so extra frames are
484    /// refused or dropped (png, jpeg, gif, webp, avif, jxl, av2f).
485    pub still_image: bool,
486}
487
488impl MuxCaps {
489    /// A format that cannot be written at all (demux-only).
490    pub const NONE: MuxCaps = MuxCaps {
491        codecs: &[],
492        max_streams: Some(0),
493        still_image: false,
494    };
495
496    /// A container interleaving any number of streams (mp4, matroska, mpegts).
497    pub const fn container(codecs: &'static [CodecId]) -> MuxCaps {
498        MuxCaps {
499            codecs,
500            max_streams: None,
501            still_image: false,
502        }
503    }
504
505    /// A file holding exactly one elementary stream (wav, mp3, ivf, ogg).
506    pub const fn single(codecs: &'static [CodecId]) -> MuxCaps {
507        MuxCaps {
508            codecs,
509            max_streams: Some(1),
510            still_image: false,
511        }
512    }
513
514    /// Narrow a [`single`](MuxCaps::single) file to one picture (png, jpeg).
515    pub const fn image(self) -> MuxCaps {
516        MuxCaps {
517            codecs: self.codecs,
518            max_streams: self.max_streams,
519            still_image: true,
520        }
521    }
522
523    /// Can this muxer write `id`?
524    pub fn accepts(&self, id: CodecId) -> bool {
525        self.codecs.contains(&id)
526    }
527
528    /// Can this muxer carry any stream of `media` at all?
529    pub fn accepts_media(&self, media: MediaType) -> bool {
530        self.codecs.iter().any(|c| c.media_type() == media)
531    }
532
533    /// The codecs this muxer accepts for one media category.
534    pub fn codecs_for(&self, media: MediaType) -> impl Iterator<Item = CodecId> + '_ {
535        self.codecs
536            .iter()
537            .copied()
538            .filter(move |c| c.media_type() == media)
539    }
540}
541
542/// Static description of a container format and its read/write support.
543pub struct Format {
544    /// Short name (`avi`, `mp4`, ...), as used by `ffmpeg -f <name>`.
545    pub name: &'static str,
546    pub long_name: &'static str,
547    /// File extensions that imply this format (without the dot).
548    pub extensions: &'static [&'static str],
549    /// Present if this format can be demuxed (read).
550    pub demuxer: Option<DemuxerFactory>,
551    /// Present if this format can be muxed (written).
552    pub muxer: Option<MuxerFactory>,
553    /// Present for formats that mux into a *path* (playlist + segment files)
554    /// rather than one byte sink — HLS, DASH. Mutually exclusive with `muxer`.
555    pub muxer_path: Option<PathMuxerFactory>,
556    /// Content sniffer for magic-byte detection (independent of the filename).
557    pub probe: Option<ProbeFn>,
558    /// What this format's muxer accepts. [`MuxCaps::NONE`] for demux-only
559    /// formats. Keep it in step with the muxer — `tests/mux_caps.rs` gates it.
560    pub mux_caps: MuxCaps,
561}
562
563impl Format {
564    pub fn can_demux(&self) -> bool {
565        self.demuxer.is_some()
566    }
567    pub fn can_mux(&self) -> bool {
568        self.muxer.is_some() || self.muxer_path.is_some()
569    }
570}
571
572/// Holds every container format known to a running engine.
573#[derive(Default)]
574pub struct FormatRegistry {
575    by_name: HashMap<&'static str, Format>,
576    /// Seek-aware demuxer factories, keyed by format name (see
577    /// [`register_seekable_demuxer`](Self::register_seekable_demuxer)).
578    seekable: HashMap<&'static str, SeekableDemuxerFactory>,
579    /// Seek-aware muxer factories, keyed by format name (see
580    /// [`register_seekable_muxer`](Self::register_seekable_muxer)).
581    seekable_muxers: HashMap<&'static str, SeekableMuxerFactory>,
582}
583
584impl FormatRegistry {
585    pub fn new() -> FormatRegistry {
586        FormatRegistry::default()
587    }
588
589    pub fn register(&mut self, format: Format) {
590        self.by_name.insert(format.name, format);
591    }
592
593    /// Give the format named `name` a demuxer that takes a [`SeekInput`]. Used
594    /// by [`open_demuxer_seekable`](Self::open_demuxer_seekable) when the caller
595    /// has a seekable source; the plain [`Format::demuxer`] still serves pipes
596    /// and sockets.
597    pub fn register_seekable_demuxer(
598        &mut self,
599        name: &'static str,
600        factory: SeekableDemuxerFactory,
601    ) {
602        self.seekable.insert(name, factory);
603    }
604
605    pub fn by_name(&self, name: &str) -> Option<&Format> {
606        self.by_name.get(name)
607    }
608
609    /// Find a format whose extension list contains `ext` (case-insensitive,
610    /// no leading dot). The cheap "guess by filename" path; [`probe`](Self::probe)
611    /// inspects content instead.
612    pub fn by_extension(&self, ext: &str) -> Option<&Format> {
613        let ext = ext.trim_start_matches('.').to_ascii_lowercase();
614        self.by_name
615            .values()
616            .find(|f| f.extensions.iter().any(|e| e.eq_ignore_ascii_case(&ext)))
617    }
618
619    /// Identify a format by sniffing a byte prefix: the registered format whose
620    /// [`probe`](Format::probe) returns the highest positive score wins. Returns
621    /// `None` if nothing recognizes the data.
622    pub fn probe(&self, data: &[u8]) -> Option<&Format> {
623        self.by_name
624            .values()
625            .filter_map(|f| f.probe.map(|p| (p(data), f)))
626            .filter(|(score, _)| *score > 0)
627            .max_by_key(|(score, _)| *score)
628            .map(|(_, f)| f)
629    }
630
631    /// Open a demuxer for the format named `name`.
632    pub fn open_demuxer(&self, name: &str, input: Input) -> Result<Box<dyn Demuxer>> {
633        self.by_name
634            .get(name)
635            .and_then(|f| f.demuxer)
636            .map(|factory| factory(input))
637            .ok_or_else(|| Error::DemuxerNotFound(name.to_string()))
638    }
639
640    /// Open a demuxer over a seekable input: the format's seek-aware demuxer if
641    /// it registered one, otherwise its plain streaming demuxer (a seekable
642    /// source is still a byte stream). Callers that hold a file should prefer
643    /// this — it is what lets MP4 read only `moov` instead of the whole file.
644    pub fn open_demuxer_seekable(&self, name: &str, input: SeekInput) -> Result<Box<dyn Demuxer>> {
645        if !self.by_name.get(name).is_some_and(Format::can_demux) {
646            return Err(Error::DemuxerNotFound(name.to_string()));
647        }
648        match self.seekable.get(name) {
649            Some(factory) => Ok(factory(input)),
650            None => self.open_demuxer(name, input),
651        }
652    }
653
654    /// Give the format named `name` a muxer that takes a [`SeekOutput`]. Used
655    /// by [`open_muxer_seekable`](Self::open_muxer_seekable) when the caller
656    /// writes to something seekable; the plain [`Format::muxer`] still serves
657    /// pipes and sockets.
658    pub fn register_seekable_muxer(&mut self, name: &'static str, factory: SeekableMuxerFactory) {
659        self.seekable_muxers.insert(name, factory);
660    }
661
662    /// Open a muxer over a seekable output: the format's seek-aware muxer if it
663    /// registered one, otherwise its plain muxer (a seekable sink is still a
664    /// byte sink). Callers writing a file should prefer this -- it is what lets
665    /// MP4/Matroska/AVI/WAV stream instead of buffering the whole output.
666    pub fn open_muxer_seekable(&self, name: &str, output: SeekOutput) -> Result<Box<dyn Muxer>> {
667        if !self.by_name.get(name).is_some_and(|f| f.muxer.is_some()) {
668            return Err(Error::MuxerNotFound(name.to_string()));
669        }
670        match self.seekable_muxers.get(name) {
671            Some(factory) => Ok(factory(output)),
672            None => self.open_muxer(name, output),
673        }
674    }
675
676    /// Open a muxer for the format named `name`.
677    pub fn open_muxer(&self, name: &str, output: Output) -> Result<Box<dyn Muxer>> {
678        self.by_name
679            .get(name)
680            .and_then(|f| f.muxer)
681            .map(|factory| factory(output))
682            .ok_or_else(|| Error::MuxerNotFound(name.to_string()))
683    }
684
685    pub fn iter(&self) -> impl Iterator<Item = &Format> {
686        self.by_name.values()
687    }
688
689    pub fn len(&self) -> usize {
690        self.by_name.len()
691    }
692
693    pub fn is_empty(&self) -> bool {
694        self.by_name.is_empty()
695    }
696}
697
698#[cfg(test)]
699mod tests {
700    use super::*;
701    use std::io::Cursor;
702
703    /// Reports which factory built it via the stream count.
704    struct Tagged(usize);
705    impl Demuxer for Tagged {
706        fn read_header(&mut self) -> Result<Vec<Stream>> {
707            Ok((0..self.0).map(|i| Stream::new(i, CodecId::None)).collect())
708        }
709        fn read_packet(&mut self) -> Result<rff_core::Packet> {
710            Err(Error::Eof)
711        }
712    }
713
714    fn format(name: &'static str) -> Format {
715        Format {
716            name,
717            long_name: name,
718            extensions: &[],
719            demuxer: Some(|_| Box::new(Tagged(1))),
720            muxer: None,
721            muxer_path: None,
722            probe: None,
723            mux_caps: MuxCaps::NONE,
724        }
725    }
726
727    fn streams(mut d: Box<dyn Demuxer>) -> usize {
728        d.read_header().unwrap().len()
729    }
730
731    #[test]
732    fn rotation_matrices_round_trip() {
733        for deg in [0.0, 90.0, 180.0, 270.0, 30.0, 315.0] {
734            let m = rotation_matrix(deg, 1920, 1080);
735            assert_eq!(matrix_rotation(&m), Some(deg), "{deg}");
736        }
737        // An iPhone portrait clip: rotate 90 degrees clockwise, translated by the height.
738        let m = rotation_matrix(-270.0, 1920, 1080);
739        assert_eq!(m, [0, 0x10000, 0, -0x10000, 0, 0, 1080 << 16, 0, 1 << 30]);
740        // A horizontal flip is not a rotation.
741        let flip = [-0x10000, 0, 0, 0, 0x10000, 0, 0, 0, 1 << 30];
742        assert_eq!(matrix_rotation(&flip), None);
743        let mut s = Stream::new(0, CodecId::H264);
744        (s.width, s.height) = (640, 480);
745        assert_eq!(s.rotation(), Some(0.0));
746        s.set_rotation(90.0);
747        assert_eq!(s.rotation(), Some(90.0));
748        s.set_rotation(360.0);
749        assert_eq!(s.display_matrix, None);
750    }
751
752    #[test]
753    fn seekable_open_prefers_the_seekable_factory_and_falls_back() {
754        let mut r = FormatRegistry::new();
755        r.register(format("plain"));
756        r.register(format("seeky"));
757        r.register_seekable_demuxer("seeky", |_| Box::new(Tagged(2)));
758        let input = || -> SeekInput { Box::new(Cursor::new(vec![0u8; 4])) };
759        assert_eq!(
760            streams(r.open_demuxer_seekable("seeky", input()).unwrap()),
761            2
762        );
763        // No seekable factory: the streaming one serves the seekable input.
764        assert_eq!(
765            streams(r.open_demuxer_seekable("plain", input()).unwrap()),
766            1
767        );
768        // A plain stream open never takes the seekable path.
769        assert_eq!(
770            streams(
771                r.open_demuxer("seeky", Box::new(Cursor::new(vec![])))
772                    .unwrap()
773            ),
774            1
775        );
776        assert!(matches!(
777            r.open_demuxer_seekable("missing", input()),
778            Err(Error::DemuxerNotFound(_))
779        ));
780    }
781
782    /// Reports which factory built it through the error `write_trailer` returns.
783    struct TaggedMux(&'static str);
784    impl Muxer for TaggedMux {
785        fn write_header(&mut self, _: &[Stream]) -> Result<()> {
786            Ok(())
787        }
788        fn write_packet(&mut self, _: &rff_core::Packet) -> Result<()> {
789            Ok(())
790        }
791        fn write_trailer(&mut self) -> Result<()> {
792            Err(Error::invalid(self.0))
793        }
794    }
795
796    fn tag(mut m: Box<dyn Muxer>) -> String {
797        m.write_trailer().unwrap_err().to_string()
798    }
799
800    #[test]
801    fn seekable_muxer_open_prefers_the_seekable_factory_and_falls_back() {
802        let mut r = FormatRegistry::new();
803        let with_muxer = |name| Format {
804            muxer: Some(|_| Box::new(TaggedMux("plain"))),
805            ..format(name)
806        };
807        r.register(with_muxer("plain"));
808        r.register(with_muxer("seeky"));
809        r.register(format("demux_only"));
810        r.register_seekable_muxer("seeky", |_| Box::new(TaggedMux("seekable")));
811        let output = || -> SeekOutput { Box::new(Cursor::new(Vec::new())) };
812        assert!(tag(r.open_muxer_seekable("seeky", output()).unwrap()).contains("seekable"));
813        // No seekable factory: the plain one serves the seekable output.
814        assert!(tag(r.open_muxer_seekable("plain", output()).unwrap()).contains("plain"));
815        // A plain open never takes the seekable path.
816        assert!(tag(r.open_muxer("seeky", Box::new(Vec::new())).unwrap()).contains("plain"));
817        assert!(matches!(
818            r.open_muxer_seekable("demux_only", output()),
819            Err(Error::MuxerNotFound(_))
820        ));
821        assert!(matches!(
822            r.open_muxer_seekable("missing", output()),
823            Err(Error::MuxerNotFound(_))
824        ));
825    }
826}