oxideav-av1 0.1.21

Pure-Rust AV1 codec — orphan-rebuild scaffold pending clean-room re-implementation.
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
//! `oxideav-core` framework integration: codec registration plus the
//! [`oxideav_core::Decoder`] implementation that bridges the crate's
//! spec-faithful frame decoder
//! ([`crate::decoder::SpecDecodeSession`]) onto the packet-to-frame
//! trait surface.
//!
//! The wrapper does not re-implement any decode logic. Each [`Packet`]
//! payload is either
//!
//! * a complete IVF v0 buffer (`DKIF` magic — the elementary-stream
//!   wrapper this crate's [`crate::encoder::ivf`] reader / writer
//!   round-trips): every frame record's payload is fed to the session
//!   in file order, or
//! * one §7.5 temporal-unit body (the low-overhead OBU bytestream a
//!   container demuxer extracts — the Matroska "Block contains one
//!   Temporal Unit" / ISOBMFF sample framing): fed to the session
//!   verbatim.
//!
//! The [`crate::decoder::SpecDecodeSession`] holds the §7.20
//! reference-frame store, the cached sequence header, and the per-slot
//! CDF / motion-field / segment-id state ACROSS packets, so a GOP
//! split one-temporal-unit-per-packet decodes identically to the same
//! bytes in one buffer. Recovered [`SpecFrame`]s are queued, and
//! successive `receive_frame` calls drain that queue one [`VideoFrame`]
//! at a time — returning `Error::NeedMore` while empty and `Error::Eof`
//! once the stream has been flushed and the queue is exhausted.
//!
//! Registration claims the three container identifiers an AV1
//! elementary stream is carried under:
//!
//! * the ISOBMFF / MP4 sample-entry type `av01` (AV1 ISOBMFF Binding
//!   Specification §2.2, `class AV1SampleEntry extends
//!   VisualSampleEntry('av01')`),
//! * the IVF codec FourCC `AV01`,
//! * the Matroska / WebM Codec ID `V_AV1` (the `V_<NAME>` video Codec
//!   ID convention WebM documents for `V_VP8` / `V_VP9`).
//!
//! Because `CodecTag::fourcc` upper-cases alphabetic bytes, the ISOBMFF
//! `av01` and IVF `AV01` sample-entry / FourCC identifiers collapse to a
//! single [`CodecTag::Fourcc`] claim.
//!
//! The registered surface equals [`crate::decoder::decode_av1_spec`]'s:
//! the full conformance-validated decoder — KEY / INTER GOPs with the
//! cross-frame session state, `show_existing_frame`, segmentation,
//! quantizer matrices, compound / OBMC / warped motion, film grain,
//! superres, 8/10/12-bit output. Out-of-scope streams surface the same
//! diagnosable [`crate::Error`] the direct API returns.

use oxideav_core::{
    CodecCapabilities, CodecId, CodecInfo, CodecParameters, CodecRegistry, CodecTag, Decoder,
    Encoder, Error as CoreError, Frame as CoreFrame, Packet, PixelFormat, Result as CoreResult,
    RuntimeContext, TimeBase, VideoFrame, VideoPlane,
};

use crate::codec_config::Av1CodecConfig;
use crate::decoder::{SpecDecodeSession, SpecFrame};
use crate::encoder::{
    encode_key_frame_yuv_with_options, encode_still_yuv, quality_to_base_q_idx, ChromaFormat,
    StillOptions, StillSpeed, YuvFrame, DEFAULT_STILL_BASE_Q_IDX,
};
use oxideav_core::ExecutionContext;

/// Canonical codec id. `oxideav-meta::register_all` calls
/// `crate::__oxideav_entry`, which delegates to [`register`].
pub const CODEC_ID_STR: &str = "av1";

/// Register the AV1 codec into `reg`.
///
/// Installs the spec-driver decoder factory ([`make_decoder`]) and
/// claims the three container identifiers (ISOBMFF `av01` / IVF `AV01`
/// FourCC, Matroska `V_AV1`).
pub fn register_codecs(reg: &mut CodecRegistry) {
    let caps = CodecCapabilities::video("av1_sw")
        .with_decode()
        .with_encode();
    reg.register(
        CodecInfo::new(CodecId::new(CODEC_ID_STR))
            .capabilities(caps)
            .decoder(make_decoder)
            .encoder(make_encoder)
            .tags([CodecTag::fourcc(b"AV01"), CodecTag::matroska("V_AV1")]),
    );
}

/// Unified entry point invoked by the macro-generated wrapper and by
/// `oxideav-meta::register_all`.
pub fn register(ctx: &mut RuntimeContext) {
    register_codecs(&mut ctx.codecs);
}

