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 /// Stream `index`'s own metadata, in FFmpeg-style key names where FFmpeg
329 /// has one and the format's own otherwise (the JPEG MPF demuxer's
330 /// `mpf_type`). Available after [`read_header`](Demuxer::read_header);
331 /// `None` when the stream has none (the default).
332 fn stream_metadata(&self, _index: usize) -> Option<&Dictionary> {
333 None
334 }
335}
336
337/// One sample (packet) of a stream as the container's index records it.
338///
339/// The timestamps are the ones [`Demuxer::read_packet`] gives the sample, in
340/// the stream's time base, with the edit list applied; the edit list itself is
341/// [`SampleIndex::edit_list`]. `offset` and `size` locate the stored bytes, so
342/// a caller can also read them itself.
343#[derive(Debug, Clone, Copy, PartialEq, Eq)]
344pub struct SampleInfo {
345 /// File offset of the stored sample.
346 pub offset: u64,
347 /// Stored size in bytes.
348 pub size: u32,
349 /// Decode timestamp.
350 pub dts: i64,
351 /// Presentation timestamp.
352 pub pts: i64,
353 /// Duration (0 when the container does not say).
354 pub duration: i64,
355 /// A sync sample (keyframe): decoding can start here.
356 pub sync: bool,
357}
358
359/// One entry of a stream's edit list (MP4 `elst`): `segment_duration` of
360/// presentation, in the movie time scale, showing the media from
361/// `media_time` (stream time base); `media_time` -1 is an empty edit (a
362/// delay). `media_rate` is 16.16 fixed point (0x10000 = normal speed).
363#[derive(Debug, Clone, Copy, PartialEq, Eq)]
364pub struct EditEntry {
365 pub segment_duration: i64,
366 pub media_time: i64,
367 pub media_rate: i32,
368}
369
370/// Random access over a demuxer's index; see [`Demuxer::sample_index`].
371pub trait SampleIndex {
372 /// Samples in stream `stream` (0 for an unknown stream).
373 fn sample_count(&self, stream: usize) -> u64;
374
375 /// The index entry of sample `index` of `stream`, in decode order.
376 fn sample_info(&self, stream: usize, index: u64) -> Option<SampleInfo>;
377
378 /// Read sample `index` of `stream` as a packet, in the same form as
379 /// [`Demuxer::read_packet`] would give it (see
380 /// [`Demuxer::set_raw_samples`]).
381 fn read_sample(&mut self, stream: usize, index: u64) -> Result<Packet>;
382
383 /// The last sync sample of `stream` whose presentation time is at or
384 /// before `pts`: where decoding starts to show the frame at `pts`.
385 /// `None` if no sync sample is that early.
386 fn sync_at_or_before(&self, stream: usize, pts: i64) -> Option<u64>;
387
388 /// The stream's edit list (empty when it has none, or the container has
389 /// no such thing).
390 fn edit_list(&self, _stream: usize) -> &[EditEntry] {
391 &[]
392 }
393
394 /// The movie time scale [`EditEntry::segment_duration`] counts in (MP4
395 /// `mvhd`), when the container has one.
396 fn movie_timescale(&self) -> Option<u32> {
397 None
398 }
399
400 /// Samples in the stream's stored sample table: what
401 /// [`raw_sample_info`](SampleIndex::raw_sample_info) numbers. Without an
402 /// edit list this is [`sample_count`](SampleIndex::sample_count); an MP4
403 /// edit list can replay samples or leave some out of the edited index.
404 fn raw_sample_count(&self, stream: usize) -> u64 {
405 self.sample_count(stream)
406 }
407
408 /// Sample `index` of the stored sample table, in decode order, with the
409 /// edit list **not** applied: for MP4 the `stbl` row verbatim, `dts` the
410 /// sum of the `stts` deltas before it (0 for the first sample), `pts` =
411 /// `dts` + its `ctts` offset, `duration` its `stts` delta, all in the
412 /// media time scale (the stream's time base). An editor applies
413 /// [`edit_list`](SampleIndex::edit_list) itself on this — for example
414 /// AAC encoder priming (the first edit's `media_time`) and padding (where
415 /// its `segment_duration` ends) — and a muxer given these samples and the
416 /// same edit list ([`Muxer::set_edit_list`]) writes the same table back.
417 /// Defaults to [`sample_info`](SampleIndex::sample_info) for containers
418 /// without edit lists.
419 fn raw_sample_info(&self, stream: usize, index: u64) -> Option<SampleInfo> {
420 self.sample_info(stream, index)
421 }
422
423 /// Read stored sample `index` (numbered as
424 /// [`raw_sample_info`](SampleIndex::raw_sample_info) numbers them) as a
425 /// packet timed by that entry, shaped as
426 /// [`read_sample`](SampleIndex::read_sample) shapes it.
427 fn read_raw_sample(&mut self, stream: usize, index: u64) -> Result<Packet> {
428 self.read_sample(stream, index)
429 }
430
431 /// A shareable, `&self` view of this index for reading samples from
432 /// several places at once (an editor's media pool): cheap to clone (an
433 /// `Arc`), `Send + Sync`, and independent of this demuxer's
434 /// [`read_packet`](Demuxer::read_packet) position and of every other
435 /// source. Each call gives a source with its own read position; they
436 /// share the index tables and the input (reads take turns on it). Packets
437 /// are shaped as [`read_sample`](SampleIndex::read_sample) shapes them
438 /// at the time of the call (see [`Demuxer::set_raw_samples`]). `None`
439 /// from demuxers that cannot share their input (the default).
440 fn sample_source(&mut self) -> Option<std::sync::Arc<dyn SampleSource>> {
441 None
442 }
443}
444
445/// `&self` random access to a demuxed file's samples: see
446/// [`SampleIndex::sample_source`]. The methods mirror [`SampleIndex`]'s.
447pub trait SampleSource: Send + Sync {
448 fn sample_count(&self, stream: usize) -> u64;
449 fn sample_info(&self, stream: usize, index: u64) -> Option<SampleInfo>;
450 fn read_sample(&self, stream: usize, index: u64) -> Result<Packet>;
451 fn sync_at_or_before(&self, stream: usize, pts: i64) -> Option<u64>;
452 fn edit_list(&self, _stream: usize) -> &[EditEntry] {
453 &[]
454 }
455 fn movie_timescale(&self) -> Option<u32> {
456 None
457 }
458 fn raw_sample_count(&self, stream: usize) -> u64 {
459 self.sample_count(stream)
460 }
461 fn raw_sample_info(&self, stream: usize, index: u64) -> Option<SampleInfo> {
462 self.sample_info(stream, index)
463 }
464 fn read_raw_sample(&self, stream: usize, index: u64) -> Result<Packet> {
465 self.read_sample(stream, index)
466 }
467}
468
469/// One input shared by several readers, each with its own position: a
470/// `Read + Seek` handle over a [`SeekInput`] behind a mutex. Every read
471/// seeks the shared input to this handle's position first (skipped when it
472/// is already there), so handles never disturb each other. Cloning gives a
473/// handle at the same position. What demuxers use to hand out
474/// [`SampleSource`]s without reopening the file.
475#[derive(Clone)]
476pub struct SharedInput {
477 /// The input and where it currently stands (`None`: unknown).
478 inner: std::sync::Arc<std::sync::Mutex<(SeekInput, Option<u64>)>>,
479 pos: u64,
480}
481
482impl SharedInput {
483 /// Share `input`; the handle starts at the input's current position.
484 pub fn new(mut input: SeekInput) -> SharedInput {
485 let pos = input.stream_position().unwrap_or(0);
486 SharedInput {
487 inner: std::sync::Arc::new(std::sync::Mutex::new((input, Some(pos)))),
488 pos,
489 }
490 }
491}
492
493type SharedState = std::sync::Mutex<(SeekInput, Option<u64>)>;
494
495fn lock_shared(
496 inner: &SharedState,
497) -> std::io::Result<std::sync::MutexGuard<'_, (SeekInput, Option<u64>)>> {
498 inner
499 .lock()
500 .map_err(|_| std::io::Error::other("shared input poisoned"))
501}
502
503impl Read for SharedInput {
504 fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
505 let mut g = lock_shared(&self.inner)?;
506 let (input, at) = &mut *g;
507 if *at != Some(self.pos) {
508 *at = None;
509 input.seek(std::io::SeekFrom::Start(self.pos))?;
510 }
511 let n = input.read(buf)?;
512 self.pos += n as u64;
513 *at = Some(self.pos);
514 Ok(n)
515 }
516}
517
518impl Seek for SharedInput {
519 fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result<u64> {
520 let invalid = || std::io::Error::new(std::io::ErrorKind::InvalidInput, "seek before start");
521 self.pos = match pos {
522 std::io::SeekFrom::Start(n) => n,
523 std::io::SeekFrom::Current(d) => self.pos.checked_add_signed(d).ok_or_else(invalid)?,
524 std::io::SeekFrom::End(d) => {
525 let mut g = lock_shared(&self.inner)?;
526 let (input, at) = &mut *g;
527 let end = input.seek(std::io::SeekFrom::End(0))?;
528 *at = Some(end);
529 end.checked_add_signed(d).ok_or_else(invalid)?
530 }
531 };
532 Ok(self.pos)
533 }
534}
535
536/// Writes a container format: declare streams, write packets, finalize.
537pub trait Muxer: Send {
538 /// Hand the muxer output metadata (`-metadata title=...`). Called before
539 /// [`write_header`](Muxer::write_header); formats without a metadata slot
540 /// simply ignore it (the default).
541 fn set_metadata(&mut self, _metadata: &Dictionary) {}
542
543 /// Hand the muxer output stream `index`'s metadata (what the demuxer's
544 /// [`Demuxer::stream_metadata`] gave for the stream it came from). Called
545 /// before [`write_header`](Muxer::write_header); formats without
546 /// per-stream metadata ignore it (the default).
547 fn set_stream_metadata(&mut self, _index: usize, _metadata: &Dictionary) {}
548
549 /// A muxer option, FFmpeg-style (`movflags`, `+faststart`). Called before
550 /// [`write_header`](Muxer::write_header). Returns whether the muxer knows
551 /// the option; the default knows none.
552 fn set_option(&mut self, _key: &str, _value: &str) -> bool {
553 false
554 }
555
556 /// Write `edits` as stream `stream`'s edit list instead of the one the
557 /// muxer would derive (encoder delay, trims, a start delay). Segment
558 /// durations are in the muxer's movie time scale (1/1000 s for MP4 unless
559 /// `set_option("movie_timescale", ..)` picks another), media
560 /// times in the stream's time base, -1 for an empty edit. Called before
561 /// [`write_trailer`](Muxer::write_trailer). Returns whether the container
562 /// has edit lists; the default has none.
563 fn set_edit_list(&mut self, _stream: usize, _edits: &[EditEntry]) -> bool {
564 false
565 }
566
567 /// Write the container header for the given set of streams.
568 fn write_header(&mut self, streams: &[Stream]) -> Result<()>;
569
570 /// Write one packet (its `stream_index` selects the target stream).
571 fn write_packet(&mut self, packet: &Packet) -> Result<()>;
572
573 /// Finalize the container (indexes, trailers, fixups).
574 fn write_trailer(&mut self) -> Result<()>;
575}
576
577/// Factory opening a demuxer over an input byte source.
578pub type DemuxerFactory = fn(Input) -> Box<dyn Demuxer>;
579/// Factory opening a demuxer over a [`SeekInput`] — registered alongside the
580/// format's [`DemuxerFactory`] by formats that read less when they can seek.
581pub type SeekableDemuxerFactory = fn(SeekInput) -> Box<dyn Demuxer>;
582/// Factory opening a muxer over an output byte sink.
583pub type MuxerFactory = fn(Output) -> Box<dyn Muxer>;
584/// Factory opening a muxer over a [`SeekOutput`] -- registered alongside the
585/// format's [`MuxerFactory`] by formats that can stream when they can seek.
586pub type SeekableMuxerFactory = fn(SeekOutput) -> Box<dyn Muxer>;
587/// Factory opening a muxer that owns its own file set (HLS/DASH write a
588/// playlist/manifest plus many segment files, so a single byte sink cannot
589/// model them). Receives the output path and the format options
590/// (`-hls_time 6` → `{"hls_time": "6"}`).
591pub type PathMuxerFactory = fn(&std::path::Path, &Dictionary) -> Result<Box<dyn Muxer>>;
592/// Content sniffer: scores how strongly a byte prefix looks like this format,
593/// `0` (no match) to `100` (certain) — mirrors FFmpeg's `AVInputFormat::read_probe`.
594pub type ProbeFn = fn(&[u8]) -> i32;
595
596/// What a container's **muxer** will accept: the machine-readable half of the
597/// rules each muxer already enforces when it writes a header.
598///
599/// Muxers validate at run time, and a few historically wrote a zero codec tag
600/// rather than refusing an unmappable codec. Declaring the same rules here lets
601/// a caller answer "what can this file become?" *before* opening an encoder —
602/// which is what `rff-targets` is built on.
603#[derive(Debug, Clone, Copy, PartialEq, Eq)]
604pub struct MuxCaps {
605 /// Every codec this muxer can write. Empty for demux-only formats.
606 pub codecs: &'static [CodecId],
607 /// Most streams the container holds; `None` when there is no fixed limit.
608 pub max_streams: Option<usize>,
609 /// True when the container holds exactly ONE picture, so extra frames are
610 /// refused or dropped (png, jpeg, gif, webp, avif, jxl, av2f).
611 pub still_image: bool,
612}
613
614impl MuxCaps {
615 /// A format that cannot be written at all (demux-only).
616 pub const NONE: MuxCaps = MuxCaps {
617 codecs: &[],
618 max_streams: Some(0),
619 still_image: false,
620 };
621
622 /// A container interleaving any number of streams (mp4, matroska, mpegts).
623 pub const fn container(codecs: &'static [CodecId]) -> MuxCaps {
624 MuxCaps {
625 codecs,
626 max_streams: None,
627 still_image: false,
628 }
629 }
630
631 /// A file holding exactly one elementary stream (wav, mp3, ivf, ogg).
632 pub const fn single(codecs: &'static [CodecId]) -> MuxCaps {
633 MuxCaps {
634 codecs,
635 max_streams: Some(1),
636 still_image: false,
637 }
638 }
639
640 /// Narrow a [`single`](MuxCaps::single) file to one picture (png, jpeg).
641 pub const fn image(self) -> MuxCaps {
642 MuxCaps {
643 codecs: self.codecs,
644 max_streams: self.max_streams,
645 still_image: true,
646 }
647 }
648
649 /// Can this muxer write `id`?
650 pub fn accepts(&self, id: CodecId) -> bool {
651 self.codecs.contains(&id)
652 }
653
654 /// Can this muxer carry any stream of `media` at all?
655 pub fn accepts_media(&self, media: MediaType) -> bool {
656 self.codecs.iter().any(|c| c.media_type() == media)
657 }
658
659 /// The codecs this muxer accepts for one media category.
660 pub fn codecs_for(&self, media: MediaType) -> impl Iterator<Item = CodecId> + '_ {
661 self.codecs
662 .iter()
663 .copied()
664 .filter(move |c| c.media_type() == media)
665 }
666}
667
668/// Static description of a container format and its read/write support.
669pub struct Format {
670 /// Short name (`avi`, `mp4`, ...), as used by `ffmpeg -f <name>`.
671 pub name: &'static str,
672 pub long_name: &'static str,
673 /// File extensions that imply this format (without the dot).
674 pub extensions: &'static [&'static str],
675 /// Present if this format can be demuxed (read).
676 pub demuxer: Option<DemuxerFactory>,
677 /// Present if this format can be muxed (written).
678 pub muxer: Option<MuxerFactory>,
679 /// Present for formats that mux into a *path* (playlist + segment files)
680 /// rather than one byte sink — HLS, DASH. Mutually exclusive with `muxer`.
681 pub muxer_path: Option<PathMuxerFactory>,
682 /// Content sniffer for magic-byte detection (independent of the filename).
683 pub probe: Option<ProbeFn>,
684 /// What this format's muxer accepts. [`MuxCaps::NONE`] for demux-only
685 /// formats. Keep it in step with the muxer — `tests/mux_caps.rs` gates it.
686 pub mux_caps: MuxCaps,
687}
688
689impl Format {
690 pub fn can_demux(&self) -> bool {
691 self.demuxer.is_some()
692 }
693 pub fn can_mux(&self) -> bool {
694 self.muxer.is_some() || self.muxer_path.is_some()
695 }
696}
697
698/// Holds every container format known to a running engine.
699#[derive(Default)]
700pub struct FormatRegistry {
701 by_name: HashMap<&'static str, Format>,
702 /// Seek-aware demuxer factories, keyed by format name (see
703 /// [`register_seekable_demuxer`](Self::register_seekable_demuxer)).
704 seekable: HashMap<&'static str, SeekableDemuxerFactory>,
705 /// Seek-aware muxer factories, keyed by format name (see
706 /// [`register_seekable_muxer`](Self::register_seekable_muxer)).
707 seekable_muxers: HashMap<&'static str, SeekableMuxerFactory>,
708}
709
710impl FormatRegistry {
711 pub fn new() -> FormatRegistry {
712 FormatRegistry::default()
713 }
714
715 pub fn register(&mut self, format: Format) {
716 self.by_name.insert(format.name, format);
717 }
718
719 /// Give the format named `name` a demuxer that takes a [`SeekInput`]. Used
720 /// by [`open_demuxer_seekable`](Self::open_demuxer_seekable) when the caller
721 /// has a seekable source; the plain [`Format::demuxer`] still serves pipes
722 /// and sockets.
723 pub fn register_seekable_demuxer(
724 &mut self,
725 name: &'static str,
726 factory: SeekableDemuxerFactory,
727 ) {
728 self.seekable.insert(name, factory);
729 }
730
731 pub fn by_name(&self, name: &str) -> Option<&Format> {
732 self.by_name.get(name)
733 }
734
735 /// Find a format whose extension list contains `ext` (case-insensitive,
736 /// no leading dot). The cheap "guess by filename" path; [`probe`](Self::probe)
737 /// inspects content instead.
738 pub fn by_extension(&self, ext: &str) -> Option<&Format> {
739 let ext = ext.trim_start_matches('.').to_ascii_lowercase();
740 self.by_name
741 .values()
742 .find(|f| f.extensions.iter().any(|e| e.eq_ignore_ascii_case(&ext)))
743 }
744
745 /// Identify a format by sniffing a byte prefix: the registered format whose
746 /// [`probe`](Format::probe) returns the highest positive score wins. Returns
747 /// `None` if nothing recognizes the data.
748 pub fn probe(&self, data: &[u8]) -> Option<&Format> {
749 self.by_name
750 .values()
751 .filter_map(|f| f.probe.map(|p| (p(data), f)))
752 .filter(|(score, _)| *score > 0)
753 .max_by_key(|(score, _)| *score)
754 .map(|(_, f)| f)
755 }
756
757 /// Open a demuxer for the format named `name`.
758 pub fn open_demuxer(&self, name: &str, input: Input) -> Result<Box<dyn Demuxer>> {
759 self.by_name
760 .get(name)
761 .and_then(|f| f.demuxer)
762 .map(|factory| factory(input))
763 .ok_or_else(|| Error::DemuxerNotFound(name.to_string()))
764 }
765
766 /// Open a demuxer over a seekable input: the format's seek-aware demuxer if
767 /// it registered one, otherwise its plain streaming demuxer (a seekable
768 /// source is still a byte stream). Callers that hold a file should prefer
769 /// this — it is what lets MP4 read only `moov` instead of the whole file.
770 pub fn open_demuxer_seekable(&self, name: &str, input: SeekInput) -> Result<Box<dyn Demuxer>> {
771 if !self.by_name.get(name).is_some_and(Format::can_demux) {
772 return Err(Error::DemuxerNotFound(name.to_string()));
773 }
774 match self.seekable.get(name) {
775 Some(factory) => Ok(factory(input)),
776 None => self.open_demuxer(name, input),
777 }
778 }
779
780 /// Give the format named `name` a muxer that takes a [`SeekOutput`]. Used
781 /// by [`open_muxer_seekable`](Self::open_muxer_seekable) when the caller
782 /// writes to something seekable; the plain [`Format::muxer`] still serves
783 /// pipes and sockets.
784 pub fn register_seekable_muxer(&mut self, name: &'static str, factory: SeekableMuxerFactory) {
785 self.seekable_muxers.insert(name, factory);
786 }
787
788 /// Open a muxer over a seekable output: the format's seek-aware muxer if it
789 /// registered one, otherwise its plain muxer (a seekable sink is still a
790 /// byte sink). Callers writing a file should prefer this -- it is what lets
791 /// MP4/Matroska/AVI/WAV stream instead of buffering the whole output.
792 pub fn open_muxer_seekable(&self, name: &str, output: SeekOutput) -> Result<Box<dyn Muxer>> {
793 if self.by_name.get(name).is_none_or(|f| f.muxer.is_none()) {
794 return Err(Error::MuxerNotFound(name.to_string()));
795 }
796 match self.seekable_muxers.get(name) {
797 Some(factory) => Ok(factory(output)),
798 None => self.open_muxer(name, output),
799 }
800 }
801
802 /// Open a muxer for the format named `name`.
803 pub fn open_muxer(&self, name: &str, output: Output) -> Result<Box<dyn Muxer>> {
804 self.by_name
805 .get(name)
806 .and_then(|f| f.muxer)
807 .map(|factory| factory(output))
808 .ok_or_else(|| Error::MuxerNotFound(name.to_string()))
809 }
810
811 pub fn iter(&self) -> impl Iterator<Item = &Format> {
812 self.by_name.values()
813 }
814
815 pub fn len(&self) -> usize {
816 self.by_name.len()
817 }
818
819 pub fn is_empty(&self) -> bool {
820 self.by_name.is_empty()
821 }
822}
823
824#[cfg(test)]
825mod tests {
826 use super::*;
827 use std::io::Cursor;
828
829 /// Reports which factory built it via the stream count.
830 struct Tagged(usize);
831 impl Demuxer for Tagged {
832 fn read_header(&mut self) -> Result<Vec<Stream>> {
833 Ok((0..self.0).map(|i| Stream::new(i, CodecId::None)).collect())
834 }
835 fn read_packet(&mut self) -> Result<rff_core::Packet> {
836 Err(Error::Eof)
837 }
838 }
839
840 fn format(name: &'static str) -> Format {
841 Format {
842 name,
843 long_name: name,
844 extensions: &[],
845 demuxer: Some(|_| Box::new(Tagged(1))),
846 muxer: None,
847 muxer_path: None,
848 probe: None,
849 mux_caps: MuxCaps::NONE,
850 }
851 }
852
853 fn streams(mut d: Box<dyn Demuxer>) -> usize {
854 d.read_header().unwrap().len()
855 }
856
857 #[test]
858 fn shared_input_handles_keep_their_own_positions() {
859 let data: Vec<u8> = (0..=255).collect();
860 let mut a = SharedInput::new(Box::new(Cursor::new(data)));
861 let mut b = a.clone();
862 b.seek(std::io::SeekFrom::Start(200)).unwrap();
863 let mut x = [0u8; 3];
864 a.read_exact(&mut x).unwrap();
865 assert_eq!(x, [0, 1, 2]);
866 b.read_exact(&mut x).unwrap();
867 assert_eq!(x, [200, 201, 202]);
868 a.read_exact(&mut x).unwrap();
869 assert_eq!(x, [3, 4, 5]);
870 assert_eq!(b.seek(std::io::SeekFrom::End(-1)).unwrap(), 255);
871 let t = std::thread::spawn(move || {
872 let mut y = [0u8; 1];
873 b.read_exact(&mut y).unwrap();
874 y[0]
875 });
876 assert_eq!(t.join().unwrap(), 255);
877 }
878
879 #[test]
880 fn rotation_matrices_round_trip() {
881 for deg in [0.0, 90.0, 180.0, 270.0, 30.0, 315.0] {
882 let m = rotation_matrix(deg, 1920, 1080);
883 assert_eq!(matrix_rotation(&m), Some(deg), "{deg}");
884 }
885 // An iPhone portrait clip: rotate 90 degrees clockwise, translated by the height.
886 let m = rotation_matrix(-270.0, 1920, 1080);
887 assert_eq!(m, [0, 0x10000, 0, -0x10000, 0, 0, 1080 << 16, 0, 1 << 30]);
888 // A horizontal flip is not a rotation.
889 let flip = [-0x10000, 0, 0, 0, 0x10000, 0, 0, 0, 1 << 30];
890 assert_eq!(matrix_rotation(&flip), None);
891 let mut s = Stream::new(0, CodecId::H264);
892 (s.width, s.height) = (640, 480);
893 assert_eq!(s.rotation(), Some(0.0));
894 s.set_rotation(90.0);
895 assert_eq!(s.rotation(), Some(90.0));
896 s.set_rotation(360.0);
897 assert_eq!(s.display_matrix, None);
898 }
899
900 #[test]
901 fn seekable_open_prefers_the_seekable_factory_and_falls_back() {
902 let mut r = FormatRegistry::new();
903 r.register(format("plain"));
904 r.register(format("seeky"));
905 r.register_seekable_demuxer("seeky", |_| Box::new(Tagged(2)));
906 let input = || -> SeekInput { Box::new(Cursor::new(vec![0u8; 4])) };
907 assert_eq!(
908 streams(r.open_demuxer_seekable("seeky", input()).unwrap()),
909 2
910 );
911 // No seekable factory: the streaming one serves the seekable input.
912 assert_eq!(
913 streams(r.open_demuxer_seekable("plain", input()).unwrap()),
914 1
915 );
916 // A plain stream open never takes the seekable path.
917 assert_eq!(
918 streams(
919 r.open_demuxer("seeky", Box::new(Cursor::new(vec![])))
920 .unwrap()
921 ),
922 1
923 );
924 assert!(matches!(
925 r.open_demuxer_seekable("missing", input()),
926 Err(Error::DemuxerNotFound(_))
927 ));
928 }
929
930 /// Reports which factory built it through the error `write_trailer` returns.
931 struct TaggedMux(&'static str);
932 impl Muxer for TaggedMux {
933 fn write_header(&mut self, _: &[Stream]) -> Result<()> {
934 Ok(())
935 }
936 fn write_packet(&mut self, _: &rff_core::Packet) -> Result<()> {
937 Ok(())
938 }
939 fn write_trailer(&mut self) -> Result<()> {
940 Err(Error::invalid(self.0))
941 }
942 }
943
944 fn tag(mut m: Box<dyn Muxer>) -> String {
945 m.write_trailer().unwrap_err().to_string()
946 }
947
948 #[test]
949 fn seekable_muxer_open_prefers_the_seekable_factory_and_falls_back() {
950 let mut r = FormatRegistry::new();
951 let with_muxer = |name| Format {
952 muxer: Some(|_| Box::new(TaggedMux("plain"))),
953 ..format(name)
954 };
955 r.register(with_muxer("plain"));
956 r.register(with_muxer("seeky"));
957 r.register(format("demux_only"));
958 r.register_seekable_muxer("seeky", |_| Box::new(TaggedMux("seekable")));
959 let output = || -> SeekOutput { Box::new(Cursor::new(Vec::new())) };
960 assert!(tag(r.open_muxer_seekable("seeky", output()).unwrap()).contains("seekable"));
961 // No seekable factory: the plain one serves the seekable output.
962 assert!(tag(r.open_muxer_seekable("plain", output()).unwrap()).contains("plain"));
963 // A plain open never takes the seekable path.
964 assert!(tag(r.open_muxer("seeky", Box::new(Vec::new())).unwrap()).contains("plain"));
965 assert!(matches!(
966 r.open_muxer_seekable("demux_only", output()),
967 Err(Error::MuxerNotFound(_))
968 ));
969 assert!(matches!(
970 r.open_muxer_seekable("missing", output()),
971 Err(Error::MuxerNotFound(_))
972 ));
973 }
974}