framefinery-api 0.0.3

Shared media pipeline APIs for FrameFinery.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
use std::fmt;
use std::io::{Read, Write};
use std::str::FromStr;
use std::time::Duration;

use crate::{
    Frame, FrameInfo, FramePsnr, MediaError, PixelFormat, Result, SettingManifest, SettingValue,
    Timestamp,
};

/// Stable codec identifier used by CLI, manifests, and library callers.
#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct CodecId(String);

/// Rational frame rate metadata.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FrameRate {
    /// Frame-rate numerator.
    pub numerator: u32,
    /// Frame-rate denominator.
    pub denominator: u32,
}

/// Rate-control mode requested from a video encoder.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum VideoRateControl {
    /// Let the codec choose its default mode.
    #[default]
    CodecDefault,
    /// Request stream-exact lossless coding.
    Lossless,
    /// Request lossy coding with a codec-local quantizer value.
    ConstantQuantizer(u8),
}

/// Reconstruction data requested from a video encoder.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ReconstructionMode {
    /// Do not return reconstructions or compute reconstruction-derived metrics.
    #[default]
    None,
    /// Compute metrics while reconstructed samples are available internally.
    MetricsOnly,
    /// Return reconstructed frames to the caller.
    Frames,
}

/// Typed value for a codec extension setting.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum VideoSettingValue {
    /// Boolean setting value.
    Boolean(bool),
    /// Integer setting value.
    Integer(i64),
    /// Text or choice setting value.
    Text(String),
}

/// One codec extension setting in a [`VideoEncoderConfig`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VideoEncoderSetting {
    /// Setting name.
    pub name: String,
    /// Typed setting value.
    pub value: VideoSettingValue,
}

/// Codec-neutral configuration for constructing or driving a video encoder.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VideoEncoderConfig {
    /// Selected codec id.
    pub codec: CodecId,
    /// Input frame geometry and pixel format.
    pub input: FrameInfo,
    /// Optional frame-rate metadata.
    pub frame_rate: Option<FrameRate>,
    /// Optional caller/source frame limit.
    pub frame_limit: Option<usize>,
    /// Requested rate-control mode.
    pub rate_control: VideoRateControl,
    /// Requested reconstruction output mode.
    pub reconstruction: ReconstructionMode,
    /// Codec extension settings.
    pub settings: Vec<VideoEncoderSetting>,
}

/// Encoded chunk category emitted by video encoders.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VideoChunkKind {
    /// Codec configuration bytes.
    Config,
    /// One coded frame or access unit.
    Frame,
    /// End-of-stream marker.
    EndOfStream,
    /// Whole stream payload used by compatibility encoders.
    Stream,
}

/// Encoded bytes plus timing and keyframe metadata.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EncodedVideoChunk {
    /// Codec that produced the chunk.
    pub codec: CodecId,
    /// Chunk category.
    pub kind: VideoChunkKind,
    /// Encoded payload bytes.
    pub data: Vec<u8>,
    /// Optional zero-based frame index associated with this chunk.
    pub frame_index: Option<usize>,
    /// Optional presentation timestamp.
    pub pts: Option<Timestamp>,
    /// Optional decode timestamp.
    pub dts: Option<Timestamp>,
    /// Optional duration.
    pub duration: Option<Timestamp>,
    /// Whether this chunk starts or represents a keyframe.
    pub keyframe: bool,
}

/// Per-frame encode metrics returned by session-style encoders.
#[derive(Debug, Clone, PartialEq)]
pub struct FrameEncodeMetrics {
    /// Zero-based frame index.
    pub frame_index: usize,
    /// Optional total frame count when known by the caller.
    pub frame_count: Option<usize>,
    /// Number of encoded bytes produced through this frame.
    pub encoded_bytes: usize,
    /// Optional aggregate PSNR for this frame.
    pub psnr: Option<f64>,
}

/// Output produced by one encoder-session operation.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct VideoEncodeOutput {
    /// Encoded chunks emitted by this operation.
    pub chunks: Vec<EncodedVideoChunk>,
    /// Reconstructed frames returned by this operation.
    pub reconstructions: Vec<Frame>,
    /// Per-frame metrics returned by this operation.
    pub metrics: Vec<FrameEncodeMetrics>,
}

/// Buffered frame-session video encoder interface.
///
/// This API is convenient for filtered frame flows and tests. Long file streams
/// should prefer source-driven encoding until the experimental codec sessions
/// become fully incremental.
pub trait VideoEncoderSession {
    /// Codec id for this encoder session.
    fn codec(&self) -> &CodecId;

    /// Configuration used to create this session.
    fn config(&self) -> &VideoEncoderConfig;

    /// Submit one frame to the encoder session.
    fn encode_frame(&mut self, frame: Frame) -> Result<VideoEncodeOutput>;

    /// Finish the stream and return any delayed output.
    fn flush(&mut self) -> Result<VideoEncodeOutput> {
        Ok(VideoEncodeOutput::default())
    }
}

#[doc(hidden)]
pub type VideoEncoderSessionFactory =
    fn(VideoEncoderConfig) -> Result<Box<dyn VideoEncoderSession>>;

