use crate::bitstream::BitWriter;
use crate::hevc::cabac::{CabacEncoder, CtxModel};
use crate::hevc::params::{HevcConfig, CTB_SIZE};
const PART_MODE_INIT_VALUE: u8 = 184;
pub struct PaddedYuv<'a> {
pub y: &'a [u8],
pub u: &'a [u8],
pub v: &'a [u8],
pub coded_width: u32,
pub coded_height: u32,
}
pub fn slice_segment_rbsp(cfg: &HevcConfig, yuv: &PaddedYuv) -> Vec<u8> {
slice_segment_rbsp_pps(cfg, yuv, 0)
}
pub fn slice_segment_rbsp_pps(cfg: &HevcConfig, yuv: &PaddedYuv, pps_id: u32) -> Vec<u8> {
let mut h = BitWriter::new();
h.flag(true); h.flag(false); h.write_ue(pps_id); h.write_ue(2); h.write_se(0); h.write_bit(1); let mut rbsp = h.finish();
let cw = yuv.coded_width;
let ch = yuv.coded_height;
let cwc = cw / 2; let half = CTB_SIZE / 2;
let mut cabac = CabacEncoder::new();
let mut part_ctx = CtxModel::init(PART_MODE_INIT_VALUE, cfg.qp);
let (nx, ny) = cfg.ctbs();
let total = nx * ny;
let mut coded = 0u32;
for cy in (0..ch).step_by(CTB_SIZE as usize) {
for cx in (0..cw).step_by(CTB_SIZE as usize) {
cabac.encode_bin(&mut part_ctx, 1);
cabac.encode_terminate(1);
let w = cabac.writer_mut();
w.align_zero();
emit_block(w, yuv.y, cw, cx, cy, CTB_SIZE); if cfg.has_chroma() {
let (ccx, ccy) = (cx / 2, cy / 2);
emit_block(w, yuv.u, cwc, ccx, ccy, half); emit_block(w, yuv.v, cwc, ccx, ccy, half); }
cabac.reinit();
coded += 1;
cabac.encode_terminate((coded == total) as u32);
}
}
rbsp.extend_from_slice(&cabac.finish());
rbsp
}
#[inline]
fn emit_block(w: &mut BitWriter, plane: &[u8], stride: u32, x0: u32, y0: u32, size: u32) {
for yy in 0..size {
let row = ((y0 + yy) * stride + x0) as usize;
for xx in 0..size as usize {
w.write_byte(plane[row + xx]);
}
}
}