287 lines · 11.7 KB · RustRaw
//! A film made from nothing: a few seconds of a sun crossing a sky, as an//! H.264 Baseline stream in an MP4 — the container and codec every phone//! plays — with no encoder in the tree.//!//! THE TRICK IS `I_PCM`. H.264 lets a macroblock carry its samples raw//! (mb_type 25 in an I slice), so a frame needs no transform, no prediction//! and no entropy coding: a slice header written bit by bit, then each//! macroblock's 256 luma and 2 × 64 chroma bytes. Every frame is an IDR//! picture, so any frame is a place to seek to. The cost is size — 18 KB a//! frame at 128 × 96 — which is why the film is small and short.//!//! The parameter sets and the slice header are spelled out field by field//! below (ITU-T H.264 §7.3) rather than pasted as magic bytes, so a reader can//! see what each one says./// Width and height in pixels — whole macroblocks.pub const WIDTH: usize = 128;pub const HEIGHT: usize = 96;/// Frames a second.pub const FPS: u32 = 10;const PROFILE_BASELINE: u8 = 66;/// constraint_set0 and constraint_set1: Baseline that a Main decoder takes.const CONSTRAINTS: u8 = 0b1100_0000;/// Level 3.0 — 10 Mbit/s, comfortably above what raw macroblocks cost here.const LEVEL: u8 = 30;#[derive(Default)]struct Bits { bytes: Vec<u8>, bit: u8,}impl Bits { fn put(&mut self, value: u32, count: u8) { for n in (0..count).rev() { if self.bit == 0 { self.bytes.push(0); } if (value >> n) & 1 == 1 { *self.bytes.last_mut().expect("a byte") |= 0x80 >> self.bit; } self.bit = (self.bit + 1) % 8; } } fn flag(&mut self, on: bool) { self.put(u32::from(on), 1); } /// Unsigned exp-Golomb. fn ue(&mut self, value: u32) { let coded = value + 1; let width = 32 - coded.leading_zeros() as u8; self.put(0, width - 1); self.put(coded, width); } /// Signed exp-Golomb. fn se(&mut self, value: i32) { let mapped = if value > 0 { 2 * value as u32 - 1 } else { (-2 * value) as u32 }; self.ue(mapped); } /// Zero bits up to the next byte. fn align(&mut self) { if self.bit != 0 { self.put(0, 8 - self.bit); } } /// rbsp_trailing_bits: a one, then zeros to the byte. fn trail(mut self) -> Vec<u8> { self.flag(true); self.align(); self.bytes }}/// A NAL unit: its header byte, then the payload with emulation prevention/// (a 0x03 after any two zeros that a byte ≤ 3 would turn into a start code).fn nal(ref_idc: u8, kind: u8, rbsp: &[u8]) -> Vec<u8> { let mut out = vec![(ref_idc << 5) | kind]; let mut zeros = 0; for &byte in rbsp { if zeros >= 2 && byte <= 3 { out.push(3); zeros = 0; } out.push(byte); zeros = if byte == 0 { zeros + 1 } else { 0 }; } out}fn sps() -> Vec<u8> { let mut b = Bits::default(); b.put(u32::from(PROFILE_BASELINE), 8); b.put(u32::from(CONSTRAINTS), 8); b.put(u32::from(LEVEL), 8); b.ue(0); // seq_parameter_set_id b.ue(0); // log2_max_frame_num_minus4 b.ue(2); // pic_order_cnt_type: order is decode order, nothing in the slice b.ue(1); // max_num_ref_frames b.flag(false); // gaps_in_frame_num_value_allowed_flag b.ue((WIDTH / 16 - 1) as u32); b.ue((HEIGHT / 16 - 1) as u32); b.flag(true); // frame_mbs_only_flag b.flag(true); // direct_8x8_inference_flag b.flag(false); // frame_cropping_flag b.flag(false); // vui_parameters_present_flag nal(3, 7, &b.trail())}fn pps() -> Vec<u8> { let mut b = Bits::default(); b.ue(0); // pic_parameter_set_id b.ue(0); // seq_parameter_set_id b.flag(false); // entropy_coding_mode_flag: CAVLC b.flag(false); // bottom_field_pic_order_in_frame_present_flag b.ue(0); // num_slice_groups_minus1 b.ue(0); // num_ref_idx_l0_default_active_minus1 b.ue(0); // num_ref_idx_l1_default_active_minus1 b.flag(false); // weighted_pred_flag b.put(0, 2); // weighted_bipred_idc b.se(0); // pic_init_qp_minus26 b.se(0); // pic_init_qs_minus26 b.se(0); // chroma_qp_index_offset b.flag(true); // deblocking_filter_control_present_flag b.flag(false); // constrained_intra_pred_flag b.flag(false); // redundant_pic_cnt_present_flag nal(3, 8, &b.trail())}/// One frame as one IDR slice of `I_PCM` macroblocks. `yuv` is the frame's/// planes, 4:2:0: luma `WIDTH × HEIGHT`, then Cb and Cr at half each way.fn idr_slice(index: u32, yuv: &[u8]) -> Vec<u8> { let mut b = Bits::default(); b.ue(0); // first_mb_in_slice b.ue(7); // slice_type: I, and every slice of the picture is b.ue(0); // pic_parameter_set_id b.put(0, 4); // frame_num (an IDR's is zero) b.ue(index % 2); // idr_pic_id: consecutive IDRs differ b.flag(false); // no_output_of_prior_pics_flag b.flag(false); // long_term_reference_flag b.se(0); // slice_qp_delta b.ue(1); // disable_deblocking_filter_idc: raw samples need no smoothing let luma = WIDTH * HEIGHT; let chroma = luma / 4; let cw = WIDTH / 2; for my in 0..HEIGHT / 16 { for mx in 0..WIDTH / 16 { b.ue(25); // mb_type I_PCM b.align(); // pcm_alignment_zero_bit for y in 0..16 { let row = (my * 16 + y) * WIDTH + mx * 16; b.bytes.extend_from_slice(&yuv[row..row + 16]); } for plane in [luma, luma + chroma] { for y in 0..8 { let row = plane + (my * 8 + y) * cw + mx * 8; b.bytes.extend_from_slice(&yuv[row..row + 8]); } } } } nal(3, 5, &b.trail())}/// What the film shows at `t` seconds of `length` — a sun crossing a sky/// that warms as it goes — as 4:2:0 planes. Samples stay inside the video/// range (16–235), which also keeps the raw bytes clear of start codes.fn frame(t: f64, length: f64) -> Vec<u8> { let progress = (t / length).clamp(0.0, 1.0); let sun = (0.12 + 0.76 * progress, 0.55 - 0.3 * (progress * std::f64::consts::PI).sin()); let rgb = |x: f64, y: f64| -> [f64; 3] { let dx = (x - sun.0) * WIDTH as f64 / HEIGHT as f64; let dy = y - sun.1; if y > 0.78 { return [40.0, 90.0 + 30.0 * progress, 60.0]; } if (dx * dx + dy * dy).sqrt() < 0.12 { return [250.0, 210.0, 90.0]; } [60.0 + 150.0 * progress * y, 110.0 + 60.0 * y, 200.0 - 80.0 * progress * y] }; let luma = WIDTH * HEIGHT; let mut out = vec![0u8; luma + luma / 2]; let clamp = |v: f64| v.round().clamp(16.0, 235.0) as u8; for y in 0..HEIGHT { for x in 0..WIDTH { let [r, g, b] = rgb(x as f64 / WIDTH as f64, y as f64 / HEIGHT as f64); out[y * WIDTH + x] = clamp(16.0 + 0.257 * r + 0.504 * g + 0.098 * b); } } let cw = WIDTH / 2; for y in 0..HEIGHT / 2 { for x in 0..cw { let [r, g, b] = rgb((2 * x) as f64 / WIDTH as f64, (2 * y) as f64 / HEIGHT as f64); out[luma + y * cw + x] = clamp(128.0 - 0.148 * r - 0.291 * g + 0.439 * b); out[luma + luma / 4 + y * cw + x] = clamp(128.0 + 0.439 * r - 0.368 * g - 0.071 * b); } } out}fn boxed(kind: &[u8; 4], body: &[u8]) -> Vec<u8> { let mut out = Vec::with_capacity(body.len() + 8); out.extend_from_slice(&u32::try_from(body.len() + 8).expect("a small box").to_be_bytes()); out.extend_from_slice(kind); out.extend_from_slice(body); out}/// A full box: version 0 and `flags`, then the body.fn full(kind: &[u8; 4], flags: u32, body: &[u8]) -> Vec<u8> { let mut inner = flags.to_be_bytes().to_vec(); inner[0] = 0; inner.extend_from_slice(body); boxed(kind, &inner)}const MATRIX: [u32; 9] = [0x0001_0000, 0, 0, 0, 0x0001_0000, 0, 0, 0, 0x4000_0000];fn be(parts: &[&[u8]]) -> Vec<u8> { parts.concat()}/// The film, `seconds` long, as an MP4 with its index ahead of the bytes so a/// player can start before the end has arrived.pub fn mp4(seconds: u32) -> Vec<u8> { let count = seconds * FPS; let (sps, pps) = (sps(), pps()); let samples: Vec<Vec<u8>> = (0..count) .map(|n| { let slice = idr_slice(n, &frame(f64::from(n) / f64::from(FPS), f64::from(seconds))); be(&[&u32::try_from(slice.len()).expect("a frame").to_be_bytes(), &slice]) }) .collect(); let duration_ms = seconds * 1000; let (w, h) = (WIDTH as u32, HEIGHT as u32); let matrix: Vec<u8> = MATRIX.iter().flat_map(|v| v.to_be_bytes()).collect(); let moov = |offset: u32| -> Vec<u8> { let mvhd = full(b"mvhd", 0, &be(&[ &0u32.to_be_bytes(), &0u32.to_be_bytes(), &1000u32.to_be_bytes(), &duration_ms.to_be_bytes(), &0x0001_0000u32.to_be_bytes(), &0x0100u16.to_be_bytes(), &[0; 10], &matrix, &[0; 24], &2u32.to_be_bytes(), ])); let tkhd = full(b"tkhd", 3, &be(&[ &0u32.to_be_bytes(), &0u32.to_be_bytes(), &1u32.to_be_bytes(), &0u32.to_be_bytes(), &duration_ms.to_be_bytes(), &[0; 8], &0u16.to_be_bytes(), &0u16.to_be_bytes(), &0u16.to_be_bytes(), &0u16.to_be_bytes(), &matrix, &(w << 16).to_be_bytes(), &(h << 16).to_be_bytes(), ])); let mdhd = full(b"mdhd", 0, &be(&[ &0u32.to_be_bytes(), &0u32.to_be_bytes(), &FPS.to_be_bytes(), &count.to_be_bytes(), &0x55c4u16.to_be_bytes(), &0u16.to_be_bytes(), ])); let hdlr = full(b"hdlr", 0, &be(&[&0u32.to_be_bytes(), b"vide", &[0; 12], b"VideoHandler\0"])); let vmhd = full(b"vmhd", 1, &[0; 8]); let dinf = boxed(b"dinf", &full(b"dref", 0, &be(&[&1u32.to_be_bytes(), &full(b"url ", 1, &[])]))); let avcc = boxed(b"avcC", &be(&[ &[1, PROFILE_BASELINE, CONSTRAINTS, LEVEL, 0xff, 0xe1], &u16::try_from(sps.len()).expect("sps").to_be_bytes(), &sps, &[1], &u16::try_from(pps.len()).expect("pps").to_be_bytes(), &pps, ])); let mut name = [0u8; 32]; name[0] = 5; name[1..6].copy_from_slice(b"Synth"); let avc1 = boxed(b"avc1", &be(&[ &[0; 6], &1u16.to_be_bytes(), &[0; 16], &(w as u16).to_be_bytes(), &(h as u16).to_be_bytes(), &0x0048_0000u32.to_be_bytes(), &0x0048_0000u32.to_be_bytes(), &0u32.to_be_bytes(), &1u16.to_be_bytes(), &name, &0x0018u16.to_be_bytes(), &0xffffu16.to_be_bytes(), &avcc, ])); let stsd = full(b"stsd", 0, &be(&[&1u32.to_be_bytes(), &avc1])); let stts = full(b"stts", 0, &be(&[&1u32.to_be_bytes(), &count.to_be_bytes(), &1u32.to_be_bytes()])); let stsc = full(b"stsc", 0, &be(&[&1u32.to_be_bytes(), &1u32.to_be_bytes(), &count.to_be_bytes(), &1u32.to_be_bytes()])); let sizes: Vec<u8> = samples.iter().flat_map(|s| u32::try_from(s.len()).expect("a frame").to_be_bytes()).collect(); let stsz = full(b"stsz", 0, &be(&[&0u32.to_be_bytes(), &count.to_be_bytes(), &sizes])); let stco = full(b"stco", 0, &be(&[&1u32.to_be_bytes(), &offset.to_be_bytes()])); let stbl = boxed(b"stbl", &be(&[&stsd, &stts, &stsc, &stsz, &stco])); let minf = boxed(b"minf", &be(&[&vmhd, &dinf, &stbl])); let mdia = boxed(b"mdia", &be(&[&mdhd, &hdlr, &minf])); let trak = boxed(b"trak", &be(&[&tkhd, &mdia])); boxed(b"moov", &be(&[&mvhd, &trak])) }; let ftyp = boxed(b"ftyp", &be(&[b"isom", &0x200u32.to_be_bytes(), b"isomiso2avc1mp41"])); // The offset does not change the index's length, so measure, then place. let head = ftyp.len() + moov(0).len() + 8; let moov = moov(u32::try_from(head).expect("a small film")); let mdat = boxed(b"mdat", &samples.concat()); be(&[&ftyp, &moov, &mdat])}