/// Pull-based raw video source used by source-driven encoders.
pub trait RawVideoFrameSource {
    /// Fill `frame` with exactly one raw frame.
    ///
    /// Returns `Ok(false)` only at clean EOF before any bytes of the next frame
    /// are read.
    fn read_frame(&mut self, frame: &mut [u8]) -> Result<bool>;
}

impl<F> RawVideoFrameSource for F
where
    F: FnMut(&mut [u8]) -> Result<bool>,
{
    fn read_frame(&mut self, frame: &mut [u8]) -> Result<bool> {
        self(frame)
    }
}

/// [`RawVideoFrameSource`] adapter for any [`Read`] implementation.
pub struct RawVideoFrameReadSource<R> {
    inner: R,
}

impl<R: Read> RawVideoFrameReadSource<R> {
    /// Wrap a reader as a raw frame source.
    pub fn new(inner: R) -> Self {
        Self { inner }
    }

    /// Return the wrapped reader.
    pub fn into_inner(self) -> R {
        self.inner
    }
}

impl<R: Read> RawVideoFrameSource for RawVideoFrameReadSource<R> {
    fn read_frame(&mut self, frame: &mut [u8]) -> Result<bool> {
        let mut offset = 0usize;
        while offset < frame.len() {
            let count = self
                .inner
                .read(&mut frame[offset..])
                .map_err(|err| MediaError::Message(format!("failed to read input frame: {err}")))?;
            if count == 0 {
                if offset == 0 {
                    return Ok(false);
                }
                return Err(MediaError::ShortFrameRead {
                    expected: frame.len(),
                    actual: offset,
                });
            }
            offset += count;
        }
        Ok(true)
    }
}

/// [`Read`] adapter for any [`RawVideoFrameSource`] implementation.
///
/// The adapter buffers one raw frame at a time so legacy stream encoders that
/// consume byte readers can still be driven from pull-based frame sources
/// without materializing a whole stream.
pub struct RawVideoFrameSourceReadAdapter<S> {
    source: S,
    frame: Vec<u8>,
    frame_offset: usize,
    frames_read: usize,
    frame_limit: Option<usize>,
}

impl<S> RawVideoFrameSourceReadAdapter<S>
where
    S: RawVideoFrameSource,
{
    /// Create a byte reader over `source` using the byte length implied by `info`.
    pub fn new(source: S, info: FrameInfo) -> Self {
        let frame_len = info.expected_len();
        Self {
            source,
            frame: vec![0; frame_len],
            frame_offset: frame_len,
            frames_read: 0,
            frame_limit: None,
        }
    }

    /// Stop reading after at most `frame_limit` complete frames.
    pub fn with_frame_limit(mut self, frame_limit: usize) -> Self {
        self.frame_limit = Some(frame_limit);
        self
    }

    /// Return the number of complete frames read from the source.
    pub const fn frames_read(&self) -> usize {
        self.frames_read
    }

    /// Consume the adapter and return the wrapped source.
    pub fn into_inner(self) -> S {
        self.source
    }

    fn load_frame(&mut self) -> std::io::Result<bool> {
        if self
            .frame_limit
            .is_some_and(|limit| self.frames_read >= limit)
        {
            return Ok(false);
        }
        let has_frame = self
            .source
            .read_frame(&mut self.frame)
            .map_err(|err| std::io::Error::new(std::io::ErrorKind::Other, err.to_string()))?;
        if !has_frame {
            return Ok(false);
        }
        self.frames_read += 1;
        self.frame_offset = 0;
        Ok(true)
    }
}

impl<S> Read for RawVideoFrameSourceReadAdapter<S>
where
    S: RawVideoFrameSource,
{
    fn read(&mut self, output: &mut [u8]) -> std::io::Result<usize> {
        if output.is_empty() {
            return Ok(0);
        }

        let mut written = 0usize;
        while written < output.len() {
            if self.frame_offset == self.frame.len() && !self.load_frame()? {
                break;
            }
            let remaining_frame = self.frame.len() - self.frame_offset;
            let count = remaining_frame.min(output.len() - written);
            output[written..written + count]
                .copy_from_slice(&self.frame[self.frame_offset..self.frame_offset + count]);
            self.frame_offset += count;
            written += count;
        }
        Ok(written)
    }
}

/// Discovery manifest for one compiled video encoder.
///
/// The manifest exposes stable metadata for catalogs, help text, and validation
/// of codec-neutral configs. Normal callers should create and drive encoders
/// through registry helpers provided by `framefinery` or `framefinery-codecs`,
/// using the codec id already stored in [`VideoEncoderConfig`].
#[derive(Debug, Clone, Copy)]
pub struct VideoEncoderManifest {
    /// Stable codec id string.
    pub name: &'static str,
    /// Cargo feature that enables this encoder.
    pub feature: &'static str,
    /// Short user-facing encoder summary.
    pub summary: &'static str,
    /// Codec-specific settings accepted by this encoder.
    pub settings: &'static [SettingManifest],
    /// Function that tests whether an input pixel format is accepted.
    pub accepts_format: fn(PixelFormat) -> bool,
    /// Function that tests whether lossless mode is accepted for an input format.
    pub supports_lossless_format: fn(PixelFormat) -> bool,
    create_session_hook: VideoEncoderSessionFactory,
    encode_source_hook: VideoEncodeSourceFn,
}

