use super::inter::{self, InterRefs}; use super::mc::{Block, McScratch}; use super::motion_field::SliceMotion; use super::pic::{BlockInfo, CtbInfo, EDGE_PU, EDGE_TU, PicState, SaoParams, SliceFilter}; use super::tiles::TileScan; use super::{cross_component, rdpcm_accumulate, rotate_180}; use crate::cabac::{CabacDecoder, Contexts, ctx}; use crate::decode::chroma_shifts; use crate::intra; use crate::residual::{ResidualCfg, decode_residual_ext}; use crate::transform::{ chroma_qp_for, dequantize_weighted, inverse_transform_bd, inverse_transform_skip_bd, uses_dst, }; use ec_core::error::{Error, Result}; use ec_h265_syntax::slice::{SliceHeader, SliceType}; use ec_h265_syntax::{Pps, ScalingFactors, Sps}; pub mod wpp; mod cu; mod pu; mod residual; mod sao; mod tu; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum PartMode { Part2Nx2N, Part2NxN, PartNx2N, PartNxN, Part2NxnU, Part2NxnD, PartnLx2N, PartnRx2N, } #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum InterPredIdc { #[default] PredL0, PredL1, PredBi, } #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct PredictionUnit { pub x: usize, pub y: usize, pub width: usize, pub height: usize, pub merge_flag: bool, pub merge_idx: u8, pub inter_pred_idc: InterPredIdc, pub ref_idx: [u8; 2], pub mvp_flag: [u8; 2], pub mvd: [[i32; 2]; 2], } #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct Motion { pub pred_flags: [bool; 2], pub ref_idx: [i8; 2], pub mv: [[i32; 2]; 2], } #[derive(Clone, Debug, PartialEq, Eq)] pub struct ResidualBlock { pub component: usize, pub x: usize, pub y: usize, pub size: usize, pub samples: Vec, } pub fn parse_slice_into( sps: &Sps, pps: &Pps, header: &SliceHeader, data: &[u8], motion: &mut SliceMotion<'_>, pic: &mut PicState, refs: Option<&InterRefs>, rows: &mut dyn FnMut(&mut PicState, usize), ) -> Result<()> { let min_cb_log2 = sps.log2_min_cb_size_minus3 + 3; let ctb_log2 = min_cb_log2 + sps.log2_diff_max_min_cb_size; let slice_qp = 26 + pps.init_qp_minus26 + header.qp_delta; if pps.log2_parallel_merge_level_minus2.saturating_add(2) > ctb_log2 { return Err(Error::corrupt( "HEVC PPS: Log2ParMrgLevel exceeds CtbLog2SizeY", )); } if pps.cu_qp_delta_enabled && pps.diff_cu_qp_delta_depth > sps.log2_diff_max_min_cb_size { return Err(Error::corrupt( "HEVC PPS: diff_cu_qp_delta_depth exceeds the CTB depth", )); } if !(-6 * sps.bit_depth_luma_minus8 as i32..=51).contains(&slice_qp) { return Err(Error::corrupt( "HEVC slice: SliceQpY is outside -QpBdOffsetY..=51", )); } let init_type = match header.slice_type { SliceType::I => 0, SliceType::P => 1 + u8::from(header.cabac_init), SliceType::B => 2 - u8::from(header.cabac_init), }; let cols = pic.ctb_cols; let total = cols * pic.ctb_rows; pic.tiles = TileScan::from_pps(pps, cols, pic.ctb_rows)?; let start_ts = pic .tiles .rs_to_ts .get(header.segment_address as usize) .copied() .ok_or_else(|| { Error::corrupt("HEVC slice: slice_segment_address is outside the picture") })?; if !header.dependent_slice_segment { pic.carry.slice_addr = header.segment_address as usize; } let slice_addr = pic.carry.slice_addr; let dependent = header.dependent_slice_segment; let slice_index = u16::try_from(pic.slices.len()).map_err(|_| { Error::unsupported("HEVC slice syntax: slice count", "more than 65535 slices") })?; pic.slices.push(SliceFilter { deblock_disabled: header.deblocking_filter_disabled, beta_offset_div2: header.beta_offset_div2, tc_offset_div2: header.tc_offset_div2, loop_filter_across_slices: header.loop_filter_across_slices_enabled, sao_luma: header.sao_luma, sao_chroma: header.sao_chroma, }); let last_qp = if dependent { pic.carry.last_qp } else { slice_qp }; let mut p = new_parser(sps, pps, header, pic, refs, motion, last_qp); let fresh = Contexts::for_init_type(slice_qp, init_type); let mut dec = CabacDecoder::new(data, fresh.clone()); let wpp = pps.entropy_coding_sync_enabled; let raster = !pps.tiles_enabled; let ctb_size = 1usize << ctb_log2; let mut ended = false; let mut ts = start_ts; let mut first = true; while ts < total { let rs = p .pic .tiles .ts_to_rs .get(ts) .copied() .ok_or_else(|| Error::corrupt("HEVC slice: CTB address past the picture"))?; let (rx, ry) = (rs % cols, rs / cols); let (x0, y0) = (rx << ctb_log2, ry << ctb_log2); let tile_start = p.pic.tiles.is_tile_start(ts); let row_start = wpp && p.pic.tiles.is_row_start(rs, cols); let tile = p.pic.tiles.tile_of_rs.get(rs).copied().unwrap_or(0); let ctb = p .pic .ctb .get_mut(rs) .ok_or_else(|| Error::corrupt("HEVC slice: CTB address past the picture"))?; *ctb = CtbInfo { slice: slice_index, slice_addr: slice_addr as u32, tile, sao: ctb.sao, }; p.ctus += 1; if tile_start { dec.contexts = fresh.clone(); } else if row_start { let top_right = p.pic.available( x0, y0, (x0 + ctb_size) as isize, y0 as isize - ctb_size as isize, ); dec.contexts = match (top_right, p.pic.carry.wpp.clone()) { (true, Some(saved)) => saved, _ => fresh.clone(), }; } else if first && dependent { dec.contexts = p.pic.carry.ds.clone().unwrap_or_else(|| fresh.clone()); } if tile_start || row_start || (first && !dependent) { p.last_qp = slice_qp; } if header.sao_luma || header.sao_chroma { p.sao(&mut dec, rs, rx, ry)?; } p.coding_quadtree(&mut dec, x0, y0, ctb_log2, 0)?; if raster && rx + 1 == cols { p.motion.row_done(p.pic, y0 + ctb_size); rows(p.pic, ry); } if wpp && (rs % cols == 1 || (rs > 1 && p.pic.tiles.tile_of_rs.get(rs) != p.pic.tiles.tile_of_rs.get(rs - 2))) { p.pic.carry.wpp = Some(dec.contexts.clone()); } if dec.decode_terminate() != 0 { ended = true; break; } ts += 1; first = false; if ts < total { let next_rs = p.pic.tiles.ts_to_rs.get(ts).copied().unwrap_or(0); let next_row = wpp && p.pic.tiles.is_row_start(next_rs, cols); if p.pic.tiles.is_tile_start(ts) || next_row { if dec.decode_terminate() != 1 { return Err(Error::corrupt( "HEVC slice syntax: end_of_subset_one_bit was not set at a substream boundary", )); } dec.restart_at_byte(dec.byte_position_aligned()); } } } if !ended { return Err(Error::corrupt( "HEVC slice syntax: end_of_slice_segment_flag 0 after the last CTB of the picture", )); } p.pic.carry.ds = Some(dec.contexts.clone()); p.pic.carry.last_qp = p.last_qp; let read = dec.bits_read(); if !trailing_bits_ok(data, read) { return Err(Error::corrupt(format!( "HEVC slice syntax: no stop bit at the end of the slice data (CABAC read {read} bits)" ))); } Ok(()) } pub(super) fn trailing_bits_ok(data: &[u8], read: usize) -> bool { let stop_at = |bit: usize| -> bool { let Some(&byte) = data.get(bit / 8) else { return false; }; let shift = 7 - (bit % 8); byte & (1 << shift) != 0 && byte & ((1u16 << shift) - 1) as u8 == 0 && data[bit / 8 + 1..].iter().all(|&b| b == 0) }; read > 0 && (stop_at(read - 1) || stop_at(read)) } fn new_parser<'a, 'm>( sps: &'a Sps, pps: &'a Pps, header: &'a SliceHeader, pic: &'a mut PicState, refs: Option<&'a InterRefs>, motion: &'a mut SliceMotion<'m>, last_qp: i32, ) -> Parser<'a, 'm> { let min_cb_log2 = sps.log2_min_cb_size_minus3 + 3; let ctb_log2 = min_cb_log2 + sps.log2_diff_max_min_cb_size; let min_tb_log2 = sps.log2_min_tb_size_minus2 + 2; let slice_qp = 26 + pps.init_qp_minus26 + header.qp_delta; Parser { s: SliceCtx { sps, pps, header, scaling: ScalingFactors::for_picture(sps, pps), min_cb_log2, ctb_log2, min_tb_log2, max_tb_log2: min_tb_log2 + sps.log2_diff_max_min_tb_size, max_depth_inter: sps.max_transform_hierarchy_depth_inter, max_depth_intra: sps.max_transform_hierarchy_depth_intra, max_merge: 5 - header.five_minus_max_num_merge_cand.min(4), qg_log2: ctb_log2 - if pps.cu_qp_delta_enabled { pps.diff_cu_qp_delta_depth } else { 0 }, qp_bd_y: 6 * sps.bit_depth_luma_minus8 as i32, qp_bd_c: 6 * sps.bit_depth_chroma_minus8 as i32, cu_chroma_qp_offset_enabled: header.cu_chroma_qp_offset_enabled, chroma_qg_log2: ctb_log2 - pps.range.diff_cu_chroma_qp_offset_depth, }, pic, refs, mc_scratch: McScratch::new(), last_qp, qg_pred: slice_qp, qp_delta: 0, qp_delta_coded: false, chroma_qg_coded: false, cu_qp_offset: [0, 0], cu_bypass: false, chroma_modes: ([1; 4], [false; 4]), motion, ctus: 0, } } #[derive(Clone, Copy)] struct TxInfo { intra: bool, intra_split: bool, inter_split: bool, max_depth: u32, chroma_modes: [u8; 4], chroma_dm: [bool; 4], cu_x: usize, cu_y: usize, cu_log2: u32, } #[derive(Clone, Copy)] struct TxNode { x0: usize, y0: usize, x_base: usize, y_base: usize, log2: u32, depth: u32, blk_idx: usize, } const MODE_422: [u8; 35] = [ 0, 1, 2, 2, 2, 2, 3, 5, 7, 8, 10, 12, 13, 15, 17, 18, 19, 20, 21, 22, 23, 23, 24, 24, 25, 25, 26, 27, 27, 28, 28, 29, 29, 30, 31, ]; #[derive(Clone, Copy)] struct Cbf { luma: bool, cb: [bool; 2], cr: [bool; 2], } struct SliceCtx<'a> { sps: &'a Sps, pps: &'a Pps, header: &'a SliceHeader, scaling: Option, min_cb_log2: u32, ctb_log2: u32, min_tb_log2: u32, max_tb_log2: u32, max_depth_inter: u32, max_depth_intra: u32, max_merge: u32, qg_log2: u32, qp_bd_y: i32, qp_bd_c: i32, cu_chroma_qp_offset_enabled: bool, chroma_qg_log2: u32, } struct Parser<'a, 'm> { s: SliceCtx<'a>, pic: &'a mut PicState, refs: Option<&'a InterRefs>, mc_scratch: McScratch, last_qp: i32, qg_pred: i32, qp_delta: i32, qp_delta_coded: bool, chroma_qg_coded: bool, cu_qp_offset: [i32; 2], cu_bypass: bool, chroma_modes: ([u8; 4], [bool; 4]), motion: &'a mut SliceMotion<'m>, ctus: usize, } fn read_raw_bits(data: &[u8], pos: &mut usize, count: u32) -> Result { let mut v = 0u32; for _ in 0..count { let byte = *data .get(*pos / 8) .ok_or_else(|| Error::corrupt("HEVC slice syntax: PCM samples run past the slice"))?; v = (v << 1) | u32::from((byte >> (7 - (*pos % 8))) & 1); *pos += 1; } Ok(v) } fn truncated_unary(dec: &mut CabacDecoder, cmax: u32, first_ctx: usize) -> u32 { let mut v = 0; while v < cmax { let bin = if v == 0 { dec.decode_bin(first_ctx) } else { dec.decode_bypass() }; if bin == 0 { break; } v += 1; } v } fn inter_pred_idc(dec: &mut CabacDecoder, width: usize, height: usize, depth: u32) -> InterPredIdc { if width + height != 12 && dec.decode_bin(ctx::INTER_PRED_IDC + depth as usize) != 0 { return InterPredIdc::PredBi; } if dec.decode_bin(ctx::INTER_PRED_IDC + 4) != 0 { InterPredIdc::PredL1 } else { InterPredIdc::PredL0 } } fn decode_exp_golomb(dec: &mut CabacDecoder, mut k: u32) -> Result { let mut value = 0u32; while dec.decode_bypass() != 0 { if k >= 31 { return Err(Error::corrupt( "HEVC slice syntax: Exp-Golomb prefix too long", )); } value += 1 << k; k += 1; } Ok(value + dec.decode_bypass_bits(k)) } fn pu_rects(part: PartMode, x: usize, y: usize, n: usize) -> Vec<(usize, usize, usize, usize)> { let h = n / 2; let q = n / 4; match part { PartMode::Part2Nx2N => vec![(x, y, n, n)], PartMode::Part2NxN => vec![(x, y, n, h), (x, y + h, n, h)], PartMode::PartNx2N => vec![(x, y, h, n), (x + h, y, h, n)], PartMode::PartNxN => vec![ (x, y, h, h), (x + h, y, h, h), (x, y + h, h, h), (x + h, y + h, h, h), ], PartMode::Part2NxnU => vec![(x, y, n, q), (x, y + q, n, n - q)], PartMode::Part2NxnD => vec![(x, y, n, n - q), (x, y + n - q, n, q)], PartMode::PartnLx2N => vec![(x, y, q, n), (x + q, y, n - q, n)], PartMode::PartnRx2N => vec![(x, y, n - q, n), (x + n - q, y, q, n)], } }