/// Decoder factory — the [`CodecInfo::decoder`] callback.
///
/// The AV1 elementary-stream framing is self-describing (the sequence
/// header OBU normally arrives in-band), so a stream needs no setup
/// from [`CodecParameters`]. r460 — when `params.extradata` carries
/// the container's codec configuration it is honoured too: either an
/// `av1C` record ([`crate::codec_config::Av1CodecConfig`] — the AVIF /
/// HEIF `av01` item property or the ISOBMFF `av01` sample-entry box
/// payload, whose `configOBUs` tail may hold a Sequence Header OBU) or
/// a bare OBU sequence (a Sequence Header OBU, optionally preceded by
/// a temporal delimiter). Those OBUs are fed to the session before the
/// first packet, so an item / sample whose payload omits the sequence
/// header still decodes; a payload that repeats it (the av1-avif §2.1
/// "exactly one Sequence Header OBU" shape) simply re-caches it.
/// `params.codec_id` is threaded through so [`Decoder::codec_id`]
/// reports the resolved id.
///
/// ## Errors
///
/// Construction fails only when the extradata's configuration OBUs
/// are malformed (`Error::invalid`); an empty / unconfigured stream is
/// represented by an idle decoder that returns `NeedMore` until fed.
pub fn make_decoder(params: &CodecParameters) -> CoreResult<Box<dyn Decoder>> {
    let mut session = SpecDecodeSession::new();
    let config_obus = codec_config_obus(&params.extradata);
    if !config_obus.is_empty() {
        session
            .decode_temporal_unit(config_obus)
            .map_err(|e| CoreError::invalid(format!("oxideav-av1: extradata: {e}")))?;
    }
    Ok(Box::new(Av1Decoder {
        codec_id: params.codec_id.clone(),
        session,
        queue: std::collections::VecDeque::new(),
        eof: false,
    }))
}

/// The configuration OBUs an extradata blob carries: the `configOBUs`
/// tail of an `av1C` record, or the blob itself when it is a bare OBU
/// sequence starting with a Sequence Header / temporal delimiter OBU
/// (§5.3.1: forbidden bit clear, `obu_type` 1 or 2). Anything else
/// yields an empty slice (ignored).
fn codec_config_obus(extradata: &[u8]) -> &[u8] {
    if let Some(cfg) = crate::codec_config::Av1CodecConfig::parse(extradata) {
        let n = cfg.config_obus.len();
        return &extradata[extradata.len() - n..];
    }
    match extradata.first() {
        Some(&b) if b & 0x80 == 0 && matches!((b >> 3) & 0xF, 1 | 2) => extradata,
        _ => &[],
    }
}

/// Packet-to-frame wrapper driving [`SpecDecodeSession`].
struct Av1Decoder {
    codec_id: CodecId,
    /// The cross-packet §7.20 session-state stack.
    session: SpecDecodeSession,
    /// Frames recovered from already-decoded packets, awaiting drain by
    /// `receive_frame`. Held as `VideoFrame` in output order.
    queue: std::collections::VecDeque<VideoFrame>,
    eof: bool,
}

impl std::fmt::Debug for Av1Decoder {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Av1Decoder")
            .field("codec_id", &self.codec_id)
            .field("queued", &self.queue.len())
            .field("eof", &self.eof)
            .finish()
    }
}

/// The IVF file-header magic (`DKIF`) — distinguishes a whole-file IVF
/// packet from a raw temporal-unit packet.
const IVF_MAGIC: &[u8; 4] = b"DKIF";

impl Decoder for Av1Decoder {
    fn codec_id(&self) -> &CodecId {
        &self.codec_id
    }

    fn send_packet(&mut self, packet: &Packet) -> CoreResult<()> {
        let mut push = |frames: Vec<SpecFrame>| {
            for frame in frames {
                self.queue
                    .push_back(spec_frame_to_video_frame(frame, packet.pts));
            }
        };
        if packet.data.len() >= 4 && &packet.data[..4] == IVF_MAGIC {
            // Whole IVF v0 buffer: walk the frame records in file
            // order through the persistent session (identical to
            // `decode_av1_spec`, but the reference state carries into
            // subsequent packets).
            let reader = crate::encoder::ivf::IvfReader::new(&packet.data)
                .map_err(|e| CoreError::invalid(format!("oxideav-av1: {e:?}")))?;
            let records = reader
                .read_all()
                .map_err(|e| CoreError::invalid(format!("oxideav-av1: {e:?}")))?;
            for record in records {
                let frames = self
                    .session
                    .decode_temporal_unit(&record.payload)
                    .map_err(|e| CoreError::invalid(format!("oxideav-av1: {e}")))?;
                push(frames);
            }
        } else {
            // One §7.5 temporal-unit body per packet (the container
            // demuxer framing).
            let frames = self
                .session
                .decode_temporal_unit(&packet.data)
                .map_err(|e| CoreError::invalid(format!("oxideav-av1: {e}")))?;
            push(frames);
        }
        Ok(())
    }

    fn receive_frame(&mut self) -> CoreResult<CoreFrame> {
        match self.queue.pop_front() {
            Some(vf) => Ok(CoreFrame::Video(vf)),
            None => {
                if self.eof {
                    Err(CoreError::Eof)
                } else {
                    Err(CoreError::NeedMore)
                }
            }
        }
    }

    fn flush(&mut self) -> CoreResult<()> {
        self.eof = true;
        Ok(())
    }

    fn reset(&mut self) -> CoreResult<()> {
        // A seek discontinuity: drop undrained frames and the §7.20
        // reference store (the landing point must be a KEY frame,
        // which rebuilds every slot); keep the cached sequence header
        // (containers need not repeat it mid-stream).
        self.queue.clear();
        self.session.reset_references();
        self.eof = false;
        Ok(())
    }

    fn set_execution_context(&mut self, ctx: &ExecutionContext) {
        // r475 — the worker budget: a multi-tile intra frame walks its
        // tiles `threads`-wide and the post-filters run by row band,
        // byte-identical to the serial decode for any budget.
        self.session.set_threads(ctx.threads.max(1));
    }
}