#[doc(hidden)]
#[derive(Debug, Clone, Copy)]
pub struct VideoEncodeSourceRequest<'a> {
    #[doc(hidden)]
    pub config: &'a VideoEncoderConfig,
}

/// Per-frame metrics passed to source-driven encode callbacks.
pub struct VideoEncodeFrameMetrics<'a> {
    /// Zero-based frame index.
    pub frame_idx: usize,
    /// Optional total frame count when known by the caller.
    pub frame_count: Option<usize>,
    /// Encoded bytes produced by this frame.
    pub bitstream_bytes: usize,
    /// Encoded bytes produced by all reported frames through this frame.
    pub total_bitstream_bytes: usize,
    /// Wall time spent encoding this frame after the source frame was read.
    pub encode_elapsed: Duration,
    /// PSNR for this frame when reconstruction metrics were requested.
    pub psnr: Option<FramePsnr>,
    /// Source frame bytes for metric calculations.
    pub source: &'a [u8],
    /// Reconstructed frame bytes for metric calculations.
    pub reconstruction: &'a [u8],
}

/// Callback type used to receive source-driven per-frame metrics.
pub type VideoEncodeFrameMetricsCallback<'a> =
    &'a mut dyn for<'frame> FnMut(VideoEncodeFrameMetrics<'frame>);

#[doc(hidden)]
pub type VideoEncodeSourceFn = for<'request, 'callback> fn(
    &mut dyn RawVideoFrameSource,
    &mut dyn Write,
    Option<&mut dyn Write>,
    VideoEncodeSourceRequest<'request>,
    Option<VideoEncodeFrameMetricsCallback<'callback>>,
) -> Result<()>;

#[doc(hidden)]
#[derive(Debug, Clone, Copy)]
pub struct VideoEncoderManifestHooks {
    #[doc(hidden)]
    pub create_session: VideoEncoderSessionFactory,
    #[doc(hidden)]
    pub encode_source: VideoEncodeSourceFn,
}

impl CodecId {
    /// Validate and create a codec id.
    ///
    /// Codec ids are lowercase ASCII names with optional digits and hyphens.
    pub fn new(value: impl Into<String>) -> Result<Self> {
        let value = value.into();
        validate_codec_id(&value)?;
        Ok(Self(value))
    }

    /// Borrow the codec id as a string slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Debug for CodecId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("CodecId").field(&self.0).finish()
    }
}

impl fmt::Display for CodecId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl FromStr for CodecId {
    type Err = MediaError;

    fn from_str(value: &str) -> Result<Self> {
        Self::new(value)
    }
}

impl TryFrom<&str> for CodecId {
    type Error = MediaError;

    fn try_from(value: &str) -> Result<Self> {
        Self::new(value)
    }
}

impl FrameRate {
    /// Create a nonzero rational frame rate.
    pub fn new(numerator: u32, denominator: u32) -> Result<Self> {
        if numerator == 0 || denominator == 0 {
            return Err(MediaError::Message(
                "frame rate numerator and denominator must be non-zero".to_string(),
            ));
        }
        Ok(Self {
            numerator,
            denominator,
        })
    }
}

impl VideoRateControl {
    /// Create a constant-quantizer rate-control mode.
    ///
    /// The accepted public range is `1..=255`.
    pub fn constant_quantizer(qp: u8) -> Result<Self> {
        if qp == 0 {
            return Err(MediaError::Message(
                "constant quantizer must be in the range 1..255".to_string(),
            ));
        }
        Ok(Self::ConstantQuantizer(qp))
    }
}

impl VideoSettingValue {
    /// Render this typed value as a CLI-compatible setting value.
    pub fn as_cli_value(&self) -> String {
        match self {
            Self::Boolean(value) => value.to_string(),
            Self::Integer(value) => value.to_string(),
            Self::Text(value) => value.clone(),
        }
    }
}

impl From<bool> for VideoSettingValue {
    fn from(value: bool) -> Self {
        Self::Boolean(value)
    }
}

impl From<i64> for VideoSettingValue {
    fn from(value: i64) -> Self {
        Self::Integer(value)
    }
}

impl From<i32> for VideoSettingValue {
    fn from(value: i32) -> Self {
        Self::Integer(i64::from(value))
    }
}

impl From<u8> for VideoSettingValue {
    fn from(value: u8) -> Self {
        Self::Integer(i64::from(value))
    }
}

impl From<String> for VideoSettingValue {
    fn from(value: String) -> Self {
        Self::Text(value)
    }
}

impl From<&str> for VideoSettingValue {
    fn from(value: &str) -> Self {
        Self::Text(value.to_string())
    }
}

impl VideoEncoderSetting {
    /// Create a setting with a validated setting name and typed value.
    pub fn new(name: impl Into<String>, value: VideoSettingValue) -> Result<Self> {
        let name = name.into();
        validate_setting_name(&name)?;
        Ok(Self { name, value })
    }

