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, Seek, Write};
20
21use rff_core::{
22 CleanAperture, CodecId, ColorInfo, ColorRange, ContentLightLevel, Dictionary, Error,
23 MasteringDisplay, MediaType, Packet, PixelFormat, Rational, Result, SampleFormat, Timecode,
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 /// The container's own code for this codec, when it has one worth
60 /// keeping: the MP4/QuickTime sample-entry fourcc (`apch` vs `apcn` names
61 /// the ProRes profile, `twos` vs `sowt` the PCM byte order on disk). A
62 /// muxer of the same family writes it back when it is valid for the
63 /// codec, so a remux keeps the original entry; `None` lets the muxer pick.
64 pub codec_tag: Option<[u8; 4]>,
65 // --- Video description (containers label; they do not convert) ---
66 /// Colour primaries / transfer / matrix (MP4 `colr`, Matroska `Colour`).
67 pub color: ColorInfo,
68 /// HDR mastering display (MP4 `mdcv`, Matroska `MasteringMetadata`).
69 pub mastering_display: Option<MasteringDisplay>,
70 /// HDR content light level (MP4 `clli`, Matroska `MaxCLL`/`MaxFALL`).
71 pub content_light: Option<ContentLightLevel>,
72 /// Pixel aspect ratio as `(horizontal, vertical)` spacing (MP4 `pasp`).
73 /// `None` when not recorded, which means square.
74 pub pixel_aspect: Option<(u32, u32)>,
75 /// Clean aperture (MP4 `clap`).
76 pub clean_aperture: Option<CleanAperture>,
77 /// Start timecode (a QuickTime `tmcd` track referenced by this video track).
78 pub timecode: Option<Timecode>,
79 /// The frames carry an alpha plane as a block addition (Matroska
80 /// `AlphaMode`; WebM VP8/VP9 alpha).
81 pub alpha_mode: bool,
82 // --- Audio timing the container records beside the packets ---
83 /// Samples the decoder must drop from the start, in nanoseconds
84 /// (Matroska `CodecDelay`; Opus pre-skip). The demuxer has already taken
85 /// it off packet timestamps; it is here so a remux can write it back.
86 pub codec_delay_ns: u64,
87 /// How far before a seek target decoding must start to converge, in
88 /// nanoseconds (Matroska `SeekPreRoll`; 80 ms for Opus).
89 pub seek_preroll_ns: u64,
90}
91
92impl Stream {
93 /// Create a stream with sane defaults for the given codec.
94 pub fn new(index: usize, codec_id: CodecId) -> Stream {
95 Stream {
96 index,
97 codec_id,
98 media_type: codec_id.media_type(),
99 time_base: Rational::new(1, 1000),
100 width: 0,
101 height: 0,
102 pixel_format: None,
103 color_range: ColorRange::Unspecified,
104 sample_rate: 0,
105 channels: 0,
106 sample_format: None,
107 extradata: Vec::new(),
108 duration: None,
109 nb_frames: None,
110 codec_tag: None,
111 color: ColorInfo::UNSPECIFIED,
112 mastering_display: None,
113 content_light: None,
114 pixel_aspect: None,
115 clean_aperture: None,
116 timecode: None,
117 alpha_mode: false,
118 codec_delay_ns: 0,
119 seek_preroll_ns: 0,
120 }
121 }
122}
123
124/// A byte source a demuxer reads from. (`Box<dyn Read + Send>` keeps the trait
125/// object-safe and lets inputs be files, network streams, or in-memory buffers.)
126pub type Input = Box<dyn Read + Send>;
127
128/// A byte source that can also seek — what a local file or an in-memory buffer
129/// offers and a pipe or socket does not. Blanket-implemented for every
130/// `Read + Seek` type.
131pub trait ReadSeek: Read + Seek {}
132impl<T: Read + Seek> ReadSeek for T {}
133
134/// A seekable [`Input`]. Formats whose index can sit anywhere in the file (MP4's
135/// `moov`) use it to read only that index and fetch each payload on demand,
136/// instead of buffering the whole file. It upcasts to [`Input`] for formats
137/// that only stream.
138pub type SeekInput = Box<dyn ReadSeek + Send>;
139/// A byte sink a muxer writes to.
140pub type Output = Box<dyn Write + Send>;
141
142/// A byte sink that can also seek -- a local file, an in-memory buffer; not a
143/// pipe or socket. Blanket-implemented for every `Write + Seek` type.
144pub trait WriteSeek: Write + Seek {}
145impl<T: Write + Seek> WriteSeek for T {}
146
147/// A seekable [`Output`]. Containers whose header records sizes or an index
148/// that is only known at the end (MP4 `mdat`/`moov`, Matroska Segment/Cues,
149/// AVI `movi`/`idx1`, WAV `RIFF`/`data`) use it to stream the payload as it
150/// arrives and patch the header afterwards, instead of holding the whole
151/// output in memory until the trailer (#28). It upcasts to [`Output`] for
152/// muxers that only stream.
153pub type SeekOutput = Box<dyn WriteSeek + Send>;
154
155/// Reads a container format: parses the header into [`Stream`]s, then yields
156/// [`Packet`]s until the input is exhausted.
157pub trait Demuxer: Send {
158 /// Parse the container header and return its streams.
159 fn read_header(&mut self) -> Result<Vec<Stream>>;
160
161 /// Read the next packet. Returns [`Error::Eof`] at end of input.
162 fn read_packet(&mut self) -> Result<Packet>;
163
164 /// Name the streams the caller will drop: `discard[i]` is stream `i`.
165 /// Called after [`read_header`](Demuxer::read_header); a demuxer may then
166 /// skip those streams' packets without reading or converting them. It is
167 /// a hint: a demuxer that ignores it (the default) still returns them and
168 /// the caller drops them, so either way the kept packets are identical.
169 fn set_discard(&mut self, _discard: &[bool]) {}
170
171 /// Random access to the container's index, for an editor that jumps to a
172 /// frame instead of reading the file in order: per-stream sample tables,
173 /// reading a sample by number, and the sync sample at or before a time.
174 /// Available after [`read_header`](Demuxer::read_header) from demuxers
175 /// whose container has an index (MP4 sample tables, Matroska clusters and
176 /// Cues); `None` from the rest (the default). Reading through the index
177 /// does not move [`read_packet`](Demuxer::read_packet)'s position.
178 fn sample_index(&mut self) -> Option<&mut dyn SampleIndex> {
179 None
180 }
181
182 /// Hand out samples as the container stores them instead of in the form
183 /// rff's decoders take: H.264 / HEVC length-prefixed (AVCC / HVCC)
184 /// rather than Annex-B with the parameter sets put in front of each
185 /// keyframe, PCM in the stored byte order, ASS events in Matroska as
186 /// stored. Storage transforms of the container itself (Matroska
187 /// ContentEncodings and header stripping, the ProRes frame header MKV
188 /// drops) are still undone, so a sample is always a whole codec frame.
189 /// Call it after
190 /// [`read_header`](Demuxer::read_header); it applies to
191 /// [`read_packet`](Demuxer::read_packet) and to [`SampleIndex::read_sample`].
192 /// Returns whether the demuxer honours it (the default does not: its
193 /// samples are already stored as they are handed out).
194 fn set_raw_samples(&mut self, _raw: bool) -> bool {
195 false
196 }
197}
198
199/// One sample (packet) of a stream as the container's index records it.
200///
201/// The timestamps are the ones [`Demuxer::read_packet`] gives the sample, in
202/// the stream's time base, with the edit list applied; the edit list itself is
203/// [`SampleIndex::edit_list`]. `offset` and `size` locate the stored bytes, so
204/// a caller can also read them itself.
205#[derive(Debug, Clone, Copy, PartialEq, Eq)]
206pub struct SampleInfo {
207 /// File offset of the stored sample.
208 pub offset: u64,
209 /// Stored size in bytes.
210 pub size: u32,
211 /// Decode timestamp.
212 pub dts: i64,
213 /// Presentation timestamp.
214 pub pts: i64,
215 /// Duration (0 when the container does not say).
216 pub duration: i64,
217 /// A sync sample (keyframe): decoding can start here.
218 pub sync: bool,
219}
220
221/// One entry of a stream's edit list (MP4 `elst`): `segment_duration` of
222/// presentation, in the movie time scale, showing the media from
223/// `media_time` (stream time base); `media_time` -1 is an empty edit (a
224/// delay). `media_rate` is 16.16 fixed point (0x10000 = normal speed).
225#[derive(Debug, Clone, Copy, PartialEq, Eq)]
226pub struct EditEntry {
227 pub segment_duration: i64,
228 pub media_time: i64,
229 pub media_rate: i32,
230}
231
232/// Random access over a demuxer's index; see [`Demuxer::sample_index`].
233pub trait SampleIndex {
234 /// Samples in stream `stream` (0 for an unknown stream).
235 fn sample_count(&self, stream: usize) -> u64;
236
237 /// The index entry of sample `index` of `stream`, in decode order.
238 fn sample_info(&self, stream: usize, index: u64) -> Option<SampleInfo>;
239
240 /// Read sample `index` of `stream` as a packet, in the same form as
241 /// [`Demuxer::read_packet`] would give it (see
242 /// [`Demuxer::set_raw_samples`]).
243 fn read_sample(&mut self, stream: usize, index: u64) -> Result<Packet>;
244
245 /// The last sync sample of `stream` whose presentation time is at or
246 /// before `pts`: where decoding starts to show the frame at `pts`.
247 /// `None` if no sync sample is that early.
248 fn sync_at_or_before(&self, stream: usize, pts: i64) -> Option<u64>;
249
250 /// The stream's edit list (empty when it has none, or the container has
251 /// no such thing).
252 fn edit_list(&self, _stream: usize) -> &[EditEntry] {
253 &[]
254 }
255
256 /// The movie time scale [`EditEntry::segment_duration`] counts in (MP4
257 /// `mvhd`), when the container has one.
258 fn movie_timescale(&self) -> Option<u32> {
259 None
260 }
261}
262
263/// Writes a container format: declare streams, write packets, finalize.
264pub trait Muxer: Send {
265 /// Hand the muxer output metadata (`-metadata title=...`). Called before
266 /// [`write_header`](Muxer::write_header); formats without a metadata slot
267 /// simply ignore it (the default).
268 fn set_metadata(&mut self, _metadata: &Dictionary) {}
269
270 /// A muxer option, FFmpeg-style (`movflags`, `+faststart`). Called before
271 /// [`write_header`](Muxer::write_header). Returns whether the muxer knows
272 /// the option; the default knows none.
273 fn set_option(&mut self, _key: &str, _value: &str) -> bool {
274 false
275 }
276
277 /// Write `edits` as stream `stream`'s edit list instead of the one the
278 /// muxer would derive (encoder delay, trims, a start delay). Segment
279 /// durations are in the muxer's movie time scale (1/1000 s for MP4), media
280 /// times in the stream's time base, -1 for an empty edit. Called before
281 /// [`write_trailer`](Muxer::write_trailer). Returns whether the container
282 /// has edit lists; the default has none.
283 fn set_edit_list(&mut self, _stream: usize, _edits: &[EditEntry]) -> bool {
284 false
285 }
286
287 /// Write the container header for the given set of streams.
288 fn write_header(&mut self, streams: &[Stream]) -> Result<()>;
289
290 /// Write one packet (its `stream_index` selects the target stream).
291 fn write_packet(&mut self, packet: &Packet) -> Result<()>;
292
293 /// Finalize the container (indexes, trailers, fixups).
294 fn write_trailer(&mut self) -> Result<()>;
295}
296
297/// Factory opening a demuxer over an input byte source.
298pub type DemuxerFactory = fn(Input) -> Box<dyn Demuxer>;
299/// Factory opening a demuxer over a [`SeekInput`] — registered alongside the
300/// format's [`DemuxerFactory`] by formats that read less when they can seek.
301pub type SeekableDemuxerFactory = fn(SeekInput) -> Box<dyn Demuxer>;
302/// Factory opening a muxer over an output byte sink.
303pub type MuxerFactory = fn(Output) -> Box<dyn Muxer>;
304/// Factory opening a muxer over a [`SeekOutput`] -- registered alongside the
305/// format's [`MuxerFactory`] by formats that can stream when they can seek.
306pub type SeekableMuxerFactory = fn(SeekOutput) -> Box<dyn Muxer>;
307/// Factory opening a muxer that owns its own file set (HLS/DASH write a
308/// playlist/manifest plus many segment files, so a single byte sink cannot
309/// model them). Receives the output path and the format options
310/// (`-hls_time 6` → `{"hls_time": "6"}`).
311pub type PathMuxerFactory = fn(&std::path::Path, &Dictionary) -> Result<Box<dyn Muxer>>;
312/// Content sniffer: scores how strongly a byte prefix looks like this format,
313/// `0` (no match) to `100` (certain) — mirrors FFmpeg's `AVInputFormat::read_probe`.
314pub type ProbeFn = fn(&[u8]) -> i32;
315
316/// What a container's **muxer** will accept: the machine-readable half of the
317/// rules each muxer already enforces when it writes a header.
318///
319/// Muxers validate at run time, and a few historically wrote a zero codec tag
320/// rather than refusing an unmappable codec. Declaring the same rules here lets
321/// a caller answer "what can this file become?" *before* opening an encoder —
322/// which is what `rff-targets` is built on.
323#[derive(Debug, Clone, Copy, PartialEq, Eq)]
324pub struct MuxCaps {
325 /// Every codec this muxer can write. Empty for demux-only formats.
326 pub codecs: &'static [CodecId],
327 /// Most streams the container holds; `None` when there is no fixed limit.
328 pub max_streams: Option<usize>,
329 /// True when the container holds exactly ONE picture, so extra frames are
330 /// refused or dropped (png, jpeg, gif, webp, avif, jxl, av2f).
331 pub still_image: bool,
332}
333
334impl MuxCaps {
335 /// A format that cannot be written at all (demux-only).
336 pub const NONE: MuxCaps = MuxCaps {
337 codecs: &[],
338 max_streams: Some(0),
339 still_image: false,
340 };
341
342 /// A container interleaving any number of streams (mp4, matroska, mpegts).
343 pub const fn container(codecs: &'static [CodecId]) -> MuxCaps {
344 MuxCaps {
345 codecs,
346 max_streams: None,
347 still_image: false,
348 }
349 }
350
351 /// A file holding exactly one elementary stream (wav, mp3, ivf, ogg).
352 pub const fn single(codecs: &'static [CodecId]) -> MuxCaps {
353 MuxCaps {
354 codecs,
355 max_streams: Some(1),
356 still_image: false,
357 }
358 }
359
360 /// Narrow a [`single`](MuxCaps::single) file to one picture (png, jpeg).
361 pub const fn image(self) -> MuxCaps {
362 MuxCaps {
363 codecs: self.codecs,
364 max_streams: self.max_streams,
365 still_image: true,
366 }
367 }
368
369 /// Can this muxer write `id`?
370 pub fn accepts(&self, id: CodecId) -> bool {
371 self.codecs.contains(&id)
372 }
373
374 /// Can this muxer carry any stream of `media` at all?
375 pub fn accepts_media(&self, media: MediaType) -> bool {
376 self.codecs.iter().any(|c| c.media_type() == media)
377 }
378
379 /// The codecs this muxer accepts for one media category.
380 pub fn codecs_for(&self, media: MediaType) -> impl Iterator<Item = CodecId> + '_ {
381 self.codecs
382 .iter()
383 .copied()
384 .filter(move |c| c.media_type() == media)
385 }
386}
387
388/// Static description of a container format and its read/write support.
389pub struct Format {
390 /// Short name (`avi`, `mp4`, ...), as used by `ffmpeg -f <name>`.
391 pub name: &'static str,
392 pub long_name: &'static str,
393 /// File extensions that imply this format (without the dot).
394 pub extensions: &'static [&'static str],
395 /// Present if this format can be demuxed (read).
396 pub demuxer: Option<DemuxerFactory>,
397 /// Present if this format can be muxed (written).
398 pub muxer: Option<MuxerFactory>,
399 /// Present for formats that mux into a *path* (playlist + segment files)
400 /// rather than one byte sink — HLS, DASH. Mutually exclusive with `muxer`.
401 pub muxer_path: Option<PathMuxerFactory>,
402 /// Content sniffer for magic-byte detection (independent of the filename).
403 pub probe: Option<ProbeFn>,
404 /// What this format's muxer accepts. [`MuxCaps::NONE`] for demux-only
405 /// formats. Keep it in step with the muxer — `tests/mux_caps.rs` gates it.
406 pub mux_caps: MuxCaps,
407}
408
409impl Format {
410 pub fn can_demux(&self) -> bool {
411 self.demuxer.is_some()
412 }
413 pub fn can_mux(&self) -> bool {
414 self.muxer.is_some() || self.muxer_path.is_some()
415 }
416}
417
418/// Holds every container format known to a running engine.
419#[derive(Default)]
420pub struct FormatRegistry {
421 by_name: HashMap<&'static str, Format>,
422 /// Seek-aware demuxer factories, keyed by format name (see
423 /// [`register_seekable_demuxer`](Self::register_seekable_demuxer)).
424 seekable: HashMap<&'static str, SeekableDemuxerFactory>,
425 /// Seek-aware muxer factories, keyed by format name (see
426 /// [`register_seekable_muxer`](Self::register_seekable_muxer)).
427 seekable_muxers: HashMap<&'static str, SeekableMuxerFactory>,
428}
429
430impl FormatRegistry {
431 pub fn new() -> FormatRegistry {
432 FormatRegistry::default()
433 }
434
435 pub fn register(&mut self, format: Format) {
436 self.by_name.insert(format.name, format);
437 }
438
439 /// Give the format named `name` a demuxer that takes a [`SeekInput`]. Used
440 /// by [`open_demuxer_seekable`](Self::open_demuxer_seekable) when the caller
441 /// has a seekable source; the plain [`Format::demuxer`] still serves pipes
442 /// and sockets.
443 pub fn register_seekable_demuxer(
444 &mut self,
445 name: &'static str,
446 factory: SeekableDemuxerFactory,
447 ) {
448 self.seekable.insert(name, factory);
449 }
450
451 pub fn by_name(&self, name: &str) -> Option<&Format> {
452 self.by_name.get(name)
453 }
454
455 /// Find a format whose extension list contains `ext` (case-insensitive,
456 /// no leading dot). The cheap "guess by filename" path; [`probe`](Self::probe)
457 /// inspects content instead.
458 pub fn by_extension(&self, ext: &str) -> Option<&Format> {
459 let ext = ext.trim_start_matches('.').to_ascii_lowercase();
460 self.by_name
461 .values()
462 .find(|f| f.extensions.iter().any(|e| e.eq_ignore_ascii_case(&ext)))
463 }
464
465 /// Identify a format by sniffing a byte prefix: the registered format whose
466 /// [`probe`](Format::probe) returns the highest positive score wins. Returns
467 /// `None` if nothing recognizes the data.
468 pub fn probe(&self, data: &[u8]) -> Option<&Format> {
469 self.by_name
470 .values()
471 .filter_map(|f| f.probe.map(|p| (p(data), f)))
472 .filter(|(score, _)| *score > 0)
473 .max_by_key(|(score, _)| *score)
474 .map(|(_, f)| f)
475 }
476
477 /// Open a demuxer for the format named `name`.
478 pub fn open_demuxer(&self, name: &str, input: Input) -> Result<Box<dyn Demuxer>> {
479 self.by_name
480 .get(name)
481 .and_then(|f| f.demuxer)
482 .map(|factory| factory(input))
483 .ok_or_else(|| Error::DemuxerNotFound(name.to_string()))
484 }
485
486 /// Open a demuxer over a seekable input: the format's seek-aware demuxer if
487 /// it registered one, otherwise its plain streaming demuxer (a seekable
488 /// source is still a byte stream). Callers that hold a file should prefer
489 /// this — it is what lets MP4 read only `moov` instead of the whole file.
490 pub fn open_demuxer_seekable(&self, name: &str, input: SeekInput) -> Result<Box<dyn Demuxer>> {
491 if !self.by_name.get(name).is_some_and(Format::can_demux) {
492 return Err(Error::DemuxerNotFound(name.to_string()));
493 }
494 match self.seekable.get(name) {
495 Some(factory) => Ok(factory(input)),
496 None => self.open_demuxer(name, input),
497 }
498 }
499
500 /// Give the format named `name` a muxer that takes a [`SeekOutput`]. Used
501 /// by [`open_muxer_seekable`](Self::open_muxer_seekable) when the caller
502 /// writes to something seekable; the plain [`Format::muxer`] still serves
503 /// pipes and sockets.
504 pub fn register_seekable_muxer(&mut self, name: &'static str, factory: SeekableMuxerFactory) {
505 self.seekable_muxers.insert(name, factory);
506 }
507
508 /// Open a muxer over a seekable output: the format's seek-aware muxer if it
509 /// registered one, otherwise its plain muxer (a seekable sink is still a
510 /// byte sink). Callers writing a file should prefer this -- it is what lets
511 /// MP4/Matroska/AVI/WAV stream instead of buffering the whole output.
512 pub fn open_muxer_seekable(&self, name: &str, output: SeekOutput) -> Result<Box<dyn Muxer>> {
513 if !self.by_name.get(name).is_some_and(|f| f.muxer.is_some()) {
514 return Err(Error::MuxerNotFound(name.to_string()));
515 }
516 match self.seekable_muxers.get(name) {
517 Some(factory) => Ok(factory(output)),
518 None => self.open_muxer(name, output),
519 }
520 }
521
522 /// Open a muxer for the format named `name`.
523 pub fn open_muxer(&self, name: &str, output: Output) -> Result<Box<dyn Muxer>> {
524 self.by_name
525 .get(name)
526 .and_then(|f| f.muxer)
527 .map(|factory| factory(output))
528 .ok_or_else(|| Error::MuxerNotFound(name.to_string()))
529 }
530
531 pub fn iter(&self) -> impl Iterator<Item = &Format> {
532 self.by_name.values()
533 }
534
535 pub fn len(&self) -> usize {
536 self.by_name.len()
537 }
538
539 pub fn is_empty(&self) -> bool {
540 self.by_name.is_empty()
541 }
542}
543
544#[cfg(test)]
545mod tests {
546 use super::*;
547 use std::io::Cursor;
548
549 /// Reports which factory built it via the stream count.
550 struct Tagged(usize);
551 impl Demuxer for Tagged {
552 fn read_header(&mut self) -> Result<Vec<Stream>> {
553 Ok((0..self.0).map(|i| Stream::new(i, CodecId::None)).collect())
554 }
555 fn read_packet(&mut self) -> Result<rff_core::Packet> {
556 Err(Error::Eof)
557 }
558 }
559
560 fn format(name: &'static str) -> Format {
561 Format {
562 name,
563 long_name: name,
564 extensions: &[],
565 demuxer: Some(|_| Box::new(Tagged(1))),
566 muxer: None,
567 muxer_path: None,
568 probe: None,
569 mux_caps: MuxCaps::NONE,
570 }
571 }
572
573 fn streams(mut d: Box<dyn Demuxer>) -> usize {
574 d.read_header().unwrap().len()
575 }
576
577 #[test]
578 fn seekable_open_prefers_the_seekable_factory_and_falls_back() {
579 let mut r = FormatRegistry::new();
580 r.register(format("plain"));
581 r.register(format("seeky"));
582 r.register_seekable_demuxer("seeky", |_| Box::new(Tagged(2)));
583 let input = || -> SeekInput { Box::new(Cursor::new(vec![0u8; 4])) };
584 assert_eq!(
585 streams(r.open_demuxer_seekable("seeky", input()).unwrap()),
586 2
587 );
588 // No seekable factory: the streaming one serves the seekable input.
589 assert_eq!(
590 streams(r.open_demuxer_seekable("plain", input()).unwrap()),
591 1
592 );
593 // A plain stream open never takes the seekable path.
594 assert_eq!(
595 streams(
596 r.open_demuxer("seeky", Box::new(Cursor::new(vec![])))
597 .unwrap()
598 ),
599 1
600 );
601 assert!(matches!(
602 r.open_demuxer_seekable("missing", input()),
603 Err(Error::DemuxerNotFound(_))
604 ));
605 }
606
607 /// Reports which factory built it through the error `write_trailer` returns.
608 struct TaggedMux(&'static str);
609 impl Muxer for TaggedMux {
610 fn write_header(&mut self, _: &[Stream]) -> Result<()> {
611 Ok(())
612 }
613 fn write_packet(&mut self, _: &rff_core::Packet) -> Result<()> {
614 Ok(())
615 }
616 fn write_trailer(&mut self) -> Result<()> {
617 Err(Error::invalid(self.0))
618 }
619 }
620
621 fn tag(mut m: Box<dyn Muxer>) -> String {
622 m.write_trailer().unwrap_err().to_string()
623 }
624
625 #[test]
626 fn seekable_muxer_open_prefers_the_seekable_factory_and_falls_back() {
627 let mut r = FormatRegistry::new();
628 let with_muxer = |name| Format {
629 muxer: Some(|_| Box::new(TaggedMux("plain"))),
630 ..format(name)
631 };
632 r.register(with_muxer("plain"));
633 r.register(with_muxer("seeky"));
634 r.register(format("demux_only"));
635 r.register_seekable_muxer("seeky", |_| Box::new(TaggedMux("seekable")));
636 let output = || -> SeekOutput { Box::new(Cursor::new(Vec::new())) };
637 assert!(tag(r.open_muxer_seekable("seeky", output()).unwrap()).contains("seekable"));
638 // No seekable factory: the plain one serves the seekable output.
639 assert!(tag(r.open_muxer_seekable("plain", output()).unwrap()).contains("plain"));
640 // A plain open never takes the seekable path.
641 assert!(tag(r.open_muxer("seeky", Box::new(Vec::new())).unwrap()).contains("plain"));
642 assert!(matches!(
643 r.open_muxer_seekable("demux_only", output()),
644 Err(Error::MuxerNotFound(_))
645 ));
646 assert!(matches!(
647 r.open_muxer_seekable("missing", output()),
648 Err(Error::MuxerNotFound(_))
649 ));
650 }
651}