Skip to main content

rff_codec/
lib.rs

1//! `rff-codec` — the codec abstraction layer (FFmpeg's `libavcodec` core,
2//! minus the codecs themselves).
3//!
4//! It defines:
5//! * the [`Decoder`] and [`Encoder`] traits, using the same *send / receive*
6//!   shape as modern FFmpeg (`avcodec_send_packet` / `avcodec_receive_frame`),
7//! * a [`Codec`] descriptor that advertises a codec's identity and which
8//!   directions (decode/encode) it supports,
9//! * a [`CodecRegistry`] that individual codec crates register into.
10//!
11//! Concrete codecs live in their own crates (`rff-codec-h264`, ...) and are
12//! pulled together by the `rff` facade.
13
14use std::collections::HashMap;
15
16use rff_core::{
17    CodecId, ColorRange, Dictionary, Error, Frame, MediaType, Packet, PixelFormat, Result,
18    SampleFormat,
19};
20
21/// Stream parameters handed to a decoder before the first packet. Self-describing
22/// codecs (AV1, PNG, ...) can ignore these; raw/parametric codecs (PCM, and
23/// codecs that carry config out of band like H.264 SPS/PPS) need them.
24#[derive(Debug, Clone, Default)]
25pub struct CodecParams {
26    pub codec_id: CodecId,
27    // Video
28    pub width: u32,
29    pub height: u32,
30    pub pixel_format: Option<PixelFormat>,
31    // Audio
32    pub sample_rate: u32,
33    pub channels: u16,
34    pub sample_format: Option<SampleFormat>,
35    /// Codec-private init data (SPS/PPS, OpusHead, ...).
36    pub extradata: Vec<u8>,
37}
38
39/// Decodes compressed [`Packet`]s into raw [`Frame`]s.
40///
41/// Drive it the FFmpeg way: feed packets with [`send_packet`](Decoder::send_packet),
42/// then pull frames with [`receive_frame`](Decoder::receive_frame) until it
43/// returns [`Error::Again`] (needs more input) or [`Error::Eof`].
44pub trait Decoder: Send {
45    /// Receive the stream's parameters before decoding begins. Default: ignore
46    /// them (the bitstream is self-describing). Called once, after construction.
47    fn configure(&mut self, _params: &CodecParams) -> Result<()> {
48        Ok(())
49    }
50
51    /// Submit one compressed packet for decoding.
52    fn send_packet(&mut self, packet: &Packet) -> Result<()>;
53
54    /// Retrieve the next decoded frame, if one is ready.
55    ///
56    /// Returns [`Error::Again`] when more packets are needed, or [`Error::Eof`]
57    /// once fully drained.
58    fn receive_frame(&mut self) -> Result<Frame>;
59
60    /// Signal end-of-input so buffered frames can be flushed out via
61    /// subsequent `receive_frame` calls. Default: no buffering.
62    fn flush(&mut self) {}
63}
64
65/// Encodes raw [`Frame`]s into compressed [`Packet`]s. Mirror of [`Decoder`].
66pub trait Encoder: Send {
67    /// Receive output options before encoding begins — rate control and tuning:
68    /// `crf`/`qp` (quality), `preset` (speed/quality trade-off), `b` (bitrate),
69    /// `pass` (1 or 2). Default: ignore them. Called once, after construction.
70    fn configure(&mut self, _options: &Dictionary) -> Result<()> {
71        Ok(())
72    }
73
74    /// The input sample rates this encoder accepts, or `None` for "any rate".
75    /// The transcode pipeline resamples audio to the nearest accepted rate
76    /// before feeding frames (mirrors FFmpeg's automatic `aresample`).
77    fn accepted_sample_rates(&self) -> Option<Vec<u32>> {
78        None
79    }
80
81    /// The pixel formats this encoder accepts, most-preferred first, or `None`
82    /// for "any format". The transcode pipeline converts video to the first
83    /// accepted format before feeding frames (FFmpeg's automatic `scale`).
84    ///
85    /// Declaring this lets decoders emit whatever layout is cheapest for them —
86    /// a JPEG decoder can hand out planar Y'CbCr instead of converting to RGB —
87    /// without breaking encoders that need something else. An encoder that
88    /// leaves this `None` must genuinely handle every format it is given.
89    fn accepted_pixel_formats(&self) -> Option<Vec<PixelFormat>> {
90        None
91    }
92
93    /// Tell a video encoder the colour range of the frames it will receive.
94    /// Called once, before the first frame, with [`ColorRange::Limited`] or
95    /// [`ColorRange::Full`].
96    ///
97    /// Return `true` when the encoder takes frames in that range: it either
98    /// signals the range in its bitstream (the AV1 sequence header's
99    /// `color_range`, the VP9 frame header's `color_range`, the H.264 VUI's
100    /// `video_full_range_flag`) or has a fixed range of its own that the
101    /// pipeline already reconciles (JPEG, PNG, raw video). Return `false` when
102    /// it cannot signal `range`: the pipeline then converts the frames to
103    /// limited range, what a bitstream without a range flag is read as, and
104    /// calls this again with `Limited`. FFmpeg's encoders do the same through
105    /// `AVCodecContext::color_range`.
106    ///
107    /// Default: `true`, with nothing signalled.
108    fn set_color_range(&mut self, _range: ColorRange) -> bool {
109        true
110    }
111
112    /// Submit one raw frame for encoding.
113    fn send_frame(&mut self, frame: &Frame) -> Result<()>;
114
115    /// Retrieve the next encoded packet, if one is ready.
116    fn receive_packet(&mut self) -> Result<Packet>;
117
118    /// Signal end-of-input to drain buffered packets.
119    fn flush(&mut self) {}
120}
121
122/// Factory function producing a fresh decoder instance.
123pub type DecoderFactory = fn() -> Box<dyn Decoder>;
124/// Factory function producing a fresh encoder instance.
125pub type EncoderFactory = fn() -> Box<dyn Encoder>;
126
127/// Static description of a codec and the implementations available for it.
128pub struct Codec {
129    pub id: CodecId,
130    /// Short name as used on the command line (`h264`, `opus`, ...).
131    pub name: &'static str,
132    /// Human-readable description (shown by `ffmpeg -codecs`).
133    pub long_name: &'static str,
134    pub media_type: MediaType,
135    /// Present if this codec can decode.
136    pub decoder: Option<DecoderFactory>,
137    /// Present if this codec can encode.
138    pub encoder: Option<EncoderFactory>,
139}
140
141impl Codec {
142    pub fn can_decode(&self) -> bool {
143        self.decoder.is_some()
144    }
145    pub fn can_encode(&self) -> bool {
146        self.encoder.is_some()
147    }
148}
149
150/// Holds every codec known to a running engine. Codec crates call
151/// [`register`](CodecRegistry::register) to add themselves.
152#[derive(Default)]
153pub struct CodecRegistry {
154    by_id: HashMap<CodecId, Codec>,
155    by_name: HashMap<&'static str, CodecId>,
156}
157
158impl CodecRegistry {
159    pub fn new() -> CodecRegistry {
160        CodecRegistry::default()
161    }
162
163    /// Register a codec. A later registration for the same [`CodecId`] replaces
164    /// the earlier one (lets downstreams override a built-in).
165    pub fn register(&mut self, codec: Codec) {
166        self.by_name.insert(codec.name, codec.id);
167        self.by_id.insert(codec.id, codec);
168    }
169
170    /// Instantiate a decoder for `id`, or [`Error::DecoderNotFound`].
171    pub fn find_decoder(&self, id: CodecId) -> Result<Box<dyn Decoder>> {
172        self.by_id
173            .get(&id)
174            .and_then(|c| c.decoder)
175            .map(|factory| factory())
176            .ok_or(Error::DecoderNotFound(id))
177    }
178
179    /// Instantiate an encoder for `id`, or [`Error::EncoderNotFound`].
180    pub fn find_encoder(&self, id: CodecId) -> Result<Box<dyn Encoder>> {
181        self.by_id
182            .get(&id)
183            .and_then(|c| c.encoder)
184            .map(|factory| factory())
185            .ok_or(Error::EncoderNotFound(id))
186    }
187
188    /// Look up a codec descriptor by its canonical name.
189    pub fn by_name(&self, name: &str) -> Option<&Codec> {
190        self.by_name.get(name).and_then(|id| self.by_id.get(id))
191    }
192
193    /// Look up a codec descriptor by id.
194    pub fn by_id(&self, id: CodecId) -> Option<&Codec> {
195        self.by_id.get(&id)
196    }
197
198    /// Iterate all registered codecs (order unspecified).
199    pub fn iter(&self) -> impl Iterator<Item = &Codec> {
200        self.by_id.values()
201    }
202
203    pub fn len(&self) -> usize {
204        self.by_id.len()
205    }
206
207    pub fn is_empty(&self) -> bool {
208        self.by_id.is_empty()
209    }
210}