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