Reset every CDF's symbol counter before saving it forward
Browse files at this commit6404564afd282d4488d088e0d26dbd5f24aa672cParent: ca633b0- fix
- reset every CDF's symbol counter before saving it forward
3 changed files +518 -77
- crates/ec-av1/src/cdf_state.rs +118 -0
- crates/ec-av1/src/decode.rs +110 -31
- crates/ec-av1/src/stream.rs +290 -46
crates/ec-av1/src/cdf_state.rsmodified+118 -0
| @@ -96,6 +96,7 @@ pub(crate) struct TxbTables<'a> { | ||
| 96 | 96 | } |
| 97 | 97 | |
| 98 | 98 | /// Every table a key frame's tile writer adapts. |
| 99 | +#[derive(Clone)] | |
| 99 | 100 | pub(crate) struct Cdfs { |
| 100 | 101 | /// The partition symbol of a 64x64 superblock. |
| 101 | 102 | pub partition_w64: [[u16; 11]; 4], |
| @@ -308,7 +309,124 @@ pub(crate) fn pick<T: Copy>(q_ctx: usize, q0: T, q1: T, q2: T, q3: T) -> T { | ||
| 308 | 309 | } |
| 309 | 310 | } |
| 310 | 311 | |
| 312 | +/// `reset_cdf_symbol_counter` (spec 7.20's `save_cdfs`, libaom | |
| 313 | +/// `av1_reset_cdf_symbol_counters`, `entropy.c`): every adapting table's last | |
| 314 | +/// entry is a symbol counter that slows [`update_cdf`](crate::msac)'s rate | |
| 315 | +/// down for a table's first 32 observations. A tile decoded with | |
| 316 | +/// `disable_frame_end_update_cdf == false` saves its *adapted* table into the | |
| 317 | +/// reference slots the frame refreshes, but the counters go back to zero | |
| 318 | +/// first -- forwarding the raw counts (this crate's bug until it was found: | |
| 319 | +/// the counts climbed unchecked, so every table forwarded across two or more | |
| 320 | +/// frames adapted *faster* than the real decoder's, a divergence too small to | |
| 321 | +/// flip any one symbol in a single hop but compounding into a visible | |
| 322 | +/// mismatch by the third). | |
| 323 | +fn reset1<const N: usize>(a: &mut [u16; N]) { | |
| 324 | + a[N - 1] = 0; | |
| 325 | +} | |
| 326 | +fn reset2<const N: usize, const M: usize>(a: &mut [[u16; N]; M]) { | |
| 327 | + a.iter_mut().for_each(reset1); | |
| 328 | +} | |
| 329 | +fn reset3<const N: usize, const M: usize, const K: usize>(a: &mut [[[u16; N]; M]; K]) { | |
| 330 | + a.iter_mut().for_each(reset2); | |
| 331 | +} | |
| 332 | + | |
| 333 | +impl MvComponentCdfs { | |
| 334 | + fn reset_counts(&mut self) { | |
| 335 | + reset1(&mut self.class); | |
| 336 | + reset1(&mut self.class0_bit); | |
| 337 | + reset2(&mut self.class0_fr); | |
| 338 | + reset2(&mut self.bit); | |
| 339 | + reset1(&mut self.fr); | |
| 340 | + reset1(&mut self.sign); | |
| 341 | + } | |
| 342 | +} | |
| 343 | + | |
| 311 | 344 | impl Cdfs { |
| 345 | + /// Zeroes every table's symbol counter (its last entry), leaving the | |
| 346 | + /// probabilities themselves untouched -- spec 7.20's `save_cdfs`. Call | |
| 347 | + /// this on the tile's own end-of-tile adapted state before storing it | |
| 348 | + /// into a reference slot for cross-frame forwarding; never on a table | |
| 349 | + /// still being read within the same tile. | |
| 350 | + pub(crate) fn reset_counts(&mut self) { | |
| 351 | + reset2(&mut self.partition_w64); | |
| 352 | + reset2(&mut self.partition_w32); | |
| 353 | + reset2(&mut self.skip); | |
| 354 | + reset3(&mut self.kf_y_mode); | |
| 355 | + reset2(&mut self.uv_mode_no_cfl); | |
| 356 | + reset2(&mut self.uv_mode_cfl); | |
| 357 | + reset1(&mut self.cfl_sign); | |
| 358 | + reset2(&mut self.cfl_alpha); | |
| 359 | + reset2(&mut self.angle_delta); | |
| 360 | + reset2(&mut self.txb_skip_luma_16); | |
| 361 | + reset2(&mut self.txb_skip_luma_8); | |
| 362 | + reset2(&mut self.txb_skip_chroma_8); | |
| 363 | + reset2(&mut self.txb_skip_chroma_4); | |
| 364 | + reset1(&mut self.eob_pt_256_luma); | |
| 365 | + reset1(&mut self.eob_pt_64_luma); | |
| 366 | + reset1(&mut self.eob_pt_64_chroma); | |
| 367 | + reset1(&mut self.eob_pt_16_chroma); | |
| 368 | + reset2(&mut self.eob_extra_luma_16); | |
| 369 | + reset2(&mut self.eob_extra_luma_8); | |
| 370 | + reset2(&mut self.eob_extra_chroma_8); | |
| 371 | + reset2(&mut self.eob_extra_chroma_4); | |
| 372 | + reset2(&mut self.base_luma_16); | |
| 373 | + reset2(&mut self.base_luma_8); | |
| 374 | + reset2(&mut self.base_chroma_8); | |
| 375 | + reset2(&mut self.base_chroma_4); | |
| 376 | + reset2(&mut self.base_eob_luma_16); | |
| 377 | + reset2(&mut self.base_eob_luma_8); | |
| 378 | + reset2(&mut self.base_eob_chroma_8); | |
| 379 | + reset2(&mut self.base_eob_chroma_4); | |
| 380 | + reset2(&mut self.br_luma_16); | |
| 381 | + reset2(&mut self.br_luma_8); | |
| 382 | + reset2(&mut self.br_chroma_8); | |
| 383 | + reset2(&mut self.br_chroma_4); | |
| 384 | + reset2(&mut self.partition_w16); | |
| 385 | + reset2(&mut self.partition_w8); | |
| 386 | + reset2(&mut self.txb_skip_luma_32); | |
| 387 | + reset2(&mut self.txb_skip_luma_64); | |
| 388 | + reset2(&mut self.txb_skip_chroma_16); | |
| 389 | + reset2(&mut self.txb_skip_chroma_32); | |
| 390 | + reset1(&mut self.eob_pt_1024_luma); | |
| 391 | + reset1(&mut self.eob_pt_1024_chroma); | |
| 392 | + reset1(&mut self.eob_pt_256_chroma); | |
| 393 | + reset2(&mut self.eob_extra_luma_32); | |
| 394 | + reset2(&mut self.eob_extra_luma_64); | |
| 395 | + reset2(&mut self.eob_extra_chroma_16); | |
| 396 | + reset2(&mut self.eob_extra_chroma_32); | |
| 397 | + reset2(&mut self.base_luma_32); | |
| 398 | + reset2(&mut self.base_luma_64); | |
| 399 | + reset2(&mut self.base_chroma_16); | |
| 400 | + reset2(&mut self.base_chroma_32); | |
| 401 | + reset2(&mut self.base_eob_luma_32); | |
| 402 | + reset2(&mut self.base_eob_luma_64); | |
| 403 | + reset2(&mut self.base_eob_chroma_16); | |
| 404 | + reset2(&mut self.base_eob_chroma_32); | |
| 405 | + reset2(&mut self.br_luma_32); | |
| 406 | + reset2(&mut self.br_chroma_16); | |
| 407 | + reset2(&mut self.br_chroma_32); | |
| 408 | + reset2(&mut self.dc_sign_luma); | |
| 409 | + reset2(&mut self.intra_tx_type_16); | |
| 410 | + reset2(&mut self.intra_tx_type_8); | |
| 411 | + reset1(&mut self.inter_tx_type_32); | |
| 412 | + reset1(&mut self.inter_tx_type_16); | |
| 413 | + reset1(&mut self.inter_tx_type_8); | |
| 414 | + reset2(&mut self.dc_sign_chroma); | |
| 415 | + reset2(&mut self.intra_inter); | |
| 416 | + reset3(&mut self.single_ref); | |
| 417 | + reset2(&mut self.y_mode); | |
| 418 | + reset2(&mut self.new_mv); | |
| 419 | + reset2(&mut self.zero_mv); | |
| 420 | + reset2(&mut self.ref_mv); | |
| 421 | + reset2(&mut self.drl_mode); | |
| 422 | + reset1(&mut self.mv_joint); | |
| 423 | + self.mv_comp | |
| 424 | + .iter_mut() | |
| 425 | + .for_each(MvComponentCdfs::reset_counts); | |
| 426 | + reset2(&mut self.filter_intra); | |
| 427 | + reset1(&mut self.filter_intra_mode); | |
| 428 | + } | |
| 429 | + | |
| 312 | 430 | /// The defaults a key frame starts from (spec 8.4, `init_coeff_cdfs` and |
| 313 | 431 | /// `init_non_coeff_cdfs`), for coefficient q-context `q_ctx` (0..=3, spec |
| 314 | 432 | /// 8.3.2's `Get_Qctx`). The non-coefficient tables do not vary with the |
crates/ec-av1/src/decode.rsmodified+110 -31
| @@ -115,7 +115,7 @@ fn unsupported(what: impl Into<String>) -> Error { | ||
| 115 | 115 | /// The coefficient q-context a frame's `base_q_idx` picks its default CDFs |
| 116 | 116 | /// from (spec `Get_Qctx`), mirroring [`crate::tile`]'s private copy of the |
| 117 | 117 | /// same rule. |
| 118 | -fn q_ctx_of(base_q_idx: u8) -> usize { | |
| 118 | +pub(crate) fn q_ctx_of(base_q_idx: u8) -> usize { | |
| 119 | 119 | match base_q_idx { |
| 120 | 120 | 0..=20 => 0, |
| 121 | 121 | 21..=60 => 1, |
| @@ -2078,6 +2078,41 @@ pub fn decode_key_frame_tile( | ||
| 2078 | 2078 | cdef: &CdefParams, |
| 2079 | 2079 | loop_filter: &LoopFilterParams, |
| 2080 | 2080 | ) -> Result<Picture> { |
| 2081 | + decode_key_frame_tile_with_cdfs( | |
| 2082 | + data, | |
| 2083 | + mi_cols, | |
| 2084 | + mi_rows, | |
| 2085 | + base_q_idx, | |
| 2086 | + frame_width, | |
| 2087 | + frame_height, | |
| 2088 | + enable_filter_intra, | |
| 2089 | + cdef, | |
| 2090 | + loop_filter, | |
| 2091 | + None, | |
| 2092 | + ) | |
| 2093 | + .map(|(picture, _)| picture) | |
| 2094 | +} | |
| 2095 | + | |
| 2096 | +/// [`decode_key_frame_tile`], threading a cross-frame CDF forward (spec | |
| 2097 | +/// 7.20's `load_cdfs`): `initial_cdfs` is the caller's forwarded state (from | |
| 2098 | +/// a prior frame's saved reference slot) when set, or the spec 8.4 defaults | |
| 2099 | +/// when `None` (the only case [`decode_key_frame_tile`] itself ever needs, | |
| 2100 | +/// since a key frame's own header always forces `primary_ref_frame == | |
| 2101 | +/// PRIMARY_REF_NONE`). Returns the tile's own end-of-tile adapted table | |
| 2102 | +/// alongside the picture, for the caller to save into whichever reference | |
| 2103 | +/// slots this frame's `refresh_frame_flags` names. | |
| 2104 | +pub(crate) fn decode_key_frame_tile_with_cdfs( | |
| 2105 | + data: &[u8], | |
| 2106 | + mi_cols: u32, | |
| 2107 | + mi_rows: u32, | |
| 2108 | + base_q_idx: u8, | |
| 2109 | + frame_width: u32, | |
| 2110 | + frame_height: u32, | |
| 2111 | + enable_filter_intra: bool, | |
| 2112 | + cdef: &CdefParams, | |
| 2113 | + loop_filter: &LoopFilterParams, | |
| 2114 | + initial_cdfs: Option<Cdfs>, | |
| 2115 | +) -> Result<(Picture, Cdfs)> { | |
| 2081 | 2116 | if mi_cols == 0 || mi_rows == 0 { |
| 2082 | 2117 | return Err(unsupported("a frame with no mode-info grid")); |
| 2083 | 2118 | } |
| @@ -2113,7 +2148,7 @@ pub fn decode_key_frame_tile( | ||
| 2113 | 2148 | let scan8 = default_scan(TX8); |
| 2114 | 2149 | let scan4 = default_scan(TX4); |
| 2115 | 2150 | |
| 2116 | - let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx)); | |
| 2151 | + let mut cdfs = initial_cdfs.unwrap_or_else(|| Cdfs::new(q_ctx_of(base_q_idx))); | |
| 2117 | 2152 | if std::env::var_os("EC_AV1_TRACE").is_some() { |
| 2118 | 2153 | eprintln!( |
| 2119 | 2154 | "TRACE key_tile_bytes len={} first8={:02x?} base_q_idx={base_q_idx} mi_cols={mi_cols} mi_rows={mi_rows}", |
| @@ -2416,13 +2451,16 @@ pub fn decode_key_frame_tile( | ||
| 2416 | 2451 | |
| 2417 | 2452 | let (fw, fh) = (frame_width as usize, frame_height as usize); |
| 2418 | 2453 | if fw == width && fh == height { |
| 2419 | - return Ok(Picture { | |
| 2420 | - width, | |
| 2421 | - height, | |
| 2422 | - y: y.data, | |
| 2423 | - u: u.data, | |
| 2424 | - v: v.data, | |
| 2425 | - }); | |
| 2454 | + return Ok(( | |
| 2455 | + Picture { | |
| 2456 | + width, | |
| 2457 | + height, | |
| 2458 | + y: y.data, | |
| 2459 | + u: u.data, | |
| 2460 | + v: v.data, | |
| 2461 | + }, | |
| 2462 | + cdfs, | |
| 2463 | + )); | |
| 2426 | 2464 | } |
| 2427 | 2465 | let crop = |plane: &PlaneBuf, w: usize, h: usize| -> Vec<u8> { |
| 2428 | 2466 | let mut out = Vec::with_capacity(w * h); |
| @@ -2431,13 +2469,16 @@ pub fn decode_key_frame_tile( | ||
| 2431 | 2469 | } |
| 2432 | 2470 | out |
| 2433 | 2471 | }; |
| 2434 | - Ok(Picture { | |
| 2435 | - width: fw, | |
| 2436 | - height: fh, | |
| 2437 | - y: crop(&y, fw, fh), | |
| 2438 | - u: crop(&u, fw / 2, fh / 2), | |
| 2439 | - v: crop(&v, fw / 2, fh / 2), | |
| 2440 | - }) | |
| 2472 | + Ok(( | |
| 2473 | + Picture { | |
| 2474 | + width: fw, | |
| 2475 | + height: fh, | |
| 2476 | + y: crop(&y, fw, fh), | |
| 2477 | + u: crop(&u, fw / 2, fh / 2), | |
| 2478 | + v: crop(&v, fw / 2, fh / 2), | |
| 2479 | + }, | |
| 2480 | + cdfs, | |
| 2481 | + )) | |
| 2441 | 2482 | } |
| 2442 | 2483 | |
| 2443 | 2484 | /// The `is_inter` context (spec 5.11.16 via `av1_get_intra_inter_context`), |
| @@ -3367,6 +3408,38 @@ pub fn decode_inter_frame_tile( | ||
| 3367 | 3408 | cdef: &CdefParams, |
| 3368 | 3409 | loop_filter: &LoopFilterParams, |
| 3369 | 3410 | ) -> Result<Picture> { |
| 3411 | + decode_inter_frame_tile_with_cdfs( | |
| 3412 | + data, | |
| 3413 | + mi_cols, | |
| 3414 | + mi_rows, | |
| 3415 | + base_q_idx, | |
| 3416 | + frame_width, | |
| 3417 | + frame_height, | |
| 3418 | + reference, | |
| 3419 | + cdef, | |
| 3420 | + loop_filter, | |
| 3421 | + None, | |
| 3422 | + ) | |
| 3423 | + .map(|(picture, _)| picture) | |
| 3424 | +} | |
| 3425 | + | |
| 3426 | +/// [`decode_inter_frame_tile`], threading a cross-frame CDF forward -- see | |
| 3427 | +/// [`decode_key_frame_tile_with_cdfs`]'s doc for `initial_cdfs`/the returned | |
| 3428 | +/// end-of-tile table. An inter frame's own header can name | |
| 3429 | +/// `primary_ref_frame == PRIMARY_REF_NONE` too (an error-resilient stream), | |
| 3430 | +/// so `None` is a real case here, not only a convenience default. | |
| 3431 | +pub(crate) fn decode_inter_frame_tile_with_cdfs( | |
| 3432 | + data: &[u8], | |
| 3433 | + mi_cols: u32, | |
| 3434 | + mi_rows: u32, | |
| 3435 | + base_q_idx: u8, | |
| 3436 | + frame_width: u32, | |
| 3437 | + frame_height: u32, | |
| 3438 | + reference: &Picture, | |
| 3439 | + cdef: &CdefParams, | |
| 3440 | + loop_filter: &LoopFilterParams, | |
| 3441 | + initial_cdfs: Option<Cdfs>, | |
| 3442 | +) -> Result<(Picture, Cdfs)> { | |
| 3370 | 3443 | if mi_cols == 0 || mi_rows == 0 { |
| 3371 | 3444 | return Err(unsupported("a frame with no mode-info grid")); |
| 3372 | 3445 | } |
| @@ -3429,7 +3502,7 @@ pub fn decode_inter_frame_tile( | ||
| 3429 | 3502 | let scan8 = default_scan(TX8); |
| 3430 | 3503 | let scan4 = default_scan(TX4); |
| 3431 | 3504 | |
| 3432 | - let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx)); | |
| 3505 | + let mut cdfs = initial_cdfs.unwrap_or_else(|| Cdfs::new(q_ctx_of(base_q_idx))); | |
| 3433 | 3506 | let mut dec = SymbolDecoder::new(data); |
| 3434 | 3507 | let mut neighbours = Neighbours::new( |
| 3435 | 3508 | cols as usize * 2, |
| @@ -3634,13 +3707,16 @@ pub fn decode_inter_frame_tile( | ||
| 3634 | 3707 | |
| 3635 | 3708 | let (fw, fh) = (frame_width as usize, frame_height as usize); |
| 3636 | 3709 | if fw == width && fh == height { |
| 3637 | - return Ok(Picture { | |
| 3638 | - width, | |
| 3639 | - height, | |
| 3640 | - y: y.data, | |
| 3641 | - u: u.data, | |
| 3642 | - v: v.data, | |
| 3643 | - }); | |
| 3710 | + return Ok(( | |
| 3711 | + Picture { | |
| 3712 | + width, | |
| 3713 | + height, | |
| 3714 | + y: y.data, | |
| 3715 | + u: u.data, | |
| 3716 | + v: v.data, | |
| 3717 | + }, | |
| 3718 | + cdfs, | |
| 3719 | + )); | |
| 3644 | 3720 | } |
| 3645 | 3721 | let crop = |plane: &PlaneBuf, w: usize, h: usize| -> Vec<u8> { |
| 3646 | 3722 | let mut out = Vec::with_capacity(w * h); |
| @@ -3649,13 +3725,16 @@ pub fn decode_inter_frame_tile( | ||
| 3649 | 3725 | } |
| 3650 | 3726 | out |
| 3651 | 3727 | }; |
| 3652 | - Ok(Picture { | |
| 3653 | - width: fw, | |
| 3654 | - height: fh, | |
| 3655 | - y: crop(&y, fw, fh), | |
| 3656 | - u: crop(&u, fw / 2, fh / 2), | |
| 3657 | - v: crop(&v, fw / 2, fh / 2), | |
| 3658 | - }) | |
| 3728 | + Ok(( | |
| 3729 | + Picture { | |
| 3730 | + width: fw, | |
| 3731 | + height: fh, | |
| 3732 | + y: crop(&y, fw, fh), | |
| 3733 | + u: crop(&u, fw / 2, fh / 2), | |
| 3734 | + v: crop(&v, fw / 2, fh / 2), | |
| 3735 | + }, | |
| 3736 | + cdfs, | |
| 3737 | + )) | |
| 3659 | 3738 | } |
| 3660 | 3739 | |
| 3661 | 3740 | #[cfg(test)] |
crates/ec-av1/src/stream.rsmodified+290 -46
| @@ -1,20 +1,31 @@ | ||
| 1 | 1 | //! The stream-level entry point a real decoder needs: walk a raw AV1 OBU |
| 2 | 2 | //! stream (`Encoded::stream`, or any low-overhead-format bitstream this |
| 3 | 3 | //! crate's own writers produce) via [`ec_av1_syntax::Av1Parser`] and dispatch |
| 4 | -//! each frame's tile payload to [`crate::decode::decode_key_frame_tile`] / | |
| 5 | -//! [`crate::decode::decode_inter_frame_tile`], threading a single-slot DPB | |
| 6 | -//! exactly as [`crate::encode::encode_sequence`] does on the write side. | |
| 4 | +//! each frame's tile payload to [`crate::decode::decode_key_frame_tile_with_cdfs`] / | |
| 5 | +//! [`crate::decode::decode_inter_frame_tile_with_cdfs`], threading a | |
| 6 | +//! single-slot picture DPB exactly as [`crate::encode::encode_sequence`] does | |
| 7 | +//! on the write side, plus the full 8-slot *CDF* reference bank spec 7.20 | |
| 8 | +//! (`load_cdfs`) and 7.4 (the reference frame update) describe: a frame whose | |
| 9 | +//! header names `primary_ref_frame != PRIMARY_REF_NONE` resumes from the | |
| 10 | +//! adapted table a previous frame's `refresh_frame_flags` left in that slot, | |
| 11 | +//! rather than the spec 8.4 defaults. | |
| 7 | 12 | //! |
| 8 | 13 | //! This is the only reachable path for a caller that does not have the |
| 9 | 14 | //! encoder's own `Encoded::tile`/`mi_cols`/`mi_rows`/`base_q_idx` fields (they |
| 10 | 15 | //! are `pub(crate)`, and rightly so: the wire is `stream`, everything else is |
| 11 | 16 | //! an implementation detail of how this crate happens to build it). |
| 12 | 17 | |
| 13 | -use ec_av1_syntax::{Av1Parser, FrameType, ObuKind, TxMode, WarpModel}; | |
| 18 | +use ec_av1_syntax::{ | |
| 19 | + Av1Parser, FrameType, NUM_REF_FRAMES, ObuKind, PRIMARY_REF_NONE, TxMode, WarpModel, | |
| 20 | +}; | |
| 14 | 21 | use ec_core::{Error, Result}; |
| 15 | 22 | |
| 23 | +use crate::cdf_state::Cdfs; | |
| 16 | 24 | use crate::decode; |
| 17 | -use crate::decode::{decode_inter_frame_tile, decode_key_frame_tile}; | |
| 25 | +use crate::decode::{ | |
| 26 | + decode_inter_frame_tile_with_cdfs, decode_key_frame_tile, decode_key_frame_tile_with_cdfs, | |
| 27 | + q_ctx_of, | |
| 28 | +}; | |
| 18 | 29 | use crate::encode::Picture; |
| 19 | 30 | |
| 20 | 31 | /// Decode every frame in a raw AV1 OBU stream, in coding order. |
| @@ -36,6 +47,11 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> { | ||
| 36 | 47 | let mut parser = Av1Parser::new(); |
| 37 | 48 | let mut pictures = Vec::new(); |
| 38 | 49 | let mut reference: Option<Picture> = None; |
| 50 | + // Spec 7.20/7.4: each of the 8 reference slots remembers the CDF state a | |
| 51 | + // previous frame's `refresh_frame_flags` stored into it -- the frame's | |
| 52 | + // own end-of-tile adapted table, or (when the frame set | |
| 53 | + // `disable_frame_end_update_cdf`) the table it started from, unchanged. | |
| 54 | + let mut cdf_slots: [Option<Cdfs>; NUM_REF_FRAMES] = std::array::from_fn(|_| None); | |
| 39 | 55 | |
| 40 | 56 | let mut pos = 0usize; |
| 41 | 57 | while pos < data.len() { |
| @@ -110,6 +126,18 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> { | ||
| 110 | 126 | "a frame with segmentation enabled (this decoder never reads a per-block segment_id symbol)", |
| 111 | 127 | )); |
| 112 | 128 | } |
| 129 | + // Loop restoration carries per-restoration-unit symbols in the tile | |
| 130 | + // (spec 5.11.57 `read_lr`, one group per LR unit reached from the | |
| 131 | + // superblock walk) that this decoder never reads -- same | |
| 132 | + // silent-desync shape as the refusals above. Traced live 2026-08-27: | |
| 133 | + // an aomenc inter frame with `Sgrproj` on the V plane desynced the | |
| 134 | + // partition walk into out-of-alphabet garbage. | |
| 135 | + if header.loop_restoration.uses_lr { | |
| 136 | + return Err(Error::unsupported( | |
| 137 | + "AV1 decode_stream", | |
| 138 | + "a frame with loop restoration enabled (this decoder never reads the per-unit lr symbols)", | |
| 139 | + )); | |
| 140 | + } | |
| 113 | 141 | // `decode_inter_block`/`decode_inter_block8`'s `GLOBALMV` arm (spec |
| 114 | 142 | // 5.11.26's `read_inter_intra`... really `assign_mv`'s `GLOBALMV` |
| 115 | 143 | // case, spec 7.10.2.1) uses `gm_get_motion_vector`, which is the |
| @@ -125,6 +153,17 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> { | ||
| 125 | 153 | "an inter frame whose LAST_FRAME global motion is not IDENTITY (GLOBALMV needs the full warp derivation this decoder does not carry)", |
| 126 | 154 | )); |
| 127 | 155 | } |
| 156 | + // `context_update_tile_id` (spec `decode_tile`/`exit_symbol`) names | |
| 157 | + // which tile's end-of-tile adapted CDFs become the frame's own; this | |
| 158 | + // decoder only ever decodes tile 0 (`tiles.first()` above), so a | |
| 159 | + // multi-tile frame is refused rather than silently forwarding the | |
| 160 | + // wrong tile's table (or leaving the rest of the picture undecoded). | |
| 161 | + if header.tile_info.cols > 1 || header.tile_info.rows > 1 { | |
| 162 | + return Err(Error::unsupported( | |
| 163 | + "AV1 decode_stream", | |
| 164 | + "a frame with more than one tile (this decoder only ever decodes tile 0)", | |
| 165 | + )); | |
| 166 | + } | |
| 128 | 167 | // `Tile::offset` is relative to the buffer `parse_obu` was handed |
| 129 | 168 | // (`&data[pos..]` at the time this OBU was parsed), so it is relative |
| 130 | 169 | // to `obu_offset`, not to `data` as a whole. |
| @@ -134,8 +173,25 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> { | ||
| 134 | 173 | .sequence_header() |
| 135 | 174 | .is_some_and(|seq| seq.enable_filter_intra); |
| 136 | 175 | |
| 137 | - let picture = if header.frame_type == FrameType::Key { | |
| 138 | - decode_key_frame_tile( | |
| 176 | + // Spec 7.20 `load_cdfs`: a frame naming a `primary_ref_frame` resumes | |
| 177 | + // from that reference slot's saved CDF state instead of the spec 8.4 | |
| 178 | + // defaults `decode_key/inter_frame_tile_with_cdfs`'s `None` case | |
| 179 | + // builds. | |
| 180 | + let initial_cdfs = if header.primary_ref_frame == PRIMARY_REF_NONE { | |
| 181 | + None | |
| 182 | + } else { | |
| 183 | + let slot = header.ref_frame_idx[header.primary_ref_frame as usize] as usize; | |
| 184 | + Some(cdf_slots[slot].clone().ok_or_else(|| { | |
| 185 | + Error::unsupported( | |
| 186 | + "AV1 decode_stream", | |
| 187 | + "a frame naming primary_ref_frame at a reference slot with no saved CDF state", | |
| 188 | + ) | |
| 189 | + })?) | |
| 190 | + }; | |
| 191 | + let started_from = initial_cdfs.clone(); | |
| 192 | + | |
| 193 | + let (picture, end_cdfs) = if header.frame_type == FrameType::Key { | |
| 194 | + decode_key_frame_tile_with_cdfs( | |
| 139 | 195 | tile_bytes, |
| 140 | 196 | header.mi_cols, |
| 141 | 197 | header.mi_rows, |
| @@ -145,6 +201,7 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> { | ||
| 145 | 201 | enable_filter_intra, |
| 146 | 202 | &header.cdef, |
| 147 | 203 | &header.loop_filter, |
| 204 | + initial_cdfs, | |
| 148 | 205 | )? |
| 149 | 206 | } else { |
| 150 | 207 | let reference = reference.as_ref().ok_or_else(|| { |
| @@ -153,7 +210,7 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> { | ||
| 153 | 210 | "an inter frame with no key frame before it", |
| 154 | 211 | ) |
| 155 | 212 | })?; |
| 156 | - decode_inter_frame_tile( | |
| 213 | + decode_inter_frame_tile_with_cdfs( | |
| 157 | 214 | tile_bytes, |
| 158 | 215 | header.mi_cols, |
| 159 | 216 | header.mi_rows, |
| @@ -163,8 +220,27 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> { | ||
| 163 | 220 | reference, |
| 164 | 221 | &header.cdef, |
| 165 | 222 | &header.loop_filter, |
| 223 | + initial_cdfs, | |
| 166 | 224 | )? |
| 167 | 225 | }; |
| 226 | + // Spec 7.20: `disable_frame_end_update_cdf` stores the frame's | |
| 227 | + // *initial* table into the slots it refreshes, not the adapted | |
| 228 | + // end-of-tile one. | |
| 229 | + let stored_cdfs = if header.disable_frame_end_update_cdf { | |
| 230 | + started_from.unwrap_or_else(|| Cdfs::new(q_ctx_of(header.quantization.base_q_idx))) | |
| 231 | + } else { | |
| 232 | + // Spec 7.20 `save_cdfs` (libaom `av1_reset_cdf_symbol_counters`): | |
| 233 | + // the adapted table is saved with every symbol counter zeroed, | |
| 234 | + // not with the counts the tile's own decode left behind. | |
| 235 | + let mut end_cdfs = end_cdfs; | |
| 236 | + end_cdfs.reset_counts(); | |
| 237 | + end_cdfs | |
| 238 | + }; | |
| 239 | + for i in 0..NUM_REF_FRAMES { | |
| 240 | + if header.refresh_frame_flags & (1 << i) != 0 { | |
| 241 | + cdf_slots[i] = Some(stored_cdfs.clone()); | |
| 242 | + } | |
| 243 | + } | |
| 168 | 244 | reference = Some(picture.clone()); |
| 169 | 245 | pictures.push(picture); |
| 170 | 246 | } |
| @@ -837,6 +913,10 @@ mod tests { | ||
| 837 | 913 | "--enable-angle-delta=0", |
| 838 | 914 | "--enable-tx-size-search=0", |
| 839 | 915 | "--enable-cdef=0", |
| 916 | + // Loop restoration is a named refusal (aomenc's RD picks | |
| 917 | + // Sgrproj on this kind of content) -- off in every recipe | |
| 918 | + // whose test targets a different surface. | |
| 919 | + "--enable-restoration=0", | |
| 840 | 920 | "--max-partition-size=32", |
| 841 | 921 | "--enable-palette=0", |
| 842 | 922 | "--enable-intrabc=0", |
| @@ -964,6 +1044,10 @@ mod tests { | ||
| 964 | 1044 | "--enable-angle-delta=0", |
| 965 | 1045 | "--enable-tx-size-search=0", |
| 966 | 1046 | "--enable-cdef=0", |
| 1047 | + // Loop restoration is a named refusal (aomenc's RD picks | |
| 1048 | + // Sgrproj on this kind of content) -- off in every recipe | |
| 1049 | + // whose test targets a different surface. | |
| 1050 | + "--enable-restoration=0", | |
| 967 | 1051 | "--max-partition-size=32", |
| 968 | 1052 | "--enable-palette=0", |
| 969 | 1053 | "--enable-intrabc=0", |
| @@ -1014,6 +1098,159 @@ mod tests { | ||
| 1014 | 1098 | } |
| 1015 | 1099 | } |
| 1016 | 1100 | |
| 1101 | + /// The decisive cross-frame CDF forwarding test: identical to | |
| 1102 | + /// [`a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact`] | |
| 1103 | + /// except it drops `--error-resilient=1`, so aomenc codes every inter | |
| 1104 | + /// frame's `primary_ref_frame` at its default (not `PRIMARY_REF_NONE`) | |
| 1105 | + /// and expects the decoder to resume from the previous frame's *adapted* | |
| 1106 | + /// CDF state (spec 7.20 `load_cdfs`). Without cross-frame forwarding, | |
| 1107 | + /// frame 1's very first tile symbol desyncs (an out-of-alphabet | |
| 1108 | + /// partition read); with it, every frame decodes pixel-exact. | |
| 1109 | + #[test] | |
| 1110 | + fn a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact() { | |
| 1111 | + if !have_ffmpeg() { | |
| 1112 | + eprintln!( | |
| 1113 | + "SKIP a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact: no ffmpeg" | |
| 1114 | + ); | |
| 1115 | + return; | |
| 1116 | + } | |
| 1117 | + if !have_aomenc() { | |
| 1118 | + eprintln!( | |
| 1119 | + "SKIP a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact: no aomenc at {}", | |
| 1120 | + aomenc_path().display() | |
| 1121 | + ); | |
| 1122 | + return; | |
| 1123 | + } | |
| 1124 | + let (width, height, frame_count) = (64usize, 64usize, 4usize); | |
| 1125 | + let y4m = Command::new("ffmpeg") | |
| 1126 | + .args([ | |
| 1127 | + "-v", | |
| 1128 | + "error", | |
| 1129 | + "-f", | |
| 1130 | + "lavfi", | |
| 1131 | + "-i", | |
| 1132 | + "gradients=size=64x64:seed=42:duration=0.16:rate=25", | |
| 1133 | + "-pix_fmt", | |
| 1134 | + "yuv420p", | |
| 1135 | + "-f", | |
| 1136 | + "yuv4mpegpipe", | |
| 1137 | + "-", | |
| 1138 | + ]) | |
| 1139 | + .stdin(Stdio::null()) | |
| 1140 | + .stdout(Stdio::piped()) | |
| 1141 | + .stderr(Stdio::piped()) | |
| 1142 | + .output() | |
| 1143 | + .expect("ffmpeg failed to run"); | |
| 1144 | + assert!( | |
| 1145 | + y4m.status.success(), | |
| 1146 | + "ffmpeg fixture: {}", | |
| 1147 | + String::from_utf8_lossy(&y4m.stderr) | |
| 1148 | + ); | |
| 1149 | + let mut child = Command::new(aomenc_path()) | |
| 1150 | + .args([ | |
| 1151 | + "--codec=av1", | |
| 1152 | + "--passes=1", | |
| 1153 | + "--end-usage=q", | |
| 1154 | + "--cq-level=55", | |
| 1155 | + "--cpu-used=0", | |
| 1156 | + "--lag-in-frames=0", | |
| 1157 | + "--auto-alt-ref=0", | |
| 1158 | + "--kf-max-dist=1000", | |
| 1159 | + // `--threads=1` (not the default): a multithreaded RD search | |
| 1160 | + // makes aomenc's screen-content-tools heuristic race (seen | |
| 1161 | + // flaky under `cargo test`'s own parallelism -- the same | |
| 1162 | + // fixture, same seed, occasionally sets | |
| 1163 | + // `allow_screen_content_tools`, a round-2 gap unrelated to | |
| 1164 | + // CDF forwarding), so pin it to one thread for a | |
| 1165 | + // deterministic header. | |
| 1166 | + "--threads=1", | |
| 1167 | + "--row-mt=0", | |
| 1168 | + // No `--error-resilient=1` here (that is the whole point of | |
| 1169 | + // this test), but every other reference/compound tool this | |
| 1170 | + // decoder's round-2 inter path does not model is still | |
| 1171 | + // disabled the same way `--error-resilient=1` incidentally | |
| 1172 | + // disabled it in the sibling test above: without | |
| 1173 | + // `--enable-order-hint=0` aomenc's RD search picks a | |
| 1174 | + // non-`LAST_FRAME` reference (`GOLDEN_FRAME`) for some | |
| 1175 | + // blocks even in this short a sequence, which is a separate, | |
| 1176 | + // already-documented round-2 gap ("a reference frame other | |
| 1177 | + // than LAST_FRAME"), not a CDF-forwarding one. | |
| 1178 | + "--enable-order-hint=0", | |
| 1179 | + "--enable-warped-motion=0", | |
| 1180 | + "--enable-obmc=0", | |
| 1181 | + "--enable-masked-comp=0", | |
| 1182 | + "--enable-interintra-comp=0", | |
| 1183 | + "--enable-dist-wtd-comp=0", | |
| 1184 | + "--enable-diff-wtd-comp=0", | |
| 1185 | + "--enable-onesided-comp=0", | |
| 1186 | + "--enable-interintra-wedge=0", | |
| 1187 | + "--enable-smooth-interintra=0", | |
| 1188 | + "--enable-rect-partitions=0", | |
| 1189 | + "--enable-ab-partitions=0", | |
| 1190 | + "--enable-1to4-partitions=0", | |
| 1191 | + "--enable-filter-intra=0", | |
| 1192 | + "--enable-smooth-intra=0", | |
| 1193 | + "--enable-paeth-intra=0", | |
| 1194 | + "--enable-directional-intra=0", | |
| 1195 | + "--enable-angle-delta=0", | |
| 1196 | + "--enable-tx-size-search=0", | |
| 1197 | + "--enable-cdef=0", | |
| 1198 | + // Loop restoration is a named refusal (aomenc's RD picks | |
| 1199 | + // Sgrproj on this kind of content) -- off in every recipe | |
| 1200 | + // whose test targets a different surface. | |
| 1201 | + "--enable-restoration=0", | |
| 1202 | + "--max-partition-size=32", | |
| 1203 | + "--enable-palette=0", | |
| 1204 | + "--enable-intrabc=0", | |
| 1205 | + "--enable-cfl-intra=0", | |
| 1206 | + "--obu", | |
| 1207 | + "-o", | |
| 1208 | + "-", | |
| 1209 | + "-", | |
| 1210 | + ]) | |
| 1211 | + .stdin(Stdio::piped()) | |
| 1212 | + .stdout(Stdio::piped()) | |
| 1213 | + .stderr(Stdio::piped()) | |
| 1214 | + .spawn() | |
| 1215 | + .expect("aomenc failed to start"); | |
| 1216 | + child | |
| 1217 | + .stdin | |
| 1218 | + .take() | |
| 1219 | + .expect("aomenc stdin") | |
| 1220 | + .write_all(&y4m.stdout) | |
| 1221 | + .expect("writing y4m to aomenc"); | |
| 1222 | + let out = child.wait_with_output().expect("aomenc failed to run"); | |
| 1223 | + assert!( | |
| 1224 | + out.status.success(), | |
| 1225 | + "aomenc refused the fixture: {}", | |
| 1226 | + String::from_utf8_lossy(&out.stderr) | |
| 1227 | + ); | |
| 1228 | + let stream = out.stdout; | |
| 1229 | + // Same nondeterministic `screen_content_tools_determination` skip as | |
| 1230 | + // `a_real_aomenc_filter_intra_stream_decodes_pixel_exact` above: that | |
| 1231 | + // refusal is a separate gap the encoder trips into on occasional | |
| 1232 | + // runs, not a CDF-forwarding failure. Every OTHER error still fails | |
| 1233 | + // the test -- a forwarding desync must never hide behind the skip. | |
| 1234 | + let frames = match decode_stream(&stream) { | |
| 1235 | + Err(e) if e.to_string().contains("allow_screen_content_tools") => { | |
| 1236 | + eprintln!( | |
| 1237 | + "SKIP a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact: {e}" | |
| 1238 | + ); | |
| 1239 | + return; | |
| 1240 | + } | |
| 1241 | + other => other.unwrap_or_else(|e| { | |
| 1242 | + panic!("cross-frame CDF forwarding failed to decode this stream: {e}") | |
| 1243 | + }), | |
| 1244 | + }; | |
| 1245 | + let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count); | |
| 1246 | + assert_eq!(frames.len(), frame_count); | |
| 1247 | + for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { | |
| 1248 | + assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg"); | |
| 1249 | + assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg"); | |
| 1250 | + assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg"); | |
| 1251 | + } | |
| 1252 | + } | |
| 1253 | + | |
| 1017 | 1254 | /// scratch: isolate a pinned mismatching stream's first divergent pixel. |
| 1018 | 1255 | #[test] |
| 1019 | 1256 | #[ignore] |
| @@ -1035,51 +1272,58 @@ mod tests { | ||
| 1035 | 1272 | ); |
| 1036 | 1273 | eprintln!("delta: {:?}", header.delta); |
| 1037 | 1274 | eprintln!("segmentation: {:?}", header.segmentation); |
| 1275 | + eprintln!("loop_restoration: {:?}", header.loop_restoration); | |
| 1276 | + eprintln!( | |
| 1277 | + "use_128x128_superblock: {:?} disable_cdf_update: {:?} disable_frame_end_update_cdf: {:?} primary_ref_frame: {:?}", | |
| 1278 | + p.sequence_header().map(|s| s.use_128x128_superblock), | |
| 1279 | + header.disable_cdf_update, | |
| 1280 | + header.disable_frame_end_update_cdf, | |
| 1281 | + header.primary_ref_frame, | |
| 1282 | + ); | |
| 1038 | 1283 | } |
| 1039 | 1284 | } |
| 1040 | 1285 | } |
| 1041 | - let width = 32; | |
| 1042 | - let height = 32; | |
| 1286 | + let width = std::env::var("EC_AV1_PIN_W") | |
| 1287 | + .map(|s| s.parse().unwrap()) | |
| 1288 | + .unwrap_or(64); | |
| 1289 | + let height = std::env::var("EC_AV1_PIN_H") | |
| 1290 | + .map(|s| s.parse().unwrap()) | |
| 1291 | + .unwrap_or(64); | |
| 1292 | + let frame_count = std::env::var("EC_AV1_PIN_N") | |
| 1293 | + .map(|s| s.parse().unwrap()) | |
| 1294 | + .unwrap_or(4); | |
| 1043 | 1295 | let frames = decode_stream(&stream).expect("our decode"); |
| 1044 | - let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1); | |
| 1045 | - let ours = &frames[0]; | |
| 1046 | - let theirs = &ffmpeg_frames[0]; | |
| 1047 | - for (plane_name, a, b, w) in [ | |
| 1048 | - ("y", &ours.y, &theirs.y, width), | |
| 1049 | - ("u", &ours.u, &theirs.u, width / 2), | |
| 1050 | - ("v", &ours.v, &theirs.v, width / 2), | |
| 1051 | - ] { | |
| 1052 | - let mut first = None; | |
| 1053 | - let mut count = 0; | |
| 1054 | - for (i, (x, y)) in a.iter().zip(b.iter()).enumerate() { | |
| 1055 | - if x != y { | |
| 1056 | - count += 1; | |
| 1057 | - if first.is_none() { | |
| 1058 | - first = Some(i); | |
| 1296 | + let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count); | |
| 1297 | + for f in 0..frame_count.min(frames.len()).min(ffmpeg_frames.len()) { | |
| 1298 | + let ours = &frames[f]; | |
| 1299 | + let theirs = &ffmpeg_frames[f]; | |
| 1300 | + for (plane_name, a, b, w) in [ | |
| 1301 | + ("y", &ours.y, &theirs.y, width), | |
| 1302 | + ("u", &ours.u, &theirs.u, width / 2), | |
| 1303 | + ("v", &ours.v, &theirs.v, width / 2), | |
| 1304 | + ] { | |
| 1305 | + let mut first = None; | |
| 1306 | + let mut count = 0; | |
| 1307 | + for (i, (x, y)) in a.iter().zip(b.iter()).enumerate() { | |
| 1308 | + if x != y { | |
| 1309 | + count += 1; | |
| 1310 | + if first.is_none() { | |
| 1311 | + first = Some(i); | |
| 1312 | + } | |
| 1059 | 1313 | } |
| 1060 | 1314 | } |
| 1315 | + if let Some(i) = first { | |
| 1316 | + eprintln!( | |
| 1317 | + "frame {f} plane {plane_name}: {count} mismatches, first at offset {i} (row {}, col {}) ours={} theirs={}", | |
| 1318 | + i / w, | |
| 1319 | + i % w, | |
| 1320 | + a[i], | |
| 1321 | + b[i] | |
| 1322 | + ); | |
| 1323 | + } else { | |
| 1324 | + eprintln!("frame {f} plane {plane_name}: MATCH"); | |
| 1325 | + } | |
| 1061 | 1326 | } |
| 1062 | - if let Some(i) = first { | |
| 1063 | - eprintln!( | |
| 1064 | - "plane {plane_name}: {count} mismatches, first at offset {i} (row {}, col {}) ours={} theirs={}", | |
| 1065 | - i / w, | |
| 1066 | - i % w, | |
| 1067 | - a[i], | |
| 1068 | - b[i] | |
| 1069 | - ); | |
| 1070 | - } else { | |
| 1071 | - eprintln!("plane {plane_name}: MATCH"); | |
| 1072 | - } | |
| 1073 | - } | |
| 1074 | - for row in 0..8 { | |
| 1075 | - eprintln!( | |
| 1076 | - "ours row{row}: {:?}", | |
| 1077 | - &ours.y[row * width..row * width + 8] | |
| 1078 | - ); | |
| 1079 | - eprintln!( | |
| 1080 | - "theirs row{row}: {:?}", | |
| 1081 | - &theirs.y[row * width..row * width + 8] | |
| 1082 | - ); | |
| 1083 | 1327 | } |
| 1084 | 1328 | } |
| 1085 | 1329 | } |