use crate::bitstream::{rbsp_trailing_bits, BitWriter};
pub const MB_SIZE: u32 = 16;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum EntropyMode {
Cavlc,
Cabac,
}
#[derive(Clone, Copy, Debug)]
pub struct H264Config {
pub width: u32,
pub height: u32,
pub coded_width: u32,
pub coded_height: u32,
pub level_idc: u8,
pub qp: i32,
pub entropy: EntropyMode,
pub deblock: bool,
pub aq_strength: f32,
}
impl H264Config {
pub fn new(width: u32, height: u32) -> Self {
let coded_width = width.div_ceil(MB_SIZE) * MB_SIZE;
let coded_height = height.div_ceil(MB_SIZE) * MB_SIZE;
Self {
width,
height,
coded_width,
coded_height,
entropy: EntropyMode::Cavlc,
deblock: false,
aq_strength: 0.0,
level_idc: 10, qp: 26,
}
}
pub fn mbs(&self) -> (u32, u32) {
(self.coded_width / MB_SIZE, self.coded_height / MB_SIZE)
}
fn needs_crop(&self) -> bool {
self.coded_width != self.width || self.coded_height != self.height
}
fn crop_offsets(&self) -> (u32, u32, u32, u32) {
let dx = self.coded_width - self.width;
let dy = self.coded_height - self.height;
(0, dx / 2, 0, dy / 2)
}
}
pub fn write_sps(cfg: &H264Config) -> Vec<u8> {
write_sps_with_refs(cfg, 0)
}
pub fn write_sps_with_refs(cfg: &H264Config, max_num_ref_frames: u32) -> Vec<u8> {
let (mbs_w, mbs_h) = cfg.mbs();
let mut w = BitWriter::new();
w.write_byte(if cfg.entropy == EntropyMode::Cabac {
77
} else {
66
}); w.flag(false); w.flag(false); w.flag(false); w.flag(false); w.flag(false); w.flag(false); w.write_bits(0, 2); w.write_byte(cfg.level_idc);
w.write_ue(0); w.write_ue(0); w.write_ue(2); w.write_ue(max_num_ref_frames); w.flag(false); w.write_ue(mbs_w - 1); w.write_ue(mbs_h - 1); w.flag(true); w.flag(true); w.flag(cfg.needs_crop()); if cfg.needs_crop() {
let (l, r, t, b) = cfg.crop_offsets();
w.write_ue(l);
w.write_ue(r);
w.write_ue(t);
w.write_ue(b);
}
w.flag(true); write_vui(&mut w);
rbsp_trailing_bits(&mut w);
w.finish()
}
fn write_vui(w: &mut BitWriter) {
w.flag(false); w.flag(false); w.flag(true); w.write_bits(5, 3); w.flag(false); w.flag(true); w.write_byte(2); w.write_byte(2); w.write_byte(6); w.flag(false); w.flag(false); w.flag(false); w.flag(false); w.flag(false); w.flag(false); }