/// Convert a decoded [`SpecFrame`] into an `oxideav-core`
/// [`VideoFrame`].
///
/// Planes are emitted in the decoder's plane-major order (luma, then
/// chroma when present). `SpecFrame::planes` already holds tight
/// row-major bytes — one byte per sample at 8-bit, packed little-endian
/// `u16` at 10/12-bit — so each plane moves verbatim with its byte
/// stride (`width` samples × 1 or 2 bytes).
fn spec_frame_to_video_frame(frame: SpecFrame, pts: Option<i64>) -> VideoFrame {
    let bytes_per_sample: usize = if frame.bit_depth > 8 { 2 } else { 1 };
    // r475 — the plane bytes MOVE into the framework frame (the
    // pre-r475 clone was a second copy of every output plane).
    let planes = frame
        .planes
        .into_iter()
        .zip(frame.plane_dims.iter())
        .map(|(data, &(w, _h))| VideoPlane {
            stride: (w as usize) * bytes_per_sample,
            data,
        })
        .collect();
    VideoFrame { pts, planes }
}

// ───────────────────────── Encoder ─────────────────────────

/// The `CodecOptions` schema of the framework encoder (r460) — the
/// string-bag twin of [`StillOptions`].
///
/// | key              | kind                              | default                      |
/// |------------------|-----------------------------------|------------------------------|
/// | `still`          | `true` / `false`                  | `false`                      |
/// | `q`              | `base_q_idx` 0..=255 (0 lossless) | `DEFAULT_STILL_BASE_Q_IDX`   |
/// | `quality`        | 0..=100 (100 lossless); overrides `q` | —                        |
/// | `lossless`       | `true` forces `base_q_idx = 0`    | `false`                      |
/// | `speed`          | `fast` / `balanced` / `thorough`  | `fast` (r464 — the measured production point) |
/// | `tile_cols_log2` | §5.9.15 `TileColsLog2`            | `0`                          |
/// | `tile_rows_log2` | §5.9.15 `TileRowsLog2`            | `0`                          |
/// | `full_range`     | `true` / `false` (§5.5.2 `color_range`) | from the pixel format (`YuvJ*` full) |
/// | `color_primaries` / `transfer_characteristics` / `matrix_coefficients` | H.273 code points (§5.5.2 colour description; all three or none) | unspecified |
/// | `threads`        | tile-search threads (`auto` = the [`ExecutionContext`] budget); > 1 derives an automatic tile layout unless `tile_*_log2` are given | `auto` (r464; serial until the caller grants a budget through `set_execution_context`) |
///
/// `still = true` codes every frame as an independent still picture
/// (`still_picture = 1` + `reduced_still_picture_header = 1`, one
/// temporal unit per packet — the AVIF / HEIF `av01` item payload);
/// `still = false` codes every frame as a KEY frame under a full
/// sequence header repeated per temporal unit (an all-intra AV1
/// video every packet of which is a sync sample).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Av1EncoderOptions {
    /// See the schema table.
    pub still: bool,
    /// The resolved `base_q_idx`.
    pub base_q_idx: u8,
    /// Search effort.
    pub speed: StillSpeed,
    /// §5.9.15 `TileColsLog2`.
    pub tile_cols_log2: u32,
    /// §5.9.15 `TileRowsLog2`.
    pub tile_rows_log2: u32,
    /// §5.5.2 `color_range`.
    pub full_range: bool,
    /// §5.5.2 colour description `(cp, tc, mc)` when all three keys
    /// are given.
    pub color_description: Option<(u8, u8, u8)>,
    /// Tile-search threads. `None` = `auto`: the
    /// [`ExecutionContext`] budget the caller grants (serial until
    /// then).
    pub threads: Option<usize>,
    /// Derive the tile layout from the thread count (set when no
    /// explicit `tile_*_log2` was given; only matters when more than
    /// one thread runs).
    pub auto_tiles: bool,
}

impl Av1EncoderOptions {
    /// Parse the option bag (see the schema table). `full_range`
    /// defaults from `pixel_format` (`YuvJ*` = full range).
    ///
    /// ## Errors
    ///
    /// `Error::invalid` on an unparsable value or unknown key.
    pub fn from_params(params: &CodecParameters) -> CoreResult<Self> {
        let mut o = Self {
            still: false,
            base_q_idx: DEFAULT_STILL_BASE_Q_IDX,
            speed: StillSpeed::Fast,
            tile_cols_log2: 0,
            tile_rows_log2: 0,
            full_range: matches!(
                params.pixel_format,
                Some(PixelFormat::YuvJ420P | PixelFormat::YuvJ422P | PixelFormat::YuvJ444P)
            ),
            color_description: None,
            threads: None,
            auto_tiles: true,
        };
        let mut cicp: [Option<u8>; 3] = [None; 3];
        let mut explicit_tiles = false;
        let bad = |k: &str, v: &str| CoreError::invalid(format!("oxideav-av1: option {k}={v:?}"));
        let parse_bool = |k: &str, v: &str| -> CoreResult<bool> {
            match v {
                "true" | "1" | "yes" => Ok(true),
                "false" | "0" | "no" => Ok(false),
                _ => Err(bad(k, v)),
            }
        };
        let mut quality: Option<u8> = None;
        let mut lossless = false;
        for (k, v) in params.options.iter() {
            match k {
                "still" => o.still = parse_bool(k, v)?,
                "q" | "base_q_idx" => o.base_q_idx = v.parse().map_err(|_| bad(k, v))?,
                "quality" => {
                    let q: u8 = v.parse().map_err(|_| bad(k, v))?;
                    if q > 100 {
                        return Err(bad(k, v));
                    }
                    quality = Some(q);
                }
                "lossless" => lossless = parse_bool(k, v)?,
                "speed" => {
                    o.speed = match v {
                        "fast" => StillSpeed::Fast,
                        "balanced" => StillSpeed::Balanced,
                        "thorough" => StillSpeed::Thorough,
                        _ => return Err(bad(k, v)),
                    }
                }
                "tile_cols_log2" => {
                    o.tile_cols_log2 = v.parse().map_err(|_| bad(k, v))?;
                    explicit_tiles = true;
                }
                "tile_rows_log2" => {
                    o.tile_rows_log2 = v.parse().map_err(|_| bad(k, v))?;
                    explicit_tiles = true;
                }
                "threads" => {
                    o.threads = if v == "auto" {
                        None
                    } else {
                        Some(v.parse::<usize>().map_err(|_| bad(k, v))?.max(1))
                    }
                }
                "full_range" => o.full_range = parse_bool(k, v)?,
                "color_primaries" => cicp[0] = Some(v.parse().map_err(|_| bad(k, v))?),
                "transfer_characteristics" => cicp[1] = Some(v.parse().map_err(|_| bad(k, v))?),
                "matrix_coefficients" => cicp[2] = Some(v.parse().map_err(|_| bad(k, v))?),
                _ => {
                    return Err(CoreError::invalid(format!(
                        "oxideav-av1: unknown option {k:?}"
                    )))
                }
            }
        }
        match cicp {
            [None, None, None] => {}
            [Some(cp), Some(tc), Some(mc)] => o.color_description = Some((cp, tc, mc)),
            _ => {
                return Err(CoreError::invalid(
                    "oxideav-av1: color_primaries / transfer_characteristics / \
                     matrix_coefficients must be given together",
                ))
            }
        }
        if let Some(q) = quality {
            o.base_q_idx = quality_to_base_q_idx(q);
        }
        if lossless {
            o.base_q_idx = 0;
        }
        o.auto_tiles = !explicit_tiles;
        Ok(o)
    }

