Skip to main content

framefinery_api/
video.rs

1use std::fmt;
2use std::io::{Read, Write};
3use std::str::FromStr;
4use std::time::Duration;
5
6use crate::{
7    Frame, FrameInfo, FramePsnr, MediaError, PixelFormat, Result, SettingManifest, SettingValue,
8    Timestamp,
9};
10
11/// Stable codec identifier used by CLI, manifests, and library callers.
12#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
13pub struct CodecId(String);
14
15/// Rational frame rate metadata.
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub struct FrameRate {
18    /// Frame-rate numerator.
19    pub numerator: u32,
20    /// Frame-rate denominator.
21    pub denominator: u32,
22}
23
24/// Rate-control mode requested from a video encoder.
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
26pub enum VideoRateControl {
27    /// Let the codec choose its default mode.
28    #[default]
29    CodecDefault,
30    /// Request stream-exact lossless coding.
31    Lossless,
32    /// Request lossy coding with a codec-local quantizer value.
33    ConstantQuantizer(u8),
34}
35
36/// Reconstruction data requested from a video encoder.
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
38pub enum ReconstructionMode {
39    /// Do not return reconstructions or compute reconstruction-derived metrics.
40    #[default]
41    None,
42    /// Compute metrics while reconstructed samples are available internally.
43    MetricsOnly,
44    /// Return reconstructed frames to the caller.
45    Frames,
46}
47
48/// Typed value for a codec extension setting.
49#[derive(Debug, Clone, PartialEq, Eq)]
50pub enum VideoSettingValue {
51    /// Boolean setting value.
52    Boolean(bool),
53    /// Integer setting value.
54    Integer(i64),
55    /// Text or choice setting value.
56    Text(String),
57}
58
59/// One codec extension setting in a [`VideoEncoderConfig`].
60#[derive(Debug, Clone, PartialEq, Eq)]
61pub struct VideoEncoderSetting {
62    /// Setting name.
63    pub name: String,
64    /// Typed setting value.
65    pub value: VideoSettingValue,
66}
67
68/// Codec-neutral configuration for constructing or driving a video encoder.
69#[derive(Debug, Clone, PartialEq, Eq)]
70pub struct VideoEncoderConfig {
71    /// Selected codec id.
72    pub codec: CodecId,
73    /// Input frame geometry and pixel format.
74    pub input: FrameInfo,
75    /// Optional frame-rate metadata.
76    pub frame_rate: Option<FrameRate>,
77    /// Optional caller/source frame limit.
78    pub frame_limit: Option<usize>,
79    /// Requested rate-control mode.
80    pub rate_control: VideoRateControl,
81    /// Requested reconstruction output mode.
82    pub reconstruction: ReconstructionMode,
83    /// Codec extension settings.
84    pub settings: Vec<VideoEncoderSetting>,
85}
86
87/// Encoded chunk category emitted by video encoders.
88#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89pub enum VideoChunkKind {
90    /// Codec configuration bytes.
91    Config,
92    /// One coded frame or access unit.
93    Frame,
94    /// End-of-stream marker.
95    EndOfStream,
96    /// Whole-stream value, including explicit caller-owned recording.
97    /// This variant does not permit sessions to defer all output until flush.
98    Stream,
99}
100
101/// Encoded bytes plus timing and keyframe metadata.
102#[derive(Debug, Clone, PartialEq, Eq)]
103pub struct EncodedVideoChunk {
104    /// Codec that produced the chunk.
105    pub codec: CodecId,
106    /// Chunk category.
107    pub kind: VideoChunkKind,
108    /// Encoded payload bytes.
109    pub data: Vec<u8>,
110    /// Optional zero-based frame index associated with this chunk.
111    pub frame_index: Option<usize>,
112    /// Optional presentation timestamp.
113    pub pts: Option<Timestamp>,
114    /// Optional decode timestamp.
115    pub dts: Option<Timestamp>,
116    /// Optional duration.
117    pub duration: Option<Timestamp>,
118    /// Whether this chunk starts or represents a keyframe.
119    pub keyframe: bool,
120}
121
122/// Per-frame encode metrics returned by session-style encoders.
123#[derive(Debug, Clone, PartialEq)]
124pub struct FrameEncodeMetrics {
125    /// Zero-based frame index.
126    pub frame_index: usize,
127    /// Optional total frame count when known by the caller.
128    pub frame_count: Option<usize>,
129    /// Number of encoded bytes produced for this frame.
130    pub encoded_bytes: usize,
131    /// Optional aggregate PSNR for this frame.
132    pub psnr: Option<f64>,
133}
134
135/// Output produced by one encoder-session operation.
136#[derive(Debug, Clone, PartialEq, Default)]
137pub struct VideoEncodeOutput {
138    /// Encoded chunks emitted by this operation.
139    pub chunks: Vec<EncodedVideoChunk>,
140    /// Reconstructed frames returned by this operation.
141    pub reconstructions: Vec<Frame>,
142    /// Per-frame metrics returned by this operation.
143    pub metrics: Vec<FrameEncodeMetrics>,
144}
145
146/// One continuous video stream with persistent codec state.
147///
148/// Current no-reordering modes must return complete frame output per call,
149/// before finalization. Internal storage must be bounded by frame geometry and
150/// codec reference/scratch requirements, independent of stream duration. Future
151/// reordering/lookahead modes must declare explicit delay and storage bounds.
152/// Consume or transfer each returned step before submitting another frame;
153/// recording output history is an explicit caller-owned allocation.
154///
155/// Native AV2 and VVC implement incremental sessions through their shared
156/// per-codec state. See `docs/api-v0.md` in the repository for retention,
157/// validation coverage and the separate unfinished WASM wrapper.
158pub trait VideoEncoderSession {
159    /// Codec id for this encoder session.
160    fn codec(&self) -> &CodecId;
161
162    /// Configuration used to create this session.
163    fn config(&self) -> &VideoEncoderConfig;
164
165    /// Encode one frame and transfer this step's output to the caller.
166    ///
167    /// Invalid input must not advance state. An error after codec state advances
168    /// terminally fails the session; later encode/flush calls must report failure.
169    /// This synchronous operation has no internal input queue or async readiness
170    /// protocol. Consumer backpressure is applied by waiting before the next call.
171    fn encode_frame(&mut self, frame: Frame) -> Result<VideoEncodeOutput>;
172
173    /// Terminally finish the stream and release retained reference frames.
174    ///
175    /// Return any remaining output. Successful repeated flushes return empty
176    /// output; encoding afterward returns [`MediaError::EncodeAfterFlush`]. A
177    /// failed session must continue reporting failure. This does not flush a
178    /// caller's writer or acknowledge transport delivery.
179    fn flush(&mut self) -> Result<VideoEncodeOutput> {
180        Ok(VideoEncodeOutput::default())
181    }
182}
183
184#[doc(hidden)]
185pub type VideoEncoderSessionFactory =
186    fn(VideoEncoderConfig) -> Result<Box<dyn VideoEncoderSession>>;
187
188/// Pull-based raw video source used by source-driven encoders.
189pub trait RawVideoFrameSource {
190    /// Fill `frame` with exactly one raw frame.
191    ///
192    /// Returns `Ok(false)` only at clean EOF before any bytes of the next frame
193    /// are read.
194    fn read_frame(&mut self, frame: &mut [u8]) -> Result<bool>;
195}
196
197impl<F> RawVideoFrameSource for F
198where
199    F: FnMut(&mut [u8]) -> Result<bool>,
200{
201    fn read_frame(&mut self, frame: &mut [u8]) -> Result<bool> {
202        self(frame)
203    }
204}
205
206/// [`RawVideoFrameSource`] adapter for any [`Read`] implementation.
207pub struct RawVideoFrameReadSource<R> {
208    inner: R,
209}
210
211impl<R: Read> RawVideoFrameReadSource<R> {
212    /// Wrap a reader as a raw frame source.
213    pub fn new(inner: R) -> Self {
214        Self { inner }
215    }
216
217    /// Return the wrapped reader.
218    pub fn into_inner(self) -> R {
219        self.inner
220    }
221}
222
223impl<R: Read> RawVideoFrameSource for RawVideoFrameReadSource<R> {
224    fn read_frame(&mut self, frame: &mut [u8]) -> Result<bool> {
225        let mut offset = 0usize;
226        while offset < frame.len() {
227            let count = self
228                .inner
229                .read(&mut frame[offset..])
230                .map_err(|err| MediaError::Message(format!("failed to read input frame: {err}")))?;
231            if count == 0 {
232                if offset == 0 {
233                    return Ok(false);
234                }
235                return Err(MediaError::ShortFrameRead {
236                    expected: frame.len(),
237                    actual: offset,
238                });
239            }
240            offset += count;
241        }
242        Ok(true)
243    }
244}
245
246/// [`Read`] adapter for any [`RawVideoFrameSource`] implementation.
247///
248/// The adapter buffers one raw frame at a time so legacy stream encoders that
249/// consume byte readers can still be driven from pull-based frame sources
250/// without materializing a whole stream.
251pub struct RawVideoFrameSourceReadAdapter<S> {
252    source: S,
253    frame: Vec<u8>,
254    frame_offset: usize,
255    frames_read: usize,
256    frame_limit: Option<usize>,
257}
258
259impl<S> RawVideoFrameSourceReadAdapter<S>
260where
261    S: RawVideoFrameSource,
262{
263    /// Create a byte reader over `source` using the byte length implied by `info`.
264    pub fn new(source: S, info: FrameInfo) -> Self {
265        let frame_len = info.expected_len();
266        Self {
267            source,
268            frame: vec![0; frame_len],
269            frame_offset: frame_len,
270            frames_read: 0,
271            frame_limit: None,
272        }
273    }
274
275    /// Stop reading after at most `frame_limit` complete frames.
276    pub fn with_frame_limit(mut self, frame_limit: usize) -> Self {
277        self.frame_limit = Some(frame_limit);
278        self
279    }
280
281    /// Return the number of complete frames read from the source.
282    pub const fn frames_read(&self) -> usize {
283        self.frames_read
284    }
285
286    /// Consume the adapter and return the wrapped source.
287    pub fn into_inner(self) -> S {
288        self.source
289    }
290
291    fn load_frame(&mut self) -> std::io::Result<bool> {
292        if self
293            .frame_limit
294            .is_some_and(|limit| self.frames_read >= limit)
295        {
296            return Ok(false);
297        }
298        let has_frame = self
299            .source
300            .read_frame(&mut self.frame)
301            .map_err(|err| std::io::Error::new(std::io::ErrorKind::Other, err.to_string()))?;
302        if !has_frame {
303            return Ok(false);
304        }
305        self.frames_read += 1;
306        self.frame_offset = 0;
307        Ok(true)
308    }
309}
310
311impl<S> Read for RawVideoFrameSourceReadAdapter<S>
312where
313    S: RawVideoFrameSource,
314{
315    fn read(&mut self, output: &mut [u8]) -> std::io::Result<usize> {
316        if output.is_empty() {
317            return Ok(0);
318        }
319
320        let mut written = 0usize;
321        while written < output.len() {
322            if self.frame_offset == self.frame.len() && !self.load_frame()? {
323                break;
324            }
325            let remaining_frame = self.frame.len() - self.frame_offset;
326            let count = remaining_frame.min(output.len() - written);
327            output[written..written + count]
328                .copy_from_slice(&self.frame[self.frame_offset..self.frame_offset + count]);
329            self.frame_offset += count;
330            written += count;
331        }
332        Ok(written)
333    }
334}
335
336/// Discovery manifest for one compiled video encoder.
337///
338/// The manifest exposes stable metadata for catalogs, help text, and validation
339/// of codec-neutral configs. Normal callers should create and drive encoders
340/// through registry helpers provided by `framefinery` or `framefinery-codecs`,
341/// using the codec id already stored in [`VideoEncoderConfig`].
342#[derive(Debug, Clone, Copy)]
343pub struct VideoEncoderManifest {
344    /// Stable codec id string.
345    pub name: &'static str,
346    /// Cargo feature that enables this encoder.
347    pub feature: &'static str,
348    /// Short user-facing encoder summary.
349    pub summary: &'static str,
350    /// Codec-specific settings accepted by this encoder.
351    pub settings: &'static [SettingManifest],
352    /// Function that tests whether an input pixel format is accepted.
353    pub accepts_format: fn(PixelFormat) -> bool,
354    /// Function that tests whether lossless mode is accepted for an input format.
355    pub supports_lossless_format: fn(PixelFormat) -> bool,
356    create_session_hook: VideoEncoderSessionFactory,
357    encode_source_hook: VideoEncodeSourceFn,
358}
359
360#[doc(hidden)]
361#[derive(Debug, Clone, Copy)]
362pub struct VideoEncodeSourceRequest<'a> {
363    #[doc(hidden)]
364    pub config: &'a VideoEncoderConfig,
365}
366
367/// Per-frame metrics passed to source-driven encode callbacks.
368pub struct VideoEncodeFrameMetrics<'a> {
369    /// Zero-based frame index.
370    pub frame_idx: usize,
371    /// Optional total frame count when known by the caller.
372    pub frame_count: Option<usize>,
373    /// Encoded bytes produced by this frame.
374    pub bitstream_bytes: usize,
375    /// Encoded bytes produced by all reported frames through this frame.
376    pub total_bitstream_bytes: usize,
377    /// Wall time spent encoding this frame after the source frame was read.
378    pub encode_elapsed: Duration,
379    /// PSNR for this frame when reconstruction metrics were requested.
380    pub psnr: Option<FramePsnr>,
381    /// Source frame bytes for metric calculations.
382    pub source: &'a [u8],
383    /// Reconstructed frame bytes for metric calculations.
384    pub reconstruction: &'a [u8],
385}
386
387/// Callback type used to receive source-driven per-frame metrics.
388pub type VideoEncodeFrameMetricsCallback<'a> =
389    &'a mut dyn for<'frame> FnMut(VideoEncodeFrameMetrics<'frame>);
390
391#[doc(hidden)]
392pub type VideoEncodeSourceFn = for<'request, 'callback> fn(
393    &mut dyn RawVideoFrameSource,
394    &mut dyn Write,
395    Option<&mut dyn Write>,
396    VideoEncodeSourceRequest<'request>,
397    Option<VideoEncodeFrameMetricsCallback<'callback>>,
398) -> Result<()>;
399
400#[doc(hidden)]
401#[derive(Debug, Clone, Copy)]
402pub struct VideoEncoderManifestHooks {
403    #[doc(hidden)]
404    pub create_session: VideoEncoderSessionFactory,
405    #[doc(hidden)]
406    pub encode_source: VideoEncodeSourceFn,
407}
408
409impl CodecId {
410    /// Validate and create a codec id.
411    ///
412    /// Codec ids are lowercase ASCII names with optional digits and hyphens.
413    pub fn new(value: impl Into<String>) -> Result<Self> {
414        let value = value.into();
415        validate_codec_id(&value)?;
416        Ok(Self(value))
417    }
418
419    /// Borrow the codec id as a string slice.
420    pub fn as_str(&self) -> &str {
421        &self.0
422    }
423}
424
425impl fmt::Debug for CodecId {
426    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
427        f.debug_tuple("CodecId").field(&self.0).finish()
428    }
429}
430
431impl fmt::Display for CodecId {
432    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
433        f.write_str(&self.0)
434    }
435}
436
437impl FromStr for CodecId {
438    type Err = MediaError;
439
440    fn from_str(value: &str) -> Result<Self> {
441        Self::new(value)
442    }
443}
444
445impl TryFrom<&str> for CodecId {
446    type Error = MediaError;
447
448    fn try_from(value: &str) -> Result<Self> {
449        Self::new(value)
450    }
451}
452
453impl FrameRate {
454    /// Create a nonzero rational frame rate.
455    pub fn new(numerator: u32, denominator: u32) -> Result<Self> {
456        if numerator == 0 || denominator == 0 {
457            return Err(MediaError::Message(
458                "frame rate numerator and denominator must be non-zero".to_string(),
459            ));
460        }
461        Ok(Self {
462            numerator,
463            denominator,
464        })
465    }
466}
467
468impl VideoRateControl {
469    /// Create a constant-quantizer rate-control mode.
470    ///
471    /// The accepted public range is `1..=255`.
472    pub fn constant_quantizer(qp: u8) -> Result<Self> {
473        if qp == 0 {
474            return Err(MediaError::Message(
475                "constant quantizer must be in the range 1..255".to_string(),
476            ));
477        }
478        Ok(Self::ConstantQuantizer(qp))
479    }
480}
481
482impl VideoSettingValue {
483    /// Render this typed value as a CLI-compatible setting value.
484    pub fn as_cli_value(&self) -> String {
485        match self {
486            Self::Boolean(value) => value.to_string(),
487            Self::Integer(value) => value.to_string(),
488            Self::Text(value) => value.clone(),
489        }
490    }
491}
492
493impl From<bool> for VideoSettingValue {
494    fn from(value: bool) -> Self {
495        Self::Boolean(value)
496    }
497}
498
499impl From<i64> for VideoSettingValue {
500    fn from(value: i64) -> Self {
501        Self::Integer(value)
502    }
503}
504
505impl From<i32> for VideoSettingValue {
506    fn from(value: i32) -> Self {
507        Self::Integer(i64::from(value))
508    }
509}
510
511impl From<u8> for VideoSettingValue {
512    fn from(value: u8) -> Self {
513        Self::Integer(i64::from(value))
514    }
515}
516
517impl From<String> for VideoSettingValue {
518    fn from(value: String) -> Self {
519        Self::Text(value)
520    }
521}
522
523impl From<&str> for VideoSettingValue {
524    fn from(value: &str) -> Self {
525        Self::Text(value.to_string())
526    }
527}
528
529impl VideoEncoderSetting {
530    /// Create a setting with a validated setting name and typed value.
531    pub fn new(name: impl Into<String>, value: VideoSettingValue) -> Result<Self> {
532        let name = name.into();
533        validate_setting_name(&name)?;
534        Ok(Self { name, value })
535    }
536
537    /// Create a boolean codec extension setting.
538    pub fn boolean(name: impl Into<String>, value: bool) -> Result<Self> {
539        Self::new(name, VideoSettingValue::Boolean(value))
540    }
541
542    /// Create an integer codec extension setting.
543    pub fn integer(name: impl Into<String>, value: i64) -> Result<Self> {
544        Self::new(name, VideoSettingValue::Integer(value))
545    }
546
547    /// Create a text or choice codec extension setting.
548    pub fn text(name: impl Into<String>, value: impl Into<String>) -> Result<Self> {
549        Self::new(name, VideoSettingValue::Text(value.into()))
550    }
551
552    /// Render this setting as a CLI-compatible `name=value` spec.
553    pub fn as_cli_spec(&self) -> String {
554        format!("{}={}", self.name, self.value.as_cli_value())
555    }
556}
557
558impl VideoEncoderConfig {
559    /// Create an encoder config using codec defaults for optional fields.
560    pub fn new(codec: CodecId, input: FrameInfo) -> Self {
561        Self {
562            codec,
563            input,
564            frame_rate: None,
565            frame_limit: None,
566            rate_control: VideoRateControl::CodecDefault,
567            reconstruction: ReconstructionMode::None,
568            settings: Vec::new(),
569        }
570    }
571
572    /// Create an encoder config from a textual codec id.
573    pub fn for_codec(codec: impl AsRef<str>, input: FrameInfo) -> Result<Self> {
574        Ok(Self::new(CodecId::new(codec.as_ref())?, input))
575    }
576
577    /// Set optional frame-rate metadata.
578    pub fn with_frame_rate(mut self, frame_rate: FrameRate) -> Self {
579        self.frame_rate = Some(frame_rate);
580        self
581    }
582
583    /// Set an optional source/caller frame limit.
584    pub fn with_frame_limit(mut self, frame_limit: usize) -> Self {
585        self.frame_limit = Some(frame_limit);
586        self
587    }
588
589    /// Set the requested rate-control mode.
590    pub fn with_rate_control(mut self, rate_control: VideoRateControl) -> Self {
591        self.rate_control = rate_control;
592        self
593    }
594
595    /// Set the requested reconstruction mode.
596    pub fn with_reconstruction(mut self, reconstruction: ReconstructionMode) -> Self {
597        self.reconstruction = reconstruction;
598        self
599    }
600
601    /// Append one codec extension setting.
602    pub fn with_setting(mut self, setting: VideoEncoderSetting) -> Self {
603        self.settings.push(setting);
604        self
605    }
606
607    /// Return explicit CLI-compatible setting specs represented by this config.
608    ///
609    /// This does not include manifest defaults. Use
610    /// [`VideoEncoderManifest::effective_setting_specs`] when a frontend needs
611    /// the full effective setting list that will be reported to users.
612    pub fn setting_specs(&self) -> Vec<String> {
613        let mut specs = Vec::new();
614        match self.rate_control {
615            VideoRateControl::CodecDefault => {}
616            VideoRateControl::Lossless => specs.push("lossless=true".to_string()),
617            VideoRateControl::ConstantQuantizer(qp) => specs.push(format!("qp={qp}")),
618        }
619        specs.extend(self.settings.iter().map(VideoEncoderSetting::as_cli_spec));
620        specs
621    }
622}
623
624impl EncodedVideoChunk {
625    /// Create an encoded chunk without timing metadata.
626    pub fn new(codec: CodecId, kind: VideoChunkKind, data: Vec<u8>) -> Self {
627        Self {
628            codec,
629            kind,
630            data,
631            frame_index: None,
632            pts: None,
633            dts: None,
634            duration: None,
635            keyframe: false,
636        }
637    }
638}
639
640impl VideoEncodeOutput {
641    /// Create output containing a single encoded chunk.
642    pub fn from_chunk(chunk: EncodedVideoChunk) -> Self {
643        Self {
644            chunks: vec![chunk],
645            reconstructions: Vec::new(),
646            metrics: Vec::new(),
647        }
648    }
649}
650
651impl VideoEncoderManifest {
652    #[doc(hidden)]
653    pub const fn new(
654        name: &'static str,
655        feature: &'static str,
656        summary: &'static str,
657        settings: &'static [SettingManifest],
658        accepts_format: fn(PixelFormat) -> bool,
659        supports_lossless_format: fn(PixelFormat) -> bool,
660        hooks: VideoEncoderManifestHooks,
661    ) -> Self {
662        Self {
663            name,
664            feature,
665            summary,
666            settings,
667            accepts_format,
668            supports_lossless_format,
669            create_session_hook: hooks.create_session,
670            encode_source_hook: hooks.encode_source,
671        }
672    }
673
674    #[doc(hidden)]
675    pub fn session_factory(self) -> VideoEncoderSessionFactory {
676        self.create_session_hook
677    }
678
679    #[doc(hidden)]
680    pub fn source_encode_hook(self) -> VideoEncodeSourceFn {
681        self.encode_source_hook
682    }
683
684    /// Return this manifest's codec id as a validated [`CodecId`].
685    pub fn codec_id(self) -> Result<CodecId> {
686        CodecId::new(self.name)
687    }
688
689    /// Find a codec-specific setting manifest by name.
690    pub fn setting(self, name: &str) -> Option<SettingManifest> {
691        self.settings
692            .iter()
693            .copied()
694            .find(|setting| setting.name == name)
695    }
696
697    /// Find a global or codec-specific setting manifest by name.
698    pub fn declared_setting(self, name: &str) -> Option<SettingManifest> {
699        crate::GLOBAL_SETTINGS
700            .iter()
701            .copied()
702            .find(|setting| setting.name == name)
703            .or_else(|| self.setting(name))
704    }
705
706    /// Apply CLI-compatible `name[=value]` setting specs to `config`.
707    ///
708    /// Global rate-control settings such as `lossless` and `qp` are folded into
709    /// [`VideoEncoderConfig::rate_control`]. Codec extension settings are stored
710    /// in [`VideoEncoderConfig::settings`]. Re-applying an extension setting
711    /// replaces the previous value in `config`, while duplicate names in the
712    /// provided `specs` are rejected.
713    pub fn apply_setting_specs<I, S>(
714        self,
715        mut config: VideoEncoderConfig,
716        specs: I,
717    ) -> Result<VideoEncoderConfig>
718    where
719        I: IntoIterator<Item = S>,
720        S: AsRef<str>,
721    {
722        if config.codec.as_str() != self.name {
723            return Err(MediaError::UnsupportedCodec {
724                codec: config.codec.to_string(),
725                reason: format!("manifest '{}' cannot configure it", self.name),
726            });
727        }
728
729        let mut seen = Vec::new();
730        for spec in specs {
731            let spec = spec.as_ref();
732            let name = crate::setting_name(spec);
733            validate_setting_name(name)?;
734            if seen.iter().any(|seen_name| seen_name == name) {
735                return Err(MediaError::DuplicateSetting {
736                    setting: name.to_string(),
737                });
738            }
739            seen.push(name.to_string());
740
741            let Some(manifest) = self.declared_setting(name) else {
742                return Err(MediaError::UnknownSetting {
743                    codec: self.name.to_string(),
744                    setting: name.to_string(),
745                });
746            };
747            let value = crate::setting_value(spec).unwrap_or("true");
748            if !manifest.value.accepts(value) {
749                return Err(MediaError::InvalidSettingValue {
750                    codec: self.name.to_string(),
751                    setting: manifest.name.to_string(),
752                    expected: crate::setting_values_label(manifest),
753                    actual: value.to_string(),
754                });
755            }
756
757            if name == "lossless" {
758                let lossless = parse_manifest_bool(self.name, manifest, value)?;
759                if lossless {
760                    if matches!(config.rate_control, VideoRateControl::ConstantQuantizer(_)) {
761                        return Err(MediaError::ConflictingSettings {
762                            setting: name.to_string(),
763                            conflict: "VideoRateControl::ConstantQuantizer".to_string(),
764                        });
765                    }
766                    config.rate_control = VideoRateControl::Lossless;
767                } else if matches!(config.rate_control, VideoRateControl::Lossless) {
768                    config.rate_control = VideoRateControl::CodecDefault;
769                }
770                continue;
771            }
772
773            if name == "qp" {
774                if matches!(config.rate_control, VideoRateControl::Lossless) {
775                    return Err(MediaError::ConflictingSettings {
776                        setting: name.to_string(),
777                        conflict: "VideoRateControl::Lossless".to_string(),
778                    });
779                }
780                let qp = value
781                    .parse::<u8>()
782                    .map_err(|_| MediaError::InvalidSettingValue {
783                        codec: self.name.to_string(),
784                        setting: manifest.name.to_string(),
785                        expected: crate::setting_values_label(manifest),
786                        actual: value.to_string(),
787                    })?;
788                config.rate_control = VideoRateControl::constant_quantizer(qp)?;
789                continue;
790            }
791
792            let setting = video_setting_from_manifest(self.name, manifest, value)?;
793            config.settings.retain(|setting| setting.name != name);
794            config.settings.push(setting);
795        }
796
797        self.validate_config(&config)?;
798        Ok(config)
799    }
800
801    /// Return all effective setting specs after manifest defaults are applied.
802    ///
803    /// The returned strings use the same `name=value` shape accepted by
804    /// [`VideoEncoderManifest::apply_setting_specs`] and are ordered with
805    /// global settings first, followed by codec-specific settings.
806    pub fn effective_setting_specs(self, config: &VideoEncoderConfig) -> Result<Vec<String>> {
807        self.validate_config(config)?;
808        let mut specs = Vec::new();
809        push_effective_setting_specs(config, crate::GLOBAL_SETTINGS, &mut specs);
810        push_effective_setting_specs(config, self.settings, &mut specs);
811        Ok(specs)
812    }
813
814    /// Return whether this encoder accepts the frame format in `input`.
815    pub fn accepts_frame_info(self, input: FrameInfo) -> bool {
816        (self.accepts_format)(input.format)
817    }
818
819    /// Return whether this encoder supports lossless coding for `input`.
820    pub fn supports_lossless_frame_info(self, input: FrameInfo) -> bool {
821        (self.supports_lossless_format)(input.format)
822    }
823
824    /// Validate codec id, input format, rate control, and extension settings.
825    pub fn validate_config(self, config: &VideoEncoderConfig) -> Result<()> {
826        if config.codec.as_str() != self.name {
827            return Err(MediaError::UnsupportedCodec {
828                codec: config.codec.to_string(),
829                reason: format!("manifest '{}' cannot create it", self.name),
830            });
831        }
832        if !self.accepts_frame_info(config.input) {
833            return Err(MediaError::UnsupportedPixelFormat {
834                codec: self.name.to_string(),
835                format: config.input.format.to_string(),
836            });
837        }
838        if matches!(config.rate_control, VideoRateControl::Lossless)
839            && !self.supports_lossless_frame_info(config.input)
840        {
841            return Err(MediaError::UnsupportedPixelFormat {
842                codec: self.name.to_string(),
843                format: format!("lossless {}", config.input.format),
844            });
845        }
846
847        let mut seen = Vec::new();
848        for setting in &config.settings {
849            if setting.name == "lossless" {
850                return Err(MediaError::ConflictingSettings {
851                    setting: setting.name.clone(),
852                    conflict: "VideoRateControl::Lossless".to_string(),
853                });
854            }
855            if matches!(config.rate_control, VideoRateControl::ConstantQuantizer(_))
856                && setting.name == "qp"
857            {
858                return Err(MediaError::ConflictingSettings {
859                    setting: setting.name.clone(),
860                    conflict: "VideoRateControl::ConstantQuantizer".to_string(),
861                });
862            }
863            if matches!(config.rate_control, VideoRateControl::Lossless) && setting.name == "qp" {
864                return Err(MediaError::ConflictingSettings {
865                    setting: setting.name.clone(),
866                    conflict: "lossless rate control".to_string(),
867                });
868            }
869            if seen.contains(&setting.name.as_str()) {
870                return Err(MediaError::DuplicateSetting {
871                    setting: setting.name.clone(),
872                });
873            }
874            seen.push(setting.name.as_str());
875            let Some(manifest) = self.setting(&setting.name) else {
876                return Err(MediaError::UnknownSetting {
877                    codec: self.name.to_string(),
878                    setting: setting.name.clone(),
879                });
880            };
881            if !setting_value_matches_manifest(setting, manifest.value) {
882                return Err(MediaError::InvalidSettingValue {
883                    codec: self.name.to_string(),
884                    setting: manifest.name.to_string(),
885                    expected: crate::setting_values_label(manifest),
886                    actual: setting.value.as_cli_value(),
887                });
888            }
889        }
890        Ok(())
891    }
892}
893
894fn parse_manifest_bool(
895    codec: &'static str,
896    manifest: SettingManifest,
897    value: &str,
898) -> Result<bool> {
899    match value {
900        "true" | "1" | "yes" | "on" => Ok(true),
901        "false" | "0" | "no" | "off" => Ok(false),
902        _ => Err(MediaError::InvalidSettingValue {
903            codec: codec.to_string(),
904            setting: manifest.name.to_string(),
905            expected: crate::setting_values_label(manifest),
906            actual: value.to_string(),
907        }),
908    }
909}
910
911fn video_setting_from_manifest(
912    codec: &'static str,
913    manifest: SettingManifest,
914    value: &str,
915) -> Result<VideoEncoderSetting> {
916    match manifest.value {
917        SettingValue::Boolean => VideoEncoderSetting::boolean(
918            manifest.name,
919            parse_manifest_bool(codec, manifest, value)?,
920        ),
921        SettingValue::Choice(_) => VideoEncoderSetting::text(manifest.name, value),
922        SettingValue::IntegerRange { .. } | SettingValue::SignedIntegerRange { .. } => {
923            let value = value
924                .parse::<i64>()
925                .map_err(|_| MediaError::InvalidSettingValue {
926                    codec: codec.to_string(),
927                    setting: manifest.name.to_string(),
928                    expected: crate::setting_values_label(manifest),
929                    actual: value.to_string(),
930                })?;
931            VideoEncoderSetting::integer(manifest.name, value)
932        }
933    }
934}
935
936fn push_effective_setting_specs(
937    config: &VideoEncoderConfig,
938    manifests: &[SettingManifest],
939    specs: &mut Vec<String>,
940) {
941    for manifest in manifests {
942        if let Some(value) = effective_setting_value(config, *manifest) {
943            specs.push(format!("{}={value}", manifest.name));
944        }
945    }
946}
947
948fn effective_setting_value(
949    config: &VideoEncoderConfig,
950    manifest: SettingManifest,
951) -> Option<String> {
952    if manifest.name == "lossless" {
953        return Some(matches!(config.rate_control, VideoRateControl::Lossless).to_string());
954    }
955    if manifest.name == "qp" {
956        return match config.rate_control {
957            VideoRateControl::ConstantQuantizer(qp) => Some(qp.to_string()),
958            VideoRateControl::CodecDefault | VideoRateControl::Lossless => {
959                manifest.default_value.map(str::to_string)
960            }
961        };
962    }
963    config
964        .settings
965        .iter()
966        .find(|setting| setting.name == manifest.name)
967        .map(|setting| setting.value.as_cli_value())
968        .or_else(|| manifest.default_value.map(str::to_string))
969}
970
971fn setting_value_matches_manifest(setting: &VideoEncoderSetting, manifest: SettingValue) -> bool {
972    match (manifest, &setting.value) {
973        (SettingValue::Boolean, VideoSettingValue::Boolean(_)) => true,
974        (SettingValue::Choice(values), VideoSettingValue::Text(value)) => {
975            values.contains(&value.as_str())
976        }
977        (SettingValue::IntegerRange { min, max }, VideoSettingValue::Integer(value)) => {
978            (i64::from(min)..=i64::from(max)).contains(value)
979        }
980        (SettingValue::SignedIntegerRange { min, max }, VideoSettingValue::Integer(value)) => {
981            (i64::from(min)..=i64::from(max)).contains(value)
982        }
983        _ => false,
984    }
985}
986
987fn validate_codec_id(value: &str) -> Result<()> {
988    if value.is_empty() {
989        return Err(MediaError::Message("codec id cannot be empty".to_string()));
990    }
991    if !value
992        .bytes()
993        .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')
994    {
995        return Err(MediaError::Message(format!(
996            "codec id '{value}' must contain only lowercase ASCII letters, digits, or '-'"
997        )));
998    }
999    Ok(())
1000}
1001
1002fn validate_setting_name(value: &str) -> Result<()> {
1003    if value.is_empty() {
1004        return Err(MediaError::Message(
1005            "setting name cannot be empty".to_string(),
1006        ));
1007    }
1008    if !value
1009        .bytes()
1010        .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')
1011    {
1012        return Err(MediaError::Message(format!(
1013            "setting name '{value}' must contain only lowercase ASCII letters, digits, or '-'"
1014        )));
1015    }
1016    Ok(())
1017}
1018
1019#[cfg(test)]
1020mod tests {
1021    use super::*;
1022    use crate::{PixelFormat, SettingManifest, SettingSpecForm, SettingSpecManifest, SettingValue};
1023
1024    const GOP_FORMS: &[SettingSpecForm] = &[SettingSpecForm {
1025        syntax: "gop=<-1..65535>",
1026        summary: "set temporal intra period",
1027    }];
1028    const GOP_SPEC: SettingSpecManifest = SettingSpecManifest {
1029        forms: GOP_FORMS,
1030        examples: &[],
1031        notes: &[],
1032    };
1033    const GOP_SETTING: SettingManifest = SettingManifest {
1034        name: "gop",
1035        value: SettingValue::SignedIntegerRange {
1036            min: -1,
1037            max: 65535,
1038        },
1039        default_value: Some("-1"),
1040        spec: &GOP_SPEC,
1041        summary: "set temporal intra period",
1042    };
1043    const TEST_SETTINGS: &[SettingManifest] = &[GOP_SETTING];
1044
1045    const TEST_CODEC: VideoEncoderManifest = VideoEncoderManifest::new(
1046        "test",
1047        "test-codec",
1048        "test codec",
1049        TEST_SETTINGS,
1050        test_accepts_format,
1051        test_supports_lossless_format,
1052        VideoEncoderManifestHooks {
1053            create_session: test_create_session,
1054            encode_source: test_encode_source,
1055        },
1056    );
1057
1058    struct TestSession {
1059        config: VideoEncoderConfig,
1060    }
1061
1062    impl VideoEncoderSession for TestSession {
1063        fn codec(&self) -> &CodecId {
1064            &self.config.codec
1065        }
1066
1067        fn config(&self) -> &VideoEncoderConfig {
1068            &self.config
1069        }
1070
1071        fn encode_frame(&mut self, _frame: Frame) -> Result<VideoEncodeOutput> {
1072            Ok(VideoEncodeOutput::default())
1073        }
1074    }
1075
1076    fn test_accepts_format(format: PixelFormat) -> bool {
1077        format == PixelFormat::Yuv420p8
1078    }
1079
1080    fn test_supports_lossless_format(format: PixelFormat) -> bool {
1081        test_accepts_format(format)
1082    }
1083
1084    fn test_create_session(config: VideoEncoderConfig) -> Result<Box<dyn VideoEncoderSession>> {
1085        Ok(Box::new(TestSession { config }))
1086    }
1087
1088    fn test_encode_source(
1089        _source: &mut dyn RawVideoFrameSource,
1090        _output: &mut dyn Write,
1091        _recon: Option<&mut dyn Write>,
1092        _request: VideoEncodeSourceRequest<'_>,
1093        _frame_metrics: Option<VideoEncodeFrameMetricsCallback<'_>>,
1094    ) -> Result<()> {
1095        Ok(())
1096    }
1097
1098    #[test]
1099    fn codec_id_accepts_stable_lowercase_names() {
1100        assert_eq!(CodecId::new("av2").unwrap().as_str(), "av2");
1101        assert_eq!(CodecId::new("vvc-main10").unwrap().as_str(), "vvc-main10");
1102    }
1103
1104    #[test]
1105    fn codec_id_rejects_names_that_do_not_round_trip_to_cli() {
1106        assert!(CodecId::new("").is_err());
1107        assert!(CodecId::new("AV2").is_err());
1108        assert!(CodecId::new("vvc/main10").is_err());
1109    }
1110
1111    #[test]
1112    fn config_collects_rate_control_and_extension_settings_as_specs() {
1113        let info = FrameInfo::new(16, 16, PixelFormat::Yuv420p8).unwrap();
1114        let config = VideoEncoderConfig::new(CodecId::new("vvc").unwrap(), info)
1115            .with_rate_control(VideoRateControl::constant_quantizer(24).unwrap())
1116            .with_setting(VideoEncoderSetting::integer("gop", 30).unwrap())
1117            .with_setting(VideoEncoderSetting::text("fast-search", "moderate").unwrap());
1118
1119        assert_eq!(
1120            config.setting_specs(),
1121            vec![
1122                "qp=24".to_string(),
1123                "gop=30".to_string(),
1124                "fast-search=moderate".to_string()
1125            ]
1126        );
1127    }
1128
1129    #[test]
1130    fn lossless_rate_control_maps_to_a_normal_setting_spec() {
1131        let info = FrameInfo::new(16, 16, PixelFormat::Yuv420p8).unwrap();
1132        let config = VideoEncoderConfig::new(CodecId::new("av2").unwrap(), info)
1133            .with_rate_control(VideoRateControl::Lossless);
1134
1135        assert_eq!(config.setting_specs(), vec!["lossless=true".to_string()]);
1136    }
1137
1138    #[test]
1139    fn manifest_validates_codec_format_and_settings() {
1140        let info = FrameInfo::new(16, 16, PixelFormat::Yuv420p8).unwrap();
1141        let config = VideoEncoderConfig::new(CodecId::new("test").unwrap(), info)
1142            .with_setting(VideoEncoderSetting::integer("gop", -1).unwrap());
1143
1144        TEST_CODEC
1145            .validate_config(&config)
1146            .expect("valid manifest config");
1147    }
1148
1149    #[test]
1150    fn manifest_applies_cli_style_setting_specs_to_config() {
1151        let info = FrameInfo::new(16, 16, PixelFormat::Yuv420p8).unwrap();
1152        let config = VideoEncoderConfig::new(CodecId::new("test").unwrap(), info);
1153        let config = TEST_CODEC
1154            .apply_setting_specs(config, ["lossless", "gop=30"])
1155            .expect("settings should apply");
1156
1157        assert!(matches!(config.rate_control, VideoRateControl::Lossless));
1158        assert_eq!(config.setting_specs(), vec!["lossless=true", "gop=30"]);
1159        assert_eq!(
1160            TEST_CODEC.effective_setting_specs(&config).unwrap(),
1161            vec!["lossless=true", "gop=30"]
1162        );
1163    }
1164
1165    #[test]
1166    fn manifest_renders_effective_setting_defaults() {
1167        let info = FrameInfo::new(16, 16, PixelFormat::Yuv420p8).unwrap();
1168        let config = VideoEncoderConfig::new(CodecId::new("test").unwrap(), info);
1169
1170        assert_eq!(
1171            TEST_CODEC.effective_setting_specs(&config).unwrap(),
1172            vec!["lossless=false", "gop=-1"]
1173        );
1174    }
1175
1176    #[test]
1177    fn manifest_setting_specs_reject_duplicate_names() {
1178        let info = FrameInfo::new(16, 16, PixelFormat::Yuv420p8).unwrap();
1179        let config = VideoEncoderConfig::new(CodecId::new("test").unwrap(), info);
1180
1181        assert!(matches!(
1182            TEST_CODEC
1183                .apply_setting_specs(config, ["gop=0", "gop=30"])
1184                .unwrap_err(),
1185            MediaError::DuplicateSetting { setting } if setting == "gop"
1186        ));
1187    }
1188
1189    #[test]
1190    fn manifest_rejects_unknown_and_duplicate_settings() {
1191        let info = FrameInfo::new(16, 16, PixelFormat::Yuv420p8).unwrap();
1192        let unknown = VideoEncoderConfig::new(CodecId::new("test").unwrap(), info)
1193            .with_setting(VideoEncoderSetting::boolean("missing", true).unwrap());
1194        let duplicate = VideoEncoderConfig::new(CodecId::new("test").unwrap(), info)
1195            .with_setting(VideoEncoderSetting::integer("gop", -1).unwrap())
1196            .with_setting(VideoEncoderSetting::integer("gop", 0).unwrap());
1197
1198        assert!(matches!(
1199            TEST_CODEC.validate_config(&unknown).unwrap_err(),
1200            MediaError::UnknownSetting { codec, setting }
1201                if codec == "test" && setting == "missing"
1202        ));
1203        assert!(matches!(
1204            TEST_CODEC.validate_config(&duplicate).unwrap_err(),
1205            MediaError::DuplicateSetting { setting } if setting == "gop"
1206        ));
1207    }
1208
1209    #[test]
1210    fn manifest_rejects_invalid_setting_values_and_conflicts() {
1211        let info = FrameInfo::new(16, 16, PixelFormat::Yuv420p8).unwrap();
1212        let invalid_value = VideoEncoderConfig::new(CodecId::new("test").unwrap(), info)
1213            .with_setting(VideoEncoderSetting::integer("gop", -2).unwrap());
1214        let conflicting_qp = VideoEncoderConfig::new(CodecId::new("test").unwrap(), info)
1215            .with_rate_control(VideoRateControl::constant_quantizer(24).unwrap())
1216            .with_setting(VideoEncoderSetting::integer("qp", 19).unwrap());
1217
1218        assert!(matches!(
1219            TEST_CODEC.validate_config(&invalid_value).unwrap_err(),
1220            MediaError::InvalidSettingValue {
1221                codec,
1222                setting,
1223                expected,
1224                actual,
1225            } if codec == "test"
1226                && setting == "gop"
1227                && expected == "-1..65535"
1228                && actual == "-2"
1229        ));
1230        assert!(matches!(
1231            TEST_CODEC.validate_config(&conflicting_qp).unwrap_err(),
1232            MediaError::ConflictingSettings { setting, conflict }
1233                if setting == "qp" && conflict == "VideoRateControl::ConstantQuantizer"
1234        ));
1235    }
1236
1237    #[test]
1238    fn manifest_rejects_codec_and_format_mismatches_structurally() {
1239        let info = FrameInfo::new(16, 16, PixelFormat::Yuv420p8).unwrap();
1240        let wrong_codec = VideoEncoderConfig::new(CodecId::new("other").unwrap(), info);
1241        let wrong_format = VideoEncoderConfig::new(
1242            CodecId::new("test").unwrap(),
1243            FrameInfo::new(16, 16, PixelFormat::Rgb24).unwrap(),
1244        );
1245
1246        assert!(matches!(
1247            TEST_CODEC.validate_config(&wrong_codec).unwrap_err(),
1248            MediaError::UnsupportedCodec { codec, .. } if codec == "other"
1249        ));
1250        assert!(matches!(
1251            TEST_CODEC.validate_config(&wrong_format).unwrap_err(),
1252            MediaError::UnsupportedPixelFormat { codec, format }
1253                if codec == "test" && format == "rgb24"
1254        ));
1255    }
1256
1257    #[test]
1258    fn raw_video_read_source_reports_short_frames_structurally() {
1259        let mut source = RawVideoFrameReadSource::new(std::io::Cursor::new(vec![1, 2, 3]));
1260        let mut frame = [0u8; 4];
1261        let err = source.read_frame(&mut frame).unwrap_err();
1262
1263        assert!(matches!(
1264            err,
1265            MediaError::ShortFrameRead {
1266                expected: 4,
1267                actual: 3,
1268            }
1269        ));
1270    }
1271}