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