    /// Create a boolean codec extension setting.
    pub fn boolean(name: impl Into<String>, value: bool) -> Result<Self> {
        Self::new(name, VideoSettingValue::Boolean(value))
    }

    /// Create an integer codec extension setting.
    pub fn integer(name: impl Into<String>, value: i64) -> Result<Self> {
        Self::new(name, VideoSettingValue::Integer(value))
    }

    /// Create a text or choice codec extension setting.
    pub fn text(name: impl Into<String>, value: impl Into<String>) -> Result<Self> {
        Self::new(name, VideoSettingValue::Text(value.into()))
    }

    /// Render this setting as a CLI-compatible `name=value` spec.
    pub fn as_cli_spec(&self) -> String {
        format!("{}={}", self.name, self.value.as_cli_value())
    }
}

impl VideoEncoderConfig {
    /// Create an encoder config using codec defaults for optional fields.
    pub fn new(codec: CodecId, input: FrameInfo) -> Self {
        Self {
            codec,
            input,
            frame_rate: None,
            frame_limit: None,
            rate_control: VideoRateControl::CodecDefault,
            reconstruction: ReconstructionMode::None,
            settings: Vec::new(),
        }
    }

    /// Create an encoder config from a textual codec id.
    pub fn for_codec(codec: impl AsRef<str>, input: FrameInfo) -> Result<Self> {
        Ok(Self::new(CodecId::new(codec.as_ref())?, input))
    }

    /// Set optional frame-rate metadata.
    pub fn with_frame_rate(mut self, frame_rate: FrameRate) -> Self {
        self.frame_rate = Some(frame_rate);
        self
    }

    /// Set an optional source/caller frame limit.
    pub fn with_frame_limit(mut self, frame_limit: usize) -> Self {
        self.frame_limit = Some(frame_limit);
        self
    }

    /// Set the requested rate-control mode.
    pub fn with_rate_control(mut self, rate_control: VideoRateControl) -> Self {
        self.rate_control = rate_control;
        self
    }

    /// Set the requested reconstruction mode.
    pub fn with_reconstruction(mut self, reconstruction: ReconstructionMode) -> Self {
        self.reconstruction = reconstruction;
        self
    }

    /// Append one codec extension setting.
    pub fn with_setting(mut self, setting: VideoEncoderSetting) -> Self {
        self.settings.push(setting);
        self
    }

    /// Return explicit CLI-compatible setting specs represented by this config.
    ///
    /// This does not include manifest defaults. Use
    /// [`VideoEncoderManifest::effective_setting_specs`] when a frontend needs
    /// the full effective setting list that will be reported to users.
    pub fn setting_specs(&self) -> Vec<String> {
        let mut specs = Vec::new();
        match self.rate_control {
            VideoRateControl::CodecDefault => {}
            VideoRateControl::Lossless => specs.push("lossless=true".to_string()),
            VideoRateControl::ConstantQuantizer(qp) => specs.push(format!("qp={qp}")),
        }
        specs.extend(self.settings.iter().map(VideoEncoderSetting::as_cli_spec));
        specs
    }
}

impl EncodedVideoChunk {
    /// Create an encoded chunk without timing metadata.
    pub fn new(codec: CodecId, kind: VideoChunkKind, data: Vec<u8>) -> Self {
        Self {
            codec,
            kind,
            data,
            frame_index: None,
            pts: None,
            dts: None,
            duration: None,
            keyframe: false,
        }
    }
}

impl VideoEncodeOutput {
    /// Create output containing a single encoded chunk.
    pub fn from_chunk(chunk: EncodedVideoChunk) -> Self {
        Self {
            chunks: vec![chunk],
            reconstructions: Vec::new(),
            metrics: Vec::new(),
        }
    }
}

impl VideoEncoderManifest {
    #[doc(hidden)]
    pub const fn new(
        name: &'static str,
        feature: &'static str,
        summary: &'static str,
        settings: &'static [SettingManifest],
        accepts_format: fn(PixelFormat) -> bool,
        supports_lossless_format: fn(PixelFormat) -> bool,
        hooks: VideoEncoderManifestHooks,
    ) -> Self {
        Self {
            name,
            feature,
            summary,
            settings,
            accepts_format,
            supports_lossless_format,
            create_session_hook: hooks.create_session,
            encode_source_hook: hooks.encode_source,
        }
    }

    #[doc(hidden)]
    pub fn session_factory(self) -> VideoEncoderSessionFactory {
        self.create_session_hook
    }

    #[doc(hidden)]
    pub fn source_encode_hook(self) -> VideoEncodeSourceFn {
        self.encode_source_hook
    }

    /// Return this manifest's codec id as a validated [`CodecId`].
    pub fn codec_id(self) -> Result<CodecId> {
        CodecId::new(self.name)
    }

    /// Find a codec-specific setting manifest by name.
    pub fn setting(self, name: &str) -> Option<SettingManifest> {
        self.settings
            .iter()
            .copied()
            .find(|setting| setting.name == name)
    }