    /// The encoder options at a resolved thread count (`budget` = the
    /// [`ExecutionContext`] budget, used when `threads` is `auto`).
    /// The automatic tile layout only engages above one thread, so a
    /// serial encode keeps the spec-minimum layout.
    fn still_options(&self, budget: usize) -> StillOptions {
        let threads = self.threads.unwrap_or(budget).max(1);
        StillOptions {
            base_q_idx: self.base_q_idx,
            tile_cols_log2: self.tile_cols_log2,
            tile_rows_log2: self.tile_rows_log2,
            speed: self.speed,
            full_range: self.full_range,
            reduced_header: true,
            color_description: self.color_description,
            threads,
            auto_tiles: self.auto_tiles && threads > 1,
        }
    }
}

/// Map a framework pixel format onto the encoder's `(bit depth,
/// chroma format)` pairing.
fn pixel_format_layout(pf: PixelFormat) -> Option<(u8, ChromaFormat)> {
    Some(match pf {
        PixelFormat::Yuv420P | PixelFormat::YuvJ420P => (8, ChromaFormat::Yuv420),
        PixelFormat::Yuv422P | PixelFormat::YuvJ422P => (8, ChromaFormat::Yuv422),
        PixelFormat::Yuv444P | PixelFormat::YuvJ444P => (8, ChromaFormat::Yuv444),
        PixelFormat::Gray8 => (8, ChromaFormat::Monochrome),
        PixelFormat::Yuv420P10Le => (10, ChromaFormat::Yuv420),
        PixelFormat::Yuv422P10Le => (10, ChromaFormat::Yuv422),
        PixelFormat::Yuv444P10Le => (10, ChromaFormat::Yuv444),
        PixelFormat::Gray10Le => (10, ChromaFormat::Monochrome),
        PixelFormat::Yuv420P12Le => (12, ChromaFormat::Yuv420),
        PixelFormat::Yuv422P12Le => (12, ChromaFormat::Yuv422),
        PixelFormat::Yuv444P12Le => (12, ChromaFormat::Yuv444),
        PixelFormat::Gray12Le => (12, ChromaFormat::Monochrome),
        _ => return None,
    })
}

/// Encoder factory — the [`CodecInfo::encoder`] callback (r460).
///
/// Needs `width`, `height` and a planar YUV / gray `pixel_format`
/// (8-bit 4:2:0 / 4:2:2 / 4:4:4 / gray, the `YuvJ*` full-range
/// variants, and the 10 / 12-bit little-endian siblings incl.
/// `Gray10Le` / `Gray12Le`). Options per [`Av1EncoderOptions`].
/// [`Encoder::output_params`] carries the `av1C` record bytes in
/// `extradata` (no `configOBUs` — av1-avif §2.2.1), so a container
/// writer fills its codec-configuration property directly.
///
/// ## Errors
///
/// `Error::invalid` on missing / unsupported geometry or format and on
/// bad options.
pub fn make_encoder(params: &CodecParameters) -> CoreResult<Box<dyn Encoder>> {
    let width = params
        .width
        .ok_or_else(|| CoreError::invalid("oxideav-av1: encoder needs width"))?;
    let height = params
        .height
        .ok_or_else(|| CoreError::invalid("oxideav-av1: encoder needs height"))?;
    // No declared layout: 8-bit 4:2:0, the Main profile's format and
    // the layout a pipeline converts to when the source has none.
    let pf = params.pixel_format.unwrap_or(PixelFormat::Yuv420P);
    let (bit_depth, format) = pixel_format_layout(pf).ok_or_else(|| {
        CoreError::invalid(format!("oxideav-av1: unsupported pixel format {pf:?}"))
    })?;
    let opts = Av1EncoderOptions::from_params(params)?;
    // Probe the geometry the same way the encoder will (the r410 shape
    // rules) so a bad size fails at construction, not at the first
    // frame.
    YuvFrame::filled(width, height, bit_depth, format, 0)
        .validate()
        .map_err(|e| CoreError::invalid(format!("oxideav-av1: unsupported geometry: {e}")))?;
    // The av1C fields follow from the pairing + size alone (the tool
    // gates the encoder opens do not appear in the record).
    let mut seq = crate::encoder::build_intra_only_seq_yuv(width, height, bit_depth, format)
        .map_err(|e| CoreError::invalid(format!("oxideav-av1: {e}")))?;
    if opts.still {
        crate::encoder::still::apply_still_picture_shape(&mut seq);
    }
    seq.color_config.color_range = opts.full_range;
    if let Some((cp, tc, mc)) = opts.color_description {
        seq.color_config.color_description_present_flag = true;
        seq.color_config.color_primaries = cp;
        seq.color_config.transfer_characteristics = tc;
        seq.color_config.matrix_coefficients = mc;
    }
    let mut out = params.clone();
    out.codec_id = CodecId::new(CODEC_ID_STR);
    out.pixel_format = Some(pf);
    out.extradata = Av1CodecConfig::from_sequence_header(&seq).to_bytes();
    let time_base = match params.frame_rate {
        Some(r) if r.num > 0 && r.den > 0 => TimeBase::new(r.den, r.num),
        _ => TimeBase::new(1, 25),
    };
    Ok(Box::new(Av1Encoder {
        codec_id: CodecId::new(CODEC_ID_STR),
        params: out,
        opts,
        width,
        height,
        bit_depth,
        format,
        time_base,
        next_pts: 0,
        queue: std::collections::VecDeque::new(),
        eof: false,
        thread_budget: 1,
    }))
}

