Merge branch 'main' (d5fc99e0) into lane-av1lr
Browse files at this commit6 changed files +864 -330
- crates/ec-av1/src/decode.rs +37 -4
- crates/ec-av1/src/encode.rs +495 -205
- crates/ec-av1/src/encoder.rs +24 -0
- crates/ec-av1/src/mvstack.rs +1 -0
- crates/ec-av1/src/stream.rs +8 -1
- crates/ec-av1/src/tile.rs +299 -120
crates/ec-av1/src/decode.rsmodified+37 -4
| @@ -32863,13 +32863,18 @@ pub(crate) fn decode_inter_frame_tile( | |||
| 32863 | // inter frames coded Select by default (class: test asserts against a | 32863 | // inter frames coded Select by default (class: test asserts against a |
| 32864 | // stale header, second instance). | 32864 | // stale header, second instance). |
| 32865 | tx_select: bool, | 32865 | tx_select: bool, |
| 32866 | + // The CDF state this frame's tile was WRITTEN from (`Encoded::start_cdfs`): | ||
| 32867 | + // an inter frame whose header leaves `disable_frame_end_update_cdf` off | ||
| 32868 | + // starts from what the previous frame stored, not from the defaults. Same | ||
| 32869 | + // class as `tx_select` above, third instance. | ||
| 32870 | + initial_cdfs: Option<Cdfs>, | ||
| 32866 | fctx: &crate::decode::FrameCtx, | 32871 | fctx: &crate::decode::FrameCtx, |
| 32867 | ) -> Result<Picture> { | 32872 | ) -> Result<Picture> { |
| 32868 | decode_inter_frame_tile_lr( | 32873 | decode_inter_frame_tile_lr( |
| 32869 | data, mi_cols, mi_rows, base_q_idx, frame_width, frame_height, refpix, cdef, | 32874 | data, mi_cols, mi_rows, base_q_idx, frame_width, frame_height, refpix, cdef, |
| 32870 | loop_filter, allow_high_precision_mv, force_integer_mv, interp_fixed, | 32875 | loop_filter, allow_high_precision_mv, force_integer_mv, interp_fixed, |
| 32871 | enable_dual_filter, reference_select, tx_select, | 32876 | enable_dual_filter, reference_select, tx_select, |
| 32872 | - &LoopRestorationParams::default(), fctx, | 32877 | + &LoopRestorationParams::default(), initial_cdfs, fctx, |
| 32873 | ) | 32878 | ) |
| 32874 | } | 32879 | } |
| 32875 | 32880 | ||
| @@ -32893,6 +32898,7 @@ pub(crate) fn decode_inter_frame_tile_lr( | |||
| 32893 | reference_select: bool, | 32898 | reference_select: bool, |
| 32894 | tx_select: bool, | 32899 | tx_select: bool, |
| 32895 | lr: &LoopRestorationParams, | 32900 | lr: &LoopRestorationParams, |
| 32901 | + initial_cdfs: Option<Cdfs>, | ||
| 32896 | fctx: &crate::decode::FrameCtx, | 32902 | fctx: &crate::decode::FrameCtx, |
| 32897 | ) -> Result<Picture> { | 32903 | ) -> Result<Picture> { |
| 32898 | let single_tile = TileInfo { | 32904 | let single_tile = TileInfo { |
| @@ -32913,7 +32919,7 @@ pub(crate) fn decode_inter_frame_tile_lr( | |||
| 32913 | cdef, | 32919 | cdef, |
| 32914 | loop_filter, | 32920 | loop_filter, |
| 32915 | lr, | 32921 | lr, |
| 32916 | - None, | 32922 | + initial_cdfs, |
| 32917 | allow_high_precision_mv, | 32923 | allow_high_precision_mv, |
| 32918 | force_integer_mv, | 32924 | force_integer_mv, |
| 32919 | NO_SIGN_BIAS, | 32925 | NO_SIGN_BIAS, |
| @@ -35909,6 +35915,22 @@ mod tests { | |||
| 35909 | RefPix::ready(refs) | 35915 | RefPix::ready(refs) |
| 35910 | } | 35916 | } |
| 35911 | 35917 | ||
| 35918 | + /// [`last_only`] plus `GOLDEN_FRAME` (index 4 of the name-keyed array) | ||
| 35919 | + /// and `ALTREF_FRAME` (index 7, the frame two back, which the encoder | ||
| 35920 | + /// keeps in the slot the current frame refreshes): what a frame this | ||
| 35921 | + /// encoder writes needs, since its blocks may name any of the three. | ||
| 35922 | + fn last_golden_altref<'a>( | ||
| 35923 | + last: &'a Picture, | ||
| 35924 | + golden: &'a Picture, | ||
| 35925 | + altref: Option<&'a Picture>, | ||
| 35926 | + ) -> RefPix<'a> { | ||
| 35927 | + let mut refs: [Option<&Picture>; 8] = [None; 8]; | ||
| 35928 | + refs[1] = Some(last); | ||
| 35929 | + refs[4] = Some(golden); | ||
| 35930 | + refs[7] = altref; | ||
| 35931 | + RefPix::ready(refs) | ||
| 35932 | + } | ||
| 35933 | + | ||
| 35912 | 35934 | ||
| 35913 | /// lane-perf6 step 2: the CDEF kernel now reads a pre-gathered window and | 35935 | /// lane-perf6 step 2: the CDEF kernel now reads a pre-gathered window and |
| 35914 | /// a pre-resolved damping shift instead of a bounds-testing closure and a | 35936 | /// a pre-resolved damping shift instead of a bounds-testing closure and a |
| @@ -37050,6 +37072,7 @@ mod tests { | |||
| 37050 | false, | 37072 | false, |
| 37051 | false, | 37073 | false, |
| 37052 | false, | 37074 | false, |
| 37075 | + None, | ||
| 37053 | fctx, | 37076 | fctx, |
| 37054 | ) | 37077 | ) |
| 37055 | .unwrap_err(); | 37078 | .unwrap_err(); |
| @@ -37440,7 +37463,11 @@ mod tests { | |||
| 37440 | frame.base_q_idx, | 37463 | frame.base_q_idx, |
| 37441 | width as u32, | 37464 | width as u32, |
| 37442 | height as u32, | 37465 | height as u32, |
| 37443 | - &last_only(&reference), | 37466 | + &last_golden_altref( |
| 37467 | + &reference, | ||
| 37468 | + &encoded.frames[0].reconstruction, | ||
| 37469 | + (i >= 2).then(|| &encoded.frames[i - 2].reconstruction), | ||
| 37470 | + ), | ||
| 37444 | &frame.cdef, | 37471 | &frame.cdef, |
| 37445 | &frame.loop_filter, | 37472 | &frame.loop_filter, |
| 37446 | false, | 37473 | false, |
| @@ -37450,6 +37477,7 @@ mod tests { | |||
| 37450 | false, | 37477 | false, |
| 37451 | frame.tx_select, | 37478 | frame.tx_select, |
| 37452 | &frame.loop_restoration, | 37479 | &frame.loop_restoration, |
| 37480 | + Some(frame.start_cdfs.0.clone()), | ||
| 37453 | fctx, | 37481 | fctx, |
| 37454 | ) | 37482 | ) |
| 37455 | .unwrap(); | 37483 | .unwrap(); |
| @@ -37753,7 +37781,11 @@ mod tests { | |||
| 37753 | frame.base_q_idx, | 37781 | frame.base_q_idx, |
| 37754 | coded_w, | 37782 | coded_w, |
| 37755 | coded_h, | 37783 | coded_h, |
| 37756 | - &last_only(&reference), | 37784 | + &last_golden_altref( |
| 37785 | + &reference, | ||
| 37786 | + &encoded.frames[0].reconstruction, | ||
| 37787 | + (i >= 2).then(|| &encoded.frames[i - 2].reconstruction), | ||
| 37788 | + ), | ||
| 37757 | &frame.cdef, | 37789 | &frame.cdef, |
| 37758 | &frame.loop_filter, | 37790 | &frame.loop_filter, |
| 37759 | false, | 37791 | false, |
| @@ -37763,6 +37795,7 @@ mod tests { | |||
| 37763 | false, | 37795 | false, |
| 37764 | frame.tx_select, | 37796 | frame.tx_select, |
| 37765 | &frame.loop_restoration, | 37797 | &frame.loop_restoration, |
| 37798 | + Some(frame.start_cdfs.0.clone()), | ||
| 37766 | fctx, | 37799 | fctx, |
| 37767 | ) | 37800 | ) |
| 37768 | .unwrap(); | 37801 | .unwrap(); |
crates/ec-av1/src/encode.rsmodified+495 -205
| @@ -491,12 +491,25 @@ pub(crate) fn crop_encoded(encoded: &Encoded, width: usize, height: usize) -> En | |||
| 491 | mi_rows: encoded.mi_rows, | 491 | mi_rows: encoded.mi_rows, |
| 492 | base_q_idx: encoded.base_q_idx, | 492 | base_q_idx: encoded.base_q_idx, |
| 493 | tx_select: encoded.tx_select, | 493 | tx_select: encoded.tx_select, |
| 494 | + start_cdfs: encoded.start_cdfs.clone(), | ||
| 495 | + next_cdfs: encoded.next_cdfs.clone(), | ||
| 494 | loop_filter: encoded.loop_filter, | 496 | loop_filter: encoded.loop_filter, |
| 495 | loop_restoration: encoded.loop_restoration, | 497 | loop_restoration: encoded.loop_restoration, |
| 496 | cdef: encoded.cdef, | 498 | cdef: encoded.cdef, |
| 497 | } | 499 | } |
| 498 | } | 500 | } |
| 499 | 501 | ||
| 502 | +/// A `Cdfs` inside a `Debug` type: the tables are tens of kilobytes of | ||
| 503 | +/// numbers nobody wants printed, and [`Encoded`] derives `Debug`. | ||
| 504 | +#[derive(Clone)] | ||
| 505 | +pub(crate) struct CdfSnapshot(pub(crate) crate::cdf_state::Cdfs); | ||
| 506 | + | ||
| 507 | +impl std::fmt::Debug for CdfSnapshot { | ||
| 508 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | ||
| 509 | + f.write_str("CdfSnapshot") | ||
| 510 | + } | ||
| 511 | +} | ||
| 512 | + | ||
| 500 | /// What one call to [`encode_key_frame`] produced. | 513 | /// What one call to [`encode_key_frame`] produced. |
| 501 | #[derive(Clone, Debug)] | 514 | #[derive(Clone, Debug)] |
| 502 | pub struct Encoded { | 515 | pub struct Encoded { |
| @@ -530,6 +543,18 @@ pub struct Encoded { | |||
| 530 | /// a `tx_depth` frame as a `TxMode::Largest` one and desyncs at the first | 543 | /// a `tx_depth` frame as a `TxMode::Largest` one and desyncs at the first |
| 531 | /// block. | 544 | /// block. |
| 532 | pub(crate) tx_select: bool, | 545 | pub(crate) tx_select: bool, |
| 546 | + /// The CDF state this frame's tile writer started from -- the defaults | ||
| 547 | + /// for a key frame and for the first inter frame, and the previous | ||
| 548 | + /// frame's stored tables after that. A test that decodes `tile` directly | ||
| 549 | + /// must feed the decoder this, exactly as `decode_stream` feeds it what | ||
| 550 | + /// the frame's `primary_ref_frame` slot holds (same class as | ||
| 551 | + /// `tx_select`: a header bit a raw tile decode cannot guess). | ||
| 552 | + pub(crate) start_cdfs: CdfSnapshot, | ||
| 553 | + /// What this frame stores into the slots it refreshes (spec 7.20, | ||
| 554 | + /// `crate::stream::stored_cdfs_for`): its end-of-tile tables with the | ||
| 555 | + /// counts reset when `disable_frame_end_update_cdf` is off, and what it | ||
| 556 | + /// started from when it is on. | ||
| 557 | + pub(crate) next_cdfs: CdfSnapshot, | ||
| 533 | /// This frame header's chosen deblocking parameters | 558 | /// This frame header's chosen deblocking parameters |
| 534 | /// ([`crate::filter_search::pick_deblock`]) — `reconstruction` is the | 559 | /// ([`crate::filter_search::pick_deblock`]) — `reconstruction` is the |
| 535 | /// picture the decoder produces UNDER them, so a test that decodes | 560 | /// picture the decoder produces UNDER them, so a test that decodes |
| @@ -708,6 +733,11 @@ pub(crate) fn key_frame_headers_colour( | |||
| 708 | Ok((seq, header)) | 733 | Ok((seq, header)) |
| 709 | } | 734 | } |
| 710 | 735 | ||
| 736 | +/// The DPB slot `GOLDEN_FRAME` names in every frame this encoder writes: the | ||
| 737 | +/// key frame refreshes all eight slots, each inter frame only slot 0, so slot | ||
| 738 | +/// 1 still holds the key frame however long the GOP runs. | ||
| 739 | +pub const GOLDEN_SLOT: u8 = 1; | ||
| 740 | + | ||
| 711 | /// The frame header for a shown inter frame that predicts from the single | 741 | /// The frame header for a shown inter frame that predicts from the single |
| 712 | /// slot `last_slot` (every `ref_frame_idx` entry names it) and refreshes that | 742 | /// slot `last_slot` (every `ref_frame_idx` entry names it) and refreshes that |
| 713 | /// same slot with itself once coded. The sequence header is [`key_frame_headers`]'s, | 743 | /// same slot with itself once coded. The sequence header is [`key_frame_headers`]'s, |
| @@ -721,6 +751,26 @@ pub fn inter_frame_headers( | |||
| 721 | base_q_idx: u8, | 751 | base_q_idx: u8, |
| 722 | order_hint: u32, | 752 | order_hint: u32, |
| 723 | last_slot: u8, | 753 | last_slot: u8, |
| 754 | +) -> Result<(SequenceHeader, FrameHeader)> { | ||
| 755 | + inter_frame_headers_slots(width, height, base_q_idx, order_hint, last_slot, last_slot, last_slot) | ||
| 756 | +} | ||
| 757 | + | ||
| 758 | +/// [`inter_frame_headers`] with the three slots named apart: the one read as | ||
| 759 | +/// `LAST_FRAME`, the one this frame refreshes, and the one read as | ||
| 760 | +/// `ALTREF_FRAME`. The encoder alternates the refreshed slot between 0 and 2 | ||
| 761 | +/// so that the frame two back is still intact in the slot this one is about | ||
| 762 | +/// to overwrite -- read before write, spec 7.20's decode order. | ||
| 763 | +/// | ||
| 764 | +/// # Errors | ||
| 765 | +/// As [`inter_frame_headers`]. | ||
| 766 | +pub fn inter_frame_headers_slots( | ||
| 767 | + width: usize, | ||
| 768 | + height: usize, | ||
| 769 | + base_q_idx: u8, | ||
| 770 | + order_hint: u32, | ||
| 771 | + last_slot: u8, | ||
| 772 | + self_slot: u8, | ||
| 773 | + altref_slot: u8, | ||
| 724 | ) -> Result<(SequenceHeader, FrameHeader)> { | 774 | ) -> Result<(SequenceHeader, FrameHeader)> { |
| 725 | let (seq, key) = key_frame_headers(width, height, base_q_idx)?; | 775 | let (seq, key) = key_frame_headers(width, height, base_q_idx)?; |
| 726 | let header = FrameHeader { | 776 | let header = FrameHeader { |
| @@ -729,12 +779,25 @@ pub fn inter_frame_headers( | |||
| 729 | show_frame: true, | 779 | show_frame: true, |
| 730 | error_resilient_mode: false, | 780 | error_resilient_mode: false, |
| 731 | disable_cdf_update: false, | 781 | disable_cdf_update: false, |
| 732 | - disable_frame_end_update_cdf: true, | 782 | + // The tile writer hands its end-of-tile tables to the next frame |
| 783 | + // (`encode_sequence_with_ctx`), so the frame stores them the way the | ||
| 784 | + // decoder will load them (spec 7.20). | ||
| 785 | + disable_frame_end_update_cdf: false, | ||
| 733 | force_integer_mv: false, | 786 | force_integer_mv: false, |
| 734 | order_hint, | 787 | order_hint, |
| 735 | primary_ref_frame: 0, | 788 | primary_ref_frame: 0, |
| 736 | - refresh_frame_flags: 1 << last_slot, | 789 | + refresh_frame_flags: 1 << self_slot, |
| 737 | - ref_frame_idx: [last_slot; ec_av1_syntax::REFS_PER_FRAME], | 790 | + // Every reference but `GOLDEN_FRAME` (index 3 of `ref_frame_idx`) |
| 791 | + // names the slot this frame both predicts from and refreshes; | ||
| 792 | + // GOLDEN names slot 1, which the key frame wrote when it refreshed | ||
| 793 | + // all eight and which no inter frame ever overwrites, so it holds | ||
| 794 | + // the key frame's own picture for the whole GOP. | ||
| 795 | + ref_frame_idx: { | ||
| 796 | + let mut idx = [last_slot; ec_av1_syntax::REFS_PER_FRAME]; | ||
| 797 | + idx[3] = GOLDEN_SLOT; | ||
| 798 | + idx[6] = altref_slot; | ||
| 799 | + idx | ||
| 800 | + }, | ||
| 738 | allow_high_precision_mv: false, | 801 | allow_high_precision_mv: false, |
| 739 | interpolation_filter: ec_av1_syntax::InterpolationFilter::Eighttap, | 802 | interpolation_filter: ec_av1_syntax::InterpolationFilter::Eighttap, |
| 740 | is_motion_mode_switchable: false, | 803 | is_motion_mode_switchable: false, |
| @@ -2357,8 +2420,10 @@ fn code_square_inter( | |||
| 2357 | eight: None, | 2420 | eight: None, |
| 2358 | tx_depth, | 2421 | tx_depth, |
| 2359 | inter: Some(InterInfo { | 2422 | inter: Some(InterInfo { |
| 2423 | + ref_frame: crate::mvstack::LAST_FRAME, | ||
| 2360 | mode: InterMode::NewMv, | 2424 | mode: InterMode::NewMv, |
| 2361 | mv: new_mv, | 2425 | mv: new_mv, |
| 2426 | + ref_mv_idx: 0, | ||
| 2362 | }), | 2427 | }), |
| 2363 | }, | 2428 | }, |
| 2364 | cost + dcost, | 2429 | cost + dcost, |
| @@ -2382,8 +2447,10 @@ fn code_square_inter( | |||
| 2382 | eight: None, | 2447 | eight: None, |
| 2383 | tx_depth, | 2448 | tx_depth, |
| 2384 | inter: Some(InterInfo { | 2449 | inter: Some(InterInfo { |
| 2450 | + ref_frame: crate::mvstack::LAST_FRAME, | ||
| 2385 | mode: InterMode::NearestMv, | 2451 | mode: InterMode::NearestMv, |
| 2386 | mv, | 2452 | mv, |
| 2453 | + ref_mv_idx: 0, | ||
| 2387 | }), | 2454 | }), |
| 2388 | }, inter_cost + dcost) | 2455 | }, inter_cost + dcost) |
| 2389 | } else { | 2456 | } else { |
| @@ -2399,7 +2466,7 @@ fn record_mi(grid: &mut MiGrid, mi_row: usize, mi_col: usize, size: u8, inter: O | |||
| 2399 | let info = match inter { | 2466 | let info = match inter { |
| 2400 | Some(info) => MiInfo { | 2467 | Some(info) => MiInfo { |
| 2401 | is_inter: true, | 2468 | is_inter: true, |
| 2402 | - ref_frame: LAST_FRAME, | 2469 | + ref_frame: info.ref_frame, |
| 2403 | ref_frame1: NO_REF1, | 2470 | ref_frame1: NO_REF1, |
| 2404 | mv1: (0, 0), | 2471 | mv1: (0, 0), |
| 2405 | mv: mv16(info.mv), | 2472 | mv: mv16(info.mv), |
| @@ -3044,13 +3111,21 @@ pub(crate) fn encode_key_frame_inner( | |||
| 3044 | 3111 | ||
| 3045 | #[cfg(test)] | 3112 | #[cfg(test)] |
| 3046 | record_predicted_bits(crate::tile::predicted_coeff_bits_sb(&superblocks, base_q_idx)); | 3113 | record_predicted_bits(crate::tile::predicted_coeff_bits_sb(&superblocks, base_q_idx)); |
| 3114 | + // A key frame always starts from the defaults (`primary_ref_frame` is | ||
| 3115 | + // `PRIMARY_REF_NONE`), and its header keeps `disable_frame_end_update_cdf` | ||
| 3116 | + // set, so what it stores into the slots it refreshes is exactly those | ||
| 3117 | + // defaults again (spec 7.20's `started_from` arm) -- the first inter | ||
| 3118 | + // frame after it therefore starts from the defaults too. | ||
| 3047 | let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows); | 3119 | let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows); |
| 3048 | - let mut tile = crate::tile::sb_coeff_key_frame_tile_tx( | 3120 | + let mut cdfs = crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx)); |
| 3121 | + let start_cdfs = CdfSnapshot(cdfs.clone()); | ||
| 3122 | + let mut tile = crate::tile::sb_coeff_key_frame_tile_cdfs( | ||
| 3049 | mi_cols, | 3123 | mi_cols, |
| 3050 | mi_rows, | 3124 | mi_rows, |
| 3051 | base_q_idx, | 3125 | base_q_idx, |
| 3052 | &superblocks, | 3126 | &superblocks, |
| 3053 | tx_select, | 3127 | tx_select, |
| 3128 | + &mut cdfs, | ||
| 3054 | )?; | 3129 | )?; |
| 3055 | // spec 7.14 deblocking: pick this frame's `loop_filter_level` by handing | 3130 | // spec 7.14 deblocking: pick this frame's `loop_filter_level` by handing |
| 3056 | // the tile just coded back to the decoder under each candidate (see | 3131 | // the tile just coded back to the decoder under each candidate (see |
| @@ -3072,15 +3147,21 @@ pub(crate) fn encode_key_frame_inner( | |||
| 3072 | &mut tile, | 3147 | &mut tile, |
| 3073 | search.lambda, | 3148 | search.lambda, |
| 3074 | fctx, | 3149 | fctx, |
| 3150 | + // Every re-code starts from this frame's OWN starting tables, never | ||
| 3151 | + // from where the first write left them: the second tile is the same | ||
| 3152 | + // symbol sequence plus new ones, so it must adapt from the same | ||
| 3153 | + // point the decoder will. | ||
| 3075 | |bits, sb_cols, grid, units| { | 3154 | |bits, sb_cols, grid, units| { |
| 3076 | crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec()); | 3155 | crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec()); |
| 3077 | crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec()); | 3156 | crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec()); |
| 3078 | - crate::tile::sb_coeff_key_frame_tile_tx( | 3157 | + let mut cdfs = start_cdfs.0.clone(); |
| 3158 | + crate::tile::sb_coeff_key_frame_tile_cdfs( | ||
| 3079 | mi_cols, | 3159 | mi_cols, |
| 3080 | mi_rows, | 3160 | mi_rows, |
| 3081 | base_q_idx, | 3161 | base_q_idx, |
| 3082 | &superblocks, | 3162 | &superblocks, |
| 3083 | tx_select, | 3163 | tx_select, |
| 3164 | + &mut cdfs, | ||
| 3084 | ) | 3165 | ) |
| 3085 | }, | 3166 | }, |
| 3086 | |lf, cdef, h, tile, lr| { | 3167 | |lf, cdef, h, tile, lr| { |
| @@ -3124,6 +3205,8 @@ pub(crate) fn encode_key_frame_inner( | |||
| 3124 | mi_rows: header.mi_rows, | 3205 | mi_rows: header.mi_rows, |
| 3125 | base_q_idx, | 3206 | base_q_idx, |
| 3126 | tx_select, | 3207 | tx_select, |
| 3208 | + next_cdfs: start_cdfs.clone(), | ||
| 3209 | + start_cdfs, | ||
| 3127 | loop_filter: header.loop_filter, | 3210 | loop_filter: header.loop_filter, |
| 3128 | cdef: header.cdef, | 3211 | cdef: header.cdef, |
| 3129 | loop_restoration: header.loop_restoration, | 3212 | loop_restoration: header.loop_restoration, |
| @@ -3483,7 +3566,13 @@ fn search_inter_block( | |||
| 3483 | search: &Search, | 3566 | search: &Search, |
| 3484 | mode_bits: &[f64; 13], | 3567 | mode_bits: &[f64; 13], |
| 3485 | reference: &Picture, | 3568 | reference: &Picture, |
| 3486 | - stack: &MvStack, fctx: &crate::decode::FrameCtx, | 3569 | + stack: &MvStack, |
| 3570 | + // `GOLDEN_FRAME`: the key frame's own reconstruction, held in DPB slot 1 | ||
| 3571 | + // for the whole GOP, with the stack this block derives against it. Only | ||
| 3572 | + // its two search-free modes are priced (`NEARESTMV`, `GLOBALMV`) -- a | ||
| 3573 | + // second motion search would double the wall of the stage that already | ||
| 3574 | + // owns most of it. | ||
| 3575 | + extra: &[(i8, &Picture, &MvStack)], fctx: &crate::decode::FrameCtx, | ||
| 3487 | ) -> (BlockCoeffs, f64) { | 3576 | ) -> (BlockCoeffs, f64) { |
| 3488 | // `luma_set` is the INTRA candidates' table; the two inter candidates | 3577 | // `luma_set` is the INTRA candidates' table; the two inter candidates |
| 3489 | // below price their coefficients through `TxbSet::Luma32Inter`, which is | 3578 | // below price their coefficients through `TxbSet::Luma32Inter`, which is |
| @@ -3496,9 +3585,17 @@ fn search_inter_block( | |||
| 3496 | // function's doc comment. | 3585 | // function's doc comment. |
| 3497 | let skip_bits = |skip: bool| symbol_bits(&cdf::SKIP[0], usize::from(skip)); | 3586 | let skip_bits = |skip: bool| symbol_bits(&cdf::SKIP[0], usize::from(skip)); |
| 3498 | let intra_inter_bits = |inter: bool| symbol_bits(&cdf::INTRA_INTER[0], usize::from(inter)); | 3587 | let intra_inter_bits = |inter: bool| symbol_bits(&cdf::INTRA_INTER[0], usize::from(inter)); |
| 3499 | - let single_ref_bits = symbol_bits(&cdf::SINGLE_REF[0][0], 0) | 3588 | + // `write_single_ref`'s own tree, at the fixed context this pricer uses |
| 3500 | - + symbol_bits(&cdf::SINGLE_REF[0][2], 0) | 3589 | + // for every neighbour-derived symbol: LAST is p1=0,p3=0,p4=0 and GOLDEN |
| 3501 | - + symbol_bits(&cdf::SINGLE_REF[0][3], 0); | 3590 | + // p1=0,p3=1,p5=1. |
| 3591 | + let single_ref_bits = |ref_frame: i8| { | ||
| 3592 | + symbol_bits(&cdf::SINGLE_REF[0][0], 0) | ||
| 3593 | + + if ref_frame == crate::mvstack::GOLDEN_FRAME { | ||
| 3594 | + symbol_bits(&cdf::SINGLE_REF[0][2], 1) + symbol_bits(&cdf::SINGLE_REF[0][4], 1) | ||
| 3595 | + } else { | ||
| 3596 | + symbol_bits(&cdf::SINGLE_REF[0][2], 0) + symbol_bits(&cdf::SINGLE_REF[0][3], 0) | ||
| 3597 | + } | ||
| 3598 | + }; | ||
| 3502 | 3599 | ||
| 3503 | struct Candidate { | 3600 | struct Candidate { |
| 3504 | cost: f64, | 3601 | cost: f64, |
| @@ -3631,100 +3728,72 @@ fn search_inter_block( | |||
| 3631 | chroma[1].true_width, | 3728 | chroma[1].true_width, |
| 3632 | chroma[1].true_height, | 3729 | chroma[1].true_height, |
| 3633 | ); | 3730 | ); |
| 3634 | - let mode_bits_inter = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1) // not NEWMV | 3731 | + // Every single-reference mode the writer can code (spec 5.11.24's symbol |
| 3635 | - + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1) // not zero | 3732 | + // chain, mirrored by `tile::write_inter_mode`), priced with the static |
| 3636 | - + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0); // NEARESTMV | 3733 | + // CDFs at this block's own stack contexts. A candidate is a motion |
| 3637 | - | 3734 | + // vector plus the cheapest syntax that reaches it, so two modes landing |
| 3638 | - // The NEARESTMV candidate: `skip` is decided below from whether its | 3735 | + // on the same vector share one set of trials: the added modes cost |
| 3639 | - // trial actually found a nonzero level, once its residual is priced | 3736 | + // mode-bit arithmetic, not another motion compensation. |
| 3640 | - // against the same CDFs the tile writer codes it with. | 3737 | + let not_new = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1); |
| 3641 | - // | 3738 | + let not_zero = symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1); |
| 3642 | - // lane-av1speed: its three trials are kept (rather than moved straight | 3739 | + // `tile::write_drl_idx`'s cost: one `drl_mode` symbol per stack entry |
| 3643 | - // into the candidate) so that a NEWMV landing on the very same vector -- | 3740 | + // past `start`, `1` to advance and `0` to stop, at most two. A `target` |
| 3644 | - // common on static content, where the stack's nearest vector is also | 3741 | + // the loop cannot reach is never offered below -- every candidate's |
| 3645 | - // what the search finds -- reuses them instead of running the same | 3742 | + // index is one this same loop walks to. |
| 3646 | - // motion compensation, transform, quantize and reconstruct again. The | 3743 | + let drl_bits = |start: usize, target: usize| { |
| 3647 | - // reused trials are the same values, so the choice is bit-identical. | 3744 | + let mut bits = 0.0; |
| 3648 | - let nearest_trials; | 3745 | + let mut idx = start; |
| 3649 | - { | 3746 | + while idx < start + 2 && stack.entries.len() > idx + 1 { |
| 3650 | - let mv = stack.nearest_mv; | 3747 | + let advance = idx < target; |
| 3651 | - let luma_trial = mc_trial( | 3748 | + bits += symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[idx]], usize::from(advance)); |
| 3652 | - luma, | 3749 | + if !advance { |
| 3653 | - x, | 3750 | + break; |
| 3654 | - y, | 3751 | + } |
| 3655 | - BLOCK, | 3752 | + idx += 1; |
| 3656 | - mv, | 3753 | + } |
| 3657 | - true, | 3754 | + bits |
| 3658 | - ref_luma.0, | 3755 | + }; |
| 3659 | - ref_luma.1, | 3756 | + let last_ref_bits = single_ref_bits(crate::mvstack::LAST_FRAME); |
| 3660 | - ref_luma.2, | 3757 | + let mut cands: Vec<((i32, i32), f64, InterInfo)> = vec![ |
| 3661 | - ref_luma.3, | 3758 | + ( |
| 3662 | - false, | 3759 | + stack.nearest_mv, |
| 3663 | - search.base_q_idx, | 3760 | + last_ref_bits + not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0), |
| 3664 | - search.deadzone, | 3761 | + InterInfo { |
| 3665 | - TxbSet::Luma32Inter, fctx, | 3762 | + ref_frame: crate::mvstack::LAST_FRAME, |
| 3666 | - ); | ||
| 3667 | - let u = mc_trial( | ||
| 3668 | - &chroma[0], | ||
| 3669 | - x / 2, | ||
| 3670 | - y / 2, | ||
| 3671 | - BLOCK / 2, | ||
| 3672 | - mv, | ||
| 3673 | - false, | ||
| 3674 | - ref_u.0, | ||
| 3675 | - ref_u.1, | ||
| 3676 | - ref_u.2, | ||
| 3677 | - ref_u.3, | ||
| 3678 | - false, | ||
| 3679 | - search.base_q_idx, | ||
| 3680 | - search.deadzone, | ||
| 3681 | - chroma_set, fctx, | ||
| 3682 | - ); | ||
| 3683 | - let v = mc_trial( | ||
| 3684 | - &chroma[1], | ||
| 3685 | - x / 2, | ||
| 3686 | - y / 2, | ||
| 3687 | - BLOCK / 2, | ||
| 3688 | - mv, | ||
| 3689 | - false, | ||
| 3690 | - ref_v.0, | ||
| 3691 | - ref_v.1, | ||
| 3692 | - ref_v.2, | ||
| 3693 | - ref_v.3, | ||
| 3694 | - false, | ||
| 3695 | - search.base_q_idx, | ||
| 3696 | - search.deadzone, | ||
| 3697 | - chroma_set, fctx, | ||
| 3698 | - ); | ||
| 3699 | - let skip = luma_trial.levels.iter().all(|&l| l == 0) | ||
| 3700 | - && u.levels.iter().all(|&l| l == 0) | ||
| 3701 | - && v.levels.iter().all(|&l| l == 0); | ||
| 3702 | - let cost = luma_trial.sse | ||
| 3703 | - + u.sse | ||
| 3704 | - + v.sse | ||
| 3705 | - + search.lambda | ||
| 3706 | - * (skip_bits(skip) | ||
| 3707 | - + intra_inter_bits(true) | ||
| 3708 | - + single_ref_bits | ||
| 3709 | - + mode_bits_inter | ||
| 3710 | - + if skip { | ||
| 3711 | - 0.0 | ||
| 3712 | - } else { | ||
| 3713 | - luma_trial.bits + u.bits + v.bits | ||
| 3714 | - }); | ||
| 3715 | - nearest_trials = (luma_trial.clone(), u.clone(), v.clone()); | ||
| 3716 | - consider(Candidate { | ||
| 3717 | - cost, | ||
| 3718 | - luma: luma_trial, | ||
| 3719 | - u, | ||
| 3720 | - v, | ||
| 3721 | - mode: DC_PRED, | ||
| 3722 | - skip, | ||
| 3723 | - inter: Some(InterInfo { | ||
| 3724 | mode: InterMode::NearestMv, | 3763 | mode: InterMode::NearestMv, |
| 3725 | - mv, | 3764 | + mv: stack.nearest_mv, |
| 3726 | - }), | 3765 | + ref_mv_idx: 0, |
| 3727 | - }); | 3766 | + }, |
| 3767 | + ), | ||
| 3768 | + // GLOBALMV is the identity model's zero vector -- this encoder writes | ||
| 3769 | + // no `gm_params` -- and the cheapest syntax of the four on the static | ||
| 3770 | + // content where that vector is also the right one. | ||
| 3771 | + ( | ||
| 3772 | + (0, 0), | ||
| 3773 | + last_ref_bits + not_new + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 0), | ||
| 3774 | + InterInfo { | ||
| 3775 | + ref_frame: crate::mvstack::LAST_FRAME, | ||
| 3776 | + mode: InterMode::GlobalMv, | ||
| 3777 | + mv: (0, 0), | ||
| 3778 | + ref_mv_idx: 0, | ||
| 3779 | + }, | ||
| 3780 | + ), | ||
| 3781 | + ]; | ||
| 3782 | + let near_bits = | ||
| 3783 | + last_ref_bits + not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 1); | ||
| 3784 | + for idx in 1..=2usize { | ||
| 3785 | + if let Some(e) = stack.entries.get(idx) { | ||
| 3786 | + cands.push(( | ||
| 3787 | + e.mv, | ||
| 3788 | + near_bits + drl_bits(1, idx), | ||
| 3789 | + InterInfo { | ||
| 3790 | + ref_frame: crate::mvstack::LAST_FRAME, | ||
| 3791 | + mode: InterMode::NearMv, | ||
| 3792 | + mv: e.mv, | ||
| 3793 | + ref_mv_idx: idx as u8, | ||
| 3794 | + }, | ||
| 3795 | + )); | ||
| 3796 | + } | ||
| 3728 | } | 3797 | } |
| 3729 | 3798 | ||
| 3730 | let source_block = luma.source_block(x, y, BLOCK); | 3799 | let source_block = luma.source_block(x, y, BLOCK); |
| @@ -3746,96 +3815,157 @@ fn search_inter_block( | |||
| 3746 | #[cfg(test)] | 3815 | #[cfg(test)] |
| 3747 | stage_add(0, t.elapsed()); | 3816 | stage_add(0, t.elapsed()); |
| 3748 | let mv = round_to_valid_mv(found.mv, stack.pred_mv); | 3817 | let mv = round_to_valid_mv(found.mv, stack.pred_mv); |
| 3749 | - if let Some(mv_bits) = mv_residual_bits(mv, stack.pred_mv) { | 3818 | + // Each DRL entry is a different `PredMv` (spec 7.10.2.10 `assign_mv`), so |
| 3750 | - let (luma_trial, u, v) = if mv == stack.nearest_mv { | 3819 | + // the same vector costs a different residual from each: take the index |
| 3751 | - nearest_trials | 3820 | + // whose residual plus DRL bits is cheapest, not entry 0 by default. |
| 3752 | - } else { | 3821 | + let mut best_new: Option<(f64, u8)> = None; |
| 3753 | - ( | 3822 | + for idx in 0..3usize { |
| 3754 | - mc_trial( | 3823 | + if idx > 0 && stack.entries.len() <= idx { |
| 3755 | - luma, | 3824 | + break; |
| 3756 | - x, | 3825 | + } |
| 3757 | - y, | 3826 | + let base = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv); |
| 3758 | - BLOCK, | 3827 | + if let Some(b) = mv_residual_bits(mv, base) { |
| 3759 | - mv, | 3828 | + let total = b + drl_bits(0, idx); |
| 3760 | - true, | 3829 | + if best_new.is_none_or(|(t, _)| total < t) { |
| 3761 | - ref_luma.0, | 3830 | + best_new = Some((total, idx as u8)); |
| 3762 | - ref_luma.1, | 3831 | + } |
| 3763 | - ref_luma.2, | 3832 | + } |
| 3764 | - ref_luma.3, | 3833 | + } |
| 3765 | - false, | 3834 | + if let Some((bits, ref_mv_idx)) = best_new { |
| 3766 | - search.base_q_idx, | 3835 | + cands.push(( |
| 3767 | - search.deadzone, | 3836 | + mv, |
| 3768 | - TxbSet::Luma32Inter, fctx, | 3837 | + last_ref_bits + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0) + bits, |
| 3769 | - ), | 3838 | + InterInfo { |
| 3770 | - mc_trial( | 3839 | + ref_frame: crate::mvstack::LAST_FRAME, |
| 3771 | - &chroma[0], | ||
| 3772 | - x / 2, | ||
| 3773 | - y / 2, | ||
| 3774 | - BLOCK / 2, | ||
| 3775 | - mv, | ||
| 3776 | - false, | ||
| 3777 | - ref_u.0, | ||
| 3778 | - ref_u.1, | ||
| 3779 | - ref_u.2, | ||
| 3780 | - ref_u.3, | ||
| 3781 | - false, | ||
| 3782 | - search.base_q_idx, | ||
| 3783 | - search.deadzone, | ||
| 3784 | - chroma_set, fctx, | ||
| 3785 | - ), | ||
| 3786 | - mc_trial( | ||
| 3787 | - &chroma[1], | ||
| 3788 | - x / 2, | ||
| 3789 | - y / 2, | ||
| 3790 | - BLOCK / 2, | ||
| 3791 | - mv, | ||
| 3792 | - false, | ||
| 3793 | - ref_v.0, | ||
| 3794 | - ref_v.1, | ||
| 3795 | - ref_v.2, | ||
| 3796 | - ref_v.3, | ||
| 3797 | - false, | ||
| 3798 | - search.base_q_idx, | ||
| 3799 | - search.deadzone, | ||
| 3800 | - chroma_set, fctx, | ||
| 3801 | - ), | ||
| 3802 | - ) | ||
| 3803 | - }; | ||
| 3804 | - let drl_bits = if stack.entries.len() > 1 { | ||
| 3805 | - symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[0]], 0) | ||
| 3806 | - } else { | ||
| 3807 | - 0.0 | ||
| 3808 | - }; | ||
| 3809 | - let skip = luma_trial.levels.iter().all(|&l| l == 0) | ||
| 3810 | - && u.levels.iter().all(|&l| l == 0) | ||
| 3811 | - && v.levels.iter().all(|&l| l == 0); | ||
| 3812 | - let cost = luma_trial.sse | ||
| 3813 | - + u.sse | ||
| 3814 | - + v.sse | ||
| 3815 | - + search.lambda | ||
| 3816 | - * (skip_bits(skip) | ||
| 3817 | - + intra_inter_bits(true) | ||
| 3818 | - + single_ref_bits | ||
| 3819 | - + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0) | ||
| 3820 | - + drl_bits | ||
| 3821 | - + mv_bits | ||
| 3822 | - + if skip { | ||
| 3823 | - 0.0 | ||
| 3824 | - } else { | ||
| 3825 | - luma_trial.bits + u.bits + v.bits | ||
| 3826 | - }); | ||
| 3827 | - consider(Candidate { | ||
| 3828 | - cost, | ||
| 3829 | - luma: luma_trial, | ||
| 3830 | - u, | ||
| 3831 | - v, | ||
| 3832 | - mode: DC_PRED, | ||
| 3833 | - skip, | ||
| 3834 | - inter: Some(InterInfo { | ||
| 3835 | mode: InterMode::NewMv, | 3840 | mode: InterMode::NewMv, |
| 3836 | mv, | 3841 | mv, |
| 3837 | - }), | 3842 | + ref_mv_idx, |
| 3838 | - }); | 3843 | + }, |
| 3844 | + )); | ||
| 3845 | + } | ||
| 3846 | + | ||
| 3847 | + for &(ref_frame, _, gstack) in extra { | ||
| 3848 | + let g_ref_bits = single_ref_bits(ref_frame); | ||
| 3849 | + let g_not_new = symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 1); | ||
| 3850 | + cands.push(( | ||
| 3851 | + gstack.nearest_mv, | ||
| 3852 | + g_ref_bits | ||
| 3853 | + + g_not_new | ||
| 3854 | + + symbol_bits(&cdf::ZERO_MV[gstack.zero_mv_ctx], 1) | ||
| 3855 | + + symbol_bits(&cdf::REF_MV[gstack.ref_mv_ctx], 0), | ||
| 3856 | + InterInfo { | ||
| 3857 | + ref_frame, | ||
| 3858 | + mode: InterMode::NearestMv, | ||
| 3859 | + mv: gstack.nearest_mv, | ||
| 3860 | + ref_mv_idx: 0, | ||
| 3861 | + }, | ||
| 3862 | + )); | ||
| 3863 | + cands.push(( | ||
| 3864 | + (0, 0), | ||
| 3865 | + g_ref_bits + g_not_new + symbol_bits(&cdf::ZERO_MV[gstack.zero_mv_ctx], 0), | ||
| 3866 | + InterInfo { | ||
| 3867 | + ref_frame, | ||
| 3868 | + mode: InterMode::GlobalMv, | ||
| 3869 | + mv: (0, 0), | ||
| 3870 | + ref_mv_idx: 0, | ||
| 3871 | + }, | ||
| 3872 | + )); | ||
| 3873 | + } | ||
| 3874 | + | ||
| 3875 | + // One trial set per distinct (reference, vector) pair: sort, cheapest | ||
| 3876 | + // syntax first, and drop the rest of each pair's run. | ||
| 3877 | + cands.sort_by(|a, b| { | ||
| 3878 | + (a.2.ref_frame, a.0) | ||
| 3879 | + .cmp(&(b.2.ref_frame, b.0)) | ||
| 3880 | + .then(a.1.total_cmp(&b.1)) | ||
| 3881 | + }); | ||
| 3882 | + cands.dedup_by_key(|c| (c.2.ref_frame, c.0)); | ||
| 3883 | + { | ||
| 3884 | + for (mv, mode_bits_inter, info) in cands { | ||
| 3885 | + let (ref_luma, ref_u, ref_v) = match extra | ||
| 3886 | + .iter() | ||
| 3887 | + .find(|(r, _, _)| *r == info.ref_frame) | ||
| 3888 | + { | ||
| 3889 | + Some(&(_, g, _)) => ( | ||
| 3890 | + (&g.y, g.width, luma.true_width, luma.true_height), | ||
| 3891 | + (&g.u, g.width / 2, chroma[0].true_width, chroma[0].true_height), | ||
| 3892 | + (&g.v, g.width / 2, chroma[1].true_width, chroma[1].true_height), | ||
| 3893 | + ), | ||
| 3894 | + None => (ref_luma, ref_u, ref_v), | ||
| 3895 | + }; | ||
| 3896 | + let luma_trial = mc_trial( | ||
| 3897 | + luma, | ||
| 3898 | + x, | ||
| 3899 | + y, | ||
| 3900 | + BLOCK, | ||
| 3901 | + mv, | ||
| 3902 | + true, | ||
| 3903 | + ref_luma.0, | ||
| 3904 | + ref_luma.1, | ||
| 3905 | + ref_luma.2, | ||
| 3906 | + ref_luma.3, | ||
| 3907 | + false, | ||
| 3908 | + search.base_q_idx, | ||
| 3909 | + search.deadzone, | ||
| 3910 | + TxbSet::Luma32Inter, fctx, | ||
| 3911 | + ); | ||
| 3912 | + let u = mc_trial( | ||
| 3913 | + &chroma[0], | ||
| 3914 | + x / 2, | ||
| 3915 | + y / 2, | ||
| 3916 | + BLOCK / 2, | ||
| 3917 | + mv, | ||
| 3918 | + false, | ||
| 3919 | + ref_u.0, | ||
| 3920 | + ref_u.1, | ||
| 3921 | + ref_u.2, | ||
| 3922 | + ref_u.3, | ||
| 3923 | + false, | ||
| 3924 | + search.base_q_idx, | ||
| 3925 | + search.deadzone, | ||
| 3926 | + chroma_set, fctx, | ||
| 3927 | + ); | ||
| 3928 | + let v = mc_trial( | ||
| 3929 | + &chroma[1], | ||
| 3930 | + x / 2, | ||
| 3931 | + y / 2, | ||
| 3932 | + BLOCK / 2, | ||
| 3933 | + mv, | ||
| 3934 | + false, | ||
| 3935 | + ref_v.0, | ||
| 3936 | + ref_v.1, | ||
| 3937 | + ref_v.2, | ||
| 3938 | + ref_v.3, | ||
| 3939 | + false, | ||
| 3940 | + search.base_q_idx, | ||
| 3941 | + search.deadzone, | ||
| 3942 | + chroma_set, fctx, | ||
| 3943 | + ); | ||
| 3944 | + let skip = luma_trial.levels.iter().all(|&l| l == 0) | ||
| 3945 | + && u.levels.iter().all(|&l| l == 0) | ||
| 3946 | + && v.levels.iter().all(|&l| l == 0); | ||
| 3947 | + let cost = luma_trial.sse | ||
| 3948 | + + u.sse | ||
| 3949 | + + v.sse | ||
| 3950 | + + search.lambda | ||
| 3951 | + * (skip_bits(skip) | ||
| 3952 | + + intra_inter_bits(true) | ||
| 3953 | + + mode_bits_inter | ||
| 3954 | + + if skip { | ||
| 3955 | + 0.0 | ||
| 3956 | + } else { | ||
| 3957 | + luma_trial.bits + u.bits + v.bits | ||
| 3958 | + }); | ||
| 3959 | + consider(Candidate { | ||
| 3960 | + cost, | ||
| 3961 | + luma: luma_trial, | ||
| 3962 | + u, | ||
| 3963 | + v, | ||
| 3964 | + mode: DC_PRED, | ||
| 3965 | + skip, | ||
| 3966 | + inter: Some(info), | ||
| 3967 | + }); | ||
| 3968 | + } | ||
| 3839 | } | 3969 | } |
| 3840 | 3970 | ||
| 3841 | let best = best.expect("the search offers at least the intra modes"); | 3971 | let best = best.expect("the search offers at least the intra modes"); |
| @@ -3867,7 +3997,20 @@ pub(crate) fn encode_inter_frame( | |||
| 3867 | base_q_idx: u8, | 3997 | base_q_idx: u8, |
| 3868 | deadzone: f64, | 3998 | deadzone: f64, |
| 3869 | order_hint: u32, | 3999 | order_hint: u32, |
| 3870 | - render: (usize, usize), fctx: &crate::decode::FrameCtx, | 4000 | + render: (usize, usize), |
| 4001 | + // The tables this frame's writer starts from: what the previous frame | ||
| 4002 | + // stored into the slot this one's `primary_ref_frame` names. `None` | ||
| 4003 | + // starts from the defaults, which is right only for the frame straight | ||
| 4004 | + // after a key frame. | ||
| 4005 | + start_cdfs: Option<&crate::cdf_state::Cdfs>, | ||
| 4006 | + // The key frame's own (padded) reconstruction, which every frame of the | ||
| 4007 | + // GOP still holds in DPB slot 1 -- `GOLDEN_FRAME`. `None` codes the frame | ||
| 4008 | + // with `LAST_FRAME` alone, exactly as before. | ||
| 4009 | + golden: Option<&Picture>, | ||
| 4010 | + // The frame two back, held in the slot this frame is about to refresh | ||
| 4011 | + // (the encoder alternates 0/2): `ALTREF_FRAME`. `None` for the first two | ||
| 4012 | + // inter frames of a GOP, where the frame two back IS the key frame. | ||
| 4013 | + altref: Option<&Picture>, fctx: &crate::decode::FrameCtx, | ||
| 3871 | ) -> Result<Encoded> { | 4014 | ) -> Result<Encoded> { |
| 3872 | picture.check()?; | 4015 | picture.check()?; |
| 3873 | if !picture.width.is_multiple_of(SUPERBLOCK) || !picture.height.is_multiple_of(SUPERBLOCK) { | 4016 | if !picture.width.is_multiple_of(SUPERBLOCK) || !picture.height.is_multiple_of(SUPERBLOCK) { |
| @@ -3890,14 +4033,33 @@ pub(crate) fn encode_inter_frame( | |||
| 3890 | // overwrites slot 0, so the frame just coded is always what the next one | 4033 | // overwrites slot 0, so the frame just coded is always what the next one |
| 3891 | // predicts against. | 4034 | // predicts against. |
| 3892 | const LAST_SLOT: u8 = 0; | 4035 | const LAST_SLOT: u8 = 0; |
| 4036 | + // Slot 0 and slot 2 alternate so the frame two back survives one more | ||
| 4037 | + // frame: frame n writes A(n) = 0 for odd n, 2 for even, so A(n) = A(n-2) | ||
| 4038 | + // and the picture this frame names as `ALTREF_FRAME` is the one sitting | ||
| 4039 | + // in the very slot it will overwrite. | ||
| 4040 | + let self_slot = if order_hint % 2 == 1 { 0 } else { 2 }; | ||
| 4041 | + let last_slot = if order_hint <= 1 { | ||
| 4042 | + LAST_SLOT | ||
| 4043 | + } else if (order_hint - 1) % 2 == 1 { | ||
| 4044 | + 0 | ||
| 4045 | + } else { | ||
| 4046 | + 2 | ||
| 4047 | + }; | ||
| 3893 | // `render`, not `picture.width`/`picture.height`: `picture` here is | 4048 | // `render`, not `picture.width`/`picture.height`: `picture` here is |
| 3894 | // already padded to a whole number of superblocks (`encode_sequence`'s | 4049 | // already padded to a whole number of superblocks (`encode_sequence`'s |
| 3895 | // `padded_to(SUPERBLOCK)`), and the header's `mi_cols`/`mi_rows` (and so | 4050 | // `padded_to(SUPERBLOCK)`), and the header's `mi_cols`/`mi_rows` (and so |
| 3896 | // every true-edge clamp downstream) must come from the frame's real, | 4051 | // every true-edge clamp downstream) must come from the frame's real, |
| 3897 | // unpadded size, same as `key_frame_headers_colour` takes `render` and | 4052 | // unpadded size, same as `key_frame_headers_colour` takes `render` and |
| 3898 | // not the padded picture in `encode_key_frame_inner`. | 4053 | // not the padded picture in `encode_key_frame_inner`. |
| 3899 | - let (seq, mut header) = | 4054 | + let (seq, mut header) = inter_frame_headers_slots( |
| 3900 | - inter_frame_headers(render.0, render.1, base_q_idx, order_hint, LAST_SLOT)?; | 4055 | + render.0, |
| 4056 | + render.1, | ||
| 4057 | + base_q_idx, | ||
| 4058 | + order_hint, | ||
| 4059 | + last_slot, | ||
| 4060 | + self_slot, | ||
| 4061 | + if altref.is_some() { self_slot } else { GOLDEN_SLOT }, | ||
| 4062 | + )?; | ||
| 3901 | header.render_width = render.0 as u32; | 4063 | header.render_width = render.0 as u32; |
| 3902 | header.render_height = render.1 as u32; | 4064 | header.render_height = render.1 as u32; |
| 3903 | // `TxMode::Select` here too: an inter block then codes one `txfm_split` | 4065 | // `TxMode::Select` here too: an inter block then codes one `txfm_split` |
| @@ -4002,6 +4164,25 @@ pub(crate) fn encode_inter_frame( | |||
| 4002 | let (mi_row, mi_col) = (r32 * 8, c32 * 8); | 4164 | let (mi_row, mi_col) = (r32 * 8, c32 * 8); |
| 4003 | let stack = | 4165 | let stack = |
| 4004 | find_mv_stack(&grid, mi_row, mi_col, 8, 8, LAST_FRAME, mi_cols, mi_rows); | 4166 | find_mv_stack(&grid, mi_row, mi_col, 8, 8, LAST_FRAME, mi_cols, mi_rows); |
| 4167 | + let extra_stacks: Vec<(i8, &Picture, MvStack)> = [ | ||
| 4168 | + (crate::mvstack::GOLDEN_FRAME, golden), | ||
| 4169 | + (crate::mvstack::ALTREF_FRAME, altref), | ||
| 4170 | + ] | ||
| 4171 | + .into_iter() | ||
| 4172 | + .filter_map(|(r, pic)| { | ||
| 4173 | + pic.map(|p| { | ||
| 4174 | + ( | ||
| 4175 | + r, | ||
| 4176 | + p, | ||
| 4177 | + find_mv_stack(&grid, mi_row, mi_col, 8, 8, r, mi_cols, mi_rows), | ||
| 4178 | + ) | ||
| 4179 | + }) | ||
| 4180 | + }) | ||
| 4181 | + .collect(); | ||
| 4182 | + let extra: Vec<(i8, &Picture, &MvStack)> = extra_stacks | ||
| 4183 | + .iter() | ||
| 4184 | + .map(|(r, p, st)| (*r, *p, st)) | ||
| 4185 | + .collect(); | ||
| 4005 | 4186 | ||
| 4006 | let base = snapshot(&luma, &chroma, (x, y), BLOCK); | 4187 | let base = snapshot(&luma, &chroma, (x, y), BLOCK); |
| 4007 | let (block, mut cost_whole) = search_inter_block( | 4188 | let (block, mut cost_whole) = search_inter_block( |
| @@ -4011,7 +4192,8 @@ pub(crate) fn encode_inter_frame( | |||
| 4011 | &search, | 4192 | &search, |
| 4012 | &mode_bits_table, | 4193 | &mode_bits_table, |
| 4013 | reference, | 4194 | reference, |
| 4014 | - &stack, fctx, | 4195 | + &stack, |
| 4196 | + &extra, fctx, | ||
| 4015 | ); | 4197 | ); |
| 4016 | cost_whole += search.lambda * partition_bits(BLOCK, false); | 4198 | cost_whole += search.lambda * partition_bits(BLOCK, false); |
| 4017 | let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK); | 4199 | let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK); |
| @@ -4331,13 +4513,22 @@ pub(crate) fn encode_inter_frame( | |||
| 4331 | / modes.len() as f64; | 4513 | / modes.len() as f64; |
| 4332 | #[cfg(test)] | 4514 | #[cfg(test)] |
| 4333 | record_predicted_bits(crate::tile::predicted_coeff_bits(&blocks, base_q_idx)); | 4515 | record_predicted_bits(crate::tile::predicted_coeff_bits(&blocks, base_q_idx)); |
| 4516 | + // This frame's header leaves `disable_frame_end_update_cdf` off, so it | ||
| 4517 | + // stores its end-of-tile tables with the counts reset (spec 7.20) and the | ||
| 4518 | + // next frame's writer starts from them -- exactly what | ||
| 4519 | + // `crate::stream::stored_cdfs_for` hands the decoder. | ||
| 4334 | let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows); | 4520 | let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows); |
| 4335 | - let mut tile = crate::tile::sb_coeff_inter_frame_tile_tx( | 4521 | + let mut cdfs = start_cdfs |
| 4522 | + .cloned() | ||
| 4523 | + .unwrap_or_else(|| crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx))); | ||
| 4524 | + let start_cdfs = CdfSnapshot(cdfs.clone()); | ||
| 4525 | + let mut tile = crate::tile::sb_coeff_inter_frame_tile_cdfs( | ||
| 4336 | mi_cols, | 4526 | mi_cols, |
| 4337 | mi_rows, | 4527 | mi_rows, |
| 4338 | base_q_idx, | 4528 | base_q_idx, |
| 4339 | &blocks, | 4529 | &blocks, |
| 4340 | tx_select, | 4530 | tx_select, |
| 4531 | + &mut cdfs, | ||
| 4341 | )?; | 4532 | )?; |
| 4342 | // Deblocking, as in `encode_key_frame_inner`: the decoder reconstructs | 4533 | // Deblocking, as in `encode_key_frame_inner`: the decoder reconstructs |
| 4343 | // this tile against the same single-slot reference this encoder predicted | 4534 | // this tile against the same single-slot reference this encoder predicted |
| @@ -4347,6 +4538,7 @@ pub(crate) fn encode_inter_frame( | |||
| 4347 | // reference whose height is not the header's own `frame_height` (spec | 4538 | // reference whose height is not the header's own `frame_height` (spec |
| 4348 | // 7.9's compatible-size rule), and the chained-decode round trips prove | 4539 | // 7.9's compatible-size rule), and the chained-decode round trips prove |
| 4349 | // the two predict identically. | 4540 | // the two predict identically. |
| 4541 | + let end_cdfs = std::cell::RefCell::new(cdfs); | ||
| 4350 | let (fw, fh) = (header.frame_width as usize, header.frame_height as usize); | 4542 | let (fw, fh) = (header.frame_width as usize, header.frame_height as usize); |
| 4351 | let trial_ref = if (reference.width, reference.height) == (fw, fh) { | 4543 | let trial_ref = if (reference.width, reference.height) == (fw, fh) { |
| 4352 | reference.clone() | 4544 | reference.clone() |
| @@ -4359,8 +4551,39 @@ pub(crate) fn encode_inter_frame( | |||
| 4359 | v: crop_plane(&reference.v, reference.width / 2, fw / 2, fh / 2), | 4551 | v: crop_plane(&reference.v, reference.width / 2, fw / 2, fh / 2), |
| 4360 | } | 4552 | } |
| 4361 | }; | 4553 | }; |
| 4554 | + // `RefPix` is indexed by the reference NAME (`LAST_FRAME` = 1, | ||
| 4555 | + // `GOLDEN_FRAME` = 4), not by DPB slot: the trial decode of a frame whose | ||
| 4556 | + // blocks may name GOLDEN needs that plane too, cropped the same way. | ||
| 4557 | + let trial_golden = golden.map(|g| { | ||
| 4558 | + if (g.width, g.height) == (fw, fh) { | ||
| 4559 | + g.clone() | ||
| 4560 | + } else { | ||
| 4561 | + Picture { | ||
| 4562 | + width: fw, | ||
| 4563 | + height: fh, | ||
| 4564 | + y: crop_plane(&g.y, g.width, fw, fh), | ||
| 4565 | + u: crop_plane(&g.u, g.width / 2, fw / 2, fh / 2), | ||
| 4566 | + v: crop_plane(&g.v, g.width / 2, fw / 2, fh / 2), | ||
| 4567 | + } | ||
| 4568 | + } | ||
| 4569 | + }); | ||
| 4570 | + let trial_altref = altref.map(|a| { | ||
| 4571 | + if (a.width, a.height) == (fw, fh) { | ||
| 4572 | + a.clone() | ||
| 4573 | + } else { | ||
| 4574 | + Picture { | ||
| 4575 | + width: fw, | ||
| 4576 | + height: fh, | ||
| 4577 | + y: crop_plane(&a.y, a.width, fw, fh), | ||
| 4578 | + u: crop_plane(&a.u, a.width / 2, fw / 2, fh / 2), | ||
| 4579 | + v: crop_plane(&a.v, a.width / 2, fw / 2, fh / 2), | ||
| 4580 | + } | ||
| 4581 | + } | ||
| 4582 | + }); | ||
| 4362 | let mut refs: [Option<&Picture>; 8] = [None; 8]; | 4583 | let mut refs: [Option<&Picture>; 8] = [None; 8]; |
| 4363 | refs[1] = Some(&trial_ref); | 4584 | refs[1] = Some(&trial_ref); |
| 4585 | + refs[4] = trial_golden.as_ref(); | ||
| 4586 | + refs[7] = trial_altref.as_ref(); | ||
| 4364 | let refpix = crate::decode::RefPix::ready(refs); | 4587 | let refpix = crate::decode::RefPix::ready(refs); |
| 4365 | // The luma restoration-unit grid this frame's `lr_params` implies | 4588 | // The luma restoration-unit grid this frame's `lr_params` implies |
| 4366 | // (`av1_lr_count_units` rounds to nearest, so a short last unit is | 4589 | // (`av1_lr_count_units` rounds to nearest, so a short last unit is |
| @@ -4381,16 +4604,26 @@ pub(crate) fn encode_inter_frame( | |||
| 4381 | &mut tile, | 4604 | &mut tile, |
| 4382 | search.lambda, | 4605 | search.lambda, |
| 4383 | fctx, | 4606 | fctx, |
| 4607 | + // As in `encode_key_frame_inner`, but this frame's end-of-tile tables | ||
| 4608 | + // are what the NEXT frame writes from, so the winning re-code | ||
| 4609 | + // publishes its own into `end_cdfs` -- the first write's are stale | ||
| 4610 | + // the moment a second tile is coded. | ||
| 4384 | |bits, sb_cols, grid, units| { | 4611 | |bits, sb_cols, grid, units| { |
| 4385 | crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec()); | 4612 | crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec()); |
| 4386 | crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec()); | 4613 | crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec()); |
| 4387 | - crate::tile::sb_coeff_inter_frame_tile_tx( | 4614 | + let mut cdfs = start_cdfs.0.clone(); |
| 4615 | + let coded = crate::tile::sb_coeff_inter_frame_tile_cdfs( | ||
| 4388 | mi_cols, | 4616 | mi_cols, |
| 4389 | mi_rows, | 4617 | mi_rows, |
| 4390 | base_q_idx, | 4618 | base_q_idx, |
| 4391 | &blocks, | 4619 | &blocks, |
| 4392 | tx_select, | 4620 | tx_select, |
| 4393 | - ) | 4621 | + &mut cdfs, |
| 4622 | + ); | ||
| 4623 | + if coded.is_ok() { | ||
| 4624 | + *end_cdfs.borrow_mut() = cdfs; | ||
| 4625 | + } | ||
| 4626 | + coded | ||
| 4394 | }, | 4627 | }, |
| 4395 | |lf, cdef, h, tile, lr| { | 4628 | |lf, cdef, h, tile, lr| { |
| 4396 | crate::decode::decode_inter_frame_tile_lr( | 4629 | crate::decode::decode_inter_frame_tile_lr( |
| @@ -4410,10 +4643,17 @@ pub(crate) fn encode_inter_frame( | |||
| 4410 | h.reference_select, | 4643 | h.reference_select, |
| 4411 | tx_select, | 4644 | tx_select, |
| 4412 | lr, | 4645 | lr, |
| 4646 | + // The trial decode re-reads the tile the writer just wrote, | ||
| 4647 | + // so it starts from the same tables the writer did (this | ||
| 4648 | + // frame's `start_cdfs`), not from the defaults. | ||
| 4649 | + Some(start_cdfs.0.clone()), | ||
| 4413 | fctx, | 4650 | fctx, |
| 4414 | ) | 4651 | ) |
| 4415 | }, | 4652 | }, |
| 4416 | )?; | 4653 | )?; |
| 4654 | + let mut cdfs = end_cdfs.into_inner(); | ||
| 4655 | + cdfs.reset_counts(); | ||
| 4656 | + let next_cdfs = CdfSnapshot(cdfs); | ||
| 4417 | let mut stream = temporal_delimiter(); | 4657 | let mut stream = temporal_delimiter(); |
| 4418 | stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?); | 4658 | stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?); |
| 4419 | 4659 | ||
| @@ -4434,6 +4674,8 @@ pub(crate) fn encode_inter_frame( | |||
| 4434 | mi_rows: header.mi_rows, | 4674 | mi_rows: header.mi_rows, |
| 4435 | base_q_idx, | 4675 | base_q_idx, |
| 4436 | tx_select, | 4676 | tx_select, |
| 4677 | + start_cdfs, | ||
| 4678 | + next_cdfs, | ||
| 4437 | loop_filter: header.loop_filter, | 4679 | loop_filter: header.loop_filter, |
| 4438 | cdef: header.cdef, | 4680 | cdef: header.cdef, |
| 4439 | loop_restoration: header.loop_restoration, | 4681 | loop_restoration: header.loop_restoration, |
| @@ -4495,6 +4737,14 @@ pub(crate) fn encode_sequence_with_ctx( | |||
| 4495 | unspecified_color_config(), fctx, | 4737 | unspecified_color_config(), fctx, |
| 4496 | )?; | 4738 | )?; |
| 4497 | let mut stream = key.stream.clone(); | 4739 | let mut stream = key.stream.clone(); |
| 4740 | + // Slot 1 keeps the key frame's own reconstruction for the whole GOP (the | ||
| 4741 | + // key frame refreshes every slot, each inter frame only slot 0), which is | ||
| 4742 | + // what `GOLDEN_FRAME` names. | ||
| 4743 | + let golden = key.reconstruction.clone(); | ||
| 4744 | + // The frame two back, once there is one that is not the key frame | ||
| 4745 | + // itself (which `GOLDEN_FRAME` already names). | ||
| 4746 | + let mut prev2: Option<Picture> = None; | ||
| 4747 | + let mut carried = key.next_cdfs.clone(); | ||
| 4498 | let mut reference = key.reconstruction.clone(); | 4748 | let mut reference = key.reconstruction.clone(); |
| 4499 | let mut frames = vec![crop_encoded(&key, render.0, render.1)]; | 4749 | let mut frames = vec![crop_encoded(&key, render.0, render.1)]; |
| 4500 | for (i, picture) in rest.iter().enumerate() { | 4750 | for (i, picture) in rest.iter().enumerate() { |
| @@ -4512,10 +4762,17 @@ pub(crate) fn encode_sequence_with_ctx( | |||
| 4512 | base_q_idx, | 4762 | base_q_idx, |
| 4513 | deadzone, | 4763 | deadzone, |
| 4514 | order_hint, | 4764 | order_hint, |
| 4515 | - render, fctx, | 4765 | + render, |
| 4766 | + Some(&carried.0), | ||
| 4767 | + Some(&golden), | ||
| 4768 | + prev2.as_ref(), fctx, | ||
| 4516 | )?; | 4769 | )?; |
| 4517 | stream.extend_from_slice(&inter.stream); | 4770 | stream.extend_from_slice(&inter.stream); |
| 4518 | - reference = inter.reconstruction.clone(); | 4771 | + carried = inter.next_cdfs.clone(); |
| 4772 | + prev2 = Some(std::mem::replace( | ||
| 4773 | + &mut reference, | ||
| 4774 | + inter.reconstruction.clone(), | ||
| 4775 | + )); | ||
| 4519 | frames.push(crop_encoded(&inter, render.0, render.1)); | 4776 | frames.push(crop_encoded(&inter, render.0, render.1)); |
| 4520 | } | 4777 | } |
| 4521 | Ok(EncodedSequence { stream, frames }) | 4778 | Ok(EncodedSequence { stream, frames }) |
| @@ -4925,15 +5182,19 @@ mod tests { | |||
| 4925 | eight: None, | 5182 | eight: None, |
| 4926 | tx_depth: 0, | 5183 | tx_depth: 0, |
| 4927 | inter: Some(InterInfo { | 5184 | inter: Some(InterInfo { |
| 5185 | + ref_frame: crate::mvstack::LAST_FRAME, | ||
| 4928 | mode: InterMode::NearestMv, | 5186 | mode: InterMode::NearestMv, |
| 4929 | mv: (0, 0), | 5187 | mv: (0, 0), |
| 5188 | + ref_mv_idx: 0, | ||
| 4930 | }), | 5189 | }), |
| 4931 | }; | 5190 | }; |
| 4932 | let skipped_block = BlockCoeffs { | 5191 | let skipped_block = BlockCoeffs { |
| 4933 | skip: true, | 5192 | skip: true, |
| 4934 | inter: Some(InterInfo { | 5193 | inter: Some(InterInfo { |
| 5194 | + ref_frame: crate::mvstack::LAST_FRAME, | ||
| 4935 | mode: InterMode::NearestMv, | 5195 | mode: InterMode::NearestMv, |
| 4936 | mv: (0, 0), | 5196 | mv: (0, 0), |
| 5197 | + ref_mv_idx: 0, | ||
| 4937 | }), | 5198 | }), |
| 4938 | ..BlockCoeffs::default() | 5199 | ..BlockCoeffs::default() |
| 4939 | }; | 5200 | }; |
| @@ -6544,7 +6805,7 @@ mod tests { | |||
| 6544 | let padded_pic = picture.padded_to(SUPERBLOCK); | 6805 | let padded_pic = picture.padded_to(SUPERBLOCK); |
| 6545 | let t = Instant::now(); | 6806 | let t = Instant::now(); |
| 6546 | let inter = | 6807 | let inter = |
| 6547 | - encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, (width, height), fctx).unwrap(); | 6808 | + encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, (width, height), None, None, None, fctx).unwrap(); |
| 6548 | let inter_t = t.elapsed(); | 6809 | let inter_t = t.elapsed(); |
| 6549 | eprintln!( | 6810 | eprintln!( |
| 6550 | "inter frame vs its own key frame: {inter_t:>9.2?} ({} bytes, inter share \ | 6811 | "inter frame vs its own key frame: {inter_t:>9.2?} ({} bytes, inter share \ |
| @@ -6642,7 +6903,7 @@ mod tests { | |||
| 6642 | stage_reset(); | 6903 | stage_reset(); |
| 6643 | let t = Instant::now(); | 6904 | let t = Instant::now(); |
| 6644 | let inter = | 6905 | let inter = |
| 6645 | - encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, (width, height), fctx).unwrap(); | 6906 | + encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, (width, height), None, None, None, fctx).unwrap(); |
| 6646 | let total_t = t.elapsed(); | 6907 | let total_t = t.elapsed(); |
| 6647 | let [motion_search, interpolation, transform_quant, entropy] = stage_read(); | 6908 | let [motion_search, interpolation, transform_quant, entropy] = stage_read(); |
| 6648 | let accounted = motion_search + transform_quant + entropy; | 6909 | let accounted = motion_search + transform_quant + entropy; |
| @@ -6819,7 +7080,7 @@ mod tests { | |||
| 6819 | q, | 7080 | q, |
| 6820 | 0.5, | 7081 | 0.5, |
| 6821 | 1, | 7082 | 1, |
| 6822 | - (width, height), fctx, | 7083 | + (width, height), None, None, None, fctx, |
| 6823 | ) | 7084 | ) |
| 6824 | .unwrap(); | 7085 | .unwrap(); |
| 6825 | let baseline_psnr = psnr(&baseline.reconstruction.y, &inter_source.y); | 7086 | let baseline_psnr = psnr(&baseline.reconstruction.y, &inter_source.y); |
| @@ -6836,7 +7097,7 @@ mod tests { | |||
| 6836 | q, | 7097 | q, |
| 6837 | 0.5, | 7098 | 0.5, |
| 6838 | 1, | 7099 | 1, |
| 6839 | - (width, height), fctx, | 7100 | + (width, height), None, None, None, fctx, |
| 6840 | ) | 7101 | ) |
| 6841 | .unwrap(); | 7102 | .unwrap(); |
| 6842 | let pruned_psnr = psnr(&pruned.reconstruction.y, &inter_source.y); | 7103 | let pruned_psnr = psnr(&pruned.reconstruction.y, &inter_source.y); |
| @@ -7221,6 +7482,12 @@ mod tests { | |||
| 7221 | /// | 7482 | /// |
| 7222 | /// The BD gate above measures quality, which a speed lane can move by a | 7483 | /// The BD gate above measures quality, which a speed lane can move by a |
| 7223 | /// hair without failing anything; this pins the streams themselves. | 7484 | /// hair without failing anything; this pins the streams themselves. |
| 7485 | + /// Re-measured on the lane-av1lr merge with main d5fc99e0: the per-64x64 | ||
| 7486 | + /// `cdef_idx` literals and the per-unit loop restoration syntax are new | ||
| 7487 | + /// bits in the tile, so the streams move (q=150 7416 -> 7458 bytes, | ||
| 7488 | + /// q=60 27927 -> 27807 -- the low-rate frame pays for the syntax, the | ||
| 7489 | + /// high-rate one more than earns it back). | ||
| 7490 | + /// | ||
| 7224 | /// Every number below was measured 2026-09-06: first on lane-av1fwd | 7491 | /// Every number below was measured 2026-09-06: first on lane-av1fwd |
| 7225 | /// (whose three speed steps left them identical to `a6649c4e`'s), then | 7492 | /// (whose three speed steps left them identical to `a6649c4e`'s), then |
| 7226 | /// re-measured on the lane-av1lr merge, which legitimately moves them -- | 7493 | /// re-measured on the lane-av1lr merge, which legitimately moves them -- |
| @@ -7248,7 +7515,7 @@ mod tests { | |||
| 7248 | }) | 7515 | }) |
| 7249 | }; | 7516 | }; |
| 7250 | let pins: [(u8, usize, u64); 2] = | 7517 | let pins: [(u8, usize, u64); 2] = |
| 7251 | - [(150, 7796, 0x70db_e81d_606b_034c), (60, 28182, 0xb23d_005b_1f2e_e008)]; | 7518 | + [(150, 7458, 0x7eb2_33c6_bd96_3baf), (60, 27807, 0xeee0_f1e5_e099_46bd)]; |
| 7252 | for (q, bytes, hash) in pins { | 7519 | for (q, bytes, hash) in pins { |
| 7253 | let encoded = encode_sequence(&source, q, 0.5).unwrap(); | 7520 | let encoded = encode_sequence(&source, q, 0.5).unwrap(); |
| 7254 | assert_eq!( | 7521 | assert_eq!( |
| @@ -7409,11 +7676,34 @@ mod tests { | |||
| 7409 | let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames); | 7676 | let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames); |
| 7410 | let _ = take_partition_hits(); | 7677 | let _ = take_partition_hits(); |
| 7411 | let _ = take_uv_mode_hits(); | 7678 | let _ = take_uv_mode_hits(); |
| 7679 | + let _ = crate::tile::take_inter_mode_hits(); | ||
| 7680 | + let _ = crate::tile::take_drl_hits(); | ||
| 7681 | + let _ = crate::tile::take_ref_hits(); | ||
| 7412 | let (ours, ours_wall) = our_ladder(&source, width, height, fctx); | 7682 | let (ours, ours_wall) = our_ladder(&source, width, height, fctx); |
| 7413 | // How often the inter split actually fired over this clip's four | 7683 | // How often the inter split actually fired over this clip's four |
| 7414 | // encodes, against the whole 32x32 that was the only outcome | 7684 | // encodes, against the whole 32x32 that was the only outcome |
| 7415 | // before (gate-blind-to-feature). | 7685 | // before (gate-blind-to-feature). |
| 7416 | let [whole32, split32, whole16, split16] = take_partition_hits(); | 7686 | let [whole32, split32, whole16, split16] = take_partition_hits(); |
| 7687 | + // Which inter modes actually fired over this clip's four encodes, | ||
| 7688 | + // and at which DRL index -- a mode nobody picks is a mode the BD | ||
| 7689 | + // number cannot be crediting (gate-blind-to-feature). | ||
| 7690 | + let [nearest, near, global, new] = crate::tile::take_inter_mode_hits(); | ||
| 7691 | + let [drl0, drl1, drl2, drl3] = crate::tile::take_drl_hits(); | ||
| 7692 | + let refs = crate::tile::take_ref_hits(); | ||
| 7693 | + let modes_total = (nearest + near + global + new).max(1); | ||
| 7694 | + eprintln!( | ||
| 7695 | + "{name}: inter modes NEAREST {nearest} ({:.1}%) NEAR {near} ({:.1}%) \ | ||
| 7696 | + GLOBAL {global} ({:.1}%) NEW {new} ({:.1}%); drl idx 0/1/2/3+ \ | ||
| 7697 | + {drl0}/{drl1}/{drl2}/{drl3}", | ||
| 7698 | + 100.0 * nearest as f64 / modes_total as f64, | ||
| 7699 | + 100.0 * near as f64 / modes_total as f64, | ||
| 7700 | + 100.0 * global as f64 / modes_total as f64, | ||
| 7701 | + 100.0 * new as f64 / modes_total as f64, | ||
| 7702 | + ); | ||
| 7703 | + eprintln!( | ||
| 7704 | + "{name}: references LAST {} GOLDEN {} (LAST2 {} LAST3 {} BWD {} ALT2 {} ALT {})", | ||
| 7705 | + refs[0], refs[3], refs[1], refs[2], refs[4], refs[5], refs[6] | ||
| 7706 | + ); | ||
| 7417 | eprintln!( | 7707 | eprintln!( |
| 7418 | "{name}: inter 32x32 split into 16s {split32} of {} blocks ({:.1}%); \ | 7708 | "{name}: inter 32x32 split into 16s {split32} of {} blocks ({:.1}%); \ |
| 7419 | 16x16 leaves split into 8s {split16} of {} ({:.1}%)", | 7709 | 16x16 leaves split into 8s {split16} of {} ({:.1}%)", |
crates/ec-av1/src/encoder.rsmodified+24 -0
| @@ -226,6 +226,17 @@ pub struct Av1Encoder { | |||
| 226 | /// thread-local. One per encoder, never per frame: several of its fields | 226 | /// thread-local. One per encoder, never per frame: several of its fields |
| 227 | /// (the inter-frame inheritance guards) carry state ACROSS frames. | 227 | /// (the inter-frame inheritance guards) carry state ACROSS frames. |
| 228 | fctx: crate::decode::FrameCtx, | 228 | fctx: crate::decode::FrameCtx, |
| 229 | + /// What the last coded frame stored into the reference slot the next | ||
| 230 | + /// inter frame reads (spec 7.20): the tables that frame's tile writer | ||
| 231 | + /// must start from, since the header leaves | ||
| 232 | + /// `disable_frame_end_update_cdf` off. `None` before the first frame. | ||
| 233 | + carried_cdfs: Option<crate::encode::CdfSnapshot>, | ||
| 234 | + /// The last key frame's own (padded) reconstruction: `GOLDEN_FRAME`, | ||
| 235 | + /// which stays in DPB slot 1 until the next key frame refreshes it. | ||
| 236 | + golden: Option<Picture>, | ||
| 237 | + /// The frame two back: `ALTREF_FRAME`, in the slot the next frame is | ||
| 238 | + /// about to refresh (`encode_inter_frame`'s 0/2 alternation). | ||
| 239 | + prev2: Option<Picture>, | ||
| 229 | } | 240 | } |
| 230 | 241 | ||
| 231 | /// The encoder stays `Send` now that it owns a `FrameCtx` (whose cells are | 242 | /// The encoder stays `Send` now that it owns a `FrameCtx` (whose cells are |
| @@ -251,6 +262,9 @@ impl Av1Encoder { | |||
| 251 | // then. | 262 | // then. |
| 252 | Picture::grey(config.width, config.height).check_even()?; | 263 | Picture::grey(config.width, config.height).check_even()?; |
| 253 | Ok(Self { | 264 | Ok(Self { |
| 265 | + carried_cdfs: None, | ||
| 266 | + golden: None, | ||
| 267 | + prev2: None, | ||
| 254 | color_config: config.colour.color_config(), | 268 | color_config: config.colour.color_config(), |
| 255 | config, | 269 | config, |
| 256 | reference: None, | 270 | reference: None, |
| @@ -355,10 +369,20 @@ impl Av1Encoder { | |||
| 355 | DEADZONE, | 369 | DEADZONE, |
| 356 | order as u32, | 370 | order as u32, |
| 357 | render, | 371 | render, |
| 372 | + self.carried_cdfs.as_ref().map(|c| &c.0), | ||
| 373 | + self.golden.as_ref(), | ||
| 374 | + self.prev2.as_ref(), | ||
| 358 | &self.fctx, | 375 | &self.fctx, |
| 359 | )? | 376 | )? |
| 360 | }; | 377 | }; |
| 361 | 378 | ||
| 379 | + self.carried_cdfs = Some(encoded.next_cdfs.clone()); | ||
| 380 | + if is_key { | ||
| 381 | + self.golden = Some(encoded.reconstruction.clone()); | ||
| 382 | + self.prev2 = None; | ||
| 383 | + } else { | ||
| 384 | + self.prev2 = self.reference.take(); | ||
| 385 | + } | ||
| 362 | self.reference = Some(encoded.reconstruction.clone()); | 386 | self.reference = Some(encoded.reconstruction.clone()); |
| 363 | self.next_index += 1; | 387 | self.next_index += 1; |
| 364 | let cropped = crop_encoded(&encoded, render.0, render.1); | 388 | let cropped = crop_encoded(&encoded, render.0, render.1); |
crates/ec-av1/src/mvstack.rsmodified+1 -0
| @@ -2399,6 +2399,7 @@ pub struct CompoundTplArgs<'a> { | |||
| 2399 | /// two-valued test: "is there an inter neighbour at all". `has_inter` | 2399 | /// two-valued test: "is there an inter neighbour at all". `has_inter` |
| 2400 | /// gathers that over the block's whole span, the way spec 5.11.39 reads any | 2400 | /// gathers that over the block's whole span, the way spec 5.11.39 reads any |
| 2401 | /// neighbour-derived context. | 2401 | /// neighbour-derived context. |
| 2402 | +#[cfg(test)] | ||
| 2402 | pub(crate) fn single_ref_ctx(has_inter_neighbour: bool) -> usize { | 2403 | pub(crate) fn single_ref_ctx(has_inter_neighbour: bool) -> usize { |
| 2403 | if has_inter_neighbour { 2 } else { 1 } | 2404 | if has_inter_neighbour { 2 } else { 1 } |
| 2404 | } | 2405 | } |
crates/ec-av1/src/stream.rsmodified+8 -1
| @@ -3396,7 +3396,13 @@ mod tests { | |||
| 3396 | 3396 | ||
| 3397 | // Frame 1: hand-coded, intra-only, refreshes slot 0 with a flat | 3397 | // Frame 1: hand-coded, intra-only, refreshes slot 0 with a flat |
| 3398 | // 128 block (no neighbours to predict `DC_PRED` from). | 3398 | // 128 block (no neighbours to predict `DC_PRED` from). |
| 3399 | - let (_, header1) = inter_frame_headers(width, height, base_q_idx, 1, 0).unwrap(); | 3399 | + let (_, mut header1) = inter_frame_headers(width, height, base_q_idx, 1, 0).unwrap(); |
| 3400 | + // These two tiles are hand-coded from a FRESH `Cdfs`, so the | ||
| 3401 | + // frames must not carry CDF state the way the encoder's own inter | ||
| 3402 | + // frames now do (spec 7.20): with the bit set, what each frame | ||
| 3403 | + // stores is what it started from -- the defaults -- which is | ||
| 3404 | + // exactly what the next hand-coded tile assumes. | ||
| 3405 | + header1.disable_frame_end_update_cdf = true; | ||
| 3400 | let tile1 = { | 3406 | let tile1 = { |
| 3401 | let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx)); | 3407 | let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx)); |
| 3402 | let mut enc = SymbolEncoder::new(); | 3408 | let mut enc = SymbolEncoder::new(); |
| @@ -3414,6 +3420,7 @@ mod tests { | |||
| 3414 | // Frame 2: hand-coded, single_ref all the way to GOLDEN_FRAME, | 3420 | // Frame 2: hand-coded, single_ref all the way to GOLDEN_FRAME, |
| 3415 | // skip zero-MV NEARESTMV -- a direct copy of slot 3 (frame 0). | 3421 | // skip zero-MV NEARESTMV -- a direct copy of slot 3 (frame 0). |
| 3416 | let (_, mut header2) = inter_frame_headers(width, height, base_q_idx, 2, 0).unwrap(); | 3422 | let (_, mut header2) = inter_frame_headers(width, height, base_q_idx, 2, 0).unwrap(); |
| 3423 | + header2.disable_frame_end_update_cdf = true; | ||
| 3417 | header2.ref_frame_idx[3] = 3; // GOLDEN_FRAME's own slot: frame 0's, untouched by frame 1 | 3424 | header2.ref_frame_idx[3] = 3; // GOLDEN_FRAME's own slot: frame 0's, untouched by frame 1 |
| 3418 | let tile2 = { | 3425 | let tile2 = { |
| 3419 | let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx)); | 3426 | let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx)); |
crates/ec-av1/src/tile.rsmodified+299 -120
| @@ -18,7 +18,7 @@ use crate::cdf; | |||
| 18 | use crate::cdf_state::{Cdfs, MvComponentCdfs, TxbSet, TxbTables}; | 18 | use crate::cdf_state::{Cdfs, MvComponentCdfs, TxbSet, TxbTables}; |
| 19 | use crate::decode::{TXFM_CTX_INIT, txfm_partition_ctx_rect}; | 19 | use crate::decode::{TXFM_CTX_INIT, txfm_partition_ctx_rect}; |
| 20 | use crate::msac::SymbolEncoder; | 20 | use crate::msac::SymbolEncoder; |
| 21 | -use crate::mvstack::{MiGrid, MiInfo, NO_REF1, find_mv_stack, mv16, single_ref_ctx}; | 21 | +use crate::mvstack::{MiGrid, MiInfo, NO_REF1, find_mv_stack, mv16}; |
| 22 | 22 | ||
| 23 | // --------------------------------------------------------------------------- | 23 | // --------------------------------------------------------------------------- |
| 24 | // lane-av1lr: per-64x64 `cdef_idx` (spec 5.11.56, `read_cdef`). The decoder | 24 | // lane-av1lr: per-64x64 `cdef_idx` (spec 5.11.56, `read_cdef`). The decoder |
| @@ -293,7 +293,7 @@ const MAX_LEVEL: i32 = MAX_BR_LEVEL + (1 << 19); | |||
| 293 | /// The coefficient q-context (spec 8.3.2's `Get_Qctx`, `Default_..._Cdf`'s | 293 | /// The coefficient q-context (spec 8.3.2's `Get_Qctx`, `Default_..._Cdf`'s |
| 294 | /// leading index) a frame's `base_q_idx` picks its default CDFs from. | 294 | /// leading index) a frame's `base_q_idx` picks its default CDFs from. |
| 295 | /// [`crate::cdf`] carries all four, one constant set per context. | 295 | /// [`crate::cdf`] carries all four, one constant set per context. |
| 296 | -fn q_ctx_of(base_q_idx: u8) -> usize { | 296 | +pub(crate) fn q_ctx_of(base_q_idx: u8) -> usize { |
| 297 | match base_q_idx { | 297 | match base_q_idx { |
| 298 | 0..=20 => 0, | 298 | 0..=20 => 0, |
| 299 | 21..=60 => 1, | 299 | 21..=60 => 1, |
| @@ -645,16 +645,21 @@ pub struct BlockCoeffs { | |||
| 645 | pub tx_depth: u8, | 645 | pub tx_depth: u8, |
| 646 | } | 646 | } |
| 647 | 647 | ||
| 648 | -/// One inter mode [`sb_coeff_inter_frame_tile`]'s blocks may take (spec | 648 | +/// One inter mode [`sb_coeff_inter_frame_tile`]'s blocks may take: the whole |
| 649 | -/// 5.11.24 `read_inter_mode`), reduced to the two branches its symbol chain | 649 | +/// single-reference set of spec 5.11.24 `read_inter_mode`, each written by |
| 650 | -/// needs to prove out: the stack's own top candidate outright, or a coded | 650 | +/// [`write_inter_mode`] with the decoder's own contexts. |
| 651 | -/// residual against it. `NEARMV`/`GLOBALMV` are never written. | ||
| 652 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] | 651 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 653 | pub enum InterMode { | 652 | pub enum InterMode { |
| 654 | /// `NEARESTMV`: takes `MvStack::nearest_mv` outright, no residual, no DRL. | 653 | /// `NEARESTMV`: takes `MvStack::nearest_mv` outright, no residual, no DRL. |
| 655 | NearestMv, | 654 | NearestMv, |
| 656 | - /// `NEWMV`: codes `mv` as a residual against `MvStack::pred_mv`, through | 655 | + /// `NEARMV`: takes the stack entry [`InterInfo::ref_mv_idx`] names |
| 657 | - /// a DRL index this writer always leaves at zero. | 656 | + /// (clamped to at least 1, the spec's own `RefMvIdx` base for this mode). |
| 657 | + NearMv, | ||
| 658 | + /// `GLOBALMV`: the identity global model's zero vector, two symbols and | ||
| 659 | + /// no MV at all. | ||
| 660 | + GlobalMv, | ||
| 661 | + /// `NEWMV`: codes `mv` as a residual against the stack entry | ||
| 662 | + /// [`InterInfo::ref_mv_idx`] names. | ||
| 658 | NewMv, | 663 | NewMv, |
| 659 | } | 664 | } |
| 660 | 665 | ||
| @@ -668,6 +673,14 @@ pub struct InterInfo { | |||
| 668 | pub mode: InterMode, | 673 | pub mode: InterMode, |
| 669 | /// The motion vector a [`InterMode::NewMv`] block's residual targets. | 674 | /// The motion vector a [`InterMode::NewMv`] block's residual targets. |
| 670 | pub mv: (i32, i32), | 675 | pub mv: (i32, i32), |
| 676 | + /// The reference this block predicts from (`LAST_FRAME`..=`ALTREF_FRAME`, | ||
| 677 | + /// spec 6.10.24's alphabet), written by [`write_single_ref`]. | ||
| 678 | + pub ref_frame: i8, | ||
| 679 | + /// The block's `RefMvIdx` (spec 5.11.24 `read_drl_idx`): which | ||
| 680 | + /// `MvStack::entries` slot `NEWMV` codes its residual against, or | ||
| 681 | + /// `NEARMV` takes outright. Ignored by the two modes that code no DRL | ||
| 682 | + /// index (`NEARESTMV`, `GLOBALMV`). | ||
| 683 | + pub ref_mv_idx: u8, | ||
| 671 | } | 684 | } |
| 672 | 685 | ||
| 673 | impl From<Vec<Coeff>> for BlockCoeffs { | 686 | impl From<Vec<Coeff>> for BlockCoeffs { |
| @@ -833,6 +846,12 @@ struct Neighbours { | |||
| 833 | above_inter: Vec<bool>, | 846 | above_inter: Vec<bool>, |
| 834 | /// The same, down the left edge. | 847 | /// The same, down the left edge. |
| 835 | left_inter: Vec<bool>, | 848 | left_inter: Vec<bool>, |
| 849 | + /// The reference each neighbour named, `-1` for an intra or unavailable | ||
| 850 | + /// one -- what the decoder keeps in its own `Neighbours::above_ref` | ||
| 851 | + /// (decode.rs) and feeds `read_single_ref`'s context functions. | ||
| 852 | + above_ref: Vec<i8>, | ||
| 853 | + /// The same, down the left edge. | ||
| 854 | + left_ref: Vec<i8>, | ||
| 836 | /// The frame's true (unpadded) width and height, in 4x4 mode-info units, | 855 | /// The frame's true (unpadded) width and height, in 4x4 mode-info units, |
| 837 | /// which is what clamps [`Self::above`]/[`Self::left`] at the edge (spec | 856 | /// which is what clamps [`Self::above`]/[`Self::left`] at the edge (spec |
| 838 | /// `av1_set_entropy_contexts`): a block whose row or column run spills | 857 | /// `av1_set_entropy_contexts`): a block whose row or column run spills |
| @@ -876,6 +895,8 @@ impl Neighbours { | |||
| 876 | left_skip: vec![false; rows * (SUB / MI)], | 895 | left_skip: vec![false; rows * (SUB / MI)], |
| 877 | above_inter: vec![false; cols * (SUB / MI)], | 896 | above_inter: vec![false; cols * (SUB / MI)], |
| 878 | left_inter: vec![false; rows * (SUB / MI)], | 897 | left_inter: vec![false; rows * (SUB / MI)], |
| 898 | + above_ref: vec![-1; cols * (SUB / MI)], | ||
| 899 | + left_ref: vec![-1; rows * (SUB / MI)], | ||
| 879 | above_tx: vec![0; cols * (SUB / MI)], | 900 | above_tx: vec![0; cols * (SUB / MI)], |
| 880 | left_tx: vec![0; rows * (SUB / MI)], | 901 | left_tx: vec![0; rows * (SUB / MI)], |
| 881 | above_txfm: vec![TXFM_CTX_INIT; cols * (SUB / MI)], | 902 | above_txfm: vec![TXFM_CTX_INIT; cols * (SUB / MI)], |
| @@ -893,6 +914,7 @@ impl Neighbours { | |||
| 893 | self.left_side_mi.iter_mut().for_each(|s| *s = SB); | 914 | self.left_side_mi.iter_mut().for_each(|s| *s = SB); |
| 894 | self.left_skip.iter_mut().for_each(|s| *s = false); | 915 | self.left_skip.iter_mut().for_each(|s| *s = false); |
| 895 | self.left_inter.iter_mut().for_each(|i| *i = false); | 916 | self.left_inter.iter_mut().for_each(|i| *i = false); |
| 917 | + self.left_ref.iter_mut().for_each(|r| *r = -1); | ||
| 896 | self.left_tx.iter_mut().for_each(|t| *t = 0); | 918 | self.left_tx.iter_mut().for_each(|t| *t = 0); |
| 897 | self.left_txfm.iter_mut().for_each(|t| *t = TXFM_CTX_INIT); | 919 | self.left_txfm.iter_mut().for_each(|t| *t = TXFM_CTX_INIT); |
| 898 | } | 920 | } |
| @@ -1092,19 +1114,21 @@ impl Neighbours { | |||
| 1092 | /// Writes one inter-frame block's skip flag and inter/intra state into | 1114 | /// Writes one inter-frame block's skip flag and inter/intra state into |
| 1093 | /// every 16x16 column and row it covers, the same span [`Self::record`] | 1115 | /// every 16x16 column and row it covers, the same span [`Self::record`] |
| 1094 | /// fills for the coefficient and mode state. | 1116 | /// fills for the coefficient and mode state. |
| 1095 | - fn record_inter(&mut self, at: (usize, usize), side: usize, skip: bool, is_inter: bool) { | 1117 | + fn record_inter(&mut self, at: (usize, usize), side: usize, skip: bool, is_inter: bool, ref_frame: i8) { |
| 1096 | let (r, c) = at; | 1118 | let (r, c) = at; |
| 1097 | - self.record_inter_mi((r * (SUB / MI), c * (SUB / MI)), side, skip, is_inter); | 1119 | + self.record_inter_mi((r * (SUB / MI), c * (SUB / MI)), side, skip, is_inter, ref_frame); |
| 1098 | } | 1120 | } |
| 1099 | 1121 | ||
| 1100 | /// [`Self::record_inter`] taking the block's position directly in 4x4 | 1122 | /// [`Self::record_inter`] taking the block's position directly in 4x4 |
| 1101 | /// mode-info units, for a block finer than one [`SUB`] slot. | 1123 | /// mode-info units, for a block finer than one [`SUB`] slot. |
| 1102 | - fn record_inter_mi(&mut self, (mi_r, mi_c): (usize, usize), side: usize, skip: bool, is_inter: bool) { | 1124 | + fn record_inter_mi(&mut self, (mi_r, mi_c): (usize, usize), side: usize, skip: bool, is_inter: bool, ref_frame: i8) { |
| 1103 | for cell in 0..side / MI { | 1125 | for cell in 0..side / MI { |
| 1104 | self.above_skip[mi_c + cell] = skip; | 1126 | self.above_skip[mi_c + cell] = skip; |
| 1105 | self.left_skip[mi_r + cell] = skip; | 1127 | self.left_skip[mi_r + cell] = skip; |
| 1106 | self.above_inter[mi_c + cell] = is_inter; | 1128 | self.above_inter[mi_c + cell] = is_inter; |
| 1107 | self.left_inter[mi_r + cell] = is_inter; | 1129 | self.left_inter[mi_r + cell] = is_inter; |
| 1130 | + self.above_ref[mi_c + cell] = ref_frame; | ||
| 1131 | + self.left_ref[mi_r + cell] = ref_frame; | ||
| 1108 | } | 1132 | } |
| 1109 | } | 1133 | } |
| 1110 | 1134 | ||
| @@ -1198,7 +1222,27 @@ pub fn sb_coeff_key_frame_tile_tx( | |||
| 1198 | superblocks: &[Superblock], | 1222 | superblocks: &[Superblock], |
| 1199 | tx_select: bool, | 1223 | tx_select: bool, |
| 1200 | ) -> Result<Vec<u8>> { | 1224 | ) -> Result<Vec<u8>> { |
| 1201 | - // Consumes whatever `arm_cdef_idx` armed, on every exit path. | 1225 | + let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx)); |
| 1226 | + sb_coeff_key_frame_tile_cdfs(mi_cols, mi_rows, base_q_idx, superblocks, tx_select, &mut cdfs) | ||
| 1227 | +} | ||
| 1228 | + | ||
| 1229 | +/// [`sb_coeff_key_frame_tile_tx`] starting from -- and leaving behind -- the | ||
| 1230 | +/// caller's own CDF state, which is what a frame whose | ||
| 1231 | +/// `disable_frame_end_update_cdf` is off needs: the next frame's writer must | ||
| 1232 | +/// start where this tile ended (spec 7.20, mirrored by | ||
| 1233 | +/// `crate::stream::stored_cdfs_for`). | ||
| 1234 | +/// | ||
| 1235 | +/// # Errors | ||
| 1236 | +/// As [`sb_coeff_key_frame_tile_tx`]. | ||
| 1237 | +pub(crate) fn sb_coeff_key_frame_tile_cdfs( | ||
| 1238 | + mi_cols: u32, | ||
| 1239 | + mi_rows: u32, | ||
| 1240 | + _base_q_idx: u8, | ||
| 1241 | + superblocks: &[Superblock], | ||
| 1242 | + tx_select: bool, | ||
| 1243 | + cdfs: &mut Cdfs, | ||
| 1244 | +) -> Result<Vec<u8>> { | ||
| 1245 | + // Consumes whatever `arm_cdef_idx`/`arm_lr` armed, on every exit path. | ||
| 1202 | let _cdef_idx = CdefIdxGuard; | 1246 | let _cdef_idx = CdefIdxGuard; |
| 1203 | check_blocks(mi_cols, mi_rows)?; | 1247 | check_blocks(mi_cols, mi_rows)?; |
| 1204 | let (cols, rows) = block_grid(mi_cols, mi_rows); | 1248 | let (cols, rows) = block_grid(mi_cols, mi_rows); |
| @@ -1258,7 +1302,7 @@ pub fn sb_coeff_key_frame_tile_tx( | |||
| 1258 | // The tile adapts every non-literal CDF it writes, exactly as the decoder | 1302 | // The tile adapts every non-literal CDF it writes, exactly as the decoder |
| 1259 | // adapts the ones it reads, so the frame header leaves `disable_cdf_update` | 1303 | // adapts the ones it reads, so the frame header leaves `disable_cdf_update` |
| 1260 | // off. | 1304 | // off. |
| 1261 | - let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx)); | 1305 | + let mut cdfs = cdfs; |
| 1262 | let mut enc = SymbolEncoder::new(); | 1306 | let mut enc = SymbolEncoder::new(); |
| 1263 | for sb_r in 0..sb_rows { | 1307 | for sb_r in 0..sb_rows { |
| 1264 | neighbours.start_row(); | 1308 | neighbours.start_row(); |
| @@ -2831,6 +2875,205 @@ fn write_mv( | |||
| 2831 | Ok(()) | 2875 | Ok(()) |
| 2832 | } | 2876 | } |
| 2833 | 2877 | ||
| 2878 | +/// What a block leaves in the neighbour reference bands: its own reference, | ||
| 2879 | +/// or `-1` when it is intra (decode.rs `Neighbours::above_ref`'s convention). | ||
| 2880 | +fn block_ref(block: &BlockCoeffs) -> i8 { | ||
| 2881 | + block.inter.map_or(-1, |i| i.ref_frame) | ||
| 2882 | +} | ||
| 2883 | + | ||
| 2884 | +/// Writer-side counterpart of decode.rs `read_single_ref` (spec 5.11.25's | ||
| 2885 | +/// `single_ref_p1`..`p6` tree): codes `ref_frame` bit by bit, each symbol at | ||
| 2886 | +/// the context its own `single_ref_p*_ctx` derives from the immediate | ||
| 2887 | +/// above/left neighbours' references -- the same functions the decoder calls, | ||
| 2888 | +/// with `-1` standing for an intra or unavailable neighbour and no second | ||
| 2889 | +/// reference (this writer codes no compound block). | ||
| 2890 | +fn write_single_ref( | ||
| 2891 | + enc: &mut SymbolEncoder, | ||
| 2892 | + cdfs: &mut Cdfs, | ||
| 2893 | + ref_frame: i8, | ||
| 2894 | + above_ref: i8, | ||
| 2895 | + left_ref: i8, | ||
| 2896 | +) { | ||
| 2897 | + REF_HITS[(ref_frame.max(1) - 1) as usize % 7].fetch_add(1, std::sync::atomic::Ordering::Relaxed); | ||
| 2898 | + use crate::mvstack::{ | ||
| 2899 | + ALTREF2_FRAME, ALTREF_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST2_FRAME, LAST3_FRAME, | ||
| 2900 | + single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx, | ||
| 2901 | + single_ref_p5_ctx, single_ref_p6_ctx, | ||
| 2902 | + }; | ||
| 2903 | + let above = (above_ref > 0).then_some(above_ref); | ||
| 2904 | + let left = (left_ref > 0).then_some(left_ref); | ||
| 2905 | + let backward = ref_frame >= BWDREF_FRAME; | ||
| 2906 | + enc.symbol( | ||
| 2907 | + usize::from(backward), | ||
| 2908 | + &mut cdfs.single_ref[single_ref_p1_ctx(above, None, left, None)][0], | ||
| 2909 | + ); | ||
| 2910 | + if backward { | ||
| 2911 | + let is_altref = ref_frame == ALTREF_FRAME; | ||
| 2912 | + enc.symbol( | ||
| 2913 | + usize::from(is_altref), | ||
| 2914 | + &mut cdfs.single_ref[single_ref_p2_ctx(above, None, left, None)][1], | ||
| 2915 | + ); | ||
| 2916 | + if !is_altref { | ||
| 2917 | + enc.symbol( | ||
| 2918 | + usize::from(ref_frame == ALTREF2_FRAME), | ||
| 2919 | + &mut cdfs.single_ref[single_ref_p6_ctx(above, None, left, None)][5], | ||
| 2920 | + ); | ||
| 2921 | + } | ||
| 2922 | + return; | ||
| 2923 | + } | ||
| 2924 | + let far = ref_frame == LAST3_FRAME || ref_frame == GOLDEN_FRAME; | ||
| 2925 | + enc.symbol( | ||
| 2926 | + usize::from(far), | ||
| 2927 | + &mut cdfs.single_ref[single_ref_p3_ctx(above, None, left, None)][2], | ||
| 2928 | + ); | ||
| 2929 | + if far { | ||
| 2930 | + enc.symbol( | ||
| 2931 | + usize::from(ref_frame == GOLDEN_FRAME), | ||
| 2932 | + &mut cdfs.single_ref[single_ref_p5_ctx(above, None, left, None)][4], | ||
| 2933 | + ); | ||
| 2934 | + } else { | ||
| 2935 | + enc.symbol( | ||
| 2936 | + usize::from(ref_frame == LAST2_FRAME), | ||
| 2937 | + &mut cdfs.single_ref[single_ref_p4_ctx(above, None, left, None)][3], | ||
| 2938 | + ); | ||
| 2939 | + } | ||
| 2940 | +} | ||
| 2941 | + | ||
| 2942 | +/// Per-mode fire counts of [`write_inter_mode`], indexed | ||
| 2943 | +/// `NEARESTMV`/`NEARMV`/`GLOBALMV`/`NEWMV`, and the DRL index each block | ||
| 2944 | +/// coded (bucket 3 collects any index past 2). Read by the BD gate, which | ||
| 2945 | +/// is the only thing that proves a newly added mode ever fires | ||
| 2946 | +/// (gate-blind-to-feature). | ||
| 2947 | +static INTER_MODE_HITS: [std::sync::atomic::AtomicUsize; 4] = [ | ||
| 2948 | + std::sync::atomic::AtomicUsize::new(0), | ||
| 2949 | + std::sync::atomic::AtomicUsize::new(0), | ||
| 2950 | + std::sync::atomic::AtomicUsize::new(0), | ||
| 2951 | + std::sync::atomic::AtomicUsize::new(0), | ||
| 2952 | +]; | ||
| 2953 | +static DRL_HITS: [std::sync::atomic::AtomicUsize; 4] = [ | ||
| 2954 | + std::sync::atomic::AtomicUsize::new(0), | ||
| 2955 | + std::sync::atomic::AtomicUsize::new(0), | ||
| 2956 | + std::sync::atomic::AtomicUsize::new(0), | ||
| 2957 | + std::sync::atomic::AtomicUsize::new(0), | ||
| 2958 | +]; | ||
| 2959 | + | ||
| 2960 | +/// One counter per reference name (`LAST`..`ALTREF`), for the gate's own | ||
| 2961 | +/// census of what the encoder actually picks. | ||
| 2962 | +static REF_HITS: [std::sync::atomic::AtomicUsize; 7] = [ | ||
| 2963 | + std::sync::atomic::AtomicUsize::new(0), | ||
| 2964 | + std::sync::atomic::AtomicUsize::new(0), | ||
| 2965 | + std::sync::atomic::AtomicUsize::new(0), | ||
| 2966 | + std::sync::atomic::AtomicUsize::new(0), | ||
| 2967 | + std::sync::atomic::AtomicUsize::new(0), | ||
| 2968 | + std::sync::atomic::AtomicUsize::new(0), | ||
| 2969 | + std::sync::atomic::AtomicUsize::new(0), | ||
| 2970 | +]; | ||
| 2971 | + | ||
| 2972 | +/// Takes and clears the per-reference histogram. | ||
| 2973 | +#[cfg(test)] | ||
| 2974 | +pub(crate) fn take_ref_hits() -> [usize; 7] { | ||
| 2975 | + std::array::from_fn(|i| REF_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) | ||
| 2976 | +} | ||
| 2977 | + | ||
| 2978 | +/// Bumps the two histograms for one coded inter block. | ||
| 2979 | +fn note_inter_mode(mode: usize, drl: usize) { | ||
| 2980 | + INTER_MODE_HITS[mode].fetch_add(1, std::sync::atomic::Ordering::Relaxed); | ||
| 2981 | + DRL_HITS[drl.min(3)].fetch_add(1, std::sync::atomic::Ordering::Relaxed); | ||
| 2982 | +} | ||
| 2983 | + | ||
| 2984 | +/// Takes and clears the inter-mode histogram (NEAREST/NEAR/GLOBAL/NEW). | ||
| 2985 | +#[cfg(test)] | ||
| 2986 | +pub(crate) fn take_inter_mode_hits() -> [usize; 4] { | ||
| 2987 | + [0, 1, 2, 3].map(|i| INTER_MODE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) | ||
| 2988 | +} | ||
| 2989 | + | ||
| 2990 | +/// Takes and clears the DRL-index histogram (0, 1, 2, 3+). | ||
| 2991 | +#[cfg(test)] | ||
| 2992 | +pub(crate) fn take_drl_hits() -> [usize; 4] { | ||
| 2993 | + [0, 1, 2, 3].map(|i| DRL_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) | ||
| 2994 | +} | ||
| 2995 | + | ||
| 2996 | +/// Writes the DRL index of one block: the loop the decoder runs (spec | ||
| 2997 | +/// 5.11.24 `read_drl_idx`, decode.rs' two copies at ~26655 and ~26695), one | ||
| 2998 | +/// `drl_mode` bit per stack entry past `start`, `1` to advance and `0` to | ||
| 2999 | +/// stop, at most two bits. `drl_ctx[idx]` is the context between | ||
| 3000 | +/// `entries[idx]` and `entries[idx + 1]`, exactly the pair the bit chooses | ||
| 3001 | +/// between. | ||
| 3002 | +fn write_drl_idx( | ||
| 3003 | + enc: &mut SymbolEncoder, | ||
| 3004 | + cdfs: &mut Cdfs, | ||
| 3005 | + stack: &crate::mvstack::MvStack, | ||
| 3006 | + start: usize, | ||
| 3007 | + target: usize, | ||
| 3008 | +) { | ||
| 3009 | + let mut idx = start; | ||
| 3010 | + while idx < start + 2 && stack.entries.len() > idx + 1 { | ||
| 3011 | + let advance = idx < target; | ||
| 3012 | + enc.symbol(usize::from(advance), &mut cdfs.drl_mode[stack.drl_ctx[idx]]); | ||
| 3013 | + if !advance { | ||
| 3014 | + return; | ||
| 3015 | + } | ||
| 3016 | + idx += 1; | ||
| 3017 | + } | ||
| 3018 | +} | ||
| 3019 | + | ||
| 3020 | +/// Writer-side counterpart of the decoder's single-reference | ||
| 3021 | +/// `read_inter_mode`/`assign_mv` chain (decode.rs ~26645): writes `info`'s | ||
| 3022 | +/// mode symbols against `stack`'s own contexts and, for `NEWMV`, the MV | ||
| 3023 | +/// residual against the DRL-selected predictor. Returns the motion vector | ||
| 3024 | +/// the decoder will derive for the block (what the MI grid must record) and | ||
| 3025 | +/// whether it is `NEWMV`. | ||
| 3026 | +/// | ||
| 3027 | +/// `GLOBALMV` resolves to `(0, 0)` because this encoder writes no global | ||
| 3028 | +/// motion parameters at all, so every `gm_get_motion_vector` the decoder | ||
| 3029 | +/// runs is the identity model's zero vector; a lane that starts writing | ||
| 3030 | +/// real `gm_params` has to feed the same vector in here. | ||
| 3031 | +/// | ||
| 3032 | +/// # Errors | ||
| 3033 | +/// As [`write_mv`]: a `NEWMV` residual needing eighth-pel precision. | ||
| 3034 | +fn write_inter_mode( | ||
| 3035 | + enc: &mut SymbolEncoder, | ||
| 3036 | + cdfs: &mut Cdfs, | ||
| 3037 | + info: InterInfo, | ||
| 3038 | + stack: &crate::mvstack::MvStack, | ||
| 3039 | +) -> Result<((i32, i32), bool)> { | ||
| 3040 | + let idx = usize::from(info.ref_mv_idx); | ||
| 3041 | + match info.mode { | ||
| 3042 | + InterMode::NewMv => { | ||
| 3043 | + enc.symbol(0, &mut cdfs.new_mv[stack.new_mv_ctx]); | ||
| 3044 | + write_drl_idx(enc, cdfs, stack, 0, idx); | ||
| 3045 | + let base = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv); | ||
| 3046 | + write_mv(enc, &mut cdfs.mv_comp, &mut cdfs.mv_joint, info.mv, base)?; | ||
| 3047 | + note_inter_mode(3, idx); | ||
| 3048 | + Ok((info.mv, true)) | ||
| 3049 | + } | ||
| 3050 | + InterMode::GlobalMv => { | ||
| 3051 | + enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not NEWMV | ||
| 3052 | + enc.symbol(0, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // GLOBALMV | ||
| 3053 | + note_inter_mode(2, 0); | ||
| 3054 | + Ok(((0, 0), false)) | ||
| 3055 | + } | ||
| 3056 | + InterMode::NearestMv => { | ||
| 3057 | + enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not NEWMV | ||
| 3058 | + enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not GLOBALMV | ||
| 3059 | + enc.symbol(0, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // NEARESTMV | ||
| 3060 | + note_inter_mode(0, 0); | ||
| 3061 | + Ok((stack.nearest_mv, false)) | ||
| 3062 | + } | ||
| 3063 | + InterMode::NearMv => { | ||
| 3064 | + enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not NEWMV | ||
| 3065 | + enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not GLOBALMV | ||
| 3066 | + enc.symbol(1, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // NEARMV | ||
| 3067 | + // `RefMvIdx` starts at 1 for NEARMV (spec 5.11.24). | ||
| 3068 | + let idx = idx.max(1); | ||
| 3069 | + write_drl_idx(enc, cdfs, stack, 1, idx); | ||
| 3070 | + let mv = stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv); | ||
| 3071 | + note_inter_mode(1, idx); | ||
| 3072 | + Ok((mv, false)) | ||
| 3073 | + } | ||
| 3074 | + } | ||
| 3075 | +} | ||
| 3076 | + | ||
| 2834 | /// Writes the payload of a one-tile inter frame built from `blocks`, one | 3077 | /// Writes the payload of a one-tile inter frame built from `blocks`, one |
| 2835 | /// 32x32 block per entry in raster order across the frame — every superblock | 3078 | /// 32x32 block per entry in raster order across the frame — every superblock |
| 2836 | /// is split into its four quadrants the way [`split_coeff_key_frame_tile`] | 3079 | /// is split into its four quadrants the way [`split_coeff_key_frame_tile`] |
| @@ -2884,7 +3127,24 @@ pub fn sb_coeff_inter_frame_tile_tx( | |||
| 2884 | blocks: &[Quadrant], | 3127 | blocks: &[Quadrant], |
| 2885 | tx_select: bool, | 3128 | tx_select: bool, |
| 2886 | ) -> Result<Vec<u8>> { | 3129 | ) -> Result<Vec<u8>> { |
| 2887 | - // Consumes whatever `arm_cdef_idx` armed, on every exit path. | 3130 | + let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx)); |
| 3131 | + sb_coeff_inter_frame_tile_cdfs(mi_cols, mi_rows, base_q_idx, blocks, tx_select, &mut cdfs) | ||
| 3132 | +} | ||
| 3133 | + | ||
| 3134 | +/// [`sb_coeff_inter_frame_tile_tx`] starting from -- and leaving behind -- | ||
| 3135 | +/// the caller's own CDF state; see [`sb_coeff_key_frame_tile_cdfs`]. | ||
| 3136 | +/// | ||
| 3137 | +/// # Errors | ||
| 3138 | +/// As [`sb_coeff_inter_frame_tile_tx`]. | ||
| 3139 | +pub(crate) fn sb_coeff_inter_frame_tile_cdfs( | ||
| 3140 | + mi_cols: u32, | ||
| 3141 | + mi_rows: u32, | ||
| 3142 | + _base_q_idx: u8, | ||
| 3143 | + blocks: &[Quadrant], | ||
| 3144 | + tx_select: bool, | ||
| 3145 | + cdfs: &mut Cdfs, | ||
| 3146 | +) -> Result<Vec<u8>> { | ||
| 3147 | + // Consumes whatever `arm_cdef_idx`/`arm_lr` armed, on every exit path. | ||
| 2888 | let _cdef_idx = CdefIdxGuard; | 3148 | let _cdef_idx = CdefIdxGuard; |
| 2889 | check_blocks(mi_cols, mi_rows)?; | 3149 | check_blocks(mi_cols, mi_rows)?; |
| 2890 | // `block_grid`'s ceiling, not a plain division: a true frame size that is | 3150 | // `block_grid`'s ceiling, not a plain division: a true frame size that is |
| @@ -2915,9 +3175,6 @@ pub fn sb_coeff_inter_frame_tile_tx( | |||
| 2915 | /// `Y_MODE`'s size group (spec `Size_Group`) for a 32x32 block, the only | 3175 | /// `Y_MODE`'s size group (spec `Size_Group`) for a 32x32 block, the only |
| 2916 | /// size this writer's inter branch codes. | 3176 | /// size this writer's inter branch codes. |
| 2917 | const SIZE_GROUP_32: usize = 3; | 3177 | const SIZE_GROUP_32: usize = 3; |
| 2918 | - /// `Ref_Frame_List`'s `LAST_FRAME` (spec 3): the only reference this | ||
| 2919 | - /// writer's single-reference chain ever names. | ||
| 2920 | - const LAST_FRAME: i8 = 1; | ||
| 2921 | 3178 | ||
| 2922 | let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2)); | 3179 | let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2)); |
| 2923 | let mut neighbours = Neighbours::new( | 3180 | let mut neighbours = Neighbours::new( |
| @@ -2927,7 +3184,7 @@ pub fn sb_coeff_inter_frame_tile_tx( | |||
| 2927 | mi_rows as usize, | 3184 | mi_rows as usize, |
| 2928 | ); | 3185 | ); |
| 2929 | let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize); | 3186 | let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize); |
| 2930 | - let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx)); | 3187 | + let mut cdfs = cdfs; |
| 2931 | let mut enc = SymbolEncoder::new(); | 3188 | let mut enc = SymbolEncoder::new(); |
| 2932 | // An `is_inter` block's 32x32 luma transform reads a different | 3189 | // An `is_inter` block's 32x32 luma transform reads a different |
| 2933 | // `tx_type` set than an intra block's (`get_tx_set`, spec 5.11.48; see | 3190 | // `tx_type` set than an intra block's (`get_tx_set`, spec 5.11.48; see |
| @@ -3214,10 +3471,7 @@ pub fn sb_coeff_inter_frame_tile_tx( | |||
| 3214 | 3471 | ||
| 3215 | let mode_for_tx; | 3472 | let mode_for_tx; |
| 3216 | if let Some(info) = block.inter { | 3473 | if let Some(info) = block.inter { |
| 3217 | - let sr_ctx = single_ref_ctx(above_inter || left_inter); | 3474 | + write_single_ref(&mut enc, &mut cdfs, info.ref_frame, neighbours.above_ref[mi_c], neighbours.left_ref[mi_r]); |
| 3218 | - enc.symbol(0, &mut cdfs.single_ref[sr_ctx][0]); // p1: forward | ||
| 3219 | - enc.symbol(0, &mut cdfs.single_ref[sr_ctx][2]); // p3: LAST/LAST2 | ||
| 3220 | - enc.symbol(0, &mut cdfs.single_ref[sr_ctx][3]); // p4: LAST | ||
| 3221 | 3475 | ||
| 3222 | let (mi_row, mi_col) = (r32 as usize * 8, c32 as usize * 8); | 3476 | let (mi_row, mi_col) = (r32 as usize * 8, c32 as usize * 8); |
| 3223 | let stack = find_mv_stack( | 3477 | let stack = find_mv_stack( |
| @@ -3226,43 +3480,18 @@ pub fn sb_coeff_inter_frame_tile_tx( | |||
| 3226 | mi_col, | 3480 | mi_col, |
| 3227 | 8, | 3481 | 8, |
| 3228 | 8, | 3482 | 8, |
| 3229 | - LAST_FRAME, | 3483 | + info.ref_frame, |
| 3230 | mi_cols as usize, | 3484 | mi_cols as usize, |
| 3231 | mi_rows as usize, | 3485 | mi_rows as usize, |
| 3232 | ); | 3486 | ); |
| 3233 | 3487 | ||
| 3234 | - let is_new_mv = matches!(info.mode, InterMode::NewMv); | 3488 | + let (mv, is_new_mv) = write_inter_mode(&mut enc, &mut cdfs, info, &stack)?; |
| 3235 | - if is_new_mv { | ||
| 3236 | - enc.symbol(0, &mut cdfs.new_mv[stack.new_mv_ctx]); // NEWMV | ||
| 3237 | - } else { | ||
| 3238 | - enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not new | ||
| 3239 | - enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not zero | ||
| 3240 | - enc.symbol(0, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // NEARESTMV | ||
| 3241 | - } | ||
| 3242 | - // This writer always keeps the first DRL candidate, so the | ||
| 3243 | - // loop (spec 5.11.24 `read_drl_idx`) only ever runs its | ||
| 3244 | - // first, breaking iteration. | ||
| 3245 | - if is_new_mv && stack.entries.len() > 1 { | ||
| 3246 | - enc.symbol(0, &mut cdfs.drl_mode[stack.drl_ctx[0]]); | ||
| 3247 | - } | ||
| 3248 | - let mv = if is_new_mv { | ||
| 3249 | - write_mv( | ||
| 3250 | - &mut enc, | ||
| 3251 | - &mut cdfs.mv_comp, | ||
| 3252 | - &mut cdfs.mv_joint, | ||
| 3253 | - info.mv, | ||
| 3254 | - stack.pred_mv, | ||
| 3255 | - )?; | ||
| 3256 | - info.mv | ||
| 3257 | - } else { | ||
| 3258 | - stack.nearest_mv | ||
| 3259 | - }; | ||
| 3260 | grid.set( | 3489 | grid.set( |
| 3261 | mi_row, | 3490 | mi_row, |
| 3262 | mi_col, | 3491 | mi_col, |
| 3263 | MiInfo { | 3492 | MiInfo { |
| 3264 | is_inter: true, | 3493 | is_inter: true, |
| 3265 | - ref_frame: LAST_FRAME, | 3494 | + ref_frame: info.ref_frame, |
| 3266 | ref_frame1: NO_REF1, | 3495 | ref_frame1: NO_REF1, |
| 3267 | mv1: (0, 0), | 3496 | mv1: (0, 0), |
| 3268 | mv: mv16(mv), | 3497 | mv: mv16(mv), |
| @@ -3283,7 +3512,7 @@ pub fn sb_coeff_inter_frame_tile_tx( | |||
| 3283 | mi_col + dc, | 3512 | mi_col + dc, |
| 3284 | MiInfo { | 3513 | MiInfo { |
| 3285 | is_inter: true, | 3514 | is_inter: true, |
| 3286 | - ref_frame: LAST_FRAME, | 3515 | + ref_frame: info.ref_frame, |
| 3287 | ref_frame1: NO_REF1, | 3516 | ref_frame1: NO_REF1, |
| 3288 | mv1: (0, 0), | 3517 | mv1: (0, 0), |
| 3289 | mv: mv16(mv), | 3518 | mv: mv16(mv), |
| @@ -3388,7 +3617,7 @@ pub fn sb_coeff_inter_frame_tile_tx( | |||
| 3388 | ); | 3617 | ); |
| 3389 | neighbours.record_planes(at, BLOCK, mode_for_tx, &grids, !split); | 3618 | neighbours.record_planes(at, BLOCK, mode_for_tx, &grids, !split); |
| 3390 | } | 3619 | } |
| 3391 | - neighbours.record_inter(at, BLOCK, block.skip, is_inter); | 3620 | + neighbours.record_inter(at, BLOCK, block.skip, is_inter, block_ref(block)); |
| 3392 | } | 3621 | } |
| 3393 | } | 3622 | } |
| 3394 | } | 3623 | } |
| @@ -3432,9 +3661,6 @@ fn write_inter_frame_leaf( | |||
| 3432 | /// `Y_MODE`'s size group (spec `Size_Group`, `common_data.h`'s | 3661 | /// `Y_MODE`'s size group (spec `Size_Group`, `common_data.h`'s |
| 3433 | /// `size_group_lookup[BLOCK_16X16]`) for this leaf's own size. | 3662 | /// `size_group_lookup[BLOCK_16X16]`) for this leaf's own size. |
| 3434 | const SIZE_GROUP_16: usize = 2; | 3663 | const SIZE_GROUP_16: usize = 2; |
| 3435 | - /// `Ref_Frame_List`'s `LAST_FRAME` (spec 3): the only reference this | ||
| 3436 | - /// writer's single-reference chain ever names, same as the 32x32 branch. | ||
| 3437 | - const LAST_FRAME: i8 = 1; | ||
| 3438 | 3664 | ||
| 3439 | let (r, c) = at; | 3665 | let (r, c) = at; |
| 3440 | let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI)); | 3666 | let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI)); |
| @@ -3450,10 +3676,7 @@ fn write_inter_frame_leaf( | |||
| 3450 | 3676 | ||
| 3451 | let mode_for_tx; | 3677 | let mode_for_tx; |
| 3452 | if let Some(info) = block.inter { | 3678 | if let Some(info) = block.inter { |
| 3453 | - let sr_ctx = single_ref_ctx(above_inter || left_inter); | 3679 | + write_single_ref(enc, cdfs, info.ref_frame, neighbours.above_ref[mi_c], neighbours.left_ref[mi_r]); |
| 3454 | - enc.symbol(0, &mut cdfs.single_ref[sr_ctx][0]); // p1: forward | ||
| 3455 | - enc.symbol(0, &mut cdfs.single_ref[sr_ctx][2]); // p3: LAST/LAST2 | ||
| 3456 | - enc.symbol(0, &mut cdfs.single_ref[sr_ctx][3]); // p4: LAST | ||
| 3457 | 3680 | ||
| 3458 | let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize); | 3681 | let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize); |
| 3459 | let stack = find_mv_stack( | 3682 | let stack = find_mv_stack( |
| @@ -3462,34 +3685,12 @@ fn write_inter_frame_leaf( | |||
| 3462 | mi_col, | 3685 | mi_col, |
| 3463 | SUB_MI as usize, | 3686 | SUB_MI as usize, |
| 3464 | SUB_MI as usize, | 3687 | SUB_MI as usize, |
| 3465 | - LAST_FRAME, | 3688 | + info.ref_frame, |
| 3466 | mi_cols as usize, | 3689 | mi_cols as usize, |
| 3467 | mi_rows as usize, | 3690 | mi_rows as usize, |
| 3468 | ); | 3691 | ); |
| 3469 | 3692 | ||
| 3470 | - let is_new_mv = matches!(info.mode, InterMode::NewMv); | 3693 | + let (mv, is_new_mv) = write_inter_mode(enc, cdfs, info, &stack)?; |
| 3471 | - if is_new_mv { | ||
| 3472 | - enc.symbol(0, &mut cdfs.new_mv[stack.new_mv_ctx]); // NEWMV | ||
| 3473 | - } else { | ||
| 3474 | - enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not new | ||
| 3475 | - enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not zero | ||
| 3476 | - enc.symbol(0, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // NEARESTMV | ||
| 3477 | - } | ||
| 3478 | - if is_new_mv && stack.entries.len() > 1 { | ||
| 3479 | - enc.symbol(0, &mut cdfs.drl_mode[stack.drl_ctx[0]]); | ||
| 3480 | - } | ||
| 3481 | - let mv = if is_new_mv { | ||
| 3482 | - write_mv( | ||
| 3483 | - enc, | ||
| 3484 | - &mut cdfs.mv_comp, | ||
| 3485 | - &mut cdfs.mv_joint, | ||
| 3486 | - info.mv, | ||
| 3487 | - stack.pred_mv, | ||
| 3488 | - )?; | ||
| 3489 | - info.mv | ||
| 3490 | - } else { | ||
| 3491 | - stack.nearest_mv | ||
| 3492 | - }; | ||
| 3493 | for dr in 0..SUB_MI as usize { | 3694 | for dr in 0..SUB_MI as usize { |
| 3494 | for dc in 0..SUB_MI as usize { | 3695 | for dc in 0..SUB_MI as usize { |
| 3495 | grid.set( | 3696 | grid.set( |
| @@ -3497,7 +3698,7 @@ fn write_inter_frame_leaf( | |||
| 3497 | mi_col + dc, | 3698 | mi_col + dc, |
| 3498 | MiInfo { | 3699 | MiInfo { |
| 3499 | is_inter: true, | 3700 | is_inter: true, |
| 3500 | - ref_frame: LAST_FRAME, | 3701 | + ref_frame: info.ref_frame, |
| 3501 | ref_frame1: NO_REF1, | 3702 | ref_frame1: NO_REF1, |
| 3502 | mv1: (0, 0), | 3703 | mv1: (0, 0), |
| 3503 | mv: mv16(mv), | 3704 | mv: mv16(mv), |
| @@ -3598,7 +3799,7 @@ fn write_inter_frame_leaf( | |||
| 3598 | ); | 3799 | ); |
| 3599 | neighbours.record_planes(at, SUB, mode_for_tx, &grids, !split); | 3800 | neighbours.record_planes(at, SUB, mode_for_tx, &grids, !split); |
| 3600 | } | 3801 | } |
| 3601 | - neighbours.record_inter(at, SUB, block.skip, is_inter); | 3802 | + neighbours.record_inter(at, SUB, block.skip, is_inter, block_ref(block)); |
| 3602 | Ok(()) | 3803 | Ok(()) |
| 3603 | } | 3804 | } |
| 3604 | 3805 | ||
| @@ -3646,9 +3847,6 @@ fn write_inter_frame_leaf8( | |||
| 3646 | /// `Y_MODE`'s size group (spec `Size_Group`, `common_data.h`'s | 3847 | /// `Y_MODE`'s size group (spec `Size_Group`, `common_data.h`'s |
| 3647 | /// `size_group_lookup[BLOCK_8X8]`) for this leaf's own size. | 3848 | /// `size_group_lookup[BLOCK_8X8]`) for this leaf's own size. |
| 3648 | const SIZE_GROUP_8: usize = 1; | 3849 | const SIZE_GROUP_8: usize = 1; |
| 3649 | - /// `Ref_Frame_List`'s `LAST_FRAME` (spec 3), same as the 16x16/32x32 | ||
| 3650 | - /// branches. | ||
| 3651 | - const LAST_FRAME: i8 = 1; | ||
| 3652 | 3850 | ||
| 3653 | // This leaf's own 4x4 mode-info cells, not the enclosing 16x16 slot's: | 3851 | // This leaf's own 4x4 mode-info cells, not the enclosing 16x16 slot's: |
| 3654 | // under a real PARTITION_SPLIT all four leaves are coded, so the | 3852 | // under a real PARTITION_SPLIT all four leaves are coded, so the |
| @@ -3671,10 +3869,7 @@ fn write_inter_frame_leaf8( | |||
| 3671 | 3869 | ||
| 3672 | let mode_for_tx; | 3870 | let mode_for_tx; |
| 3673 | if let Some(info) = block.inter { | 3871 | if let Some(info) = block.inter { |
| 3674 | - let sr_ctx = single_ref_ctx(above_inter || left_inter); | 3872 | + write_single_ref(enc, cdfs, info.ref_frame, neighbours.above_ref[leaf_mi.1], neighbours.left_ref[leaf_mi.0]); |
| 3675 | - enc.symbol(0, &mut cdfs.single_ref[sr_ctx][0]); // p1: forward | ||
| 3676 | - enc.symbol(0, &mut cdfs.single_ref[sr_ctx][2]); // p3: LAST/LAST2 | ||
| 3677 | - enc.symbol(0, &mut cdfs.single_ref[sr_ctx][3]); // p4: LAST | ||
| 3678 | 3873 | ||
| 3679 | let (mi_row, mi_col) = leaf_mi; | 3874 | let (mi_row, mi_col) = leaf_mi; |
| 3680 | let stack = find_mv_stack( | 3875 | let stack = find_mv_stack( |
| @@ -3683,34 +3878,12 @@ fn write_inter_frame_leaf8( | |||
| 3683 | mi_col, | 3878 | mi_col, |
| 3684 | 2, | 3879 | 2, |
| 3685 | 2, | 3880 | 2, |
| 3686 | - LAST_FRAME, | 3881 | + info.ref_frame, |
| 3687 | mi_cols as usize, | 3882 | mi_cols as usize, |
| 3688 | mi_rows as usize, | 3883 | mi_rows as usize, |
| 3689 | ); | 3884 | ); |
| 3690 | 3885 | ||
| 3691 | - let is_new_mv = matches!(info.mode, InterMode::NewMv); | 3886 | + let (mv, is_new_mv) = write_inter_mode(enc, cdfs, info, &stack)?; |
| 3692 | - if is_new_mv { | ||
| 3693 | - enc.symbol(0, &mut cdfs.new_mv[stack.new_mv_ctx]); // NEWMV | ||
| 3694 | - } else { | ||
| 3695 | - enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not new | ||
| 3696 | - enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not zero | ||
| 3697 | - enc.symbol(0, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // NEARESTMV | ||
| 3698 | - } | ||
| 3699 | - if is_new_mv && stack.entries.len() > 1 { | ||
| 3700 | - enc.symbol(0, &mut cdfs.drl_mode[stack.drl_ctx[0]]); | ||
| 3701 | - } | ||
| 3702 | - let mv = if is_new_mv { | ||
| 3703 | - write_mv( | ||
| 3704 | - enc, | ||
| 3705 | - &mut cdfs.mv_comp, | ||
| 3706 | - &mut cdfs.mv_joint, | ||
| 3707 | - info.mv, | ||
| 3708 | - stack.pred_mv, | ||
| 3709 | - )?; | ||
| 3710 | - info.mv | ||
| 3711 | - } else { | ||
| 3712 | - stack.nearest_mv | ||
| 3713 | - }; | ||
| 3714 | for dr in 0..2 { | 3887 | for dr in 0..2 { |
| 3715 | for dc in 0..2 { | 3888 | for dc in 0..2 { |
| 3716 | grid.set( | 3889 | grid.set( |
| @@ -3718,7 +3891,7 @@ fn write_inter_frame_leaf8( | |||
| 3718 | mi_col + dc, | 3891 | mi_col + dc, |
| 3719 | MiInfo { | 3892 | MiInfo { |
| 3720 | is_inter: true, | 3893 | is_inter: true, |
| 3721 | - ref_frame: LAST_FRAME, | 3894 | + ref_frame: info.ref_frame, |
| 3722 | ref_frame1: NO_REF1, | 3895 | ref_frame1: NO_REF1, |
| 3723 | mv1: (0, 0), | 3896 | mv1: (0, 0), |
| 3724 | mv: mv16(mv), | 3897 | mv: mv16(mv), |
| @@ -3796,7 +3969,7 @@ fn write_inter_frame_leaf8( | |||
| 3796 | vec![0i32; TX4 * TX4], | 3969 | vec![0i32; TX4 * TX4], |
| 3797 | ]; | 3970 | ]; |
| 3798 | neighbours.record_mi(leaf_mi, 8, &zero_grids); | 3971 | neighbours.record_mi(leaf_mi, 8, &zero_grids); |
| 3799 | - neighbours.record_inter_mi(leaf_mi, 8, block.skip, block.inter.is_some()); | 3972 | + neighbours.record_inter_mi(leaf_mi, 8, block.skip, block.inter.is_some(), block_ref(block)); |
| 3800 | } else { | 3973 | } else { |
| 3801 | let grids = [ | 3974 | let grids = [ |
| 3802 | level_grid(&block.luma, TX8)?, | 3975 | level_grid(&block.luma, TX8)?, |
| @@ -3819,7 +3992,7 @@ fn write_inter_frame_leaf8( | |||
| 3819 | split, | 3992 | split, |
| 3820 | ); | 3993 | ); |
| 3821 | neighbours.record_mi_planes(leaf_mi, 8, &grids, !split); | 3994 | neighbours.record_mi_planes(leaf_mi, 8, &grids, !split); |
| 3822 | - neighbours.record_inter_mi(leaf_mi, 8, block.skip, is_inter); | 3995 | + neighbours.record_inter_mi(leaf_mi, 8, block.skip, is_inter, block_ref(block)); |
| 3823 | } | 3996 | } |
| 3824 | Ok((block.skip, is_inter)) | 3997 | Ok((block.skip, is_inter)) |
| 3825 | } | 3998 | } |
| @@ -5987,7 +6160,7 @@ mod tests { | |||
| 5987 | let is_inter = dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1; | 6160 | let is_inter = dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1; |
| 5988 | 6161 | ||
| 5989 | let (mode, mv) = if is_inter { | 6162 | let (mode, mv) = if is_inter { |
| 5990 | - let sr_ctx = single_ref_ctx(above_inter[c32] || left_inter[r32]); | 6163 | + let sr_ctx = crate::mvstack::single_ref_ctx(above_inter[c32] || left_inter[r32]); |
| 5991 | count += 3; | 6164 | count += 3; |
| 5992 | assert_eq!( | 6165 | assert_eq!( |
| 5993 | dec.symbol(&mut cdfs.single_ref[sr_ctx][0]), | 6166 | dec.symbol(&mut cdfs.single_ref[sr_ctx][0]), |
| @@ -6101,8 +6274,10 @@ mod tests { | |||
| 6101 | fn an_all_skip_inter_superblock_is_small_and_reads_back() { | 6274 | fn an_all_skip_inter_superblock_is_small_and_reads_back() { |
| 6102 | let block = BlockCoeffs { | 6275 | let block = BlockCoeffs { |
| 6103 | inter: Some(InterInfo { | 6276 | inter: Some(InterInfo { |
| 6277 | + ref_frame: crate::mvstack::LAST_FRAME, | ||
| 6104 | mode: InterMode::NearestMv, | 6278 | mode: InterMode::NearestMv, |
| 6105 | mv: (0, 0), | 6279 | mv: (0, 0), |
| 6280 | + ref_mv_idx: 0, | ||
| 6106 | }), | 6281 | }), |
| 6107 | skip: true, | 6282 | skip: true, |
| 6108 | ..BlockCoeffs::default() | 6283 | ..BlockCoeffs::default() |
| @@ -6142,16 +6317,20 @@ mod tests { | |||
| 6142 | fn a_newmv_block_reads_back_the_exact_symbol_sequence_it_was_written_with() { | 6317 | fn a_newmv_block_reads_back_the_exact_symbol_sequence_it_was_written_with() { |
| 6143 | let nearest = BlockCoeffs { | 6318 | let nearest = BlockCoeffs { |
| 6144 | inter: Some(InterInfo { | 6319 | inter: Some(InterInfo { |
| 6320 | + ref_frame: crate::mvstack::LAST_FRAME, | ||
| 6145 | mode: InterMode::NearestMv, | 6321 | mode: InterMode::NearestMv, |
| 6146 | mv: (0, 0), | 6322 | mv: (0, 0), |
| 6323 | + ref_mv_idx: 0, | ||
| 6147 | }), | 6324 | }), |
| 6148 | skip: true, | 6325 | skip: true, |
| 6149 | ..BlockCoeffs::default() | 6326 | ..BlockCoeffs::default() |
| 6150 | }; | 6327 | }; |
| 6151 | let newmv = BlockCoeffs { | 6328 | let newmv = BlockCoeffs { |
| 6152 | inter: Some(InterInfo { | 6329 | inter: Some(InterInfo { |
| 6330 | + ref_frame: crate::mvstack::LAST_FRAME, | ||
| 6153 | mode: InterMode::NewMv, | 6331 | mode: InterMode::NewMv, |
| 6154 | mv: (0, 2), | 6332 | mv: (0, 2), |
| 6333 | + ref_mv_idx: 0, | ||
| 6155 | }), | 6334 | }), |
| 6156 | skip: true, | 6335 | skip: true, |
| 6157 | ..BlockCoeffs::default() | 6336 | ..BlockCoeffs::default() |