rff_format/lib.rs
1//! `rff-format` — the container (muxer/demuxer) abstraction layer (FFmpeg's
2//! `libavformat` core, minus the formats themselves).
3//!
4//! A container is the file wrapper (AVI, MP4, Matroska, ...) that interleaves
5//! one or more elementary streams. This crate defines:
6//! * [`Stream`] — the description of one elementary stream inside a container,
7//! * [`Demuxer`] — reads a container, exposing streams and [`Packet`]s,
8//! * [`Muxer`] — writes streams + packets back into a container,
9//! * [`FormatRegistry`] — what individual format crates register into.
10//!
11//! Concrete formats live in their own crates (`rff-format-avi`, ...).
12
13pub mod aac;
14pub mod av1;
15pub mod avc;
16pub mod hvc;
17
18use std::collections::HashMap;
19use std::io::{Read, Write};
20
21use rff_core::{
22 CodecId, ColorRange, Dictionary, Error, MediaType, Packet, PixelFormat, Rational, Result,
23 SampleFormat,
24};
25
26/// Description of one elementary stream within a container.
27#[derive(Debug, Clone)]
28pub struct Stream {
29 /// Position of this stream within its container.
30 pub index: usize,
31 pub codec_id: CodecId,
32 pub media_type: MediaType,
33 /// Unit of all timestamps on packets of this stream.
34 pub time_base: Rational,
35 // --- Video parameters (zero/ignored for non-video) ---
36 pub width: u32,
37 pub height: u32,
38 /// Raw pixel layout, when known (raw video). Self-describing codecs leave this `None`.
39 pub pixel_format: Option<PixelFormat>,
40 /// Luma/chroma value range. JPEG and PNG sources are always
41 /// [`ColorRange::Full`]; leaving it [`Unspecified`](ColorRange::Unspecified)
42 /// makes containers label the data limited-range, which silently corrupts it.
43 pub color_range: ColorRange,
44 // --- Audio parameters (zero/ignored for non-audio) ---
45 pub sample_rate: u32,
46 pub channels: u16,
47 /// Raw sample layout, when known (PCM). Self-describing codecs leave this `None`.
48 pub sample_format: Option<SampleFormat>,
49 /// Codec-private initialization data (e.g. H.264 SPS/PPS, OpusHead). Empty
50 /// for codecs whose bitstream is fully self-describing.
51 pub extradata: Vec<u8>,
52 /// Total stream duration in [`time_base`](Stream::time_base) units, when
53 /// the container declares it (MP4 `mdhd`, Matroska `Duration`). `None` when
54 /// unknown (live streams, TS).
55 pub duration: Option<i64>,
56 /// Total packet count (frames for video), when the container's index
57 /// declares it. `None` when unknown — never a guess.
58 pub nb_frames: Option<u64>,
59}
60
61impl Stream {
62 /// Create a stream with sane defaults for the given codec.
63 pub fn new(index: usize, codec_id: CodecId) -> Stream {
64 Stream {
65 index,
66 codec_id,
67 media_type: codec_id.media_type(),
68 time_base: Rational::new(1, 1000),
69 width: 0,
70 height: 0,
71 pixel_format: None,
72 color_range: ColorRange::Unspecified,
73 sample_rate: 0,
74 channels: 0,
75 sample_format: None,
76 extradata: Vec::new(),
77 duration: None,
78 nb_frames: None,
79 }
80 }
81}
82
83/// A byte source a demuxer reads from. (`Box<dyn Read + Send>` keeps the trait
84/// object-safe and lets inputs be files, network streams, or in-memory buffers.)
85pub type Input = Box<dyn Read + Send>;
86/// A byte sink a muxer writes to.
87pub type Output = Box<dyn Write + Send>;
88
89/// Reads a container format: parses the header into [`Stream`]s, then yields
90/// [`Packet`]s until the input is exhausted.
91pub trait Demuxer: Send {
92 /// Parse the container header and return its streams.
93 fn read_header(&mut self) -> Result<Vec<Stream>>;
94
95 /// Read the next packet. Returns [`Error::Eof`] at end of input.
96 fn read_packet(&mut self) -> Result<Packet>;
97}
98
99/// Writes a container format: declare streams, write packets, finalize.
100pub trait Muxer: Send {
101 /// Hand the muxer output metadata (`-metadata title=...`). Called before
102 /// [`write_header`](Muxer::write_header); formats without a metadata slot
103 /// simply ignore it (the default).
104 fn set_metadata(&mut self, _metadata: &Dictionary) {}
105
106 /// Write the container header for the given set of streams.
107 fn write_header(&mut self, streams: &[Stream]) -> Result<()>;
108
109 /// Write one packet (its `stream_index` selects the target stream).
110 fn write_packet(&mut self, packet: &Packet) -> Result<()>;
111
112 /// Finalize the container (indexes, trailers, fixups).
113 fn write_trailer(&mut self) -> Result<()>;
114}
115
116/// Factory opening a demuxer over an input byte source.
117pub type DemuxerFactory = fn(Input) -> Box<dyn Demuxer>;
118/// Factory opening a muxer over an output byte sink.
119pub type MuxerFactory = fn(Output) -> Box<dyn Muxer>;
120/// Factory opening a muxer that owns its own file set (HLS/DASH write a
121/// playlist/manifest plus many segment files, so a single byte sink cannot
122/// model them). Receives the output path and the format options
123/// (`-hls_time 6` → `{"hls_time": "6"}`).
124pub type PathMuxerFactory =
125 fn(&std::path::Path, &Dictionary) -> Result<Box<dyn Muxer>>;
126/// Content sniffer: scores how strongly a byte prefix looks like this format,
127/// `0` (no match) to `100` (certain) — mirrors FFmpeg's `AVInputFormat::read_probe`.
128pub type ProbeFn = fn(&[u8]) -> i32;
129
130/// What a container's **muxer** will accept: the machine-readable half of the
131/// rules each muxer already enforces when it writes a header.
132///
133/// Muxers validate at run time, and a few historically wrote a zero codec tag
134/// rather than refusing an unmappable codec. Declaring the same rules here lets
135/// a caller answer "what can this file become?" *before* opening an encoder —
136/// which is what `rff-targets` is built on.
137#[derive(Debug, Clone, Copy, PartialEq, Eq)]
138pub struct MuxCaps {
139 /// Every codec this muxer can write. Empty for demux-only formats.
140 pub codecs: &'static [CodecId],
141 /// Most streams the container holds; `None` when there is no fixed limit.
142 pub max_streams: Option<usize>,
143 /// True when the container holds exactly ONE picture, so extra frames are
144 /// refused or dropped (png, jpeg, gif, webp, avif, jxl, av2f).
145 pub still_image: bool,
146}
147
148impl MuxCaps {
149 /// A format that cannot be written at all (demux-only).
150 pub const NONE: MuxCaps = MuxCaps {
151 codecs: &[],
152 max_streams: Some(0),
153 still_image: false,
154 };
155
156 /// A container interleaving any number of streams (mp4, matroska, mpegts).
157 pub const fn container(codecs: &'static [CodecId]) -> MuxCaps {
158 MuxCaps {
159 codecs,
160 max_streams: None,
161 still_image: false,
162 }
163 }
164
165 /// A file holding exactly one elementary stream (wav, mp3, ivf, ogg).
166 pub const fn single(codecs: &'static [CodecId]) -> MuxCaps {
167 MuxCaps {
168 codecs,
169 max_streams: Some(1),
170 still_image: false,
171 }
172 }
173
174 /// Narrow a [`single`](MuxCaps::single) file to one picture (png, jpeg).
175 pub const fn image(self) -> MuxCaps {
176 MuxCaps {
177 codecs: self.codecs,
178 max_streams: self.max_streams,
179 still_image: true,
180 }
181 }
182
183 /// Can this muxer write `id`?
184 pub fn accepts(&self, id: CodecId) -> bool {
185 self.codecs.contains(&id)
186 }
187
188 /// Can this muxer carry any stream of `media` at all?
189 pub fn accepts_media(&self, media: MediaType) -> bool {
190 self.codecs.iter().any(|c| c.media_type() == media)
191 }
192
193 /// The codecs this muxer accepts for one media category.
194 pub fn codecs_for(&self, media: MediaType) -> impl Iterator<Item = CodecId> + '_ {
195 self.codecs
196 .iter()
197 .copied()
198 .filter(move |c| c.media_type() == media)
199 }
200}
201
202/// Static description of a container format and its read/write support.
203pub struct Format {
204 /// Short name (`avi`, `mp4`, ...), as used by `ffmpeg -f <name>`.
205 pub name: &'static str,
206 pub long_name: &'static str,
207 /// File extensions that imply this format (without the dot).
208 pub extensions: &'static [&'static str],
209 /// Present if this format can be demuxed (read).
210 pub demuxer: Option<DemuxerFactory>,
211 /// Present if this format can be muxed (written).
212 pub muxer: Option<MuxerFactory>,
213 /// Present for formats that mux into a *path* (playlist + segment files)
214 /// rather than one byte sink — HLS, DASH. Mutually exclusive with `muxer`.
215 pub muxer_path: Option<PathMuxerFactory>,
216 /// Content sniffer for magic-byte detection (independent of the filename).
217 pub probe: Option<ProbeFn>,
218 /// What this format's muxer accepts. [`MuxCaps::NONE`] for demux-only
219 /// formats. Keep it in step with the muxer — `tests/mux_caps.rs` gates it.
220 pub mux_caps: MuxCaps,
221}
222
223impl Format {
224 pub fn can_demux(&self) -> bool {
225 self.demuxer.is_some()
226 }
227 pub fn can_mux(&self) -> bool {
228 self.muxer.is_some() || self.muxer_path.is_some()
229 }
230}
231
232/// Holds every container format known to a running engine.
233#[derive(Default)]
234pub struct FormatRegistry {
235 by_name: HashMap<&'static str, Format>,
236}
237
238impl FormatRegistry {
239 pub fn new() -> FormatRegistry {
240 FormatRegistry::default()
241 }
242
243 pub fn register(&mut self, format: Format) {
244 self.by_name.insert(format.name, format);
245 }
246
247 pub fn by_name(&self, name: &str) -> Option<&Format> {
248 self.by_name.get(name)
249 }
250
251 /// Find a format whose extension list contains `ext` (case-insensitive,
252 /// no leading dot). The cheap "guess by filename" path; [`probe`](Self::probe)
253 /// inspects content instead.
254 pub fn by_extension(&self, ext: &str) -> Option<&Format> {
255 let ext = ext.trim_start_matches('.').to_ascii_lowercase();
256 self.by_name
257 .values()
258 .find(|f| f.extensions.iter().any(|e| e.eq_ignore_ascii_case(&ext)))
259 }
260
261 /// Identify a format by sniffing a byte prefix: the registered format whose
262 /// [`probe`](Format::probe) returns the highest positive score wins. Returns
263 /// `None` if nothing recognizes the data.
264 pub fn probe(&self, data: &[u8]) -> Option<&Format> {
265 self.by_name
266 .values()
267 .filter_map(|f| f.probe.map(|p| (p(data), f)))
268 .filter(|(score, _)| *score > 0)
269 .max_by_key(|(score, _)| *score)
270 .map(|(_, f)| f)
271 }
272
273 /// Open a demuxer for the format named `name`.
274 pub fn open_demuxer(&self, name: &str, input: Input) -> Result<Box<dyn Demuxer>> {
275 self.by_name
276 .get(name)
277 .and_then(|f| f.demuxer)
278 .map(|factory| factory(input))
279 .ok_or_else(|| Error::DemuxerNotFound(name.to_string()))
280 }
281
282 /// Open a muxer for the format named `name`.
283 pub fn open_muxer(&self, name: &str, output: Output) -> Result<Box<dyn Muxer>> {
284 self.by_name
285 .get(name)
286 .and_then(|f| f.muxer)
287 .map(|factory| factory(output))
288 .ok_or_else(|| Error::MuxerNotFound(name.to_string()))
289 }
290
291 pub fn iter(&self) -> impl Iterator<Item = &Format> {
292 self.by_name.values()
293 }
294
295 pub fn len(&self) -> usize {
296 self.by_name.len()
297 }
298
299 pub fn is_empty(&self) -> bool {
300 self.by_name.is_empty()
301 }
302}