diff --git a/crates/ec-h265-syntax/src/lib.rs b/crates/ec-h265-syntax/src/lib.rs index 2262c216..b8551324 100644 --- a/crates/ec-h265-syntax/src/lib.rs +++ b/crates/ec-h265-syntax/src/lib.rs @@ -36,6 +36,11 @@ pub mod slice; pub mod vui; pub use nal::{AnnexBNal, NalHeader, NalUnitType, escape_rbsp, split_annex_b, unescape_rbsp}; -pub use ps::{ConformanceWindow, Pps, ProfileTierLevel, ShortTermRefPicSet, Sps, Vps}; -pub use slice::{ParsePositions, SliceHeader, SliceType, count_emulation_prevention_bytes}; +pub use ps::{ + ConformanceWindow, MAX_ST_REF_PICS, Pps, ProfileTierLevel, ShortTermRefPicSet, Sps, Vps, +}; +pub use slice::{ + LongTermRef, ParsePositions, PredWeightTable, SliceHeader, SliceType, WeightEntry, + count_emulation_prevention_bytes, +}; pub use vui::{ColourDescription, VideoSignalType, VuiParameters}; diff --git a/crates/ec-h265-syntax/src/ps.rs b/crates/ec-h265-syntax/src/ps.rs index 98904959..94454712 100644 --- a/crates/ec-h265-syntax/src/ps.rs +++ b/crates/ec-h265-syntax/src/ps.rs @@ -312,10 +312,16 @@ pub struct Sps { pub pcm: Option<(u32, u32, u32, u32, bool)>, /// `num_short_term_ref_pic_sets`. pub num_short_term_ref_pic_sets: u32, + /// The sets themselves, in bitstream order: a slice header may name one by + /// index instead of carrying it, and a decoder then needs it from here. + pub short_term_ref_pic_sets: Vec, /// `long_term_ref_pics_present_flag`. pub long_term_ref_pics_present: bool, /// `num_long_term_ref_pics_sps`. pub num_long_term_ref_pics_sps: u32, + /// `(lt_ref_pic_poc_lsb_sps, used_by_curr_pic_lt_sps_flag)` per SPS long + /// term picture, which a slice header names by index. + pub long_term_ref_pics_sps: Vec<(u32, bool)>, /// `sps_temporal_mvp_enabled_flag`. pub temporal_mvp_enabled: bool, /// `strong_intra_smoothing_enabled_flag`. @@ -417,9 +423,16 @@ impl Sps { w.write_bit(filter_off); } w.write_ue(self.num_short_term_ref_pic_sets); + for (i, set) in self.short_term_ref_pic_sets.iter().enumerate() { + set.write(&mut w, i as u32); + } w.write_bit(self.long_term_ref_pics_present); if self.long_term_ref_pics_present { w.write_ue(self.num_long_term_ref_pics_sps); + for &(poc_lsb_lt, used_by_curr) in &self.long_term_ref_pics_sps { + w.write_bits(poc_lsb_lt, self.log2_max_poc_lsb_minus4 + 4); + w.write_bit(used_by_curr); + } } w.write_bit(self.temporal_mvp_enabled); w.write_bit(self.strong_intra_smoothing); @@ -546,6 +559,7 @@ impl Sps { } let long_term_ref_pics_present = r.read_bit()?; let mut num_long_term_ref_pics_sps = 0; + let mut long_term_ref_pics_sps = Vec::new(); if long_term_ref_pics_present { num_long_term_ref_pics_sps = r.read_ue()?; if num_long_term_ref_pics_sps > 32 { @@ -554,8 +568,9 @@ impl Sps { ))); } for _ in 0..num_long_term_ref_pics_sps { - r.read_bits(log2_max_poc_lsb_minus4 + 4)?; - r.read_bit()?; + let poc_lsb_lt = r.read_bits(log2_max_poc_lsb_minus4 + 4)?; + let used_by_curr = r.read_bit()?; + long_term_ref_pics_sps.push((poc_lsb_lt, used_by_curr)); } } let temporal_mvp_enabled = r.read_bit()?; @@ -590,8 +605,10 @@ impl Sps { pcm_enabled, pcm, num_short_term_ref_pic_sets, + short_term_ref_pic_sets: sets, long_term_ref_pics_present, num_long_term_ref_pics_sps, + long_term_ref_pics_sps, temporal_mvp_enabled, strong_intra_smoothing, ptl, @@ -600,12 +617,18 @@ impl Sps { } } -/// One `st_ref_pic_set()` (7.3.7), kept only as far as re-parsing needs. +/// Largest `st_ref_pic_set()` this crate carries in either direction; the spec +/// caps `NumNegativePics` and `NumPositivePics` at `sps_max_dec_pic_buffering`, +/// which itself cannot exceed 16. +pub const MAX_ST_REF_PICS: usize = 16; + +/// One `st_ref_pic_set()` (7.3.7), with the POC deltas a decoder needs. /// -/// The delta values themselves are a decoder's reference-list problem; what a -/// *parser* has to get right is the number of pictures in each direction, -/// because the next set's syntax depends on it. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +/// A *stateless hardware* decoder is the reason the deltas are here: the driver +/// is handed `RefPicSetStCurrBefore` / `StCurrAfter` as picture lists, so +/// something has to turn `delta_poc_sX_minus1` into actual reference pictures, +/// and that something is the caller of this crate. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct ShortTermRefPicSet { /// `NumNegativePics`. pub num_negative: u32, @@ -614,6 +637,28 @@ pub struct ShortTermRefPicSet { /// How many of them have `used_by_curr_pic` set — the count that feeds /// `NumPicTotalCurr`, which sizes the reference list modification syntax. pub num_used_by_curr: u32, + /// `DeltaPocS0[i]`, negative, in decreasing order (7-59). + pub delta_poc_s0: [i32; MAX_ST_REF_PICS], + /// `UsedByCurrPicS0[i]`. + pub used_s0: [bool; MAX_ST_REF_PICS], + /// `DeltaPocS1[i]`, positive, in increasing order (7-60). + pub delta_poc_s1: [i32; MAX_ST_REF_PICS], + /// `UsedByCurrPicS1[i]`. + pub used_s1: [bool; MAX_ST_REF_PICS], +} + +impl Default for ShortTermRefPicSet { + fn default() -> ShortTermRefPicSet { + ShortTermRefPicSet { + num_negative: 0, + num_positive: 0, + num_used_by_curr: 0, + delta_poc_s0: [0; MAX_ST_REF_PICS], + used_s0: [false; MAX_ST_REF_PICS], + delta_poc_s1: [0; MAX_ST_REF_PICS], + used_s1: [false; MAX_ST_REF_PICS], + } + } } impl ShortTermRefPicSet { @@ -636,46 +681,153 @@ impl ShortTermRefPicSet { let reference = *prev .get(ref_idx as usize) .ok_or_else(|| Error::corrupt("HEVC st_ref_pic_set: unknown reference set"))?; - r.read_bit()?; // delta_rps_sign - r.read_ue()?; // abs_delta_rps_minus1 - let num_delta_pocs = reference.num_negative + reference.num_positive; - let mut kept = 0; - let mut used_by_curr = 0; - for _ in 0..=num_delta_pocs { - let used = r.read_bit()?; - if used { - kept += 1; - used_by_curr += 1; - } else if r.read_bit()? { - kept += 1; + let delta_rps_sign = r.read_bit()?; + let abs_delta_rps_minus1 = r.read_ue()?; + let delta_rps = if delta_rps_sign { + -((abs_delta_rps_minus1 + 1) as i32) + } else { + (abs_delta_rps_minus1 + 1) as i32 + }; + let num_delta_pocs = (reference.num_negative + reference.num_positive) as usize; + if num_delta_pocs >= MAX_ST_REF_PICS * 2 { + return Err(Error::corrupt( + "HEVC st_ref_pic_set: reference set too large", + )); + } + let mut used_by_curr = [false; MAX_ST_REF_PICS * 2 + 1]; + let mut use_delta = [true; MAX_ST_REF_PICS * 2 + 1]; + for j in 0..=num_delta_pocs { + used_by_curr[j] = r.read_bit()?; + if !used_by_curr[j] { + use_delta[j] = r.read_bit()?; } } - // Without reconstructing the POCs the split between negative and - // positive is not knowable; the total is, and that is what the - // syntax of any following set depends on. - Ok(ShortTermRefPicSet { - num_negative: kept, - num_positive: 0, - num_used_by_curr: used_by_curr, - }) + Ok(reference.predict(delta_rps, &used_by_curr, &use_delta)) } else { let num_negative = r.read_ue()?; let num_positive = r.read_ue()?; - if num_negative > 16 || num_positive > 16 { + if num_negative as usize > MAX_ST_REF_PICS || num_positive as usize > MAX_ST_REF_PICS { return Err(Error::corrupt("HEVC st_ref_pic_set: too many pictures")); } - let mut num_used_by_curr = 0; - for _ in 0..num_negative + num_positive { - r.read_ue()?; // delta_poc_sX_minus1 - if r.read_bit()? { - num_used_by_curr += 1; // used_by_curr_pic_sX_flag - } - } - Ok(ShortTermRefPicSet { + let mut set = ShortTermRefPicSet { num_negative, num_positive, - num_used_by_curr, - }) + ..ShortTermRefPicSet::default() + }; + let mut poc = 0i32; + for i in 0..num_negative as usize { + let delta = r.read_ue()? as i32 + 1; + poc -= delta; + set.delta_poc_s0[i] = poc; + set.used_s0[i] = r.read_bit()?; + if set.used_s0[i] { + set.num_used_by_curr += 1; + } + } + let mut poc = 0i32; + for i in 0..num_positive as usize { + let delta = r.read_ue()? as i32 + 1; + poc += delta; + set.delta_poc_s1[i] = poc; + set.used_s1[i] = r.read_bit()?; + if set.used_s1[i] { + set.num_used_by_curr += 1; + } + } + Ok(set) + } + } + + /// Derive a set predicted from this one (7-61, 7-62). + /// + /// The two loops per direction are the spec's, and their order is what puts + /// `DeltaPocS0` in decreasing and `DeltaPocS1` in increasing order without a + /// sort: entries derived from the *other* direction of the reference set + /// come first, then the reference picture itself, then the same direction. + fn predict( + &self, + delta_rps: i32, + used_by_curr: &[bool], + use_delta: &[bool], + ) -> ShortTermRefPicSet { + let mut out = ShortTermRefPicSet::default(); + let neg = self.num_negative as usize; + let pos = self.num_positive as usize; + let num_delta_pocs = neg + pos; + + let mut i = 0usize; + for j in (0..pos).rev() { + let d = self.delta_poc_s1[j] + delta_rps; + if d < 0 && use_delta[neg + j] && i < MAX_ST_REF_PICS { + out.delta_poc_s0[i] = d; + out.used_s0[i] = used_by_curr[neg + j]; + i += 1; + } + } + if delta_rps < 0 && use_delta[num_delta_pocs] && i < MAX_ST_REF_PICS { + out.delta_poc_s0[i] = delta_rps; + out.used_s0[i] = used_by_curr[num_delta_pocs]; + i += 1; + } + for j in 0..neg { + let d = self.delta_poc_s0[j] + delta_rps; + if d < 0 && use_delta[j] && i < MAX_ST_REF_PICS { + out.delta_poc_s0[i] = d; + out.used_s0[i] = used_by_curr[j]; + i += 1; + } + } + out.num_negative = i as u32; + + let mut i = 0usize; + for j in (0..neg).rev() { + let d = self.delta_poc_s0[j] + delta_rps; + if d > 0 && use_delta[j] && i < MAX_ST_REF_PICS { + out.delta_poc_s1[i] = d; + out.used_s1[i] = used_by_curr[j]; + i += 1; + } + } + if delta_rps > 0 && use_delta[num_delta_pocs] && i < MAX_ST_REF_PICS { + out.delta_poc_s1[i] = delta_rps; + out.used_s1[i] = used_by_curr[num_delta_pocs]; + i += 1; + } + for j in 0..pos { + let d = self.delta_poc_s1[j] + delta_rps; + if d > 0 && use_delta[neg + j] && i < MAX_ST_REF_PICS { + out.delta_poc_s1[i] = d; + out.used_s1[i] = used_by_curr[neg + j]; + i += 1; + } + } + out.num_positive = i as u32; + out.num_used_by_curr = out.used_s0[..out.num_negative as usize] + .iter() + .chain(out.used_s1[..out.num_positive as usize].iter()) + .filter(|&&u| u) + .count() as u32; + out + } + + /// Write the set in its non-predicted form (7.3.7), which is always legal. + pub fn write(&self, w: &mut ec_core::BitWriter, idx: u32) { + if idx != 0 { + w.write_bit(false); // inter_ref_pic_set_prediction_flag + } + w.write_ue(self.num_negative); + w.write_ue(self.num_positive); + let mut prev = 0i32; + for i in 0..self.num_negative as usize { + w.write_ue((prev - self.delta_poc_s0[i] - 1).max(0) as u32); + prev = self.delta_poc_s0[i]; + w.write_bit(self.used_s0[i]); + } + let mut prev = 0i32; + for i in 0..self.num_positive as usize { + w.write_ue((self.delta_poc_s1[i] - prev - 1).max(0) as u32); + prev = self.delta_poc_s1[i]; + w.write_bit(self.used_s1[i]); } } } @@ -988,8 +1140,10 @@ mod tests { pcm_enabled: false, pcm: None, num_short_term_ref_pic_sets: 0, + short_term_ref_pic_sets: Vec::new(), long_term_ref_pics_present: false, num_long_term_ref_pics_sps: 0, + long_term_ref_pics_sps: Vec::new(), temporal_mvp_enabled: false, strong_intra_smoothing: true, ptl: ProfileTierLevel::main(120), diff --git a/crates/ec-h265-syntax/src/slice.rs b/crates/ec-h265-syntax/src/slice.rs index b9a3a269..e483291b 100644 --- a/crates/ec-h265-syntax/src/slice.rs +++ b/crates/ec-h265-syntax/src/slice.rs @@ -37,6 +37,41 @@ impl SliceType { } } +/// One long-term reference picture named by a slice header (7.3.6.1). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct LongTermRef { + /// `PocLsbLt`: the low bits of the reference's picture order count. + pub poc_lsb_lt: u32, + /// `UsedByCurrPicLt`: whether the current picture may predict from it. + pub used_by_curr: bool, + /// `delta_poc_msb_present_flag`. + pub delta_poc_msb_present: bool, + /// `DeltaPocMsbCycleLt`, accumulated as equation 7-52 requires. + pub delta_poc_msb_cycle: u32, +} + +/// One entry of a `pred_weight_table()` (7.3.6.3). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct WeightEntry { + /// `(delta_luma_weight, luma_offset)`, absent when the flag was 0. + pub luma: Option<(i32, i32)>, + /// `(delta_chroma_weight, ChromaOffset)` per chroma component. + pub chroma: Option<[(i32, i32); 2]>, +} + +/// A parsed `pred_weight_table()` (7.3.6.3). +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct PredWeightTable { + /// `luma_log2_weight_denom`. + pub luma_log2_weight_denom: u32, + /// `delta_chroma_log2_weight_denom`. + pub delta_chroma_log2_weight_denom: i32, + /// One entry per active list 0 reference. + pub l0: Vec, + /// One entry per active list 1 reference. + pub l1: Vec, +} + /// A slice segment header, as far as an intra encoder writes one and a /// stateless hardware decoder reads one. #[derive(Debug, Clone, PartialEq, Eq)] @@ -96,6 +131,22 @@ pub struct SliceHeader { pub loop_filter_across_slices_enabled: bool, /// Substream entry points: one per WPP CTB row (or tile) after the first. pub entry_point_offsets: Vec, + /// The short-term reference picture set in force, whether it came from the + /// SPS by index or was written out in this header. + /// + /// This and the three fields after it are what a *stateless hardware* + /// decoder needs and a software one derives on the fly: the driver is given + /// `RefPicSetStCurrBefore` / `StCurrAfter` / `LtCurr` as picture lists, so + /// the caller has to turn these deltas into reference pictures itself. + pub short_term_ref_pic_set: ShortTermRefPicSet, + /// True when the set above came from the SPS rather than this header. + pub short_term_ref_pic_set_sps_flag: bool, + /// The long-term reference pictures this slice names, in bitstream order. + pub long_term: Vec, + /// `list_entry_l0` / `list_entry_l1`; empty when the list is not modified. + pub list_entry: [Vec; 2], + /// `pred_weight_table()`, when the PPS turns weighted prediction on. + pub pred_weight_table: Option, } impl SliceHeader { @@ -129,6 +180,11 @@ impl SliceHeader { tc_offset_div2: 0, loop_filter_across_slices_enabled: pps.loop_filter_across_slices_enabled, entry_point_offsets: Vec::new(), + short_term_ref_pic_set: ShortTermRefPicSet::default(), + short_term_ref_pic_set_sps_flag: true, + long_term: Vec::new(), + list_entry: [Vec::new(), Vec::new()], + pred_weight_table: None, } } @@ -138,6 +194,26 @@ impl SliceHeader { /// encoder codes its substreams first and builds the header afterwards — /// the offsets are not knowable any earlier. pub fn write(&self, w: &mut BitWriter, sps: &Sps, pps: &Pps, nal_type: NalUnitType) { + self.write_without_alignment(w, sps, pps, nal_type); + // byte_alignment(): a one bit then zeros. + w.write_bit(true); + w.align_to_byte(); + } + + /// The header without its closing `byte_alignment()`. + /// + /// A VA-API encoder wants exactly this: the driver is told how many bits of + /// header the application wrote and appends the alignment itself, so + /// including it here leaves the alignment bit sitting where the driver + /// expects slice data (measured on radeonsi: every P picture then decodes + /// as `alignment_bit_equal_to_one = 0`). + pub fn write_without_alignment( + &self, + w: &mut BitWriter, + sps: &Sps, + pps: &Pps, + nal_type: NalUnitType, + ) { w.write_bit(self.first_slice_segment_in_pic); if nal_type.is_irap() { w.write_bit(self.no_output_of_prior_pics); @@ -159,11 +235,17 @@ impl SliceHeader { } if !nal_type.is_idr() { w.write_bits(self.poc_lsb, sps.log2_max_poc_lsb_minus4 + 4); - // An intra encoder writes no reference picture sets at all; a - // non-IDR picture from this family does not exist yet. - w.write_bit(true); // short_term_ref_pic_set_sps_flag - if sps.num_short_term_ref_pic_sets > 1 { - w.write_bits(0, ceil_log2(sps.num_short_term_ref_pic_sets)); + w.write_bit(self.short_term_ref_pic_set_sps_flag); + if self.short_term_ref_pic_set_sps_flag { + if sps.num_short_term_ref_pic_sets > 1 { + w.write_bits(0, ceil_log2(sps.num_short_term_ref_pic_sets)); + } + } else { + // Written out here, which is what a stream whose SPS carries + // no sets must do — and what a hardware encoder's driver + // does for its own single reference. + self.short_term_ref_pic_set + .write(w, sps.num_short_term_ref_pic_sets); } if sps.temporal_mvp_enabled { w.write_bit(self.temporal_mvp_enabled); @@ -210,9 +292,6 @@ impl SliceHeader { } } } - // byte_alignment(): a one bit then zeros. - w.write_bit(true); - w.align_to_byte(); } /// Parse a slice segment header out of an unescaped slice NAL payload. @@ -250,20 +329,44 @@ impl SliceHeader { if sps.separate_colour_plane { h.colour_plane_id = r.read_bits(2)? as u8; } - let mut st_rps = ShortTermRefPicSet::default(); let mut num_long_term = 0; if !nal_type.is_idr() { h.poc_lsb = r.read_bits(sps.log2_max_poc_lsb_minus4 + 4)?; let from_sps = r.read_bit()?; + h.short_term_ref_pic_set_sps_flag = from_sps; let before = r.bit_position(); if !from_sps { - // The sets in the SPS are not kept, so an inter-set - // predicted slice set cannot be resolved here. - st_rps = ShortTermRefPicSet::parse(&mut r, 0, &[])?; - } else if sps.num_short_term_ref_pic_sets > 1 { - r.read_bits(ceil_log2(sps.num_short_term_ref_pic_sets))?; + // Written out here, possibly predicted from the SPS sets — + // hence `num_short_term_ref_pic_sets` as this set's index + // and the SPS sets as the prediction source (7.3.7). + h.short_term_ref_pic_set = ShortTermRefPicSet::parse( + &mut r, + sps.num_short_term_ref_pic_sets, + &sps.short_term_ref_pic_sets, + )?; + } else { + let idx = if sps.num_short_term_ref_pic_sets > 1 { + r.read_bits(ceil_log2(sps.num_short_term_ref_pic_sets))? + } else { + 0 + }; + h.short_term_ref_pic_set = sps + .short_term_ref_pic_sets + .get(idx as usize) + .copied() + .ok_or_else(|| { + Error::corrupt(format!( + "HEVC slice: short_term_ref_pic_set_idx {idx} is not in the SPS" + )) + })?; } - pos.st_rps_bits = (r.bit_position() - before) as u32; + // Only a set written *in the header* costs the driver bits to + // skip; for an SPS-indexed one libva wants zero. + pos.st_rps_bits = if from_sps { + 0 + } else { + (r.bit_position() - before) as u32 + }; if sps.long_term_ref_pics_present { let num_long_term_sps = if sps.num_long_term_ref_pics_sps > 0 { r.read_ue()? @@ -271,21 +374,42 @@ impl SliceHeader { 0 }; let num_long_term_pics = r.read_ue()?; + let mut prev_delta_msb = 0u32; for i in 0..num_long_term_sps + num_long_term_pics { + let mut entry = LongTermRef::default(); if i < num_long_term_sps { - if sps.num_long_term_ref_pics_sps > 1 { - r.read_bits(ceil_log2(sps.num_long_term_ref_pics_sps))?; - } - num_long_term += 1; + let idx = if sps.num_long_term_ref_pics_sps > 1 { + r.read_bits(ceil_log2(sps.num_long_term_ref_pics_sps))? + } else { + 0 + }; + let (poc_lsb_lt, used) = sps + .long_term_ref_pics_sps + .get(idx as usize) + .copied() + .unwrap_or((0, false)); + entry.poc_lsb_lt = poc_lsb_lt; + entry.used_by_curr = used; } else { - r.read_bits(sps.log2_max_poc_lsb_minus4 + 4)?; // poc_lsb_lt - if r.read_bit()? { - num_long_term += 1; // used_by_curr_pic_lt_flag - } + entry.poc_lsb_lt = r.read_bits(sps.log2_max_poc_lsb_minus4 + 4)?; + entry.used_by_curr = r.read_bit()?; } - if r.read_bit()? { - r.read_ue()?; // delta_poc_msb_cycle_lt + if entry.used_by_curr { + num_long_term += 1; + } + entry.delta_poc_msb_present = r.read_bit()?; + if entry.delta_poc_msb_present { + // 7-52: coded as a delta against the previous entry, + // except for the first of each kind. + let delta = r.read_ue()?; + entry.delta_poc_msb_cycle = if i == 0 || i == num_long_term_sps { + delta + } else { + delta + prev_delta_msb + }; + prev_delta_msb = entry.delta_poc_msb_cycle; } + h.long_term.push(entry); } } if sps.temporal_mvp_enabled { @@ -307,17 +431,19 @@ impl SliceHeader { h.num_ref_idx_l1_active_minus1 = r.read_ue()?; } } - let num_pic_total_curr = st_rps.num_used_by_curr + num_long_term; + let num_pic_total_curr = h.short_term_ref_pic_set.num_used_by_curr + num_long_term; if pps.lists_modification_present && num_pic_total_curr > 1 { let bits = ceil_log2(num_pic_total_curr); if r.read_bit()? { for _ in 0..=h.num_ref_idx_l0_active_minus1 { - r.read_bits(bits)?; + let entry = r.read_bits(bits)?; + h.list_entry[0].push(entry); } } if h.slice_type == SliceType::B && r.read_bit()? { for _ in 0..=h.num_ref_idx_l1_active_minus1 { - r.read_bits(bits)?; + let entry = r.read_bits(bits)?; + h.list_entry[1].push(entry); } } } @@ -340,7 +466,7 @@ impl SliceHeader { if (pps.weighted_pred && h.slice_type == SliceType::P) || (pps.weighted_bipred && h.slice_type == SliceType::B) { - skip_pred_weight_table(&mut r, &h, sps)?; + h.pred_weight_table = Some(parse_pred_weight_table(&mut r, &h, sps)?); } h.five_minus_max_num_merge_cand = r.read_ue()?; } @@ -464,13 +590,34 @@ pub fn count_emulation_prevention_bytes(escaped_payload: &[u8]) -> usize { count } -/// Walk past a `pred_weight_table()` (7.3.6.3). -fn skip_pred_weight_table(r: &mut BitReader, h: &SliceHeader, sps: &Sps) -> Result<()> { - r.read_ue()?; // luma_log2_weight_denom +/// Parse a `pred_weight_table()` (7.3.6.3). +/// +/// The chroma *offset* is derived, not coded: equation 7-56 turns +/// `delta_chroma_offset_lX` into `ChromaOffsetLX` against the weight, and a +/// decoder that forwards the raw delta to hardware shifts every weighted +/// chroma sample. +fn parse_pred_weight_table( + r: &mut BitReader, + h: &SliceHeader, + sps: &Sps, +) -> Result { + let mut table = PredWeightTable { + luma_log2_weight_denom: r.read_ue()?, + ..PredWeightTable::default() + }; let chroma = sps.chroma_format_idc != 0; if chroma { - r.read_se()?; // delta_chroma_log2_weight_denom + table.delta_chroma_log2_weight_denom = r.read_se()?; } + let chroma_log2 = table.luma_log2_weight_denom as i32 + table.delta_chroma_log2_weight_denom; + if !(0..=7).contains(&chroma_log2) { + return Err(Error::corrupt( + "HEVC pred_weight_table: ChromaLog2WeightDenom out of range", + )); + } + // A fuzzed SPS can name any bit depth; the shift below has to survive it. + let half_range = 1i64 << (sps.bit_depth_chroma_minus8.min(8) + 7); + let lists: &[u32] = if h.slice_type == SliceType::B { &[ h.num_ref_idx_l0_active_minus1, @@ -479,32 +626,50 @@ fn skip_pred_weight_table(r: &mut BitReader, h: &SliceHeader, sps: &Sps) -> Resu } else { &[h.num_ref_idx_l0_active_minus1] }; - for &active_minus1 in lists { - let count = active_minus1 + 1; - let mut luma_flags = Vec::with_capacity(count as usize); + for (list, &active_minus1) in lists.iter().enumerate() { + let count = (active_minus1 + 1) as usize; + let mut luma_flags = Vec::with_capacity(count); for _ in 0..count { luma_flags.push(r.read_bit()?); } - let mut chroma_flags = Vec::with_capacity(count as usize); + let mut chroma_flags = vec![false; count]; if chroma { - for _ in 0..count { - chroma_flags.push(r.read_bit()?); + for flag in chroma_flags.iter_mut() { + *flag = r.read_bit()?; } } - for i in 0..count as usize { + let mut entries = Vec::with_capacity(count); + for i in 0..count { + let mut entry = WeightEntry::default(); if luma_flags[i] { - r.read_se()?; // delta_luma_weight - r.read_se()?; // luma_offset + let delta_weight = r.read_se()?; + let offset = r.read_se()?; + entry.luma = Some((delta_weight, offset)); } if chroma && chroma_flags[i] { - for _ in 0..2 { - r.read_se()?; // delta_chroma_weight - r.read_se()?; // delta_chroma_offset + let mut pair = [(0i32, 0i32); 2]; + for component in &mut pair { + let delta_weight = r.read_se()?; + let delta_offset = r.read_se()?; + let weight = (1i64 << chroma_log2) + i64::from(delta_weight); + // 7-56, in 64 bits because both terms come straight off the + // wire and a corrupt stream must not overflow the derivation. + let offset = (half_range + i64::from(delta_offset) + - ((half_range * weight) >> chroma_log2)) + .clamp(-half_range, half_range - 1); + *component = (delta_weight, offset as i32); } + entry.chroma = Some(pair); } + entries.push(entry); + } + if list == 0 { + table.l0 = entries; + } else { + table.l1 = entries; } } - Ok(()) + Ok(table) } #[cfg(test)] @@ -538,8 +703,10 @@ mod tests { pcm_enabled: false, pcm: None, num_short_term_ref_pic_sets: 0, + short_term_ref_pic_sets: Vec::new(), long_term_ref_pics_present: false, num_long_term_ref_pics_sps: 0, + long_term_ref_pics_sps: Vec::new(), temporal_mvp_enabled: false, strong_intra_smoothing: true, ptl: ProfileTierLevel::main(120), diff --git a/crates/ec-h265-syntax/tests/fuzz.rs b/crates/ec-h265-syntax/tests/fuzz.rs index 67542af4..44e58c7a 100644 --- a/crates/ec-h265-syntax/tests/fuzz.rs +++ b/crates/ec-h265-syntax/tests/fuzz.rs @@ -65,8 +65,10 @@ fn reference_sps() -> Sps { pcm_enabled: false, pcm: None, num_short_term_ref_pic_sets: 0, + short_term_ref_pic_sets: Vec::new(), long_term_ref_pics_present: false, num_long_term_ref_pics_sps: 0, + long_term_ref_pics_sps: Vec::new(), temporal_mvp_enabled: true, strong_intra_smoothing: true, ptl: ProfileTierLevel::main(120), diff --git a/crates/ec-h265/src/encoder.rs b/crates/ec-h265/src/encoder.rs index 6e5a938d..1cb53f46 100644 --- a/crates/ec-h265/src/encoder.rs +++ b/crates/ec-h265/src/encoder.rs @@ -199,8 +199,10 @@ impl Encoder { pcm_enabled: false, pcm: None, num_short_term_ref_pic_sets: 0, + short_term_ref_pic_sets: Vec::new(), long_term_ref_pics_present: false, num_long_term_ref_pics_sps: 0, + long_term_ref_pics_sps: Vec::new(), temporal_mvp_enabled: false, strong_intra_smoothing: true, ptl,