/// Frame-to-packet wrapper around [`encode_still_yuv`] /
/// [`encode_key_frame_yuv_with_q`].
struct Av1Encoder {
    codec_id: CodecId,
    params: CodecParameters,
    opts: Av1EncoderOptions,
    width: u32,
    height: u32,
    bit_depth: u8,
    format: ChromaFormat,
    time_base: TimeBase,
    next_pts: i64,
    queue: std::collections::VecDeque<Packet>,
    eof: bool,
    /// r464 — the [`ExecutionContext`] thread budget (serial until
    /// the caller grants one).
    thread_budget: usize,
}

impl std::fmt::Debug for Av1Encoder {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Av1Encoder")
            .field("opts", &self.opts)
            .field("width", &self.width)
            .field("height", &self.height)
            .field("bit_depth", &self.bit_depth)
            .field("format", &self.format)
            .field("queued", &self.queue.len())
            .finish()
    }
}

impl Av1Encoder {
    /// Lift a framework frame's planes into the encoder's `u16`
    /// representation (little-endian pairs at 10 / 12 bit).
    fn to_yuv(&self, frame: &VideoFrame) -> CoreResult<YuvFrame> {
        let planes = frame.image_planes();
        let need = usize::from(self.format.num_planes());
        if planes.len() < need {
            return Err(CoreError::invalid(format!(
                "oxideav-av1: frame carries {} planes, format needs {need}",
                planes.len()
            )));
        }
        let bps: usize = if self.bit_depth > 8 { 2 } else { 1 };
        let lift = |p: &VideoPlane, w: usize, h: usize| -> CoreResult<Vec<u16>> {
            let row_bytes = w * bps;
            if p.stride < row_bytes || p.data.len() < p.stride * (h - 1) + row_bytes {
                return Err(CoreError::invalid(
                    "oxideav-av1: frame plane shorter than the declared geometry",
                ));
            }
            let mut out = Vec::with_capacity(w * h);
            for y in 0..h {
                let row = &p.data[y * p.stride..y * p.stride + row_bytes];
                if bps == 1 {
                    out.extend(row.iter().map(|&b| u16::from(b)));
                } else {
                    out.extend(
                        row.chunks_exact(2)
                            .map(|c| u16::from_le_bytes([c[0], c[1]])),
                    );
                }
            }
            Ok(out)
        };
        let (w, h) = (self.width as usize, self.height as usize);
        let probe = YuvFrame::filled(self.width, self.height, self.bit_depth, self.format, 0);
        let (cw, ch) = (
            probe.chroma_width() as usize,
            probe.chroma_height() as usize,
        );
        let y = lift(&planes[0], w, h)?;
        let (u, v) = if need > 1 {
            (lift(&planes[1], cw, ch)?, lift(&planes[2], cw, ch)?)
        } else {
            (Vec::new(), Vec::new())
        };
        Ok(YuvFrame {
            width: self.width,
            height: self.height,
            bit_depth: self.bit_depth,
            format: self.format,
            y,
            u,
            v,
        })
    }
}

impl Encoder for Av1Encoder {
    fn codec_id(&self) -> &CodecId {
        &self.codec_id
    }

    fn output_params(&self) -> &CodecParameters {
        &self.params
    }

    fn send_frame(&mut self, frame: &CoreFrame) -> CoreResult<()> {
        let CoreFrame::Video(vf) = frame else {
            return Err(CoreError::invalid(
                "oxideav-av1: encoder takes video frames",
            ));
        };
        let input = self.to_yuv(vf)?;
        let opts = self.opts.still_options(self.thread_budget);
        let tu = if self.opts.still {
            encode_still_yuv(&input, &opts)
                .map_err(|e| CoreError::invalid(format!("oxideav-av1: {e}")))?
                .temporal_unit_bytes
        } else {
            // r464 — the all-intra arm rides the same quality / speed /
            // tile / thread controls under a full, non-still sequence
            // header.
            encode_key_frame_yuv_with_options(&input, &opts)
                .map_err(|e| CoreError::invalid(format!("oxideav-av1: {e}")))?
                .temporal_unit_bytes
        };
        let pts = vf.pts.unwrap_or(self.next_pts);
        self.next_pts = pts + 1;
        self.queue.push_back(
            Packet::new(0, self.time_base, tu)
                .with_pts(pts)
                .with_dts(pts)
                .with_duration(1)
                .with_keyframe(true),
        );
        Ok(())
    }

