Skip to main content

framefinery_codecs/
lib.rs

1//! Experimental video encoders for FrameFinery.
2#![cfg_attr(not(feature = "dead-code-audit"), allow(dead_code, unused_imports))]
3//!
4//! The public API is the generic encoder registry exposed as [`ENCODERS`],
5//! [`find_encoder_manifest`], [`encoder`], [`create_encoder`],
6//! [`encode_frame`], and [`encode_source`]. Codec-specific modules are
7//! internal implementation territory while the generic v0 video API settles.
8
9#[cfg(feature = "av2")]
10#[doc(hidden)]
11mod av2;
12mod bitstream;
13mod builder;
14mod instrumentation;
15#[cfg(any(feature = "av2", feature = "vvc"))]
16mod picture;
17#[cfg(any(feature = "av2", feature = "vvc"))]
18mod session;
19#[cfg(any(feature = "av2", feature = "vvc"))]
20mod settings;
21#[cfg(any(feature = "av2", feature = "vvc"))]
22mod timing;
23#[cfg(test)]
24mod trace;
25#[cfg(feature = "vvc")]
26#[doc(hidden)]
27mod vvc;
28
29#[cfg(feature = "bench-internals")]
30#[doc(hidden)]
31pub mod bench {
32    #[cfg(feature = "av2")]
33    pub mod av2 {
34        pub use crate::av2::{bench, Av2VideoGeometry};
35    }
36
37    #[cfg(feature = "vvc")]
38    pub mod vvc {
39        pub use crate::vvc::{bench, VvcVideoGeometry};
40    }
41}
42
43use std::io::Write;
44
45use framefinery_api::{
46    Frame, MediaError, RawVideoFrameSource, Result, VideoEncodeFrameMetricsCallback,
47    VideoEncodeOutput, VideoEncodeSourceRequest, VideoEncoderConfig, VideoEncoderManifest,
48    VideoEncoderSession,
49};
50
51pub use builder::{encoder, VideoEncoderBuilder};
52pub use framefinery_api::{ChromaSampling, PixelFormat, SampleBitDepth};
53#[cfg(feature = "vvc")]
54pub use vvc::VvcProfile;
55
56/// Video encoder manifests compiled into this build.
57pub const ENCODERS: &[VideoEncoderManifest] = &[
58    #[cfg(feature = "av2")]
59    av2::AV2_CODEC,
60    #[cfg(feature = "vvc")]
61    vvc::VVC_CODEC,
62];
63
64/// Find a compiled video encoder manifest by codec id.
65pub fn find_encoder_manifest(name: &str) -> Option<VideoEncoderManifest> {
66    ENCODERS
67        .iter()
68        .copied()
69        .find(|encoder| encoder.name == name)
70}
71
72/// Fetch a compiled video encoder manifest or return a structured error.
73pub fn fetch_encoder_manifest(name: impl AsRef<str>) -> Result<VideoEncoderManifest> {
74    let name = name.as_ref();
75    find_encoder_manifest(name).ok_or_else(|| unsupported_codec(name))
76}
77
78/// Apply CLI-compatible encoder setting specs through the selected manifest.
79///
80/// This is a convenience wrapper around
81/// [`VideoEncoderManifest::apply_setting_specs`] for callers that already have a
82/// [`VideoEncoderConfig`] with its codec id set.
83pub fn apply_encoder_settings<I, S>(
84    config: VideoEncoderConfig,
85    specs: I,
86) -> Result<VideoEncoderConfig>
87where
88    I: IntoIterator<Item = S>,
89    S: AsRef<str>,
90{
91    fetch_encoder_manifest(config.codec.as_str())?.apply_setting_specs(config, specs)
92}
93
94/// Render effective encoder setting specs through the selected manifest.
95///
96/// This includes manifest defaults and uses the same ordering as the CLI
97/// startup summary.
98pub fn effective_encoder_settings(config: &VideoEncoderConfig) -> Result<Vec<String>> {
99    fetch_encoder_manifest(config.codec.as_str())?.effective_setting_specs(config)
100}
101
102/// Create a persistent encoder session from a codec-neutral config.
103///
104/// AV2 and VVC emit complete frame chunks per call using the same per-codec
105/// state as their source adapters. Consume each returned step before submitting
106/// more input; see [`VideoEncoderSession`] for lifecycle and ownership rules.
107pub fn create_encoder(config: VideoEncoderConfig) -> Result<Box<dyn VideoEncoderSession>> {
108    let manifest = fetch_encoder_manifest(config.codec.as_str())?;
109    manifest.validate_config(&config)?;
110    (manifest.session_factory())(config)
111}
112
113/// Encode frames pulled from `source` using the codec selected by `config`.
114///
115/// This path avoids buffering whole streams in memory and is intended for file,
116/// capture, and validation adapters. `frame_metrics`, when present, is called
117/// after each encoded frame with timing, per-frame bytes, cumulative bytes, and
118/// optional PSNR while source and reconstruction samples are still available.
119pub fn encode_source<'callback>(
120    config: &VideoEncoderConfig,
121    source: &mut dyn RawVideoFrameSource,
122    output: &mut dyn Write,
123    recon: Option<&mut dyn Write>,
124    frame_metrics: Option<VideoEncodeFrameMetricsCallback<'callback>>,
125) -> Result<()> {
126    let manifest = fetch_encoder_manifest(config.codec.as_str())?;
127    manifest.validate_config(config)?;
128    (manifest.source_encode_hook())(
129        source,
130        output,
131        recon,
132        VideoEncodeSourceRequest { config },
133        frame_metrics,
134    )
135}
136
137/// Encode one frame using the codec selected by `config`.
138///
139/// This is the convenience path for one-frame callers. It creates a session,
140/// submits `frame`, flushes the encoder, and returns the combined output.
141pub fn encode_frame(config: VideoEncoderConfig, frame: Frame) -> Result<VideoEncodeOutput> {
142    let mut encoder = create_encoder(config)?;
143    let mut output = encoder.encode_frame(frame)?;
144    let tail = encoder.flush()?;
145    output.chunks.extend(tail.chunks);
146    output.reconstructions.extend(tail.reconstructions);
147    output.metrics.extend(tail.metrics);
148    Ok(output)
149}
150
151pub(crate) fn unsupported_codec(codec: &str) -> MediaError {
152    MediaError::UnsupportedCodec {
153        codec: codec.to_string(),
154        reason: "no encoder with this codec id is compiled into this build".to_string(),
155    }
156}
157
158#[cfg(all(test, feature = "av2"))]
159mod tests {
160    use super::*;
161    use framefinery_api::{
162        CodecId, Frame, FrameInfo, PixelFormat, ReconstructionMode, VideoEncoderConfig,
163        VideoRateControl,
164    };
165
166    #[test]
167    fn generic_encoder_session_emits_av2_frames_before_terminal_flush() {
168        let info = FrameInfo::new(8, 8, PixelFormat::Yuv420p8).unwrap();
169        let config = VideoEncoderConfig::new(CodecId::new("av2").unwrap(), info)
170            .with_rate_control(VideoRateControl::Lossless)
171            .with_reconstruction(ReconstructionMode::Frames);
172        let mut encoder = create_encoder(config).expect("generic av2 encoder");
173        for frame_index in 0..2 {
174            let output = encoder
175                .encode_frame(Frame::blank(info))
176                .expect("encode frame through generic session");
177            assert_eq!(output.chunks.len(), 1);
178            assert_eq!(
179                output.chunks[0].kind,
180                framefinery_api::VideoChunkKind::Frame
181            );
182            assert_eq!(output.chunks[0].frame_index, Some(frame_index));
183            assert!(!output.chunks[0].data.is_empty());
184            assert_eq!(output.reconstructions, vec![Frame::blank(info)]);
185        }
186        assert_eq!(encoder.flush().unwrap(), VideoEncodeOutput::default());
187        assert_eq!(encoder.flush().unwrap(), VideoEncodeOutput::default());
188        assert_eq!(
189            encoder.encode_frame(Frame::blank(info)),
190            Err(MediaError::EncodeAfterFlush)
191        );
192    }
193}