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#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
13pub struct CodecId(String);
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub struct FrameRate {
18 pub numerator: u32,
20 pub denominator: u32,
22}
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
26pub enum VideoRateControl {
27 #[default]
29 CodecDefault,
30 Lossless,
32 ConstantQuantizer(u8),
34}
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
38pub enum ReconstructionMode {
39 #[default]
41 None,
42 MetricsOnly,
44 Frames,
46}
47
48#[derive(Debug, Clone, PartialEq, Eq)]
50pub enum VideoSettingValue {
51 Boolean(bool),
53 Integer(i64),
55 Text(String),
57}
58
59#[derive(Debug, Clone, PartialEq, Eq)]
61pub struct VideoEncoderSetting {
62 pub name: String,
64 pub value: VideoSettingValue,
66}
67
68#[derive(Debug, Clone, PartialEq, Eq)]
70pub struct VideoEncoderConfig {
71 pub codec: CodecId,
73 pub input: FrameInfo,
75 pub frame_rate: Option<FrameRate>,
77 pub frame_limit: Option<usize>,
79 pub rate_control: VideoRateControl,
81 pub reconstruction: ReconstructionMode,
83 pub settings: Vec<VideoEncoderSetting>,
85}
86
87#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89pub enum VideoChunkKind {
90 Config,
92 Frame,
94 EndOfStream,
96 Stream,
99}
100
101#[derive(Debug, Clone, PartialEq, Eq)]
103pub struct EncodedVideoChunk {
104 pub codec: CodecId,
106 pub kind: VideoChunkKind,
108 pub data: Vec<u8>,
110 pub frame_index: Option<usize>,
112 pub pts: Option<Timestamp>,
114 pub dts: Option<Timestamp>,
116 pub duration: Option<Timestamp>,
118 pub keyframe: bool,
120}
121
122#[derive(Debug, Clone, PartialEq)]
124pub struct FrameEncodeMetrics {
125 pub frame_index: usize,
127 pub frame_count: Option<usize>,
129 pub encoded_bytes: usize,
131 pub psnr: Option<f64>,
133}
134
135#[derive(Debug, Clone, PartialEq, Default)]
137pub struct VideoEncodeOutput {
138 pub chunks: Vec<EncodedVideoChunk>,
140 pub reconstructions: Vec<Frame>,
142 pub metrics: Vec<FrameEncodeMetrics>,
144}
145
146pub trait VideoEncoderSession {
159 fn codec(&self) -> &CodecId;
161
162 fn config(&self) -> &VideoEncoderConfig;
164
165 fn encode_frame(&mut self, frame: Frame) -> Result<VideoEncodeOutput>;
172
173 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
188pub trait RawVideoFrameSource {
190 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
206pub struct RawVideoFrameReadSource<R> {
208 inner: R,
209}
210
211impl<R: Read> RawVideoFrameReadSource<R> {
212 pub fn new(inner: R) -> Self {
214 Self { inner }
215 }
216
217 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
246pub 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 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 pub fn with_frame_limit(mut self, frame_limit: usize) -> Self {
277 self.frame_limit = Some(frame_limit);
278 self
279 }
280
281 pub const fn frames_read(&self) -> usize {
283 self.frames_read
284 }
285
286 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#[derive(Debug, Clone, Copy)]
343pub struct VideoEncoderManifest {
344 pub name: &'static str,
346 pub feature: &'static str,
348 pub summary: &'static str,
350 pub settings: &'static [SettingManifest],
352 pub accepts_format: fn(PixelFormat) -> bool,
354 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
367pub struct VideoEncodeFrameMetrics<'a> {
369 pub frame_idx: usize,
371 pub frame_count: Option<usize>,
373 pub bitstream_bytes: usize,
375 pub total_bitstream_bytes: usize,
377 pub encode_elapsed: Duration,
379 pub psnr: Option<FramePsnr>,
381 pub source: &'a [u8],
383 pub reconstruction: &'a [u8],
385}
386
387pub 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 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 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 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 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 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 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 pub fn boolean(name: impl Into<String>, value: bool) -> Result<Self> {
539 Self::new(name, VideoSettingValue::Boolean(value))
540 }
541
542 pub fn integer(name: impl Into<String>, value: i64) -> Result<Self> {
544 Self::new(name, VideoSettingValue::Integer(value))
545 }
546
547 pub fn text(name: impl Into<String>, value: impl Into<String>) -> Result<Self> {
549 Self::new(name, VideoSettingValue::Text(value.into()))
550 }
551
552 pub fn as_cli_spec(&self) -> String {
554 format!("{}={}", self.name, self.value.as_cli_value())
555 }
556}
557
558impl VideoEncoderConfig {
559 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 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 pub fn with_frame_rate(mut self, frame_rate: FrameRate) -> Self {
579 self.frame_rate = Some(frame_rate);
580 self
581 }
582
583 pub fn with_frame_limit(mut self, frame_limit: usize) -> Self {
585 self.frame_limit = Some(frame_limit);
586 self
587 }
588
589 pub fn with_rate_control(mut self, rate_control: VideoRateControl) -> Self {
591 self.rate_control = rate_control;
592 self
593 }
594
595 pub fn with_reconstruction(mut self, reconstruction: ReconstructionMode) -> Self {
597 self.reconstruction = reconstruction;
598 self
599 }
600
601 pub fn with_setting(mut self, setting: VideoEncoderSetting) -> Self {
603 self.settings.push(setting);
604 self
605 }
606
607 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 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 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 pub fn codec_id(self) -> Result<CodecId> {
686 CodecId::new(self.name)
687 }
688
689 pub fn setting(self, name: &str) -> Option<SettingManifest> {
691 self.settings
692 .iter()
693 .copied()
694 .find(|setting| setting.name == name)
695 }
696
697 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 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 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 pub fn accepts_frame_info(self, input: FrameInfo) -> bool {
816 (self.accepts_format)(input.format)
817 }
818
819 pub fn supports_lossless_frame_info(self, input: FrameInfo) -> bool {
821 (self.supports_lossless_format)(input.format)
822 }
823
824 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}