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