forge
Explore
Log in

Don't you dare go Hollow

ec-av1: StreamDecoder, a persistent decoder fed one temporal unit at a time (decode / decode_temporal_unit), so inter frames decode across calls; decode_stream_with_threads is a wrapper over it; lanes: hwvideo charter (Vulkan Video first, VA frozen)

Browse files at this commit

b63bf80b30de2314eadb4ffd66d23402184a55b1Ahmet Kaan GümüşParent: 19320a9
crates/ec-av1/src/stream/mod.rsmodified+777 -680
@@ -856,43 +856,13 @@ fn collect_one(
856856 reorder.drain(sink)
857857 }
858858
859-/// [`decode_stream_with`] with an explicit worker count (lane-thread2).
860-///
861-/// `threads == 1` is the serial decoder. Above that, frames that no later
862-/// frame can reference -- a shown, non-key frame whose `refresh_frame_flags`
863-/// is 0, i.e. a leaf of the reference graph -- are decoded on worker threads
864-/// while the main thread keeps parsing headers and decoding the frames that
865-/// DO feed the reference banks; `sink` still sees every picture in coded
866-/// order. Each worker owns a fresh [`crate::decode::FrameCtx`] and a snapshot
867-/// of the banks taken before dispatch, so no decode state is shared.
868-///
869-/// The per-decode counters this crate's gates read are thread-local, so at
870-/// `threads > 1` a leaf frame's counts land on the worker and are invisible
871-/// to the caller; that is why the default is 1.
872-///
873-/// # Errors
874-/// As [`decode_stream_with`]; a worker's error aborts the stream.
875-pub fn decode_stream_with_threads(
876- data: &[u8],
859+/// A persistent AV1 stream decoder: feed it temporal units in decode order.
860+pub struct StreamDecoder {
877861 threads: usize,
878- mut sink: impl FnMut(&Picture, usize, bool) -> Result<()>,
879-) -> Result<()> {
880- // lane-pool1: this replaced a `std::thread::scope` -- frame workers now
881- // come from a persistent pool (one per submitting thread, workers reused
882- // across frames, so their `thread_local!` decode scratch survives the
883- // frame). `jobs` is declared here and dropped at the end of the function,
884- // including on `?`, so no job outlives the data it borrows.
885- let jobs = crate::par::Batch::new("ec-av1-frame");
886- // lane-av1recon: at more than one decode thread the recon wavefront and
887- // the filter bands default on (an explicit env value still wins).
888- let _split = crate::par::DecodeSplit::install(threads);
889- // lane-thread1: this stream's per-frame decode state (was 38 thread_local
890- // statics in decode.rs) -- one object, threaded down the decode call graph.
891- let fctx = &crate::decode::FrameCtx::new();
892- let final_dump = final_dump_prefix();
893- let mut parser = Av1Parser::new();
894- let mut pictures_shown: usize = 0;
895- let mut pictures_decoded: usize = 0;
862+ final_dump: Option<String>,
863+ parser: Av1Parser,
864+ pictures_shown: usize,
865+ pictures_decoded: usize,
896866 // Spec 7.20/7.4: each of the 8 reference slots remembers the picture a
897867 // previous frame's `refresh_frame_flags` stored into it, exactly like the
898868 // CDF slots below -- `LAST_FRAME` names a slot via `ref_frame_idx[0]`,
@@ -907,55 +877,49 @@ pub fn decode_stream_with_threads(
907877 // what made it look like a rounding bug rather than a wrong reference.
908878 // lane-pool1: shared, not owned -- a frame refreshing k slots used to copy
909879 // its whole picture k times, and its output a (k+1)-th time.
910- let mut ref_slots: [Option<std::sync::Arc<Picture>>; NUM_REF_FRAMES] =
911- std::array::from_fn(|_| None);
880+ ref_slots: [Option<std::sync::Arc<Picture>>; NUM_REF_FRAMES],
912881 // lane-av1tmvp: each of the 8 reference slots' own saved temporal motion
913882 // field (spec 7.9's per-frame `MotionFieldMvs` storage, libaom
914883 // `cur_frame->mvs`) plus the `OrderHint` the picture in that slot was
915884 // decoded with -- `Picture` itself carries neither, so both ride
916885 // alongside `ref_slots` on the exact same `refresh_frame_flags` update.
917- let mut motion_field_slots: [Option<crate::motion_field::MotionField>; NUM_REF_FRAMES] =
918- std::array::from_fn(|_| None);
919- let mut order_hint_slots: [u32; NUM_REF_FRAMES] = [0; NUM_REF_FRAMES];
886+ motion_field_slots: [Option<crate::motion_field::MotionField>; NUM_REF_FRAMES],
887+ order_hint_slots: [u32; NUM_REF_FRAMES],
920888 // Spec 7.20/7.4: each of the 8 reference slots remembers the CDF state a
921889 // previous frame's `refresh_frame_flags` stored into it -- the frame's
922890 // own end-of-tile adapted table, or (when the frame set
923891 // `disable_frame_end_update_cdf`) the table it started from, unchanged.
924- let mut cdf_slots: [Option<Cdfs>; NUM_REF_FRAMES] = std::array::from_fn(|_| None);
892+ cdf_slots: [Option<Cdfs>; NUM_REF_FRAMES],
925893 // lane-seg, spec 7.20's `SavedSegmentIds`: each reference slot also
926894 // remembers the segment map the frame stored there decoded, which is what
927895 // a later frame's `primary_ref_frame` reads back as `PrevSegmentIds`
928896 // (spec `load_previous_segment_ids`) for temporal segment-id prediction
929897 // and for a `segmentation_update_map == 0` frame's inherited map.
930- let mut seg_map_slots: [Option<Vec<u8>>; NUM_REF_FRAMES] = std::array::from_fn(|_| None);
931-
898+ seg_map_slots: [Option<Vec<u8>>; NUM_REF_FRAMES],
932899 // lane-thread2: output plumbing (inert at `threads == 1`, where nothing
933900 // is ever dispatched and `reorder` emits each picture the moment it is
934901 // pushed).
935- let mut emit_seq = 0usize;
936- let mut reorder = Reorder::default();
902+ emit_seq: usize,
903+ reorder: Reorder,
937904 // lane-thread3: frame decodes and `show_existing_frame` outputs are
938905 // bounded separately -- an output job is a promise wait plus a memcpy, so
939906 // letting it eat a decode's budget just idles a core (measured: sharing
940907 // one bound cost 4K 18.7 s at 244% CPU against 17.7 s at 287%).
941- let mut in_flight_decodes = 0usize;
942- let mut in_flight_shows = 0usize;
943- let in_flight_cap = threads + 2;
944- let (tx, rx) = std::sync::mpsc::channel::<LeafResult>();
908+ in_flight_decodes: usize,
909+ in_flight_shows: usize,
910+ tx: std::sync::mpsc::Sender<LeafResult>,
911+ rx: std::sync::mpsc::Receiver<LeafResult>,
945912 // lane-thread3: at `threads > 1` THIS is the reference bank -- one
946913 // [`SlotPromise`] per DPB slot, ready for a slot the parsing thread filled
947914 // itself and pending for one an in-flight frame will fill. The owned
948915 // arrays above are then untouched (and the single-threaded path never
949916 // creates a promise: it stays exactly the decoder it was, which is what
950917 // keeps every counter-reading gate meaningful).
951- let mut slot_promises: [Option<std::sync::Arc<SlotPromise>>; NUM_REF_FRAMES] =
952- std::array::from_fn(|_| None);
918+ slot_promises: [Option<std::sync::Arc<SlotPromise>>; NUM_REF_FRAMES],
953919 // lane-timeline: which decoded frame installed each slot's promise, so
954920 // the timeline records a dependency EDGE (frame -> producing frame) and
955921 // not just a slot number. `usize::MAX` = nobody yet.
956- let mut slot_owner = [usize::MAX; NUM_REF_FRAMES];
957-
958- let mut pos = 0usize;
922+ slot_owner: [usize; NUM_REF_FRAMES],
959923 // A frame whose tiles are split across several `OBU_TILE_GROUP`s (spec
960924 // 5.11.1, aomenc's `--num-tile-groups`) sends a standalone
961925 // `OBU_FRAME_HEADER` first, with `show_existing_frame == false` and no
@@ -963,67 +927,371 @@ pub fn decode_stream_with_threads(
963927 // only ever folds ONE tile group into the header's own OBU. Stash the
964928 // header here and accumulate tiles from each `OBU_TILE_GROUP` that
965929 // follows until every tile of the frame has arrived.
966- let mut pending_header: Option<Box<FrameHeader>> = None;
967- let mut pending_tiles: Vec<Tile> = Vec::new();
968- while pos < data.len() {
969- let obu = parser.parse_obu(&data[pos..])?;
970- let obu_offset = pos;
971- pos += obu.total_size;
972-
973- if let ObuKind::FrameHeader(header) = &obu.kind {
974- if !header.show_existing_frame {
975- // Before this fix, this branch fired unconditionally for
976- // EVERY `FrameHeader` OBU (including this one), so a
977- // standalone header always fell into the `show_existing_frame`
978- // slot lookup below and misreported "a show_existing_frame
979- // header naming an empty reference slot" for a frame that was
980- // never a show_existing_frame header at all.
981- pending_header = Some(header.clone());
982- pending_tiles = Vec::new();
983- continue;
930+ pending_header: Option<Box<FrameHeader>>,
931+ pending_tiles: Vec<Tile>,
932+ // lane-thread1: this stream's per-frame decode state (was 38 thread_local
933+ // statics in decode.rs) -- one object, threaded down the decode call graph.
934+ fctx: crate::decode::FrameCtx,
935+}
936+impl StreamDecoder {
937+ /// A decoder with `threads` frame workers (see [`decode_stream_with_threads`]).
938+ pub fn new(threads: usize) -> Self {
939+ let (tx, rx) = std::sync::mpsc::channel::<LeafResult>();
940+ Self {
941+ threads,
942+ final_dump: final_dump_prefix(),
943+ parser: Av1Parser::new(),
944+ pictures_shown: 0,
945+ pictures_decoded: 0,
946+ ref_slots: std::array::from_fn(|_| None),
947+ motion_field_slots: std::array::from_fn(|_| None),
948+ order_hint_slots: [0; NUM_REF_FRAMES],
949+ cdf_slots: std::array::from_fn(|_| None),
950+ seg_map_slots: std::array::from_fn(|_| None),
951+ emit_seq: 0,
952+ reorder: Reorder::default(),
953+ in_flight_decodes: 0,
954+ in_flight_shows: 0,
955+ tx,
956+ rx,
957+ slot_promises: std::array::from_fn(|_| None),
958+ slot_owner: [usize::MAX; NUM_REF_FRAMES],
959+ pending_header: None,
960+ pending_tiles: Vec::new(),
961+ fctx: crate::decode::FrameCtx::new(),
962+ }
963+ }
964+
965+ /// Decode one temporal unit and return its shown pictures.
966+ ///
967+ /// # Errors
968+ /// As [`decode_stream`]. After an error, start a new decoder at a key frame.
969+ pub fn decode_temporal_unit(&mut self, data: &[u8]) -> Result<Vec<Picture>> {
970+ let mut pictures = Vec::new();
971+ self.decode(data, |picture, _decode_idx, shown| {
972+ if shown {
973+ pictures.push(picture.clone());
984974 }
985- // `show_existing_frame` (spec 7.21/5.9.2): no tile payload, this
986- // OBU only names a DPB slot to output again -- the coded-frame
987- // count and the shown-picture count are different things (a
988- // hidden altref's own `Frame` OBU below is never pushed to
989- // `pictures` on its own; it is only pushed here, later, when a
990- // `show_existing_frame` header names its slot). Before r15 this
991- // arm didn't exist at all: every `ObuKind::Frame` was pushed
992- // unconditionally regardless of `show_frame`, so a hidden altref
993- // was emitted (wrongly, in decode order) and its real
994- // `show_existing_frame` output was silently dropped.
995- let slot = header.frame_to_show_map_idx as usize;
996- // lane-hdrlossless: libaom errors on the same stream
997- // (`decodeframe.c:4651`: `if (frame_to_show == NULL)
998- // aom_internal_error(... AOM_CODEC_UNSUP_BITSTREAM, "Buffer does
999- // not contain a decoded frame")`) -- a spec-conformant guard.
1000- let empty_slot = || {
1001- Error::unsupported(
1002- "AV1 decode_stream",
1003- "a show_existing_frame header naming an empty reference slot",
1004- )
1005- };
1006- if threads > 1 {
1007- // lane-thread3: the named slot may still be decoding on a
1008- // worker, and the copy into the slots this header refreshes
1009- // is then just the promise -- no value needed. The OUTPUT
1010- // does need the picture, so it is produced on a worker too:
1011- // waiting for it here would stall the parsing thread, and a
1012- // stalled parser dispatches nothing (measured before this
1013- // arm existed: 7.9 s of an 8.8 s 1080p decode, 18.9 s of
1014- // 23.3 s at 4K, spent in this one wait). The wait still
1015- // points at an earlier coded frame, so the argument in
1016- // [`SlotPromise`] is unchanged.
1017- let promise = slot_promises[slot].clone().ok_or_else(empty_slot)?;
1018- for i in 0..NUM_REF_FRAMES {
1019- if header.refresh_frame_flags & (1 << i) != 0 {
1020- slot_promises[i] = Some(promise.clone());
1021- slot_owner[i] = slot_owner[slot];
975+ Ok(())
976+ })?;
977+ Ok(pictures)
978+ }
979+
980+ /// Decode whole frames from `data` (one or more temporal units), handing
981+ /// every picture to `sink` as [`decode_stream_with`] does, before returning.
982+ ///
983+ /// # Errors
984+ /// As [`decode_stream_with`].
985+ pub fn decode(
986+ &mut self,
987+ data: &[u8],
988+ mut sink: impl FnMut(&Picture, usize, bool) -> Result<()>,
989+ ) -> Result<()> {
990+ let mut pictures_shown = self.pictures_shown;
991+ let mut pictures_decoded = self.pictures_decoded;
992+ let mut emit_seq = self.emit_seq;
993+ let mut in_flight_decodes = self.in_flight_decodes;
994+ let mut in_flight_shows = self.in_flight_shows;
995+ let mut order_hint_slots = self.order_hint_slots;
996+ let mut slot_owner = self.slot_owner;
997+ let mut reorder = std::mem::take(&mut self.reorder);
998+ let mut pending_header = self.pending_header.take();
999+ let mut pending_tiles = std::mem::take(&mut self.pending_tiles);
1000+ let threads = self.threads;
1001+ let StreamDecoder {
1002+ final_dump,
1003+ parser,
1004+ ref_slots,
1005+ motion_field_slots,
1006+ cdf_slots,
1007+ seg_map_slots,
1008+ tx,
1009+ rx,
1010+ slot_promises,
1011+ fctx,
1012+ ..
1013+ } = self;
1014+ // lane-pool1: this replaced a `std::thread::scope` -- frame workers now
1015+ // come from a persistent pool (one per submitting thread, workers reused
1016+ // across frames, so their `thread_local!` decode scratch survives the
1017+ // frame). `jobs` is declared here and dropped at the end of the function,
1018+ // including on `?`, so no job outlives the data it borrows.
1019+ let jobs = crate::par::Batch::new("ec-av1-frame");
1020+ // lane-av1recon: at more than one decode thread the recon wavefront and
1021+ // the filter bands default on (an explicit env value still wins).
1022+ let _split = crate::par::DecodeSplit::install(threads);
1023+ let in_flight_cap = threads + 2;
1024+ let mut pos = 0usize;
1025+ while pos < data.len() {
1026+ let obu = parser.parse_obu(&data[pos..])?;
1027+ let obu_offset = pos;
1028+ pos += obu.total_size;
1029+
1030+ if let ObuKind::FrameHeader(header) = &obu.kind {
1031+ if !header.show_existing_frame {
1032+ // Before this fix, this branch fired unconditionally for
1033+ // EVERY `FrameHeader` OBU (including this one), so a
1034+ // standalone header always fell into the `show_existing_frame`
1035+ // slot lookup below and misreported "a show_existing_frame
1036+ // header naming an empty reference slot" for a frame that was
1037+ // never a show_existing_frame header at all.
1038+ pending_header = Some(header.clone());
1039+ pending_tiles = Vec::new();
1040+ continue;
1041+ }
1042+ // `show_existing_frame` (spec 7.21/5.9.2): no tile payload, this
1043+ // OBU only names a DPB slot to output again -- the coded-frame
1044+ // count and the shown-picture count are different things (a
1045+ // hidden altref's own `Frame` OBU below is never pushed to
1046+ // `pictures` on its own; it is only pushed here, later, when a
1047+ // `show_existing_frame` header names its slot). Before r15 this
1048+ // arm didn't exist at all: every `ObuKind::Frame` was pushed
1049+ // unconditionally regardless of `show_frame`, so a hidden altref
1050+ // was emitted (wrongly, in decode order) and its real
1051+ // `show_existing_frame` output was silently dropped.
1052+ let slot = header.frame_to_show_map_idx as usize;
1053+ // lane-hdrlossless: libaom errors on the same stream
1054+ // (`decodeframe.c:4651`: `if (frame_to_show == NULL)
1055+ // aom_internal_error(... AOM_CODEC_UNSUP_BITSTREAM, "Buffer does
1056+ // not contain a decoded frame")`) -- a spec-conformant guard.
1057+ let empty_slot = || {
1058+ Error::unsupported(
1059+ "AV1 decode_stream",
1060+ "a show_existing_frame header naming an empty reference slot",
1061+ )
1062+ };
1063+ if threads > 1 {
1064+ // lane-thread3: the named slot may still be decoding on a
1065+ // worker, and the copy into the slots this header refreshes
1066+ // is then just the promise -- no value needed. The OUTPUT
1067+ // does need the picture, so it is produced on a worker too:
1068+ // waiting for it here would stall the parsing thread, and a
1069+ // stalled parser dispatches nothing (measured before this
1070+ // arm existed: 7.9 s of an 8.8 s 1080p decode, 18.9 s of
1071+ // 23.3 s at 4K, spent in this one wait). The wait still
1072+ // points at an earlier coded frame, so the argument in
1073+ // [`SlotPromise`] is unchanged.
1074+ let promise = slot_promises[slot].clone().ok_or_else(empty_slot)?;
1075+ for i in 0..NUM_REF_FRAMES {
1076+ if header.refresh_frame_flags & (1 << i) != 0 {
1077+ slot_promises[i] = Some(promise.clone());
1078+ slot_owner[i] = slot_owner[slot];
1079+ }
1080+ }
1081+ let cap_t0 = crate::timeline::now();
1082+ let capped = in_flight_shows >= in_flight_cap;
1083+ while in_flight_shows >= in_flight_cap {
1084+ collect_one(
1085+ &rx,
1086+ &mut in_flight_decodes,
1087+ &mut in_flight_shows,
1088+ &mut reorder,
1089+ &mut sink,
1090+ )?;
1091+ }
1092+ if capped {
1093+ crate::timeline::cap_wait("show", cap_t0, crate::timeline::now());
1094+ }
1095+ let (job_seq, decode_idx) = (emit_seq, pictures_decoded);
1096+ emit_seq += 1;
1097+ pictures_shown += 1;
1098+ let grain = header.film_grain;
1099+ let seq = SeqFlags::read(&parser);
1100+ let tx = tx.clone();
1101+ jobs.submit(move || {
1102+ let mut answer = JobAnswer::new(tx, job_seq, false, None, None);
1103+ let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1104+ let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1105+ let value = promise.wait()?;
1106+ let shown_picture = value.pixels.wait()?;
1107+ let output = if grain.apply_grain && !no_grain() {
1108+ std::sync::Arc::new(crate::film_grain::apply_grain(
1109+ &shown_picture,
1110+ &grain,
1111+ seq.mc_identity,
1112+ u32::from(seq.bit_depth),
1113+ &crate::decode::FrameCtx::new(),
1114+ ))
1115+ } else {
1116+ std::sync::Arc::clone(&shown_picture)
1117+ };
1118+ Ok((output, decode_idx, true))
1119+ }))
1120+ .unwrap_or_else(|_| {
1121+ Err(Error::corrupt(
1122+ "AV1 decode_stream: a worker thread panicked on a show_existing_frame output",
1123+ ))
1124+ });
1125+ answer.send(reply);
1126+ }));
1127+ });
1128+ in_flight_shows += 1;
1129+ while let Ok((seq, decode_job, result)) = rx.try_recv() {
1130+ if decode_job {
1131+ in_flight_decodes -= 1;
1132+ } else {
1133+ in_flight_shows -= 1;
1134+ }
1135+ let (picture, decode_idx, shown) = result?;
1136+ reorder.push(seq, picture, decode_idx, shown);
1137+ reorder.drain(&mut sink)?;
10221138 }
1139+ continue;
10231140 }
1141+ let picture = {
1142+ let picture = ref_slots[slot].clone().ok_or_else(empty_slot)?;
1143+ for i in 0..NUM_REF_FRAMES {
1144+ if header.refresh_frame_flags & (1 << i) != 0 {
1145+ cdf_slots[i] = cdf_slots[slot].clone();
1146+ ref_slots[i] = Some(picture.clone());
1147+ motion_field_slots[i] = motion_field_slots[slot].clone();
1148+ seg_map_slots[i] = seg_map_slots[slot].clone();
1149+ order_hint_slots[i] = order_hint_slots[slot];
1150+ }
1151+ }
1152+ picture
1153+ };
1154+ let output = if header.film_grain.apply_grain && !no_grain() {
1155+ // lane-hbd10 r1: grain synthesis is bit-depth generic
1156+ // (`film_grain.rs`'s `grain_range`/`scale_lut`, spec 7.18.3).
1157+ let bit_depth = parser
1158+ .sequence_header()
1159+ .map_or(8, |seq| seq.color_config.bit_depth);
1160+ let mc_identity = parser
1161+ .sequence_header()
1162+ .is_some_and(|seq| seq.color_config.matrix_coefficients == 0);
1163+ std::sync::Arc::new(crate::film_grain::apply_grain(
1164+ &picture,
1165+ &header.film_grain,
1166+ mc_identity,
1167+ bit_depth as u32,
1168+ fctx,
1169+ ))
1170+ } else {
1171+ picture
1172+ };
1173+ reorder.push(emit_seq, output, pictures_decoded, true);
1174+ emit_seq += 1;
1175+ reorder.drain(&mut sink)?;
1176+ pictures_shown += 1;
1177+ continue;
1178+ }
1179+ // `tiles_base_offset` is added to every `Tile::offset` below to reach
1180+ // an absolute position in `data`. `OBU_FRAME`'s tiles are relative to
1181+ // this OBU's own `obu_offset`; an accumulated run of `OBU_TILE_GROUP`s
1182+ // may span several different OBUs (each at a different offset in
1183+ // `data`), so those tiles are normalised to an absolute offset the
1184+ // moment they are appended to `pending_tiles`, and `tiles_base_offset`
1185+ // is 0 for that case.
1186+ let (header, tiles, tiles_base_offset): (Box<FrameHeader>, Vec<Tile>, usize) =
1187+ match obu.kind {
1188+ ObuKind::Frame(header, tiles) => (header, tiles, obu_offset),
1189+ ObuKind::TileGroup(new_tiles) => {
1190+ let header = pending_header.clone().ok_or_else(|| {
1191+ Error::corrupt(
1192+ "AV1 decode_stream: a tile group OBU with no preceding frame header",
1193+ )
1194+ })?;
1195+ let expected = header.tile_info.cols * header.tile_info.rows;
1196+ pending_tiles.extend(new_tiles.into_iter().map(|mut t| {
1197+ t.offset += obu_offset;
1198+ t
1199+ }));
1200+ if (pending_tiles.len() as u32) < expected {
1201+ continue;
1202+ }
1203+ pending_header = None;
1204+ (header, std::mem::take(&mut pending_tiles), 0)
1205+ }
1206+ _ => continue,
1207+ };
1208+ // Every tile is decoded below through `tile_bufs`; this only rejects a
1209+ // frame OBU that carries no tile group at all.
1210+ if tiles.is_empty() {
1211+ return Err(Error::unsupported(
1212+ "AV1 decode_stream",
1213+ "a frame OBU with no tile group",
1214+ ));
1215+ }
1216+ // `read_cdef` (spec `decodeframe.c`, called at the first non-skip
1217+ // block of each 64x64) only reads a literal `cdef_idx` when
1218+ // `cdef_bits > 0`; at `cdef_bits == 0` there is nothing to read (a
1219+ // true no-op). lane-realworld r1: the per-64x64 `cdef_idx` literal is
1220+ // now read (`maybe_read_cdef_idx` in decode.rs) and threaded into
1221+ // [`crate::decode::apply_cdef`]'s per-superblock strength lookup, so
1222+ // a `cdef_bits > 0` stream no longer needs this refusal.
1223+ // Both frame types now read their transform size under
1224+ // `TxMode::Select`: an intra frame's `decode_key_frame_tile*` reads
1225+ // `tx_depth` (lane-av1txsel, spec 5.11.16), and an inter frame's
1226+ // `decode_inter_block`/`decode_inter_block8` read the recursive
1227+ // `txfm_split` var-tx tree (lane-txselect, spec 5.11.17) -- so the
1228+ // blanket inter-frame refusal that used to stand here is gone. What
1229+ // remains refused is named at its own site in `read_block_tx_size`.
1230+ // lane-av1real r11's blindness-audit sweep (`read_intra_frame_mode_info`,
1231+ // libaom decodemv.c): three more per-block/per-SB symbols this crate
1232+ // never reads at all, each gated by a header field this decoder
1233+ // otherwise accepts uncomplaining -- the same silent-desync shape
1234+ // `use_filter_intra` was. `allow_screen_content_tools` gates both
1235+ // `read_intrabc_info` and `read_palette_mode_info`; `delta.q_present`/
1236+ // `delta.lf_present` gate `read_delta_qindex`/`read_delta_lflevel`
1237+ // (spec 5.11.10/5.11.11, one symbol group per superblock). Refuse
1238+ // before desyncing rather than silently miscode, the same pattern as
1239+ // the CDEF/TxMode::Select refusals above.
1240+ // lane-screen r2: key frames consume (not reconstruct) palette/
1241+ // intrabc syntax via read_intra_mode, and decode_inter_block/
1242+ // decode_inter_block8's own intra-sub-block branches now consume
1243+ // palette the same way (libaom's read_intra_block_mode_info has no
1244+ // intrabc call at all -- that symbol is intra-frame-only). A
1245+ // genuine palette/intrabc use still refuses by name deeper in the
1246+ // block readers, so no whole-frame refusal is needed here anymore.
1247+ // lane-realworld r5: both delta_q (maybe_read_delta_q, CURRENT_Q_IDX)
1248+ // and delta_lf (maybe_read_delta_lf, CURRENT_DELTA_LF ->
1249+ // Neighbours::delta_lf_grid -> lf_level) are now read and applied;
1250+ // no whole-frame refusal needed here anymore.
1251+ //
1252+ // lane-hbd r5: `Picture`'s `y`/`u`/`v` are `u16` now (widened an
1253+ // earlier round), `BIT_DEPTH` is wired from this frame's own sequence
1254+ // header (`set_bit_depth` above), and a real `aomenc --bit-depth=10`
1255+ // stream decodes pixel-exact against ffmpeg's own decode of the same
1256+ // bytes (`a_real_aomenc_10bit_stream_decodes_pixel_exact`). The
1257+ // blanket refusal that used to be here is gone; `film_grain.rs` and
1258+ // `superres.rs` still refuse narrowly by name (their own hardcoded
1259+ // 8-bit LUT/clamp, above), and any other rounding gap 10-bit exposes
1260+ // will show up as a real pixel mismatch, not a silent truncation --
1261+ // the whole reason the widen (and this wiring) happened.
1262+ // lane-seg: `segment_id` is read per block now (spec 5.11.7-5.11.9,
1263+ // `decode::intra_segment_id`/`inter_segment_id`) and consumed by the
1264+ // per-segment quantizer (spec 7.12.2) and loop-filter level
1265+ // (spec 7.14.4). The three features that instead REWRITE a block's
1266+ // mode/reference decisions -- `SEG_LVL_REF_FRAME` (forces the
1267+ // reference), `SEG_LVL_SKIP` and `SEG_LVL_GLOBALMV` (both suppress
1268+ // symbols `decode_inter_block` unconditionally reads) -- have no
1269+ // reader on the inter path, so they still refuse by name rather than
1270+ // desyncing. aomenc's `--aq-mode` segmentation only ever sets
1271+ // `SEG_LVL_ALT_Q` (census gate
1272+ // `a_segmentation_census_over_real_aq_streams_finds_no_mode_overriding_feature`:
1273+ // 1-pass, alt-ref-lag and two-pass arms, every frame header parsed).
1274+ let tile_bufs: Vec<&[u8]> = tiles
1275+ .iter()
1276+ .map(|t| {
1277+ data.get(tiles_base_offset + t.offset..tiles_base_offset + t.offset + t.size)
1278+ .ok_or(Error::NeedMore)
1279+ })
1280+ .collect::<Result<_>>()?;
1281+ let seq = SeqFlags::read(&parser);
1282+ // lane-thread3: at `threads > 1` every coded frame that is not a key
1283+ // frame is decoded on a worker -- frames that refresh reference slots
1284+ // included, which on a pyramid stream is nearly all of them. Its
1285+ // inputs are taken as promises and its output is published as one,
1286+ // installed into the slots it refreshes HERE, on the parsing thread,
1287+ // in decode order, so the next frame's dependencies are known without
1288+ // waiting for this one to finish (see [`SlotPromise`] for the
1289+ // deadlock argument). A key frame stays inline: it resets the whole
1290+ // bank and reads nothing, so there is nothing to gain.
1291+ if threads > 1 && header.frame_type != FrameType::Key && !header.show_existing_frame {
10241292 let cap_t0 = crate::timeline::now();
1025- let capped = in_flight_shows >= in_flight_cap;
1026- while in_flight_shows >= in_flight_cap {
1293+ let capped = in_flight_decodes >= in_flight_cap;
1294+ while in_flight_decodes >= in_flight_cap {
10271295 collect_one(
10281296 &rx,
10291297 &mut in_flight_decodes,
@@ -1033,42 +1301,265 @@ pub fn decode_stream_with_threads(
10331301 )?;
10341302 }
10351303 if capped {
1036- crate::timeline::cap_wait("show", cap_t0, crate::timeline::now());
1304+ crate::timeline::cap_wait("decode", cap_t0, crate::timeline::now());
1305+ }
1306+ // Exactly the slots this frame reads: `ref_frame_idx` names its
1307+ // references, and its `primary_ref_frame` CDFs/segment map, its
1308+ // reference order hints and every field `setup_motion_field`
1309+ // projects all come from those same slots. Nothing else is
1310+ // waited on.
1311+ let mut deps: [Option<std::sync::Arc<SlotPromise>>; NUM_REF_FRAMES] =
1312+ std::array::from_fn(|_| None);
1313+ for i in 0..7 {
1314+ let slot = header.ref_frame_idx[i] as usize;
1315+ deps[slot] = slot_promises[slot].clone();
10371316 }
1038- let (job_seq, decode_idx) = (emit_seq, pictures_decoded);
1317+ let dep_owner = slot_owner;
1318+ let produces = (header.refresh_frame_flags != 0).then(SlotPromise::pending);
1319+ if let Some(promise) = &produces {
1320+ for i in 0..NUM_REF_FRAMES {
1321+ if header.refresh_frame_flags & (1 << i) != 0 {
1322+ slot_promises[i] = Some(promise.clone());
1323+ slot_owner[i] = pictures_decoded;
1324+ }
1325+ }
1326+ }
1327+ let (job_seq, decode_idx, shown_idx) = (emit_seq, pictures_decoded, pictures_shown);
10391328 emit_seq += 1;
1040- pictures_shown += 1;
1041- let grain = header.film_grain;
1042- let seq = SeqFlags::read(&parser);
1329+ pictures_decoded += 1;
1330+ let shown = header.show_frame;
1331+ if shown {
1332+ pictures_shown += 1;
1333+ }
10431334 let tx = tx.clone();
1335+ let dump = final_dump.clone();
1336+ crate::timeline::submit(decode_idx, if shown { 'P' } else { 'A' }, shown);
1337+ // The job outlives this call, so it owns its tile bytes (a copy of
1338+ // this frame's compressed tiles) instead of borrowing `data`.
1339+ let owned_tiles: Vec<Vec<u8>> = tile_bufs.iter().map(|t| t.to_vec()).collect();
10441340 jobs.submit(move || {
1045- let mut answer = JobAnswer::new(tx, job_seq, false, None, None);
1341+ let tile_views: Vec<&[u8]> = owned_tiles.iter().map(Vec::as_slice).collect();
1342+ let promise = produces;
1343+ // lane-twostage: stage 2 -- this frame's filtered pixels. Its
1344+ // consumers hold this promise from the moment stage 1 (CDFs,
1345+ // segment map, motion field, size) is published at the tile
1346+ // boundary, and wait on it at their first prediction.
1347+ let pixels: std::sync::Arc<SlotPromise<std::sync::Arc<Picture>>> =
1348+ SlotPromise::pending();
1349+ let mut answer = JobAnswer::new(
1350+ tx,
1351+ job_seq,
1352+ true,
1353+ promise.clone(),
1354+ Some(pixels.clone()),
1355+ );
10461356 let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1047- let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1048- let value = promise.wait()?;
1049- let shown_picture = value.pixels.wait()?;
1050- let output = if grain.apply_grain && !no_grain() {
1051- std::sync::Arc::new(crate::film_grain::apply_grain(
1052- &shown_picture,
1053- &grain,
1054- seq.mc_identity,
1055- u32::from(seq.bit_depth),
1056- &crate::decode::FrameCtx::new(),
1357+ let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1358+ crate::fault::point("frame");
1359+ crate::timeline::start(decode_idx);
1360+ // The wait happens HERE, off the parsing thread, and only
1361+ // for this frame's own references.
1362+ let mut resolved: [Option<std::sync::Arc<SlotValue>>; NUM_REF_FRAMES] =
1363+ std::array::from_fn(|_| None);
1364+ for (slot, dep) in deps.iter().enumerate() {
1365+ if let Some(dep) = dep {
1366+ let t0 = crate::timeline::now();
1367+ resolved[slot] = Some(dep.wait()?);
1368+ crate::timeline::ref_wait(
1369+ decode_idx,
1370+ slot,
1371+ dep_owner[slot],
1372+ crate::timeline::now().saturating_sub(t0),
1373+ );
1374+ }
1375+ }
1376+ crate::timeline::refs_ready();
1377+ // Fresh per-thread state: every field this path reads is
1378+ // written from this frame's own header before it is read.
1379+ let fctx = crate::decode::FrameCtx::new();
1380+ // lane-twostage: the pictures behind this frame's own
1381+ // references, waited for at the first `ref_planes` call
1382+ // inside the tile decode rather than here.
1383+ let ref_metas: [Option<std::sync::Arc<SlotValue>>; 8] =
1384+ std::array::from_fn(|i| {
1385+ if i == 0 {
1386+ None
1387+ } else {
1388+ resolved
1389+ .get(header.ref_frame_idx[i - 1] as usize)
1390+ .cloned()
1391+ .flatten()
1392+ }
1393+ });
1394+ let pix_cell: std::sync::OnceLock<
1395+ [Option<std::sync::Arc<Picture>>; 8],
1396+ > = std::sync::OnceLock::new();
1397+ let wait_pixels = || -> Result<[Option<&Picture>; 8]> {
1398+ if pix_cell.get().is_none() {
1399+ let mut pics: [Option<std::sync::Arc<Picture>>; 8] =
1400+ Default::default();
1401+ for (i, meta) in ref_metas.iter().enumerate() {
1402+ if let Some(meta) = meta {
1403+ let slot = header.ref_frame_idx[i - 1] as usize;
1404+ let t0 = crate::timeline::now();
1405+ pics[i] = Some(meta.pixels.wait()?);
1406+ crate::timeline::ref_wait(
1407+ decode_idx,
1408+ slot,
1409+ dep_owner[slot],
1410+ crate::timeline::now().saturating_sub(t0),
1411+ );
1412+ }
1413+ }
1414+ let _ = pix_cell.set(pics);
1415+ }
1416+ let pics = pix_cell.get().expect("the pictures were just set");
1417+ Ok(std::array::from_fn(|i| pics[i].as_deref()))
1418+ };
1419+ let ref_dims: [Option<(usize, usize)>; 8] =
1420+ std::array::from_fn(|i| {
1421+ ref_metas[i].as_ref().map(|m| (m.width, m.height))
1422+ });
1423+ // The same references for the recon workers, which wait
1424+ // for the pictures themselves (off the parse thread).
1425+ let shared_refs = {
1426+ let metas = ref_metas.clone();
1427+ let ref_idx = header.ref_frame_idx;
1428+ let owners = dep_owner;
1429+ decode::SharedRefs {
1430+ dims: ref_dims,
1431+ wait: std::sync::Arc::new(move || {
1432+ let mut pics: [Option<std::sync::Arc<Picture>>; 8] =
1433+ Default::default();
1434+ for (i, meta) in metas.iter().enumerate() {
1435+ if let Some(meta) = meta {
1436+ let slot = ref_idx[i - 1] as usize;
1437+ let t0 = crate::timeline::now();
1438+ pics[i] = Some(meta.pixels.wait()?);
1439+ crate::timeline::ref_wait(
1440+ decode_idx,
1441+ slot,
1442+ owners[slot],
1443+ crate::timeline::now().saturating_sub(t0),
1444+ );
1445+ }
1446+ }
1447+ Ok(pics)
1448+ }),
1449+ }
1450+ };
1451+ let refpix =
1452+ decode::RefPix::lazy(ref_dims, &wait_pixels, Some(shared_refs));
1453+ // Stage 1: published at this frame's tile boundary, before
1454+ // its filters run (`take_segment_ids` copies the map, so
1455+ // the filters that read it are unaffected).
1456+ let stage1 = |cdfs: Cdfs,
1457+ motion_field: crate::motion_field::MotionField,
1458+ width: usize,
1459+ height: usize| {
1460+ if let Some(promise) = &promise {
1461+ promise.fulfil(std::sync::Arc::new(SlotValue {
1462+ pixels: pixels.clone(),
1463+ width,
1464+ height,
1465+ cdfs,
1466+ motion_field,
1467+ seg_map: decode::take_segment_ids(&fctx),
1468+ order_hint: header.order_hint,
1469+ }));
1470+ crate::timeline::slot_fulfil();
1471+ }
1472+ };
1473+ // spec 7.9's `av1_setup_motion_field` runs inside
1474+ // `RefSnapshot::take`, i.e. here, after those waits --
1475+ // it reads the referenced slots' saved motion fields.
1476+ let motion_fields =
1477+ std::array::from_fn(|i| resolved[i].as_ref().map(|v| &v.motion_field));
1478+ let snap = RefSnapshot::take(
1479+ &header,
1480+ seq,
1481+ &refpix,
1482+ std::array::from_fn(|i| resolved[i].as_ref().map(|v| &v.cdfs)),
1483+ std::array::from_fn(|i| {
1484+ resolved[i].as_ref().map(|v| v.seg_map.as_slice())
1485+ }),
1486+ &motion_fields,
1487+ std::array::from_fn(|i| resolved[i].as_ref().map_or(0, |v| v.order_hint)),
1488+ );
1489+ let out = decode_frame(
1490+ &fctx,
1491+ &header,
1492+ &tile_views,
1493+ seq,
1494+ snap,
1495+ decode_idx,
1496+ shown_idx,
1497+ dump.as_deref(),
1498+ // lane-twostage publishes a frame's meta at its tile
1499+ // boundary instead of after its filters, so a consumer
1500+ // parses over its producer's filter tail. It is ON by
1501+ // default since lane-sub8group: with every reference
1502+ // pixel read deferred to the recon workers, the
1503+ // consumer parses its WHOLE tile before it needs a
1504+ // pixel, and the 4K critical chain shortens by 11-14%
1505+ // in three interleaved pairs (14450/10594/14407 ms off
1506+ // vs 12790/9207/12463 ms on) where it moved 3-7%
1507+ // before. `EC_AV1_TWO_STAGE=0` turns it back off.
1508+ (crate::envflags::var("EC_AV1_TWO_STAGE").as_deref() != Ok("0"))
1509+ .then_some(&stage1 as &dyn Fn(_, _, _, _)),
1510+ )?;
1511+ // Publish before grain synthesis: every frame waiting on
1512+ // this slot can start the moment the clean picture exists
1513+ // (spec 7.18.3.1 -- the bank never stores grain).
1514+ let picture = std::sync::Arc::new(out.picture);
1515+ pixels.fulfil(picture.clone());
1516+ if let Some(promise) = &promise {
1517+ // Only a frame whose stage-1 sink never fired (a
1518+ // superres frame) still has meta to publish here.
1519+ promise.fulfil_if_pending(|| {
1520+ std::sync::Arc::new(SlotValue {
1521+ pixels: pixels.clone(),
1522+ width: picture.width,
1523+ height: picture.height,
1524+ cdfs: out.stored_cdfs,
1525+ motion_field: out.motion_field.expect(
1526+ "a frame that published no stage 1 carries its motion field back",
1527+ ),
1528+ seg_map: out.seg_map,
1529+ order_hint: header.order_hint,
1530+ })
1531+ });
1532+ crate::timeline::slot_fulfil();
1533+ }
1534+ // Grain is synthesised for OUTPUT only: a hidden frame is
1535+ // reported to the sink clean, exactly as the inline path
1536+ // below reports it (spec 7.18.3.1).
1537+ let output = if shown && header.film_grain.apply_grain && !no_grain() {
1538+ std::sync::Arc::new(crate::film_grain::apply_grain(
1539+ &picture,
1540+ &header.film_grain,
1541+ seq.mc_identity,
1542+ u32::from(seq.bit_depth),
1543+ &fctx,
1544+ ))
1545+ } else {
1546+ picture
1547+ };
1548+ crate::timeline::grain_done();
1549+ Ok((output, decode_idx, shown))
1550+ }))
1551+ .unwrap_or_else(|_| {
1552+ Err(Error::corrupt(
1553+ "AV1 decode_stream: a worker thread panicked decoding a frame",
10571554 ))
1058- } else {
1059- std::sync::Arc::clone(&shown_picture)
1060- };
1061- Ok((output, decode_idx, true))
1062- }))
1063- .unwrap_or_else(|_| {
1064- Err(Error::corrupt(
1065- "AV1 decode_stream: a worker thread panicked on a show_existing_frame output",
1066- ))
1067- });
1068- answer.send(reply);
1555+ });
1556+ crate::fault::point("frame-after");
1557+ answer.send(reply);
10691558 }));
10701559 });
1071- in_flight_shows += 1;
1560+ in_flight_decodes += 1;
1561+ FRAMES_DISPATCHED.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1562+ // Anything that finished while this frame was being set up.
10721563 while let Ok((seq, decode_job, result)) = rx.try_recv() {
10731564 if decode_job {
10741565 in_flight_decodes -= 1;
@@ -1081,563 +1572,169 @@ pub fn decode_stream_with_threads(
10811572 }
10821573 continue;
10831574 }
1084- let picture = {
1085- let picture = ref_slots[slot].clone().ok_or_else(empty_slot)?;
1086- for i in 0..NUM_REF_FRAMES {
1087- if header.refresh_frame_flags & (1 << i) != 0 {
1088- cdf_slots[i] = cdf_slots[slot].clone();
1089- ref_slots[i] = Some(picture.clone());
1090- motion_field_slots[i] = motion_field_slots[slot].clone();
1091- seg_map_slots[i] = seg_map_slots[slot].clone();
1092- order_hint_slots[i] = order_hint_slots[slot];
1093- }
1575+ // lane-twostage: the inline path's references are decoded already,
1576+ // so its handle never waits.
1577+ let inline_refpix = decode::RefPix::ready(std::array::from_fn(|i| {
1578+ if i == 0 {
1579+ None
1580+ } else {
1581+ ref_slots
1582+ .get(header.ref_frame_idx[i - 1] as usize)
1583+ .and_then(|p| p.as_deref())
10941584 }
1095- picture
1096- };
1097- let output = if header.film_grain.apply_grain && !no_grain() {
1098- // lane-hbd10 r1: grain synthesis is bit-depth generic
1099- // (`film_grain.rs`'s `grain_range`/`scale_lut`, spec 7.18.3).
1100- let bit_depth = parser
1101- .sequence_header()
1102- .map_or(8, |seq| seq.color_config.bit_depth);
1103- let mc_identity = parser
1104- .sequence_header()
1105- .is_some_and(|seq| seq.color_config.matrix_coefficients == 0);
1106- std::sync::Arc::new(crate::film_grain::apply_grain(
1107- &picture,
1108- &header.film_grain,
1109- mc_identity,
1110- bit_depth as u32,
1111- fctx,
1112- ))
1113- } else {
1114- picture
1115- };
1116- reorder.push(emit_seq, output, pictures_decoded, true);
1117- emit_seq += 1;
1118- reorder.drain(&mut sink)?;
1119- pictures_shown += 1;
1120- continue;
1121- }
1122- // `tiles_base_offset` is added to every `Tile::offset` below to reach
1123- // an absolute position in `data`. `OBU_FRAME`'s tiles are relative to
1124- // this OBU's own `obu_offset`; an accumulated run of `OBU_TILE_GROUP`s
1125- // may span several different OBUs (each at a different offset in
1126- // `data`), so those tiles are normalised to an absolute offset the
1127- // moment they are appended to `pending_tiles`, and `tiles_base_offset`
1128- // is 0 for that case.
1129- let (header, tiles, tiles_base_offset): (Box<FrameHeader>, Vec<Tile>, usize) =
1130- match obu.kind {
1131- ObuKind::Frame(header, tiles) => (header, tiles, obu_offset),
1132- ObuKind::TileGroup(new_tiles) => {
1133- let header = pending_header.clone().ok_or_else(|| {
1134- Error::corrupt(
1135- "AV1 decode_stream: a tile group OBU with no preceding frame header",
1136- )
1137- })?;
1138- let expected = header.tile_info.cols * header.tile_info.rows;
1139- pending_tiles.extend(new_tiles.into_iter().map(|mut t| {
1140- t.offset += obu_offset;
1141- t
1585+ }));
1586+ let snap = RefSnapshot::take(
1587+ &header,
1588+ seq,
1589+ &inline_refpix,
1590+ std::array::from_fn(|i| cdf_slots[i].as_ref()),
1591+ std::array::from_fn(|i| seg_map_slots[i].as_deref()),
1592+ &std::array::from_fn(|i| motion_field_slots[i].as_ref()),
1593+ order_hint_slots,
1594+ );
1595+ let bit_depth = seq.bit_depth;
1596+ let FrameOutput {
1597+ picture,
1598+ stored_cdfs,
1599+ motion_field,
1600+ seg_map: decoded_seg_map,
1601+ } = decode_frame(
1602+ fctx,
1603+ &header,
1604+ &tile_bufs,
1605+ seq,
1606+ snap,
1607+ pictures_decoded,
1608+ pictures_shown,
1609+ final_dump.as_deref(),
1610+ None,
1611+ )?;
1612+ let motion_field = motion_field.expect("the inline path passes no stage-1 sink");
1613+ pictures_decoded += 1;
1614+ // lane-pool1: one allocation, then every slot store and the output
1615+ // itself are refcount bumps instead of plane copies.
1616+ let picture = std::sync::Arc::new(picture);
1617+ if threads > 1 {
1618+ // lane-thread3: only a key frame reaches this inline path at
1619+ // `threads > 1`, and the bank it fills is the promise array --
1620+ // already resolved, since the picture exists right here.
1621+ if header.refresh_frame_flags != 0 {
1622+ let promise = SlotPromise::ready(std::sync::Arc::new(SlotValue {
1623+ pixels: SlotPromise::ready(std::sync::Arc::clone(&picture)),
1624+ width: picture.width,
1625+ height: picture.height,
1626+ cdfs: stored_cdfs,
1627+ motion_field,
1628+ seg_map: decoded_seg_map,
1629+ order_hint: header.order_hint,
11421630 }));
1143- if (pending_tiles.len() as u32) < expected {
1144- continue;
1631+ for i in 0..NUM_REF_FRAMES {
1632+ if header.refresh_frame_flags & (1 << i) != 0 {
1633+ slot_promises[i] = Some(promise.clone());
1634+ slot_owner[i] = pictures_decoded - 1;
1635+ }
11451636 }
1146- pending_header = None;
1147- (header, std::mem::take(&mut pending_tiles), 0)
11481637 }
1149- _ => continue,
1150- };
1151- // Every tile is decoded below through `tile_bufs`; this only rejects a
1152- // frame OBU that carries no tile group at all.
1153- if tiles.is_empty() {
1154- return Err(Error::unsupported(
1155- "AV1 decode_stream",
1156- "a frame OBU with no tile group",
1157- ));
1158- }
1159- // `read_cdef` (spec `decodeframe.c`, called at the first non-skip
1160- // block of each 64x64) only reads a literal `cdef_idx` when
1161- // `cdef_bits > 0`; at `cdef_bits == 0` there is nothing to read (a
1162- // true no-op). lane-realworld r1: the per-64x64 `cdef_idx` literal is
1163- // now read (`maybe_read_cdef_idx` in decode.rs) and threaded into
1164- // [`crate::decode::apply_cdef`]'s per-superblock strength lookup, so
1165- // a `cdef_bits > 0` stream no longer needs this refusal.
1166- // Both frame types now read their transform size under
1167- // `TxMode::Select`: an intra frame's `decode_key_frame_tile*` reads
1168- // `tx_depth` (lane-av1txsel, spec 5.11.16), and an inter frame's
1169- // `decode_inter_block`/`decode_inter_block8` read the recursive
1170- // `txfm_split` var-tx tree (lane-txselect, spec 5.11.17) -- so the
1171- // blanket inter-frame refusal that used to stand here is gone. What
1172- // remains refused is named at its own site in `read_block_tx_size`.
1173- // lane-av1real r11's blindness-audit sweep (`read_intra_frame_mode_info`,
1174- // libaom decodemv.c): three more per-block/per-SB symbols this crate
1175- // never reads at all, each gated by a header field this decoder
1176- // otherwise accepts uncomplaining -- the same silent-desync shape
1177- // `use_filter_intra` was. `allow_screen_content_tools` gates both
1178- // `read_intrabc_info` and `read_palette_mode_info`; `delta.q_present`/
1179- // `delta.lf_present` gate `read_delta_qindex`/`read_delta_lflevel`
1180- // (spec 5.11.10/5.11.11, one symbol group per superblock). Refuse
1181- // before desyncing rather than silently miscode, the same pattern as
1182- // the CDEF/TxMode::Select refusals above.
1183- // lane-screen r2: key frames consume (not reconstruct) palette/
1184- // intrabc syntax via read_intra_mode, and decode_inter_block/
1185- // decode_inter_block8's own intra-sub-block branches now consume
1186- // palette the same way (libaom's read_intra_block_mode_info has no
1187- // intrabc call at all -- that symbol is intra-frame-only). A
1188- // genuine palette/intrabc use still refuses by name deeper in the
1189- // block readers, so no whole-frame refusal is needed here anymore.
1190- // lane-realworld r5: both delta_q (maybe_read_delta_q, CURRENT_Q_IDX)
1191- // and delta_lf (maybe_read_delta_lf, CURRENT_DELTA_LF ->
1192- // Neighbours::delta_lf_grid -> lf_level) are now read and applied;
1193- // no whole-frame refusal needed here anymore.
1194- //
1195- // lane-hbd r5: `Picture`'s `y`/`u`/`v` are `u16` now (widened an
1196- // earlier round), `BIT_DEPTH` is wired from this frame's own sequence
1197- // header (`set_bit_depth` above), and a real `aomenc --bit-depth=10`
1198- // stream decodes pixel-exact against ffmpeg's own decode of the same
1199- // bytes (`a_real_aomenc_10bit_stream_decodes_pixel_exact`). The
1200- // blanket refusal that used to be here is gone; `film_grain.rs` and
1201- // `superres.rs` still refuse narrowly by name (their own hardcoded
1202- // 8-bit LUT/clamp, above), and any other rounding gap 10-bit exposes
1203- // will show up as a real pixel mismatch, not a silent truncation --
1204- // the whole reason the widen (and this wiring) happened.
1205- // lane-seg: `segment_id` is read per block now (spec 5.11.7-5.11.9,
1206- // `decode::intra_segment_id`/`inter_segment_id`) and consumed by the
1207- // per-segment quantizer (spec 7.12.2) and loop-filter level
1208- // (spec 7.14.4). The three features that instead REWRITE a block's
1209- // mode/reference decisions -- `SEG_LVL_REF_FRAME` (forces the
1210- // reference), `SEG_LVL_SKIP` and `SEG_LVL_GLOBALMV` (both suppress
1211- // symbols `decode_inter_block` unconditionally reads) -- have no
1212- // reader on the inter path, so they still refuse by name rather than
1213- // desyncing. aomenc's `--aq-mode` segmentation only ever sets
1214- // `SEG_LVL_ALT_Q` (census gate
1215- // `a_segmentation_census_over_real_aq_streams_finds_no_mode_overriding_feature`:
1216- // 1-pass, alt-ref-lag and two-pass arms, every frame header parsed).
1217- let tile_bufs: Vec<&[u8]> = tiles
1218- .iter()
1219- .map(|t| {
1220- data.get(tiles_base_offset + t.offset..tiles_base_offset + t.offset + t.size)
1221- .ok_or(Error::NeedMore)
1222- })
1223- .collect::<Result<_>>()?;
1224- let seq = SeqFlags::read(&parser);
1225- // lane-thread3: at `threads > 1` every coded frame that is not a key
1226- // frame is decoded on a worker -- frames that refresh reference slots
1227- // included, which on a pyramid stream is nearly all of them. Its
1228- // inputs are taken as promises and its output is published as one,
1229- // installed into the slots it refreshes HERE, on the parsing thread,
1230- // in decode order, so the next frame's dependencies are known without
1231- // waiting for this one to finish (see [`SlotPromise`] for the
1232- // deadlock argument). A key frame stays inline: it resets the whole
1233- // bank and reads nothing, so there is nothing to gain.
1234- if threads > 1 && header.frame_type != FrameType::Key && !header.show_existing_frame {
1235- let cap_t0 = crate::timeline::now();
1236- let capped = in_flight_decodes >= in_flight_cap;
1237- while in_flight_decodes >= in_flight_cap {
1238- collect_one(
1239- &rx,
1240- &mut in_flight_decodes,
1241- &mut in_flight_shows,
1242- &mut reorder,
1243- &mut sink,
1244- )?;
1245- }
1246- if capped {
1247- crate::timeline::cap_wait("decode", cap_t0, crate::timeline::now());
1248- }
1249- // Exactly the slots this frame reads: `ref_frame_idx` names its
1250- // references, and its `primary_ref_frame` CDFs/segment map, its
1251- // reference order hints and every field `setup_motion_field`
1252- // projects all come from those same slots. Nothing else is
1253- // waited on.
1254- let mut deps: [Option<std::sync::Arc<SlotPromise>>; NUM_REF_FRAMES] =
1255- std::array::from_fn(|_| None);
1256- for i in 0..7 {
1257- let slot = header.ref_frame_idx[i] as usize;
1258- deps[slot] = slot_promises[slot].clone();
1259- }
1260- let dep_owner = slot_owner;
1261- let produces = (header.refresh_frame_flags != 0).then(SlotPromise::pending);
1262- if let Some(promise) = &produces {
1638+ } else {
12631639 for i in 0..NUM_REF_FRAMES {
12641640 if header.refresh_frame_flags & (1 << i) != 0 {
1265- slot_promises[i] = Some(promise.clone());
1266- slot_owner[i] = pictures_decoded;
1641+ cdf_slots[i] = Some(stored_cdfs.clone());
1642+ // Spec 7.18.3.1: synthesized grain is never stored for
1643+ // later prediction -- the reference bank always keeps the
1644+ // clean, pre-grain decode, even though the frame pushed
1645+ // onto the caller's output below carries the grained
1646+ // picture.
1647+ ref_slots[i] = Some(std::sync::Arc::clone(&picture));
1648+ motion_field_slots[i] = Some(motion_field.clone());
1649+ seg_map_slots[i] = Some(decoded_seg_map.clone());
1650+ order_hint_slots[i] = header.order_hint;
12671651 }
12681652 }
12691653 }
1270- let (job_seq, decode_idx, shown_idx) = (emit_seq, pictures_decoded, pictures_shown);
1271- emit_seq += 1;
1272- pictures_decoded += 1;
1273- let shown = header.show_frame;
1274- if shown {
1275- pictures_shown += 1;
1654+ // lane-defon r1: a forward keyframe (aomenc `--enable-fwd-kf`) is a
1655+ // KEY frame coded with `show_frame == 0`, output later by a
1656+ // `show_existing_frame` header -- counted only once its tiles have
1657+ // decoded, so the gate's assert covers decoded-and-compared frames.
1658+ if header.frame_type == FrameType::Key && !header.show_frame {
1659+ decode::note_fwd_kf();
12761660 }
1277- let tx = tx.clone();
1278- let dump = final_dump.clone();
1279- crate::timeline::submit(decode_idx, if shown { 'P' } else { 'A' }, shown);
1280- // The job outlives this call, so it owns its tile bytes (a copy of
1281- // this frame's compressed tiles) instead of borrowing `data`.
1282- let owned_tiles: Vec<Vec<u8>> = tile_bufs.iter().map(|t| t.to_vec()).collect();
1283- jobs.submit(move || {
1284- let tile_views: Vec<&[u8]> = owned_tiles.iter().map(Vec::as_slice).collect();
1285- let promise = produces;
1286- // lane-twostage: stage 2 -- this frame's filtered pixels. Its
1287- // consumers hold this promise from the moment stage 1 (CDFs,
1288- // segment map, motion field, size) is published at the tile
1289- // boundary, and wait on it at their first prediction.
1290- let pixels: std::sync::Arc<SlotPromise<std::sync::Arc<Picture>>> =
1291- SlotPromise::pending();
1292- let mut answer = JobAnswer::new(
1293- tx,
1294- job_seq,
1295- true,
1296- promise.clone(),
1297- Some(pixels.clone()),
1298- );
1299- let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1300- let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1301- crate::fault::point("frame");
1302- crate::timeline::start(decode_idx);
1303- // The wait happens HERE, off the parsing thread, and only
1304- // for this frame's own references.
1305- let mut resolved: [Option<std::sync::Arc<SlotValue>>; NUM_REF_FRAMES] =
1306- std::array::from_fn(|_| None);
1307- for (slot, dep) in deps.iter().enumerate() {
1308- if let Some(dep) = dep {
1309- let t0 = crate::timeline::now();
1310- resolved[slot] = Some(dep.wait()?);
1311- crate::timeline::ref_wait(
1312- decode_idx,
1313- slot,
1314- dep_owner[slot],
1315- crate::timeline::now().saturating_sub(t0),
1316- );
1317- }
1318- }
1319- crate::timeline::refs_ready();
1320- // Fresh per-thread state: every field this path reads is
1321- // written from this frame's own header before it is read.
1322- let fctx = crate::decode::FrameCtx::new();
1323- // lane-twostage: the pictures behind this frame's own
1324- // references, waited for at the first `ref_planes` call
1325- // inside the tile decode rather than here.
1326- let ref_metas: [Option<std::sync::Arc<SlotValue>>; 8] =
1327- std::array::from_fn(|i| {
1328- if i == 0 {
1329- None
1330- } else {
1331- resolved
1332- .get(header.ref_frame_idx[i - 1] as usize)
1333- .cloned()
1334- .flatten()
1335- }
1336- });
1337- let pix_cell: std::sync::OnceLock<
1338- [Option<std::sync::Arc<Picture>>; 8],
1339- > = std::sync::OnceLock::new();
1340- let wait_pixels = || -> Result<[Option<&Picture>; 8]> {
1341- if pix_cell.get().is_none() {
1342- let mut pics: [Option<std::sync::Arc<Picture>>; 8] =
1343- Default::default();
1344- for (i, meta) in ref_metas.iter().enumerate() {
1345- if let Some(meta) = meta {
1346- let slot = header.ref_frame_idx[i - 1] as usize;
1347- let t0 = crate::timeline::now();
1348- pics[i] = Some(meta.pixels.wait()?);
1349- crate::timeline::ref_wait(
1350- decode_idx,
1351- slot,
1352- dep_owner[slot],
1353- crate::timeline::now().saturating_sub(t0),
1354- );
1355- }
1356- }
1357- let _ = pix_cell.set(pics);
1358- }
1359- let pics = pix_cell.get().expect("the pictures were just set");
1360- Ok(std::array::from_fn(|i| pics[i].as_deref()))
1361- };
1362- let ref_dims: [Option<(usize, usize)>; 8] =
1363- std::array::from_fn(|i| {
1364- ref_metas[i].as_ref().map(|m| (m.width, m.height))
1365- });
1366- // The same references for the recon workers, which wait
1367- // for the pictures themselves (off the parse thread).
1368- let shared_refs = {
1369- let metas = ref_metas.clone();
1370- let ref_idx = header.ref_frame_idx;
1371- let owners = dep_owner;
1372- decode::SharedRefs {
1373- dims: ref_dims,
1374- wait: std::sync::Arc::new(move || {
1375- let mut pics: [Option<std::sync::Arc<Picture>>; 8] =
1376- Default::default();
1377- for (i, meta) in metas.iter().enumerate() {
1378- if let Some(meta) = meta {
1379- let slot = ref_idx[i - 1] as usize;
1380- let t0 = crate::timeline::now();
1381- pics[i] = Some(meta.pixels.wait()?);
1382- crate::timeline::ref_wait(
1383- decode_idx,
1384- slot,
1385- owners[slot],
1386- crate::timeline::now().saturating_sub(t0),
1387- );
1388- }
1389- }
1390- Ok(pics)
1391- }),
1392- }
1393- };
1394- let refpix =
1395- decode::RefPix::lazy(ref_dims, &wait_pixels, Some(shared_refs));
1396- // Stage 1: published at this frame's tile boundary, before
1397- // its filters run (`take_segment_ids` copies the map, so
1398- // the filters that read it are unaffected).
1399- let stage1 = |cdfs: Cdfs,
1400- motion_field: crate::motion_field::MotionField,
1401- width: usize,
1402- height: usize| {
1403- if let Some(promise) = &promise {
1404- promise.fulfil(std::sync::Arc::new(SlotValue {
1405- pixels: pixels.clone(),
1406- width,
1407- height,
1408- cdfs,
1409- motion_field,
1410- seg_map: decode::take_segment_ids(&fctx),
1411- order_hint: header.order_hint,
1412- }));
1413- crate::timeline::slot_fulfil();
1414- }
1415- };
1416- // spec 7.9's `av1_setup_motion_field` runs inside
1417- // `RefSnapshot::take`, i.e. here, after those waits --
1418- // it reads the referenced slots' saved motion fields.
1419- let motion_fields =
1420- std::array::from_fn(|i| resolved[i].as_ref().map(|v| &v.motion_field));
1421- let snap = RefSnapshot::take(
1422- &header,
1423- seq,
1424- &refpix,
1425- std::array::from_fn(|i| resolved[i].as_ref().map(|v| &v.cdfs)),
1426- std::array::from_fn(|i| {
1427- resolved[i].as_ref().map(|v| v.seg_map.as_slice())
1428- }),
1429- &motion_fields,
1430- std::array::from_fn(|i| resolved[i].as_ref().map_or(0, |v| v.order_hint)),
1431- );
1432- let out = decode_frame(
1433- &fctx,
1434- &header,
1435- &tile_views,
1436- seq,
1437- snap,
1438- decode_idx,
1439- shown_idx,
1440- dump.as_deref(),
1441- // lane-twostage publishes a frame's meta at its tile
1442- // boundary instead of after its filters, so a consumer
1443- // parses over its producer's filter tail. It is ON by
1444- // default since lane-sub8group: with every reference
1445- // pixel read deferred to the recon workers, the
1446- // consumer parses its WHOLE tile before it needs a
1447- // pixel, and the 4K critical chain shortens by 11-14%
1448- // in three interleaved pairs (14450/10594/14407 ms off
1449- // vs 12790/9207/12463 ms on) where it moved 3-7%
1450- // before. `EC_AV1_TWO_STAGE=0` turns it back off.
1451- (crate::envflags::var("EC_AV1_TWO_STAGE").as_deref() != Ok("0"))
1452- .then_some(&stage1 as &dyn Fn(_, _, _, _)),
1453- )?;
1454- // Publish before grain synthesis: every frame waiting on
1455- // this slot can start the moment the clean picture exists
1456- // (spec 7.18.3.1 -- the bank never stores grain).
1457- let picture = std::sync::Arc::new(out.picture);
1458- pixels.fulfil(picture.clone());
1459- if let Some(promise) = &promise {
1460- // Only a frame whose stage-1 sink never fired (a
1461- // superres frame) still has meta to publish here.
1462- promise.fulfil_if_pending(|| {
1463- std::sync::Arc::new(SlotValue {
1464- pixels: pixels.clone(),
1465- width: picture.width,
1466- height: picture.height,
1467- cdfs: out.stored_cdfs,
1468- motion_field: out.motion_field.expect(
1469- "a frame that published no stage 1 carries its motion field back",
1470- ),
1471- seg_map: out.seg_map,
1472- order_hint: header.order_hint,
1473- })
1474- });
1475- crate::timeline::slot_fulfil();
1476- }
1477- // Grain is synthesised for OUTPUT only: a hidden frame is
1478- // reported to the sink clean, exactly as the inline path
1479- // below reports it (spec 7.18.3.1).
1480- let output = if shown && header.film_grain.apply_grain && !no_grain() {
1481- std::sync::Arc::new(crate::film_grain::apply_grain(
1482- &picture,
1483- &header.film_grain,
1484- seq.mc_identity,
1485- u32::from(seq.bit_depth),
1486- &fctx,
1487- ))
1488- } else {
1489- picture
1490- };
1491- crate::timeline::grain_done();
1492- Ok((output, decode_idx, shown))
1493- }))
1494- .unwrap_or_else(|_| {
1495- Err(Error::corrupt(
1496- "AV1 decode_stream: a worker thread panicked decoding a frame",
1497- ))
1498- });
1499- crate::fault::point("frame-after");
1500- answer.send(reply);
1501- }));
1502- });
1503- in_flight_decodes += 1;
1504- FRAMES_DISPATCHED.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1505- // Anything that finished while this frame was being set up.
1506- while let Ok((seq, decode_job, result)) = rx.try_recv() {
1507- if decode_job {
1508- in_flight_decodes -= 1;
1661+ if header.show_frame {
1662+ let output = if header.film_grain.apply_grain && !no_grain() {
1663+ let mc_identity = seq.mc_identity;
1664+ std::sync::Arc::new(crate::film_grain::apply_grain(
1665+ &picture,
1666+ &header.film_grain,
1667+ mc_identity,
1668+ bit_depth as u32,
1669+ fctx,
1670+ ))
15091671 } else {
1510- in_flight_shows -= 1;
1511- }
1512- let (picture, decode_idx, shown) = result?;
1513- reorder.push(seq, picture, decode_idx, shown);
1672+ picture
1673+ };
1674+ reorder.push(emit_seq, output, pictures_decoded - 1, true);
1675+ emit_seq += 1;
15141676 reorder.drain(&mut sink)?;
1515- }
1516- continue;
1517- }
1518- // lane-twostage: the inline path's references are decoded already,
1519- // so its handle never waits.
1520- let inline_refpix = decode::RefPix::ready(std::array::from_fn(|i| {
1521- if i == 0 {
1522- None
1677+ pictures_shown += 1;
15231678 } else {
1524- ref_slots
1525- .get(header.ref_frame_idx[i - 1] as usize)
1526- .and_then(|p| p.as_deref())
1527- }
1528- }));
1529- let snap = RefSnapshot::take(
1530- &header,
1531- seq,
1532- &inline_refpix,
1533- std::array::from_fn(|i| cdf_slots[i].as_ref()),
1534- std::array::from_fn(|i| seg_map_slots[i].as_deref()),
1535- &std::array::from_fn(|i| motion_field_slots[i].as_ref()),
1536- order_hint_slots,
1537- );
1538- let bit_depth = seq.bit_depth;
1539- let FrameOutput {
1540- picture,
1541- stored_cdfs,
1542- motion_field,
1543- seg_map: decoded_seg_map,
1544- } = decode_frame(
1545- fctx,
1546- &header,
1547- &tile_bufs,
1548- seq,
1549- snap,
1550- pictures_decoded,
1551- pictures_shown,
1552- final_dump.as_deref(),
1553- None,
1554- )?;
1555- let motion_field = motion_field.expect("the inline path passes no stage-1 sink");
1556- pictures_decoded += 1;
1557- // lane-pool1: one allocation, then every slot store and the output
1558- // itself are refcount bumps instead of plane copies.
1559- let picture = std::sync::Arc::new(picture);
1560- if threads > 1 {
1561- // lane-thread3: only a key frame reaches this inline path at
1562- // `threads > 1`, and the bank it fills is the promise array --
1563- // already resolved, since the picture exists right here.
1564- if header.refresh_frame_flags != 0 {
1565- let promise = SlotPromise::ready(std::sync::Arc::new(SlotValue {
1566- pixels: SlotPromise::ready(std::sync::Arc::clone(&picture)),
1567- width: picture.width,
1568- height: picture.height,
1569- cdfs: stored_cdfs,
1570- motion_field,
1571- seg_map: decoded_seg_map,
1572- order_hint: header.order_hint,
1573- }));
1574- for i in 0..NUM_REF_FRAMES {
1575- if header.refresh_frame_flags & (1 << i) != 0 {
1576- slot_promises[i] = Some(promise.clone());
1577- slot_owner[i] = pictures_decoded - 1;
1578- }
1579- }
1580- }
1581- } else {
1582- for i in 0..NUM_REF_FRAMES {
1583- if header.refresh_frame_flags & (1 << i) != 0 {
1584- cdf_slots[i] = Some(stored_cdfs.clone());
1585- // Spec 7.18.3.1: synthesized grain is never stored for
1586- // later prediction -- the reference bank always keeps the
1587- // clean, pre-grain decode, even though the frame pushed
1588- // onto the caller's output below carries the grained
1589- // picture.
1590- ref_slots[i] = Some(std::sync::Arc::clone(&picture));
1591- motion_field_slots[i] = Some(motion_field.clone());
1592- seg_map_slots[i] = Some(decoded_seg_map.clone());
1593- order_hint_slots[i] = header.order_hint;
1594- }
1679+ // Hidden (alt-ref/forward-key) frames never reach
1680+ // `decode_stream`'s output, but a decode-order consumer -- the
1681+ // `EC_AV1_FINAL_DUMP` comparison against aomdec, say -- needs
1682+ // them, so they are reported too, with `shown == false`.
1683+ reorder.push(emit_seq, picture, pictures_decoded - 1, false);
1684+ emit_seq += 1;
1685+ reorder.drain(&mut sink)?;
15951686 }
15961687 }
1597- // lane-defon r1: a forward keyframe (aomenc `--enable-fwd-kf`) is a
1598- // KEY frame coded with `show_frame == 0`, output later by a
1599- // `show_existing_frame` header -- counted only once its tiles have
1600- // decoded, so the gate's assert covers decoded-and-compared frames.
1601- if header.frame_type == FrameType::Key && !header.show_frame {
1602- decode::note_fwd_kf();
1603- }
1604- if header.show_frame {
1605- let output = if header.film_grain.apply_grain && !no_grain() {
1606- let mc_identity = seq.mc_identity;
1607- std::sync::Arc::new(crate::film_grain::apply_grain(
1608- &picture,
1609- &header.film_grain,
1610- mc_identity,
1611- bit_depth as u32,
1612- fctx,
1613- ))
1614- } else {
1615- picture
1616- };
1617- reorder.push(emit_seq, output, pictures_decoded - 1, true);
1618- emit_seq += 1;
1619- reorder.drain(&mut sink)?;
1620- pictures_shown += 1;
1621- } else {
1622- // Hidden (alt-ref/forward-key) frames never reach
1623- // `decode_stream`'s output, but a decode-order consumer -- the
1624- // `EC_AV1_FINAL_DUMP` comparison against aomdec, say -- needs
1625- // them, so they are reported too, with `shown == false`.
1626- reorder.push(emit_seq, picture, pictures_decoded - 1, false);
1627- emit_seq += 1;
1628- reorder.drain(&mut sink)?;
1688+ while in_flight_decodes + in_flight_shows > 0 {
1689+ collect_one(
1690+ &rx,
1691+ &mut in_flight_decodes,
1692+ &mut in_flight_shows,
1693+ &mut reorder,
1694+ &mut sink,
1695+ )?;
16291696 }
1697+ self.pictures_shown = pictures_shown;
1698+ self.pictures_decoded = pictures_decoded;
1699+ self.emit_seq = emit_seq;
1700+ self.in_flight_decodes = in_flight_decodes;
1701+ self.in_flight_shows = in_flight_shows;
1702+ self.order_hint_slots = order_hint_slots;
1703+ self.slot_owner = slot_owner;
1704+ self.reorder = reorder;
1705+ self.pending_header = pending_header;
1706+ self.pending_tiles = pending_tiles;
1707+ Ok(())
16301708 }
1631- while in_flight_decodes + in_flight_shows > 0 {
1632- collect_one(
1633- &rx,
1634- &mut in_flight_decodes,
1635- &mut in_flight_shows,
1636- &mut reorder,
1637- &mut sink,
1638- )?;
1639- }
1640- debug_assert!(reorder.pending.is_empty(), "a frame was never emitted");
1709+}
1710+
1711+/// [`decode_stream_with`] with an explicit worker count (lane-thread2).
1712+///
1713+/// `threads == 1` is the serial decoder. Above that, frames that no later
1714+/// frame can reference -- a shown, non-key frame whose `refresh_frame_flags`
1715+/// is 0, i.e. a leaf of the reference graph -- are decoded on worker threads
1716+/// while the main thread keeps parsing headers and decoding the frames that
1717+/// DO feed the reference banks; `sink` still sees every picture in coded
1718+/// order. Each worker owns a fresh [`crate::decode::FrameCtx`] and a snapshot
1719+/// of the banks taken before dispatch, so no decode state is shared.
1720+///
1721+/// The per-decode counters this crate's gates read are thread-local, so at
1722+/// `threads > 1` a leaf frame's counts land on the worker and are invisible
1723+/// to the caller; that is why the default is 1.
1724+///
1725+/// # Errors
1726+/// As [`decode_stream_with`]; a worker's error aborts the stream.
1727+pub fn decode_stream_with_threads(
1728+ data: &[u8],
1729+ threads: usize,
1730+ sink: impl FnMut(&Picture, usize, bool) -> Result<()>,
1731+) -> Result<()> {
1732+ let mut decoder = StreamDecoder::new(threads);
1733+ decoder.decode(data, sink)?;
1734+ debug_assert!(
1735+ decoder.reorder.pending.is_empty(),
1736+ "a frame was never emitted"
1737+ );
16411738 crate::timeline::dump();
16421739 Ok(())
16431740 }
crates/ec-av1/src/stream/tests/mod.rsmodified+3 -2
@@ -3,9 +3,11 @@ use crate::encode::{Picture as Pic, encode_sequence_with_ctx};
33 use crate::probe::run_with_stdin;
44 use std::process::{Command, Stdio};
55
6-mod support;
76 mod gates_a;
87 mod gates_b;
8+mod layers;
9+mod streaming;
10+mod support;
911 mod t01;
1012 mod t02;
1113 mod t03;
@@ -16,6 +18,5 @@ mod t07;
1618 mod t08;
1719 mod t09;
1820 mod t10;
19-mod layers;
2021
2122 pub(crate) use gates_a::lock_gate_counters;
crates/ec-av1/src/stream/tests/streaming.rsadded+35 -0
@@ -0,0 +1,35 @@
1+use super::*;
2+use crate::encoder::{Av1Encoder, Colour, EncoderConfig};
3+
4+#[test]
5+fn stream_decoder_fed_per_packet_matches_decode_stream() {
6+ let (w, h) = (64, 64);
7+ let mut enc = Av1Encoder::new(EncoderConfig::new(w, h, 120, 30, Colour::Unspecified)).unwrap();
8+ let mut packets: Vec<Vec<u8>> = (0..6)
9+ .flat_map(|t| {
10+ let mut p = Pic::grey(w, h);
11+ for (i, v) in p.y.iter_mut().enumerate() {
12+ *v = ((i % w + t * 3 + (i / w) * 2) % 230) as u16;
13+ }
14+ enc.encode_frames(&p).unwrap()
15+ })
16+ .map(|p| p.data)
17+ .collect();
18+ packets.extend(enc.flush().unwrap().into_iter().map(|p| p.data));
19+ let want = decode_stream(&packets.concat()).unwrap();
20+ let mut dec = StreamDecoder::new(1);
21+ let got: Vec<Picture> = packets
22+ .iter()
23+ .flat_map(|p| {
24+ let pics = dec.decode_temporal_unit(p).unwrap();
25+ assert_eq!(pics.len(), 1);
26+ pics
27+ })
28+ .collect();
29+ assert_eq!(got.len(), want.len());
30+ assert!(
31+ got.iter()
32+ .zip(&want)
33+ .all(|(a, b)| a.y == b.y && a.u == b.u && a.v == b.v)
34+ );
35+}
lanes/hwvideo.charter.mdadded+147 -0
@@ -0,0 +1,147 @@
1+# lane hwvideo: hardware video backend strategy (charter)
2+
3+Date 2026-11-25. Base `19320a9d`. Decision + plan only; no code changed.
4+Consumer: yumush (QUIC screen share: low latency, simulcast, keyframe on request, no B-frames).
5+
6+## Decision
7+
8+**(c) Hybrid, Vulkan-first.**
9+
10+1. **Vulkan Video is the one new backend**, for Linux and Windows (encode H.264/H.265/AV1, decode H.264/H.265/AV1/VP9).
11+2. **VA-API stays on Linux, frozen** (no new features): fallback for hardware without Vulkan Video, and the test oracle.
12+3. **No Media Foundation.** A Windows-native backend is deferred and, if needed, is **D3D12 Video** (same stateless model as VA/Vulkan, so it reuses the ec-hw core). Trigger: measured demand for Intel-on-Windows encode plus access to a Windows GPU.
13+
14+Why:
15+- Only Vulkan can be developed and verified on the machine we have. ~90% of the Windows path (session, DPB, RC, headers, convert) is the same code that runs here; only handle import differs.
16+- Vulkan Video has the same shape as ec-hw (app owns parameter sets, DPB slots, GOP, RC), so the codec logic is shared. MF is a black-box async MFT with per-vendor quirks and shares nothing.
17+- Linux gain: NVIDIA proprietary has no VA-API encode; Vulkan Video covers it.
18+- Cost of (a) alone: loses pre-VCN AMD, older Intel, and the existing proven path. Cost of (b): a Windows backend nobody here can test, and zero shared code.
19+- Known hole: Intel on Windows (see Q1). Until phase 6 it falls back to the software encoders already in this workspace.
20+
21+## Evidence
22+
23+Update 2026-11-25 (after the charter): `mesa-vulkan-drivers-freeworld` 26.2.7 is installed. H.264/H.265 encode and decode now enumerate (qf2 decode H264|H265|AV1|VP9, qf3 encode H264|H265|AV1); H.264 encode: refs 2, maxP 2, CABAC/CAVLC, 8x8 transform, NV12 encode source with STORAGE usage. User: first-party unsafe shim approved (option 1).
24+
25+### Measured on this machine (RX 9060 XT, RADV, Mesa 26.2.7, `RADV_PERFTEST` unset)
26+
27+Probes: `/tmp/claude-1000/-home-tahinli-Documents-Code-Rust-edith-codecs/7157f4ec-94bf-4064-bfe0-585b17ba11a7/scratchpad/vkprobe` and `.../scratchpad/vkprobe2`.
28+
29+- **No `RADV_PERFTEST` needed**: video queues enumerate by default (qf2 decode, qf3 encode).
30+- **The brief's "machine fact" is wrong for H.264/H.265.** Device extensions present: `video_queue`, `video_decode_queue`, `video_encode_queue`, `video_decode_av1`, `video_decode_vp9`, `video_encode_av1`, `video_encode_intra_refresh`, `video_encode_quantization_map`, `video_maintenance1/2`, `VALVE_video_encode_rgb_conversion`. **Absent: `video_decode_h264/h265`, `video_encode_h264/h265`.** Queue families advertise only `DECODE_AV1|DECODE_VP9` and `ENCODE_AV1`.
31+ Cause: `mesa-vulkan-drivers` is Fedora stock (patent-stripped); only `mesa-va-drivers-freeworld` is installed. The strings exist in `libvulkan_radeon.so`, but the codecs are compiled out. `mesa-vulkan-drivers-freeworld-26.2.7` is available in the enabled repos.
32+- AV1 encode: 8192x4352, RC `DISABLED|CBR|VBR`, 4 RC layers, 4 temporal layers, 1 single reference, SB 64. VP9/AV1 decode: 8192x4352, 9 DPB slots, `DPB_AND_OUTPUT_DISTINCT`.
33+- H.264/H.265 capability queries returned SUCCESS anyway (RADV answers without checking the build). Those numbers are not trustworthy until freeworld is installed.
34+- Interop extensions present: `EXT_external_memory_dma_buf`, `EXT_image_drm_format_modifier`, `EXT_queue_family_foreign`, `KHR_external_memory_fd`, `KHR_sampler_ycbcr_conversion`.
35+- `B8G8R8A8_UNORM`: 9 DRM modifiers, all with `SAMPLED|STORAGE|COLOR_ATTACHMENT|BLIT_SRC|BLIT_DST`.
36+- NV12 encode-source images accept extra usage `STORAGE` and `COLOR_ATTACHMENT`, tilings OPTIMAL/LINEAR/DRM_FORMAT_MODIFIER, create flags `MUTABLE_FORMAT|EXTENDED_USAGE` (per-plane R8/RG8 views are allowed).
37+- **RGB encode source works on RADV** (`VALVE_video_encode_rgb_conversion`, AV1 profile): `B8G8R8A8`/`R8G8B8A8` as `VIDEO_ENCODE_SRC`, including **DRM_FORMAT_MODIFIER tiling**, with `TRANSFER_DST|SAMPLED|COLOR_ATTACHMENT`. BT.709 narrow range only.
38+
39+### Crates (checked in the registry / crates.io today)
40+
41+| crate | state | verdict |
42+|---|---|---|
43+| ash 0.38.0+1.3.281 | latest release (2024). Has H.264/H.265 encode, AV1 decode. **No AV1 encode, no VP9 decode.** 0.39 unreleased | rejected: misses exactly the codecs this machine exposes |
44+| pixelforge-ash 0.38.1+1.4.352 | single-maintainer fork of ash master (different API from 0.38: `push`, `load`). Has everything | usable, bus factor 1 |
45+| vulkanalia / vulkanalia-sys 0.35.0 | upstream release. `structs.rs`/`video.rs` contain AV1 encode, VP9 decode, intra refresh, VALVE RGB conversion, StdVideo* | **chosen binding** |
46+| vulkano 0.35.2 | no video API (draft PR closed 2026-05, issue open) | rejected |
47+| gpu-video 0.5.0 (ex vk-video) | 22.5k lines, 289 `unsafe`, pulls wgpu 30 + ash 0.38 + vk-mem; H.264 enc/dec, H.265 enc only; no DMA-BUF import | rejected as dependency, useful as reference |
48+| windows 0.62.2 | covers D3D11, D3D12 Video, MF, WGC; every COM method is `unsafe fn` | only for phase 4/6 shims |
49+
50+No safe wrapper with Vulkan Video exists. Every Vulkan call is `unsafe` in all bindings.
51+
52+### Binding choice: own crate, borrowed types
53+
54+User direction (2026-11-25): forging our own Vulkan crate is acceptable. So:
55+- The safe layer **is** our own crate (`shims/vk-video-ffi`); no existing wrapper is adopted.
56+- Raw types and function pointers come from `vulkanalia-sys 0.35` only (generated structs, no logic). The high-level `vulkanalia` crate is not needed; the loader is `libloading` plus ~40 `vkGet*ProcAddr` lookups inside the shim.
57+- Not hand-writing the raw layer now: the video subset is ~40 commands but several hundred `Vk*`/`StdVideo*` structs with bitfields, about 4-6k lines of transcription with layout risk and no gain (YAGNI).
58+- Exit: if vulkanalia-sys lags a header we need, replace it inside the shim with a hand-written or `vk.xml`/`video.xml`-generated subset. Nothing above the shim sees raw types, so the swap is local.
59+
60+### Web research (delegated; source quality noted)
61+
62+- NVIDIA Windows: decode H.264/H.265 since 2022, AV1 2024, VP9 2025; encode H.264/H.265 since late 2023, AV1 since 2024-11 (NVIDIA Vulkan driver page).
63+- AMD Windows: encode H.264/H.265 in Adrenalin 25.6.1, AV1 in 25.10.2 (**search snippets only**; AMD decode on Windows unconfirmed).
64+- Intel Windows: H.264/H.265 **decode** only (driver 101.4314, snippet). **No evidence of Vulkan encode.**
65+- D3D12 Video Encode: H.264/HEVC on Windows 11, AV1 on 24H2; NVIDIA GTX 10+, Intel Tiger Lake+, AMD RX 5000+ (Microsoft docs/devblog).
66+- Dozen/WARP: no evidence of Vulkan Video. A GPU-less VM has no video queues.
67+
68+## Answers
69+
70+**Q1 Windows driver reality.** Vulkan Video: NVIDIA complete; AMD encode yes (snippet-level), decode unconfirmed; Intel no encode. D3D12 Video/MF cover all three vendors. So Vulkan-only on Windows misses Intel encode. Phase 0 ships a probe binary so this is measured on real machines instead of read from release notes.
71+
72+**Q2 Linux zero-copy.** Feasible, three paths, picked per device at session creation:
73+- `RgbDirect`: import the BGRx DMA-BUF (`dma_buf` + `drm_format_modifier`, explicit modifier and plane layout) as the encode source itself. Zero passes. RADV only (VALVE extension), BT.709 narrow. Confirmed by capability query; not yet by an actual encode.
74+- `BlitRgb`: `vkCmdBlitImage` (linear) from the import to a smaller BGRA encode-source image. Simulcast layers on RADV, no shader.
75+- `ComputeNv12`: portable path. One compute pass samples the import and writes the NV12 encode-source image through R8 and RG8 plane views (`STORAGE` on encode source confirmed here). Scale and RGB to YCbCr in the same pass. One SPIR-V blob, committed.
76+Open: the imported image must be created with the video profile list when used as direct encode source; queue-family transfer from graphics/compute to the encode queue costs one barrier pair.
77+
78+**Q3 Windows capture.** `VK_KHR_external_memory_win32` defines `D3D11_TEXTURE` (NT handle) and `D3D11_TEXTURE_KMT`. WGC frame-pool textures are not shareable, so: `CopyResource` into a texture created with `SHARED_NTHANDLE` (GPU copy, no CPU touch), import that into Vulkan, then `ComputeNv12`. Per-vendor import support is unconfirmed (NVIDIA reported working, Intel reported failing, both anecdotal). Session creation queries `vkGetPhysicalDeviceImageFormatProperties2` with the handle type; on failure the layer takes a CPU upload. Feeding D3D11 textures straight into a D3D11 video processor + encoder is more robust; that is the price of this decision and the argument for phase 6.
79+
80+**Q4 First value.** VA-API already gives yumush zero-copy encode on AMD/Intel Linux. New value is Windows and NVIDIA Linux, so **encode comes before decode**, and H.264 first (the codec all Windows Vulkan encoders have).
81+
82+**Q5 Testing without a Windows GPU.**
83+1. All codec logic and the whole Vulkan path run on Linux against VA-API and ffmpeg.
84+2. `cargo check --target x86_64-pc-windows-msvc` (target installed; no linker needed) for `cfg(windows)` code.
85+3. Khronos validation layers on in every Linux test run: RADV is lenient, NVIDIA is not.
86+4. Windows VM: probe + "no video queue gives `Error::Unsupported` and software fallback" (this is exactly what the VM can show).
87+5. `ec-vk` example `selftest` (headless: encode, decode, PSNR, caps dump) to run on any borrowed Windows GPU machine.
88+6. An NVIDIA Linux box approximates NVIDIA Windows (shared driver core).
89+
90+**Q6 Keep VA-API.** Yes, frozen. Cost: only the vendored cros-libva. Value: pre-VCN AMD and older Intel, md5 oracle for the Vulkan decoder, PSNR reference for the encoder. Default on Linux stays VA until phase 3 gates pass, then Vulkan first, VA second.
91+
92+## Crate layout
93+
94+| crate | unsafe | role |
95+|---|---|---|
96+| `shims/vk-video-ffi` (new, ours) | **yes, the only place** | safe RAII API over `vulkanalia-sys` raw types: instance/device/queues, images (create, import fd / win32 handle, export), mapped bitstream buffers behind slice closures, video session + parameters, a closed command set (video begin/end/control, decode, encode, blit, copy, barrier, dispatch), fences, feedback queries, compute pipeline from SPIR-V bytes. Builds every `StdVideo*`/`pNext` chain from plain owned Rust structs, so no pointer crosses its API. Estimate 2.5-3k lines, ~40 Vulkan entry points, ~70 unsafe call sites |
97+| `crates/ec-vk` (new) | forbid | analog of ec-va: device pick, caps (`enum Codec x enum Direction`), image pool, `enum Convert { RgbDirect, BlitRgb, ComputeNv12 }`, frame export |
98+| `crates/ec-hw` (refactor) | forbid | codec core + `enum Backend { Va, Vk }`, features `va` (Linux) and `vk` |
99+| `shims/d3d11-share` (phase 4) | yes, ~150 lines | shared-NT-handle texture + `CopyResource`, over `windows` |
100+
101+Soundness limit, stated plainly: Vulkan validity rules (image layouts, slot activation) cannot all be typed. The shim enforces them with runtime state enums on a closed command set and is tested under validation layers. This follows the cros-libva precedent in spirit, but the shim is ours, not vendored third-party code.
102+
103+### Backend shape
104+
105+```rust
106+enum Backend { Va(VaSession), Vk(VkSession) }
107+
108+impl Backend {
109+ fn decode(&mut self, pic: &DecodePicture) -> Result<Frame>;
110+ fn encode(&mut self, pic: &EncodePicture, src: &Source) -> Result<Pending>;
111+}
112+```
113+
114+`DecodePicture`/`EncodePicture` are neutral per-codec enums (parsed parameter sets, slot index, reference slots with POC/frame_num, slice offsets). Each backend translates them: VA through today's `params/*`, Vulkan through `vk-video-ffi`.
115+
116+Share estimate of ec-hw (11.5k lines):
117+- Backend-independent, ~60%: `dec/dpb264.rs`, the DPB/RPS/ref logic in `dec/{h264,hevc,av1,vp9}.rs`, `enc/headers.rs` SPS/PPS/VPS/AV1 sequence header, GOP + keyframe-on-demand, RC feedback, level selection, `reset.rs`, errors.
118+- VA-specific, ~40%: `params/*` (1.8k), `Session` in `dec/mod.rs`, surface upload/VPP half of `enc/mod.rs`, `frame.rs`, `pool.rs`, and `headers::h264_slice_header` (Vulkan drivers write slice headers themselves).
119+- Public API leaks VA types today (`Rc<Display>`, `Surface<PrimeImport>`, `Frame::surface()`). New neutral constructors are added; the VA signatures stay.
120+
121+## Phases
122+
123+Effort in focused dev-days. Subagents run `cargo check` only; the parent runs tests.
124+
125+| # | work | days | acceptance |
126+|---|---|---|---|
127+| 0 | Install `mesa-vulkan-drivers-freeworld` (user, sudo). `ec-vk` example `caps` from the probes. Run it in the Windows VM | 1 | H.264/H.265 extensions enumerate here; caps matrix recorded in the report |
128+| 1 | `vk-video-ffi` core + `ec-vk`; **H.264 encode** from I420 upload; then H.265 and AV1 | 8 | ffmpeg decodes every frame; PSNR within 0.3 dB of the VA encoder at equal bitrate (CBR 8 Mb/s 1080p); bitrate within 5%; forced IDR lands on the requested frame; SPS/PPS from `vkGetEncodedVideoSessionParametersKHR` equal `headers.rs` bytes when the driver reports no overrides (otherwise the driver's bytes are the single source); validation layers clean |
129+| 2 | ec-hw refactor to `enum Backend`; neutral picture structs | 4 | existing VA tests and md5 gates unchanged |
130+| 3 | **Linux zero-copy**: DMA-BUF import + `Convert`; simulcast (one import, N layers) | 5 | BGRx import at 3 layer sizes; PSNR within 0.5 dB of VA `submit_prime`; no CPU map on the path; then flip Linux default to Vulkan |
131+| 4 | **Windows**: `cfg(windows)` build, win32 handle import, `d3d11-share`, `selftest` | 4 + hardware access | `cargo check` for msvc clean; VM returns `Unsupported` cleanly; selftest passes on one real NVIDIA or AMD Windows machine |
132+| 5 | **Decode** H.264, H.265, AV1, VP9 on the shared DPB code; output as DMA-BUF / win32 handle / I420 | 8 | md5 equals VA path equals ffmpeg on the benchhw clips (1800/1800 each) |
133+| 6 | Conditional: D3D12 Video backend as third `Backend` variant | 10+ | only with a Windows GPU box and probe data showing Intel demand |
134+
135+AV1 encode and AV1/VP9 decode can start before phase 0 completes; they work on the stock driver.
136+
137+## Risks
138+
139+- **Intel Windows has no hardware encode until phase 6.** Mitigation: software fallback, probe data, phase 6.
140+- Windows results rest on release notes and snippets, not measurements. Phase 0 probe fixes that.
141+- D3D11 texture import into Vulkan is unproven per vendor. Fallback is a CPU upload for that layer.
142+- Driver spread: RADV accepts what NVIDIA rejects. Validation layers in tests; selftest on real hardware before claiming Windows support.
143+- Probe caveat: a capabilities query without the codec capability struct in the chain segfaults inside RADV (probe bug, fixed), and the RGB-conversion check was run for AV1 only; H.264/H.265 with RGB source is unmeasured until phase 0.
144+- `RgbDirect` is confirmed by capability query only, and is BT.709 narrow only; `ComputeNv12` is the baseline, `RgbDirect` an optimisation.
145+- H.264 CQP: AV1 reports `DISABLED|CBR|VBR`; H.264/H.265 RC modes must be re-read after phase 0.
146+- The unsafe shim is new first-party unsafe code (~3k lines). Keep the command set closed and small; no general Vulkan wrapper.
147+- Fedora-stock users get AV1/VP9 only on both VA and Vulkan; software codecs cover the rest.