    /// Find a global or codec-specific setting manifest by name.
    pub fn declared_setting(self, name: &str) -> Option<SettingManifest> {
        crate::GLOBAL_SETTINGS
            .iter()
            .copied()
            .find(|setting| setting.name == name)
            .or_else(|| self.setting(name))
    }

    /// Apply CLI-compatible `name[=value]` setting specs to `config`.
    ///
    /// Global rate-control settings such as `lossless` and `qp` are folded into
    /// [`VideoEncoderConfig::rate_control`]. Codec extension settings are stored
    /// in [`VideoEncoderConfig::settings`]. Re-applying an extension setting
    /// replaces the previous value in `config`, while duplicate names in the
    /// provided `specs` are rejected.
    pub fn apply_setting_specs<I, S>(
        self,
        mut config: VideoEncoderConfig,
        specs: I,
    ) -> Result<VideoEncoderConfig>
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        if config.codec.as_str() != self.name {
            return Err(MediaError::UnsupportedCodec {
                codec: config.codec.to_string(),
                reason: format!("manifest '{}' cannot configure it", self.name),
            });
        }

        let mut seen = Vec::new();
        for spec in specs {
            let spec = spec.as_ref();
            let name = crate::setting_name(spec);
            validate_setting_name(name)?;
            if seen.iter().any(|seen_name| seen_name == name) {
                return Err(MediaError::DuplicateSetting {
                    setting: name.to_string(),
                });
            }
            seen.push(name.to_string());

            let Some(manifest) = self.declared_setting(name) else {
                return Err(MediaError::UnknownSetting {
                    codec: self.name.to_string(),
                    setting: name.to_string(),
                });
            };
            let value = crate::setting_value(spec).unwrap_or("true");
            if !manifest.value.accepts(value) {
                return Err(MediaError::InvalidSettingValue {
                    codec: self.name.to_string(),
                    setting: manifest.name.to_string(),
                    expected: crate::setting_values_label(manifest),
                    actual: value.to_string(),
                });
            }

            if name == "lossless" {
                let lossless = parse_manifest_bool(self.name, manifest, value)?;
                if lossless {
                    if matches!(config.rate_control, VideoRateControl::ConstantQuantizer(_)) {
                        return Err(MediaError::ConflictingSettings {
                            setting: name.to_string(),
                            conflict: "VideoRateControl::ConstantQuantizer".to_string(),
                        });
                    }
                    config.rate_control = VideoRateControl::Lossless;
                } else if matches!(config.rate_control, VideoRateControl::Lossless) {
                    config.rate_control = VideoRateControl::CodecDefault;
                }
                continue;
            }

            if name == "qp" {
                if matches!(config.rate_control, VideoRateControl::Lossless) {
                    return Err(MediaError::ConflictingSettings {
                        setting: name.to_string(),
                        conflict: "VideoRateControl::Lossless".to_string(),
                    });
                }
                let qp = value
                    .parse::<u8>()
                    .map_err(|_| MediaError::InvalidSettingValue {
                        codec: self.name.to_string(),
                        setting: manifest.name.to_string(),
                        expected: crate::setting_values_label(manifest),
                        actual: value.to_string(),
                    })?;
                config.rate_control = VideoRateControl::constant_quantizer(qp)?;
                continue;
            }

            let setting = video_setting_from_manifest(self.name, manifest, value)?;
            config.settings.retain(|setting| setting.name != name);
            config.settings.push(setting);
        }

        self.validate_config(&config)?;
        Ok(config)
    }

    /// Return all effective setting specs after manifest defaults are applied.
    ///
    /// The returned strings use the same `name=value` shape accepted by
    /// [`VideoEncoderManifest::apply_setting_specs`] and are ordered with
    /// global settings first, followed by codec-specific settings.
    pub fn effective_setting_specs(self, config: &VideoEncoderConfig) -> Result<Vec<String>> {
        self.validate_config(config)?;
        let mut specs = Vec::new();
        push_effective_setting_specs(config, crate::GLOBAL_SETTINGS, &mut specs);
        push_effective_setting_specs(config, self.settings, &mut specs);
        Ok(specs)
    }

    /// Return whether this encoder accepts the frame format in `input`.
    pub fn accepts_frame_info(self, input: FrameInfo) -> bool {
        (self.accepts_format)(input.format)
    }

    /// Return whether this encoder supports lossless coding for `input`.
    pub fn supports_lossless_frame_info(self, input: FrameInfo) -> bool {
        (self.supports_lossless_format)(input.format)
    }

    /// Validate codec id, input format, rate control, and extension settings.
    pub fn validate_config(self, config: &VideoEncoderConfig) -> Result<()> {
        if config.codec.as_str() != self.name {
            return Err(MediaError::UnsupportedCodec {
                codec: config.codec.to_string(),
                reason: format!("manifest '{}' cannot create it", self.name),
            });
        }
        if !self.accepts_frame_info(config.input) {
            return Err(MediaError::UnsupportedPixelFormat {
                codec: self.name.to_string(),
                format: config.input.format.to_string(),
            });
        }
        if matches!(config.rate_control, VideoRateControl::Lossless)
            && !self.supports_lossless_frame_info(config.input)
        {
            return Err(MediaError::UnsupportedPixelFormat {
                codec: self.name.to_string(),
                format: format!("lossless {}", config.input.format),
            });
        }

        let mut seen = Vec::new();
        for setting in &config.settings {
            if setting.name == "lossless" {
                return Err(MediaError::ConflictingSettings {
                    setting: setting.name.clone(),
                    conflict: "VideoRateControl::Lossless".to_string(),
                });
            }
            if matches!(config.rate_control, VideoRateControl::ConstantQuantizer(_))
                && setting.name == "qp"
            {
                return Err(MediaError::ConflictingSettings {
                    setting: setting.name.clone(),
                    conflict: "VideoRateControl::ConstantQuantizer".to_string(),
                });
            }
            if matches!(config.rate_control, VideoRateControl::Lossless) && setting.name == "qp" {
                return Err(MediaError::ConflictingSettings {
                    setting: setting.name.clone(),
                    conflict: "lossless rate control".to_string(),
                });
            }
            if seen.contains(&setting.name.as_str()) {
                return Err(MediaError::DuplicateSetting {
                    setting: setting.name.clone(),
                });
            }
            seen.push(setting.name.as_str());
            let Some(manifest) = self.setting(&setting.name) else {
                return Err(MediaError::UnknownSetting {
                    codec: self.name.to_string(),
                    setting: setting.name.clone(),
                });
            };
            if !setting_value_matches_manifest(setting, manifest.value) {
                return Err(MediaError::InvalidSettingValue {
                    codec: self.name.to_string(),
                    setting: manifest.name.to_string(),
                    expected: crate::setting_values_label(manifest),
                    actual: setting.value.as_cli_value(),
                });
            }
        }
        Ok(())
    }
}