    fn receive_packet(&mut self) -> CoreResult<Packet> {
        match self.queue.pop_front() {
            Some(p) => Ok(p),
            None if self.eof => Err(CoreError::Eof),
            None => Err(CoreError::NeedMore),
        }
    }

    fn flush(&mut self) -> CoreResult<()> {
        self.eof = true;
        Ok(())
    }

    fn set_execution_context(&mut self, ctx: &ExecutionContext) {
        self.thread_budget = ctx.threads.max(1);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use oxideav_core::ProbeContext;

    fn textured_frame(width: u32, height: u32, pf: PixelFormat) -> (VideoFrame, YuvFrame) {
        let (bd, fmt) = pixel_format_layout(pf).expect("supported");
        let mut yuv = YuvFrame::filled(width, height, bd, fmt, 0);
        let max = (1u32 << bd) - 1;
        for (i, s) in yuv.y.iter_mut().enumerate() {
            *s = ((i as u32 * 37 + (i as u32 / width) * 91) % max) as u16;
        }
        for (i, s) in yuv.u.iter_mut().enumerate() {
            *s = ((i as u32 * 13) % max) as u16;
        }
        for (i, s) in yuv.v.iter_mut().enumerate() {
            *s = ((i as u32 * 29 + 5) % max) as u16;
        }
        let pack = |p: &[u16], w: usize| -> VideoPlane {
            let mut data = Vec::new();
            for &s in p {
                if bd > 8 {
                    data.extend_from_slice(&s.to_le_bytes());
                } else {
                    data.push(s as u8);
                }
            }
            VideoPlane {
                stride: w * if bd > 8 { 2 } else { 1 },
                data,
            }
        };
        let mut planes = vec![pack(&yuv.y, width as usize)];
        if fmt != ChromaFormat::Monochrome {
            planes.push(pack(&yuv.u, yuv.chroma_width() as usize));
            planes.push(pack(&yuv.v, yuv.chroma_width() as usize));
        }
        (
            VideoFrame {
                pts: Some(7),
                planes,
            },
            yuv,
        )
    }

    fn video_params(width: u32, height: u32, pf: PixelFormat) -> CodecParameters {
        let mut p = CodecParameters::video(CodecId::new(CODEC_ID_STR));
        p.width = Some(width);
        p.height = Some(height);
        p.pixel_format = Some(pf);
        p
    }

    /// r460 — the framework encoder's still arm produces a
    /// reduced-header still per frame whose `av1C` extradata matches
    /// the in-band sequence header, and the framework decoder (fed
    /// that extradata + the packet) reproduces the direct-API
    /// reconstruction.
    #[test]
    fn framework_still_encode_round_trips_through_the_framework_decoder() {
        for (pf, opts) in [
            (PixelFormat::Yuv420P, [("still", "true"), ("quality", "60")]),
            (PixelFormat::Gray10Le, [("still", "true"), ("q", "80")]),
            (
                PixelFormat::YuvJ444P,
                [("still", "true"), ("lossless", "true")],
            ),
        ] {
            let mut params = video_params(32, 24, pf);
            for (k, v) in opts {
                params.options.insert(k, v);
            }
            let mut enc = make_encoder(&params).expect("encoder constructs");
            let (frame, yuv) = textured_frame(32, 24, pf);
            enc.send_frame(&CoreFrame::Video(frame))
                .expect("frame accepted");
            let pkt = enc.receive_packet().expect("one packet");
            assert!(pkt.flags.keyframe && pkt.pts == Some(7));
            assert!(matches!(enc.receive_packet(), Err(CoreError::NeedMore)));
            enc.flush().unwrap();
            assert!(matches!(enc.receive_packet(), Err(CoreError::Eof)));

            let extradata = enc.output_params().extradata.clone();
            let cfg = Av1CodecConfig::parse(&extradata).expect("av1C extradata");
            let seq = crate::sequence_header::parse_sequence_header(
                crate::obu::ObuIter::new(&pkt.data)
                    .filter_map(Result::ok)
                    .find(|d| d.obu_type == crate::obu::ObuType::SequenceHeader)
                    .expect("in-band sequence header")
                    .payload,
            )
            .expect("parses");
            assert!(seq.still_picture && seq.reduced_still_picture_header);
            assert!(cfg.matches_sequence_header(&seq), "{pf:?}: av1C mismatch");
            assert_eq!(seq.color_config.color_range, pf == PixelFormat::YuvJ444P);

            let opts = Av1EncoderOptions::from_params(&params).unwrap();
            let direct = encode_still_yuv(&yuv, &opts.still_options(1)).expect("direct still");
            assert_eq!(
                direct.temporal_unit_bytes, pkt.data,
                "{pf:?}: framework != direct"
            );

            let mut dparams = CodecParameters::video(CodecId::new(CODEC_ID_STR));
            dparams.extradata = extradata;
            let mut dec = make_decoder(&dparams).expect("decoder");
            dec.send_packet(&pkt).expect("decodes");
            let CoreFrame::Video(out) = dec.receive_frame().expect("frame") else {
                panic!("video frame expected");
            };
            let widen = |p: &[u8]| -> Vec<u16> {
                if cfg.bit_depth() > 8 {
                    p.chunks(2)
                        .map(|c| u16::from_le_bytes([c[0], c[1]]))
                        .collect()
                } else {
                    p.iter().map(|&b| u16::from(b)).collect()
                }
            };
            assert_eq!(widen(&out.planes[0].data), direct.recon_y);
            if opts.base_q_idx == 0 {
                assert_eq!(direct.recon_y, yuv.y, "{pf:?}: lossless luma");
            }
        }
    }

    /// r460 — the all-intra (video) arm emits KEY frames under a full
    /// sequence header, one packet per frame with running timestamps.
    #[test]
    fn framework_all_intra_encode_emits_one_key_packet_per_frame() {
        let mut params = video_params(16, 16, PixelFormat::Yuv420P);
        params.options.insert("q", "200");
        params.options.insert("speed", "fast");
        let mut enc = make_encoder(&params).expect("encoder constructs");
        assert_eq!(enc.output_params().extradata, vec![0x81, 0x00, 0x0c, 0x00]);
        for i in 0..2 {
            let (mut frame, _) = textured_frame(16, 16, PixelFormat::Yuv420P);
            frame.pts = None;
            enc.send_frame(&CoreFrame::Video(frame)).expect("frame");
            let pkt = enc.receive_packet().expect("packet");
            assert_eq!(pkt.pts, Some(i));
            let frames = crate::decoder::decode_av1_spec(&{
                let mut buf = Vec::new();
                let cur = std::io::Cursor::new(&mut buf);
                let mut w = crate::encoder::IvfWriter::new(
                    cur,
                    crate::encoder::ivf::FOURCC_AV01,
                    16,
                    16,
                    25,
                    1,
                )
                .unwrap();
                w.write_frame(&pkt.data, 0).unwrap();
                w.patch_frame_count().unwrap();
                buf
            })
            .expect("decodes");
            assert_eq!(frames.len(), 1);
        }
    }

    #[test]
    fn encoder_options_and_geometry_are_validated() {
        let mut params = video_params(16, 16, PixelFormat::Yuv420P);
        params.options.insert("speed", "warp");
        assert!(make_encoder(&params).is_err());
        let mut params = video_params(16, 16, PixelFormat::Yuv420P);
        params.options.insert("bogus", "1");
        assert!(make_encoder(&params).is_err());
        let params = video_params(16, 16, PixelFormat::Rgb24);
        assert!(make_encoder(&params).is_err());
        let mut params = video_params(16, 16, PixelFormat::Yuv420P);
        params.options.insert("quality", "100");
        let o = Av1EncoderOptions::from_params(&params).unwrap();
        assert_eq!(o.base_q_idx, 0);
        params.options.insert("full_range", "true");
        params.options.insert("tile_cols_log2", "1");
        let o = Av1EncoderOptions::from_params(&params).unwrap();
        assert!(o.full_range && o.tile_cols_log2 == 1);
        params.options.insert("color_primaries", "1");
        assert!(Av1EncoderOptions::from_params(&params).is_err());
        params.options.insert("transfer_characteristics", "13");
        params.options.insert("matrix_coefficients", "6");
        let o = Av1EncoderOptions::from_params(&params).unwrap();
        assert_eq!(o.color_description, Some((1, 13, 6)));
    }

    /// r464 — the production defaults: `speed = fast`, `threads =
    /// auto` (the execution-context budget; serial until granted, the
    /// automatic tile layout engaging above one thread), the all-intra
    /// arm riding the same options. A budgeted 4-thread encode of a
    /// multi-tile still equals the direct 4-thread encode byte for
    /// byte, and the serial encode is the single-tile one.
    #[test]
    fn defaults_are_fast_and_auto_threaded_under_the_execution_budget() {
        let params = video_params(512, 256, PixelFormat::Yuv420P);
        let o = Av1EncoderOptions::from_params(&params).unwrap();
        assert_eq!(o.speed, StillSpeed::Fast);
        assert_eq!(o.threads, None);
        assert!(o.auto_tiles);
        assert_eq!(o.still_options(1).threads, 1);
        assert!(!o.still_options(1).auto_tiles);
        let four = o.still_options(4);
        assert_eq!(four.threads, 4);
        assert!(four.auto_tiles);
        let mut explicit = params.clone();
        explicit.options.insert("threads", "2");
        explicit.options.insert("tile_rows_log2", "1");
        let e = Av1EncoderOptions::from_params(&explicit).unwrap();
        assert_eq!(e.still_options(8).threads, 2);
        assert!(!e.still_options(8).auto_tiles);
        let mut auto = params.clone();
        auto.options.insert("threads", "auto");
        assert_eq!(Av1EncoderOptions::from_params(&auto).unwrap().threads, None);

        let (frame, yuv) = textured_frame(512, 256, PixelFormat::Yuv420P);
        for still in [true, false] {
            let mut p = params.clone();
            p.options
                .insert("still", if still { "true" } else { "false" });
            let mut enc = make_encoder(&p).expect("encoder");
            enc.set_execution_context(&ExecutionContext::with_threads(4));
            enc.send_frame(&CoreFrame::Video(frame.clone()))
                .expect("frame");
            enc.flush().expect("flush");
            let pkt = enc.receive_packet().expect("packet");
            let direct = if still {
                encode_still_yuv(&yuv, &o.still_options(4)).expect("direct")
            } else {
                encode_key_frame_yuv_with_options(&yuv, &o.still_options(4)).expect("direct")
            };
            assert_eq!(pkt.data, direct.temporal_unit_bytes, "still={still}");
            let ti = direct.fh.tile_info.as_ref().expect("tile info");
            assert!(
                ti.tile_cols_log2 + ti.tile_rows_log2 > 0,
                "auto tiles engaged"
            );
            let seq = crate::sequence_header::parse_sequence_header(
                crate::obu::ObuIter::new(&pkt.data)
                    .filter_map(Result::ok)
                    .find(|d| d.obu_type == crate::obu::ObuType::SequenceHeader)
                    .expect("in-band sequence header")
                    .payload,
            )
            .expect("parses");
            assert_eq!(seq.still_picture, still);
            assert_eq!(seq.reduced_still_picture_header, still);
            let frames = crate::decoder::decode_av1_spec(&direct.ivf_bytes).expect("decodes");
            assert_eq!(frames.len(), 1);
            assert_eq!(
                frames[0].planes[0]
                    .iter()
                    .map(|&b| u16::from(b))
                    .collect::<Vec<_>>(),
                direct.recon_y
            );
        }
    }

    #[test]
    fn register_via_runtime_context_installs_decoder() {
        let mut ctx = RuntimeContext::new();
        register(&mut ctx);
        let codec_id = CodecId::new(CODEC_ID_STR);
        assert!(
            ctx.codecs.has_decoder(&codec_id),
            "codec registration should install a decoder factory"
        );
    }

    /// r460 — an `av1C` extradata whose `configOBUs` carry the
    /// sequence header lets an item payload that omits it decode; the
    /// same payload without the extradata is refused (no sequence
    /// header), and a payload that repeats the header decodes to the
    /// same pixels.
    #[test]
    fn av1c_extradata_config_obus_seed_the_sequence_header() {
        use crate::encoder::{encode_still_yuv420, StillOptions, Yuv420Frame};
        use crate::obu::{ObuIter, ObuType};
        let mut frame = Yuv420Frame::filled(32, 16, 60);
        for (i, s) in frame.y.iter_mut().enumerate() {
            *s = (i * 7 % 200) as u8 + 20;
        }
        let still = encode_still_yuv420(&frame, &StillOptions::new(90)).expect("encodes");
        // Split the temporal unit into its sequence header OBU and a
        // header-less payload (temporal delimiter + frame OBU).
        let mut seq_obu = Vec::new();
        let mut frame_obus = Vec::new();
        for desc in ObuIter::new(&still.temporal_unit_bytes) {
            let desc = desc.expect("well-formed OBU");
            let obu = crate::encoder::obu::ObuFrame::new(desc.obu_type, desc.payload.to_vec());
            if desc.obu_type == ObuType::SequenceHeader {
                seq_obu.push(obu);
            } else {
                frame_obus.push(obu);
            }
        }
        let config_obus = crate::encoder::obu::write_temporal_unit(&seq_obu);
        let payload = crate::encoder::obu::write_temporal_unit(&frame_obus);
        let mut av1c = still.codec_config.clone();
        av1c.config_obus = config_obus.clone();

        let decode_with = |extradata: Vec<u8>, packet: &[u8]| -> CoreResult<Vec<Vec<u8>>> {
            let mut params = CodecParameters::video(CodecId::new(CODEC_ID_STR));
            params.extradata = extradata;
            let mut dec = make_decoder(&params)?;
            dec.send_packet(&Packet::new(
                0,
                oxideav_core::TimeBase::new(1, 1),
                packet.to_vec(),
            ))?;
            match dec.receive_frame()? {
                CoreFrame::Video(v) => Ok(v.planes.into_iter().map(|p| p.data).collect()),
                other => panic!("expected a video frame, got {other:?}"),
            }
        };
        let expected = decode_with(Vec::new(), &still.temporal_unit_bytes).expect("in-band");
        assert!(
            decode_with(Vec::new(), &payload).is_err(),
            "a header-less payload must be refused without extradata"
        );
        let via_av1c = decode_with(av1c.to_bytes(), &payload).expect("av1C configOBUs");
        assert_eq!(via_av1c, expected);
        let via_raw = decode_with(config_obus, &payload).expect("bare OBU extradata");
        assert_eq!(via_raw, expected);
        let repeated = decode_with(av1c.to_bytes(), &still.temporal_unit_bytes)
            .expect("repeated sequence header");
        assert_eq!(repeated, expected);
        // A record without configOBUs is accepted and ignored.
        let bare = decode_with(still.codec_config.to_bytes(), &still.temporal_unit_bytes)
            .expect("bare av1C");
        assert_eq!(bare, expected);
    }

    #[test]
    fn register_claims_container_tags() {
        let mut reg = CodecRegistry::new();
        register_codecs(&mut reg);

        // ISOBMFF sample-entry `av01` / IVF FourCC `AV01` collapse to a
        // single upper-cased Fourcc tag.
        let fourcc = CodecTag::fourcc(b"AV01");
        assert_eq!(
            reg.resolve_tag_ref(&ProbeContext::new(&fourcc))
                .map(oxideav_core::CodecId::as_str),
            Some(CODEC_ID_STR),
            "FourCC AV01 / sample-entry av01 must resolve to av1"
        );

        // Matroska / WebM Codec ID.
        let mkv = CodecTag::matroska("V_AV1");
        assert_eq!(
            reg.resolve_tag_ref(&ProbeContext::new(&mkv))
                .map(oxideav_core::CodecId::as_str),
            Some(CODEC_ID_STR),
            "Matroska V_AV1 must resolve to av1"
        );
    }
}