fn parse_manifest_bool(
    codec: &'static str,
    manifest: SettingManifest,
    value: &str,
) -> Result<bool> {
    match value {
        "true" | "1" | "yes" | "on" => Ok(true),
        "false" | "0" | "no" | "off" => Ok(false),
        _ => Err(MediaError::InvalidSettingValue {
            codec: codec.to_string(),
            setting: manifest.name.to_string(),
            expected: crate::setting_values_label(manifest),
            actual: value.to_string(),
        }),
    }
}

fn video_setting_from_manifest(
    codec: &'static str,
    manifest: SettingManifest,
    value: &str,
) -> Result<VideoEncoderSetting> {
    match manifest.value {
        SettingValue::Boolean => VideoEncoderSetting::boolean(
            manifest.name,
            parse_manifest_bool(codec, manifest, value)?,
        ),
        SettingValue::Choice(_) => VideoEncoderSetting::text(manifest.name, value),
        SettingValue::IntegerRange { .. } | SettingValue::SignedIntegerRange { .. } => {
            let value = value
                .parse::<i64>()
                .map_err(|_| MediaError::InvalidSettingValue {
                    codec: codec.to_string(),
                    setting: manifest.name.to_string(),
                    expected: crate::setting_values_label(manifest),
                    actual: value.to_string(),
                })?;
            VideoEncoderSetting::integer(manifest.name, value)
        }
    }
}

fn push_effective_setting_specs(
    config: &VideoEncoderConfig,
    manifests: &[SettingManifest],
    specs: &mut Vec<String>,
) {
    for manifest in manifests {
        if let Some(value) = effective_setting_value(config, *manifest) {
            specs.push(format!("{}={value}", manifest.name));
        }
    }
}

fn effective_setting_value(
    config: &VideoEncoderConfig,
    manifest: SettingManifest,
) -> Option<String> {
    if manifest.name == "lossless" {
        return Some(matches!(config.rate_control, VideoRateControl::Lossless).to_string());
    }
    if manifest.name == "qp" {
        return match config.rate_control {
            VideoRateControl::ConstantQuantizer(qp) => Some(qp.to_string()),
            VideoRateControl::CodecDefault | VideoRateControl::Lossless => {
                manifest.default_value.map(str::to_string)
            }
        };
    }
    config
        .settings
        .iter()
        .find(|setting| setting.name == manifest.name)
        .map(|setting| setting.value.as_cli_value())
        .or_else(|| manifest.default_value.map(str::to_string))
}

fn setting_value_matches_manifest(setting: &VideoEncoderSetting, manifest: SettingValue) -> bool {
    match (manifest, &setting.value) {
        (SettingValue::Boolean, VideoSettingValue::Boolean(_)) => true,
        (SettingValue::Choice(values), VideoSettingValue::Text(value)) => {
            values.contains(&value.as_str())
        }
        (SettingValue::IntegerRange { min, max }, VideoSettingValue::Integer(value)) => {
            (i64::from(min)..=i64::from(max)).contains(value)
        }
        (SettingValue::SignedIntegerRange { min, max }, VideoSettingValue::Integer(value)) => {
            (i64::from(min)..=i64::from(max)).contains(value)
        }
        _ => false,
    }
}

fn validate_codec_id(value: &str) -> Result<()> {
    if value.is_empty() {
        return Err(MediaError::Message("codec id cannot be empty".to_string()));
    }
    if !value
        .bytes()
        .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')
    {
        return Err(MediaError::Message(format!(
            "codec id '{value}' must contain only lowercase ASCII letters, digits, or '-'"
        )));
    }
    Ok(())
}

fn validate_setting_name(value: &str) -> Result<()> {
    if value.is_empty() {
        return Err(MediaError::Message(
            "setting name cannot be empty".to_string(),
        ));
    }
    if !value
        .bytes()
        .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')
    {
        return Err(MediaError::Message(format!(
            "setting name '{value}' must contain only lowercase ASCII letters, digits, or '-'"
        )));
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{PixelFormat, SettingManifest, SettingSpecForm, SettingSpecManifest, SettingValue};

    const GOP_FORMS: &[SettingSpecForm] = &[SettingSpecForm {
        syntax: "gop=<-1..65535>",
        summary: "set temporal intra period",
    }];
    const GOP_SPEC: SettingSpecManifest = SettingSpecManifest {
        forms: GOP_FORMS,
        examples: &[],
        notes: &[],
    };
    const GOP_SETTING: SettingManifest = SettingManifest {
        name: "gop",
        value: SettingValue::SignedIntegerRange {
            min: -1,
            max: 65535,
        },
        default_value: Some("-1"),
        spec: &GOP_SPEC,
        summary: "set temporal intra period",
    };
    const TEST_SETTINGS: &[SettingManifest] = &[GOP_SETTING];

    const TEST_CODEC: VideoEncoderManifest = VideoEncoderManifest::new(
        "test",
        "test-codec",
        "test codec",
        TEST_SETTINGS,
        test_accepts_format,
        test_supports_lossless_format,
        VideoEncoderManifestHooks {
            create_session: test_create_session,
            encode_source: test_encode_source,
        },
    );

    struct TestSession {
        config: VideoEncoderConfig,
    }

    impl VideoEncoderSession for TestSession {
        fn codec(&self) -> &CodecId {
            &self.config.codec
        }

        fn config(&self) -> &VideoEncoderConfig {
            &self.config
        }

        fn encode_frame(&mut self, _frame: Frame) -> Result<VideoEncodeOutput> {
            Ok(VideoEncodeOutput::default())
        }
    }

    fn test_accepts_format(format: PixelFormat) -> bool {
        format == PixelFormat::Yuv420p8
    }

    fn test_supports_lossless_format(format: PixelFormat) -> bool {
        test_accepts_format(format)
    }

    fn test_create_session(config: VideoEncoderConfig) -> Result<Box<dyn VideoEncoderSession>> {
        Ok(Box::new(TestSession { config }))
    }

    fn test_encode_source(
        _source: &mut dyn RawVideoFrameSource,
        _output: &mut dyn Write,
        _recon: Option<&mut dyn Write>,
        _request: VideoEncodeSourceRequest<'_>,
        _frame_metrics: Option<VideoEncodeFrameMetricsCallback<'_>>,
    ) -> Result<()> {
        Ok(())
    }

    #[test]
    fn codec_id_accepts_stable_lowercase_names() {
        assert_eq!(CodecId::new("av2").unwrap().as_str(), "av2");
        assert_eq!(CodecId::new("vvc-main10").unwrap().as_str(), "vvc-main10");
    }

    #[test]
    fn codec_id_rejects_names_that_do_not_round_trip_to_cli() {
        assert!(CodecId::new("").is_err());
        assert!(CodecId::new("AV2").is_err());
        assert!(CodecId::new("vvc/main10").is_err());
    }

    #[test]
    fn config_collects_rate_control_and_extension_settings_as_specs() {
        let info = FrameInfo::new(16, 16, PixelFormat::Yuv420p8).unwrap();
        let config = VideoEncoderConfig::new(CodecId::new("vvc").unwrap(), info)
            .with_rate_control(VideoRateControl::constant_quantizer(24).unwrap())
            .with_setting(VideoEncoderSetting::integer("gop", 30).unwrap())
            .with_setting(VideoEncoderSetting::text("fast-search", "moderate").unwrap());

        assert_eq!(
            config.setting_specs(),
            vec![
                "qp=24".to_string(),
                "gop=30".to_string(),
                "fast-search=moderate".to_string()
            ]
        );
    }

    #[test]
    fn lossless_rate_control_maps_to_a_normal_setting_spec() {
        let info = FrameInfo::new(16, 16, PixelFormat::Yuv420p8).unwrap();
        let config = VideoEncoderConfig::new(CodecId::new("av2").unwrap(), info)
            .with_rate_control(VideoRateControl::Lossless);

        assert_eq!(config.setting_specs(), vec!["lossless=true".to_string()]);
    }

    #[test]
    fn manifest_validates_codec_format_and_settings() {
        let info = FrameInfo::new(16, 16, PixelFormat::Yuv420p8).unwrap();
        let config = VideoEncoderConfig::new(CodecId::new("test").unwrap(), info)
            .with_setting(VideoEncoderSetting::integer("gop", -1).unwrap());

        TEST_CODEC
            .validate_config(&config)
            .expect("valid manifest config");
    }

    #[test]
    fn manifest_applies_cli_style_setting_specs_to_config() {
        let info = FrameInfo::new(16, 16, PixelFormat::Yuv420p8).unwrap();
        let config = VideoEncoderConfig::new(CodecId::new("test").unwrap(), info);
        let config = TEST_CODEC
            .apply_setting_specs(config, ["lossless", "gop=30"])
            .expect("settings should apply");

        assert!(matches!(config.rate_control, VideoRateControl::Lossless));
        assert_eq!(config.setting_specs(), vec!["lossless=true", "gop=30"]);
        assert_eq!(
            TEST_CODEC.effective_setting_specs(&config).unwrap(),
            vec!["lossless=true", "gop=30"]
        );
    }

    #[test]
    fn manifest_renders_effective_setting_defaults() {
        let info = FrameInfo::new(16, 16, PixelFormat::Yuv420p8).unwrap();
        let config = VideoEncoderConfig::new(CodecId::new("test").unwrap(), info);

        assert_eq!(
            TEST_CODEC.effective_setting_specs(&config).unwrap(),
            vec!["lossless=false", "gop=-1"]
        );
    }

    #[test]
    fn manifest_setting_specs_reject_duplicate_names() {
        let info = FrameInfo::new(16, 16, PixelFormat::Yuv420p8).unwrap();
        let config = VideoEncoderConfig::new(CodecId::new("test").unwrap(), info);

        assert!(matches!(
            TEST_CODEC
                .apply_setting_specs(config, ["gop=0", "gop=30"])
                .unwrap_err(),
            MediaError::DuplicateSetting { setting } if setting == "gop"
        ));
    }

    #[test]
    fn manifest_rejects_unknown_and_duplicate_settings() {
        let info = FrameInfo::new(16, 16, PixelFormat::Yuv420p8).unwrap();
        let unknown = VideoEncoderConfig::new(CodecId::new("test").unwrap(), info)
            .with_setting(VideoEncoderSetting::boolean("missing", true).unwrap());
        let duplicate = VideoEncoderConfig::new(CodecId::new("test").unwrap(), info)
            .with_setting(VideoEncoderSetting::integer("gop", -1).unwrap())
            .with_setting(VideoEncoderSetting::integer("gop", 0).unwrap());

        assert!(matches!(
            TEST_CODEC.validate_config(&unknown).unwrap_err(),
            MediaError::UnknownSetting { codec, setting }
                if codec == "test" && setting == "missing"
        ));
        assert!(matches!(
            TEST_CODEC.validate_config(&duplicate).unwrap_err(),
            MediaError::DuplicateSetting { setting } if setting == "gop"
        ));
    }

    #[test]
    fn manifest_rejects_invalid_setting_values_and_conflicts() {
        let info = FrameInfo::new(16, 16, PixelFormat::Yuv420p8).unwrap();
        let invalid_value = VideoEncoderConfig::new(CodecId::new("test").unwrap(), info)
            .with_setting(VideoEncoderSetting::integer("gop", -2).unwrap());
        let conflicting_qp = VideoEncoderConfig::new(CodecId::new("test").unwrap(), info)
            .with_rate_control(VideoRateControl::constant_quantizer(24).unwrap())
            .with_setting(VideoEncoderSetting::integer("qp", 19).unwrap());

        assert!(matches!(
            TEST_CODEC.validate_config(&invalid_value).unwrap_err(),
            MediaError::InvalidSettingValue {
                codec,
                setting,
                expected,
                actual,
            } if codec == "test"
                && setting == "gop"
                && expected == "-1..65535"
                && actual == "-2"
        ));
        assert!(matches!(
            TEST_CODEC.validate_config(&conflicting_qp).unwrap_err(),
            MediaError::ConflictingSettings { setting, conflict }
                if setting == "qp" && conflict == "VideoRateControl::ConstantQuantizer"
        ));
    }

    #[test]
    fn manifest_rejects_codec_and_format_mismatches_structurally() {
        let info = FrameInfo::new(16, 16, PixelFormat::Yuv420p8).unwrap();
        let wrong_codec = VideoEncoderConfig::new(CodecId::new("other").unwrap(), info);
        let wrong_format = VideoEncoderConfig::new(
            CodecId::new("test").unwrap(),
            FrameInfo::new(16, 16, PixelFormat::Rgb24).unwrap(),
        );

        assert!(matches!(
            TEST_CODEC.validate_config(&wrong_codec).unwrap_err(),
            MediaError::UnsupportedCodec { codec, .. } if codec == "other"
        ));
        assert!(matches!(
            TEST_CODEC.validate_config(&wrong_format).unwrap_err(),
            MediaError::UnsupportedPixelFormat { codec, format }
                if codec == "test" && format == "rgb24"
        ));
    }

    #[test]
    fn raw_video_read_source_reports_short_frames_structurally() {
        let mut source = RawVideoFrameReadSource::new(std::io::Cursor::new(vec![1, 2, 3]));
        let mut frame = [0u8; 4];
        let err = source.read_frame(&mut frame).unwrap_err();

        assert!(matches!(
            err,
            MediaError::ShortFrameRead {
                expected: 4,
                actual: 3,
            }
        ));
    }
}