forge
Explore
Log in

Don't you dare go Hollow

Encode a key-frame picture

Browse files at this commit

a4fb030e8cbb84c57c8bd92919ed7d3df8e0ef0bAhmet Kaan GümüşParent: 5f0963e
  • feat
    • encode a key-frame picture
Show full message
feat(av1): encode a key-frame picture

DC intra prediction over the reconstruction, the forward transform and
quantizer, and the tile writer, joined into an encoder that takes a planar
4:2:0 picture and produces a stream. Blocks are 32x32 luma and 16x16
chroma, coded in the order a decoder walks a superblock's quadrants.

The gate is an equality: ffmpeg's decode of the stream matches the
encoder's own reconstruction sample for sample, on every plane, for test
cards at three sizes and for a frame of real video. Prediction reads the
reconstruction, so a single sample of drift would spread through every
block below and to the right of it.

At q_idx 100 a 640x352 film frame costs 32 366 bytes at 39.26 dB, which is
about 2.4 dB behind libaom at the same rate -- the size of what is not
implemented yet: one block size, one transform type, DC prediction only,
no rate-distortion decision, no CDF adaptation.
crates/ec-av1/src/encode.rsadded+641 -0
@@ -0,0 +1,641 @@
1+//! A key-frame picture encoder: a planar 4:2:0 picture in, an AV1 stream out.
2+//!
3+//! This is the layer that turns the pieces below it — DC intra prediction, the
4+//! forward transform and quantizer of [`crate::transform`], and the tile writer
5+//! of [`crate::tile`] — into something that takes a picture. Every block is
6+//! DC-predicted and 32x32 (its chroma 16x16), which is the subset the tile
7+//! writer codes; block sizes, transform types and mode decision are what a
8+//! rate-distortion loop above this would choose between.
9+//!
10+//! The encoder carries its own reconstruction, because prediction reads it: a
11+//! block predicts from the reconstructed samples above and to its left, exactly
12+//! as the decoder will. That makes the reconstruction a claim about what a
13+//! decoder produces, and it is gated as one — sample for sample against ffmpeg.
14+
15+use ec_av1_syntax::sequence::{ColorConfig, OperatingPoint, SequenceHeader};
16+use ec_av1_syntax::{
17+ ChromaSamplePosition, FrameHeader, FrameType, PRIMARY_REF_NONE, QuantizationParams, TileInfo,
18+ TxMode,
19+};
20+use ec_core::{Error, Result};
21+
22+use crate::frame::frame_obu;
23+use crate::obu::temporal_delimiter;
24+use crate::sequence::sequence_header_obu;
25+use crate::tile::{BlockCoeffs, Coeff, Superblock, sb_coeff_key_frame_tile};
26+use crate::transform::{dequant_and_inverse, forward_and_quantize};
27+
28+/// The side of the luma blocks this encoder codes, in samples.
29+const BLOCK: usize = 32;
30+
31+/// One 8-bit planar 4:2:0 picture.
32+#[derive(Clone, Debug, PartialEq, Eq)]
33+pub struct Picture {
34+ /// The picture's width in luma samples.
35+ pub width: usize,
36+ /// Its height in luma samples.
37+ pub height: usize,
38+ /// The luma plane, `width * height` samples in raster order.
39+ pub y: Vec<u8>,
40+ /// The U plane, at half the width and half the height.
41+ pub u: Vec<u8>,
42+ /// The V plane, the same shape as U.
43+ pub v: Vec<u8>,
44+}
45+
46+impl Picture {
47+ /// A mid-grey picture of the given size.
48+ #[must_use]
49+ pub fn grey(width: usize, height: usize) -> Self {
50+ Self {
51+ width,
52+ height,
53+ y: vec![128; width * height],
54+ u: vec![128; width * height / 4],
55+ v: vec![128; width * height / 4],
56+ }
57+ }
58+
59+ fn check(&self) -> Result<()> {
60+ if self.width == 0
61+ || !self.width.is_multiple_of(BLOCK)
62+ || !self.height.is_multiple_of(BLOCK)
63+ || !self.height.is_multiple_of(BLOCK)
64+ {
65+ return Err(Error::unsupported(
66+ "AV1 encode",
67+ "the picture must be a whole number of 32x32 blocks in each direction",
68+ ));
69+ }
70+ let (luma, chroma) = (self.width * self.height, self.width * self.height / 4);
71+ if self.y.len() != luma || self.u.len() != chroma || self.v.len() != chroma {
72+ return Err(Error::unsupported(
73+ "AV1 encode",
74+ "each plane must carry one sample per position at 4:2:0",
75+ ));
76+ }
77+ Ok(())
78+ }
79+}
80+
81+/// What one call to [`encode_key_frame`] produced.
82+#[derive(Clone, Debug)]
83+pub struct Encoded {
84+ /// The AV1 stream: a temporal delimiter, a sequence header OBU and a frame
85+ /// OBU carrying one tile.
86+ pub stream: Vec<u8>,
87+ /// What a decoder will produce from `stream` — the encoder's own
88+ /// reconstruction, which its prediction was built on.
89+ pub reconstruction: Picture,
90+}
91+
92+/// The sequence and frame headers a picture of this size is coded under: one
93+/// tile, one transform size per block, no in-loop filtering, no CDF adaptation
94+/// and no tool the tile writer does not code.
95+///
96+/// # Errors
97+/// Returns an error when the picture is larger than the 16-bit frame size the
98+/// sequence header carries.
99+pub fn key_frame_headers(
100+ width: usize,
101+ height: usize,
102+ base_q_idx: u8,
103+) -> Result<(SequenceHeader, FrameHeader)> {
104+ let bits = |n: usize| -> Result<u32> {
105+ let n = u32::try_from(n).map_err(|_| too_large())?;
106+ if n == 0 || n > 1 << 16 {
107+ return Err(too_large());
108+ }
109+ Ok((32 - (n - 1).leading_zeros()).max(1))
110+ };
111+ let (frame_width_bits, frame_height_bits) = (bits(width)?, bits(height)?);
112+ let (w, h) = (width as u32, height as u32);
113+ let seq = SequenceHeader {
114+ seq_profile: 0,
115+ operating_points: vec![OperatingPoint {
116+ seq_level_idx: 8,
117+ ..OperatingPoint::default()
118+ }],
119+ frame_width_bits,
120+ frame_height_bits,
121+ max_frame_width: w,
122+ max_frame_height: h,
123+ use_128x128_superblock: false,
124+ enable_filter_intra: false,
125+ enable_intra_edge_filter: false,
126+ enable_order_hint: true,
127+ order_hint_bits: 7,
128+ enable_superres: false,
129+ enable_cdef: false,
130+ enable_restoration: false,
131+ seq_force_screen_content_tools: 0,
132+ seq_force_integer_mv: 0,
133+ color_config: ColorConfig {
134+ bit_depth: 8,
135+ mono_chrome: false,
136+ num_planes: 3,
137+ color_primaries: 2,
138+ transfer_characteristics: 2,
139+ matrix_coefficients: 2,
140+ color_range: false,
141+ subsampling_x: 1,
142+ subsampling_y: 1,
143+ chroma_sample_position: ChromaSamplePosition::Unknown,
144+ separate_uv_delta_q: false,
145+ },
146+ still_picture: false,
147+ reduced_still_picture_header: false,
148+ timing_info: None,
149+ decoder_model_info: None,
150+ initial_display_delay_present_flag: false,
151+ operating_point: 0,
152+ operating_point_idc: 0,
153+ frame_id_numbers_present_flag: false,
154+ delta_frame_id_length: 0,
155+ additional_frame_id_length: 0,
156+ enable_interintra_compound: false,
157+ enable_masked_compound: false,
158+ enable_warped_motion: false,
159+ enable_dual_filter: false,
160+ enable_jnt_comp: false,
161+ enable_ref_frame_mvs: false,
162+ film_grain_params_present: false,
163+ };
164+ let (mi_cols, mi_rows) = (w / 4, h / 4);
165+ let header = FrameHeader {
166+ frame_type: FrameType::Key,
167+ frame_is_intra: true,
168+ show_frame: true,
169+ error_resilient_mode: true,
170+ disable_cdf_update: true,
171+ force_integer_mv: true,
172+ refresh_frame_flags: 0xFF,
173+ primary_ref_frame: PRIMARY_REF_NONE,
174+ frame_width: w,
175+ frame_height: h,
176+ upscaled_width: w,
177+ render_width: w,
178+ render_height: h,
179+ mi_cols,
180+ mi_rows,
181+ tile_info: TileInfo {
182+ uniform_spacing: true,
183+ cols: 1,
184+ rows: 1,
185+ mi_col_starts: vec![0, mi_cols],
186+ mi_row_starts: vec![0, mi_rows],
187+ tile_size_bytes: 1,
188+ ..TileInfo::default()
189+ },
190+ quantization: QuantizationParams {
191+ base_q_idx,
192+ ..QuantizationParams::default()
193+ },
194+ tx_mode: TxMode::Largest,
195+ ..FrameHeader::default()
196+ };
197+ Ok((seq, header))
198+}
199+
200+fn too_large() -> Error {
201+ Error::unsupported(
202+ "AV1 encode",
203+ "the picture is larger than a frame size can carry",
204+ )
205+}
206+
207+/// `dc_predict` (spec 7.11.2): the average of the reconstructed row above and
208+/// the reconstructed column to the left, of whichever of them exists.
209+fn dc_predict(above: Option<&[u8]>, left: Option<&[u8]>) -> u8 {
210+ match (above, left) {
211+ (None, None) => 128,
212+ (Some(a), None) => {
213+ let sum: u32 = a.iter().map(|&s| u32::from(s)).sum();
214+ ((sum + (a.len() as u32 >> 1)) / a.len() as u32) as u8
215+ }
216+ (None, Some(l)) => {
217+ let sum: u32 = l.iter().map(|&s| u32::from(s)).sum();
218+ ((sum + (l.len() as u32 >> 1)) / l.len() as u32) as u8
219+ }
220+ (Some(a), Some(l)) => {
221+ let sum: u32 = a.iter().chain(l).map(|&s| u32::from(s)).sum();
222+ let count = (a.len() + l.len()) as u32;
223+ ((sum + (count >> 1)) / count) as u8
224+ }
225+ }
226+}
227+
228+/// One plane of the picture being coded, and the reconstruction being built
229+/// beside it.
230+struct Plane<'a> {
231+ source: &'a [u8],
232+ reconstruction: Vec<u8>,
233+ width: usize,
234+ height: usize,
235+}
236+
237+impl Plane<'_> {
238+ /// Codes one block: predicts it from the reconstruction, transforms and
239+ /// quantizes what is left, writes the reconstruction back and hands the
240+ /// levels to the caller.
241+ fn code_block(
242+ &mut self,
243+ x: usize,
244+ y: usize,
245+ side: usize,
246+ base_q_idx: u8,
247+ deadzone: f64,
248+ ) -> Vec<Coeff> {
249+ let above = (y > 0).then(|| &self.reconstruction[(y - 1) * self.width + x..][..side]);
250+ let left = (x > 0).then(|| {
251+ (0..side)
252+ .map(|i| self.reconstruction[(y + i) * self.width + x - 1])
253+ .collect::<Vec<_>>()
254+ });
255+ let prediction = i32::from(dc_predict(above, left.as_deref()));
256+
257+ let mut residual = vec![0i32; side * side];
258+ for row in 0..side {
259+ for col in 0..side {
260+ residual[row * side + col] =
261+ i32::from(self.source[(y + row) * self.width + x + col]) - prediction;
262+ }
263+ }
264+ let levels = forward_and_quantize(&residual, side, 8, i32::from(base_q_idx), deadzone);
265+ let coded = dequant_and_inverse(&levels, side, 8, i32::from(base_q_idx));
266+ for row in 0..side {
267+ for col in 0..side {
268+ self.reconstruction[(y + row) * self.width + x + col] =
269+ (prediction + coded[row * side + col]).clamp(0, 255) as u8;
270+ }
271+ }
272+ levels
273+ .iter()
274+ .enumerate()
275+ .filter(|&(_, &level)| level != 0)
276+ .map(|(i, &level)| Coeff {
277+ row: (i / side) as u8,
278+ col: (i % side) as u8,
279+ level,
280+ })
281+ .collect()
282+ }
283+}
284+
285+/// Encodes one picture as a key frame.
286+///
287+/// `base_q_idx` is the frame's quantizer index, and has to sit in the band
288+/// whose coefficient CDFs the tile writer carries (61..=120). `deadzone` is the
289+/// quantizer's rounding offset: 0.5 rounds to nearest, and smaller values trade
290+/// fidelity for rate.
291+///
292+/// # Errors
293+/// Returns an error when the picture is not a whole number of 32x32 blocks,
294+/// when its planes are not 4:2:0 of that size, or when the tile writer refuses
295+/// the quantizer index.
296+pub fn encode_key_frame(picture: &Picture, base_q_idx: u8, deadzone: f64) -> Result<Encoded> {
297+ picture.check()?;
298+ let (seq, header) = key_frame_headers(picture.width, picture.height, base_q_idx)?;
299+
300+ let mut luma = Plane {
301+ source: &picture.y,
302+ reconstruction: vec![128; picture.y.len()],
303+ width: picture.width,
304+ height: picture.height,
305+ };
306+ let mut chroma = [
307+ Plane {
308+ source: &picture.u,
309+ reconstruction: vec![128; picture.u.len()],
310+ width: picture.width / 2,
311+ height: picture.height / 2,
312+ },
313+ Plane {
314+ source: &picture.v,
315+ reconstruction: vec![128; picture.v.len()],
316+ width: picture.width / 2,
317+ height: picture.height / 2,
318+ },
319+ ];
320+
321+ let (cols, rows) = (picture.width / BLOCK, picture.height / BLOCK);
322+ let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
323+ let mut superblocks = Vec::with_capacity(sb_cols * sb_rows);
324+ for sb_row in 0..sb_rows {
325+ for sb_col in 0..sb_cols {
326+ // The quadrants of a superblock are coded in the order the decoder
327+ // walks them, which for a 64x64 split into 32x32 blocks is raster
328+ // order among the quadrants that are inside the frame.
329+ let mut blocks = Vec::with_capacity(4);
330+ for quadrant in 0..4 {
331+ let (col, row) = (sb_col * 2 + quadrant % 2, sb_row * 2 + quadrant / 2);
332+ if col >= cols || row >= rows {
333+ continue;
334+ }
335+ let (x, y) = (col * BLOCK, row * BLOCK);
336+ blocks.push(BlockCoeffs {
337+ luma: luma.code_block(x, y, BLOCK, base_q_idx, deadzone),
338+ u: chroma[0].code_block(x / 2, y / 2, BLOCK / 2, base_q_idx, deadzone),
339+ v: chroma[1].code_block(x / 2, y / 2, BLOCK / 2, base_q_idx, deadzone),
340+ mode: 0,
341+ });
342+ }
343+ superblocks.push(Superblock::Split(blocks));
344+ }
345+ }
346+
347+ let tile = sb_coeff_key_frame_tile(header.mi_cols, header.mi_rows, base_q_idx, &superblocks)?;
348+ let mut stream = temporal_delimiter();
349+ stream.extend_from_slice(&sequence_header_obu(&seq)?);
350+ stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);
351+
352+ let [u, v] = chroma;
353+ Ok(Encoded {
354+ stream,
355+ reconstruction: Picture {
356+ width: luma.width,
357+ height: luma.height,
358+ y: luma.reconstruction,
359+ u: u.reconstruction,
360+ v: v.reconstruction,
361+ },
362+ })
363+}
364+
365+#[cfg(test)]
366+mod tests {
367+ use super::*;
368+ use std::io::Write;
369+ use std::process::{Command, Stdio};
370+
371+ fn have_ffmpeg() -> bool {
372+ Command::new("ffmpeg")
373+ .arg("-version")
374+ .stdout(Stdio::null())
375+ .stderr(Stdio::null())
376+ .status()
377+ .is_ok_and(|s| s.success())
378+ }
379+
380+ /// Decodes an AV1 OBU stream with ffmpeg and hands back the three planes.
381+ fn ffmpeg_decode(stream: &[u8], width: usize, height: usize) -> Picture {
382+ let mut child = Command::new("ffmpeg")
383+ .args([
384+ "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
385+ ])
386+ .stdin(Stdio::piped())
387+ .stdout(Stdio::piped())
388+ .stderr(Stdio::piped())
389+ .spawn()
390+ .expect("ffmpeg failed to start");
391+ child
392+ .stdin
393+ .take()
394+ .expect("ffmpeg stdin")
395+ .write_all(stream)
396+ .expect("writing the stream to ffmpeg");
397+ let out = child.wait_with_output().expect("ffmpeg failed to run");
398+ assert!(
399+ out.status.success(),
400+ "ffmpeg refused the stream: {}",
401+ String::from_utf8_lossy(&out.stderr)
402+ );
403+ let (luma, chroma) = (width * height, width * height / 4);
404+ assert_eq!(
405+ out.stdout.len(),
406+ luma + 2 * chroma,
407+ "expected one 4:2:0 frame"
408+ );
409+ Picture {
410+ width,
411+ height,
412+ y: out.stdout[..luma].to_vec(),
413+ u: out.stdout[luma..luma + chroma].to_vec(),
414+ v: out.stdout[luma + chroma..].to_vec(),
415+ }
416+ }
417+
418+ /// A picture with something of everything in it: a gradient, an edge, a
419+ /// ripple and a block of flat colour, none of them aligned to the block
420+ /// grid.
421+ fn test_card(width: usize, height: usize) -> Picture {
422+ let mut picture = Picture::grey(width, height);
423+ for y in 0..height {
424+ for x in 0..width {
425+ let gradient = x as f64 * 200.0 / width as f64;
426+ let ripple = 30.0
427+ * (x as f64 * std::f64::consts::PI / 23.0).sin()
428+ * (y as f64 * std::f64::consts::PI / 37.0).cos();
429+ let edge = if x > width * 3 / 7 && y > height / 3 {
430+ 40.0
431+ } else {
432+ 0.0
433+ };
434+ picture.y[y * width + x] =
435+ (20.0 + gradient + ripple + edge).clamp(0.0, 255.0) as u8;
436+ }
437+ }
438+ for y in 0..height / 2 {
439+ for x in 0..width / 2 {
440+ let i = y * width / 2 + x;
441+ picture.u[i] = (100 + (x * 60 / (width / 2))) as u8;
442+ picture.v[i] = (200 - (y * 80 / (height / 2))) as u8;
443+ }
444+ }
445+ picture
446+ }
447+
448+ fn psnr(a: &[u8], b: &[u8]) -> f64 {
449+ let squared: f64 = a
450+ .iter()
451+ .zip(b)
452+ .map(|(&x, &y)| {
453+ let d = f64::from(x) - f64::from(y);
454+ d * d
455+ })
456+ .sum();
457+ if squared == 0.0 {
458+ return f64::INFINITY;
459+ }
460+ 10.0 * (255.0 * 255.0 * a.len() as f64 / squared).log10()
461+ }
462+
463+ /// The claim the whole encoder rests on: what a decoder produces is what
464+ /// the encoder said it would, sample for sample, on every plane.
465+ ///
466+ /// Prediction reads the reconstruction, so a single sample of drift
467+ /// anywhere would spread into every block below and to the right of it —
468+ /// which is why this is an equality and not a tolerance.
469+ #[test]
470+ fn ffmpeg_decodes_exactly_what_the_encoder_reconstructed() {
471+ if !have_ffmpeg() {
472+ eprintln!("SKIP ffmpeg_decodes_exactly_what_the_encoder_reconstructed: no ffmpeg");
473+ return;
474+ }
475+ for &(width, height) in &[(64usize, 64usize), (96, 64), (160, 96)] {
476+ let picture = test_card(width, height);
477+ let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();
478+ let decoded = ffmpeg_decode(&encoded.stream, width, height);
479+ assert_eq!(
480+ decoded.y, encoded.reconstruction.y,
481+ "{width}x{height}: luma"
482+ );
483+ assert_eq!(decoded.u, encoded.reconstruction.u, "{width}x{height}: U");
484+ assert_eq!(decoded.v, encoded.reconstruction.v, "{width}x{height}: V");
485+ }
486+ }
487+
488+ /// The picture that comes back is the picture that went in, to within the
489+ /// quantizer. A prediction that read the wrong neighbours, or a block
490+ /// written into the wrong place, would still decode to what the encoder
491+ /// reconstructed — it is this gate that says the reconstruction is of the
492+ /// right picture.
493+ #[test]
494+ fn the_encoded_picture_is_the_one_that_went_in() {
495+ let picture = test_card(160, 96);
496+ let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();
497+ let luma = psnr(&encoded.reconstruction.y, &picture.y);
498+ assert!(luma > 36.0, "luma PSNR {luma} at q 100");
499+ for (plane, (got, want)) in [
500+ (encoded.reconstruction.u.as_slice(), picture.u.as_slice()),
501+ (encoded.reconstruction.v.as_slice(), picture.v.as_slice()),
502+ ]
503+ .iter()
504+ .enumerate()
505+ {
506+ let chroma = psnr(got, want);
507+ assert!(chroma > 40.0, "chroma plane {plane} PSNR {chroma} at q 100");
508+ }
509+ }
510+
511+ /// A finer quantizer costs bits and buys fidelity, and a wider deadzone
512+ /// does the opposite. Both are monotone, which is what a rate-distortion
513+ /// loop above this will assume.
514+ #[test]
515+ fn fidelity_and_rate_move_with_the_quantizer() {
516+ let picture = test_card(128, 128);
517+ let mut previous: Option<(usize, f64)> = None;
518+ for &q in &[70u8, 90, 110] {
519+ let encoded = encode_key_frame(&picture, q, 0.5).unwrap();
520+ let quality = psnr(&encoded.reconstruction.y, &picture.y);
521+ if let Some((bytes, better)) = previous {
522+ assert!(
523+ encoded.stream.len() < bytes,
524+ "q {q}: {} bytes",
525+ encoded.stream.len()
526+ );
527+ assert!(quality < better, "q {q}: PSNR {quality}");
528+ }
529+ previous = Some((encoded.stream.len(), quality));
530+ }
531+
532+ let mut previous = None;
533+ for &deadzone in &[0.5f64, 0.3, 0.15] {
534+ let encoded = encode_key_frame(&picture, 100, deadzone).unwrap();
535+ let quality = psnr(&encoded.reconstruction.y, &picture.y);
536+ if let Some((bytes, better)) = previous {
537+ assert!(
538+ encoded.stream.len() < bytes,
539+ "deadzone {deadzone}: {} bytes",
540+ encoded.stream.len()
541+ );
542+ assert!(quality < better, "deadzone {deadzone}: PSNR {quality}");
543+ }
544+ previous = Some((encoded.stream.len(), quality));
545+ }
546+ }
547+
548+ /// A flat picture is a flat stream: every block predicts its neighbours'
549+ /// average, which is the picture's own value, and codes nothing.
550+ #[test]
551+ fn a_flat_picture_costs_almost_nothing() {
552+ let mut picture = Picture::grey(128, 128);
553+ picture.y.fill(97);
554+ let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();
555+ // The first block has no neighbour and predicts 128, so it carries a
556+ // DC; every block after it predicts 97 and carries nothing.
557+ assert!(
558+ encoded.stream.len() < 100,
559+ "{} bytes for a flat picture",
560+ encoded.stream.len()
561+ );
562+ for (i, &s) in encoded.reconstruction.y.iter().enumerate().skip(32 * 128) {
563+ assert_eq!(s, 97, "sample {i} of a flat picture");
564+ }
565+ }
566+
567+ /// The sizes the encoder refuses, refused for a reason rather than by
568+ /// panicking somewhere below.
569+ #[test]
570+ fn a_picture_off_the_block_grid_is_refused() {
571+ assert!(encode_key_frame(&Picture::grey(40, 32), 100, 0.5).is_err());
572+ assert!(encode_key_frame(&Picture::grey(32, 48), 100, 0.5).is_err());
573+ let mut short = Picture::grey(64, 64);
574+ short.u.truncate(10);
575+ assert!(encode_key_frame(&short, 100, 0.5).is_err());
576+ // The tile writer carries the CDFs of one q context only.
577+ assert!(encode_key_frame(&Picture::grey(64, 64), 40, 0.5).is_err());
578+ }
579+
580+ /// A frame of real video, rather than a picture built to be easy.
581+ ///
582+ /// `EC_AV1_CLIP` names the clip and `EC_AV1_CLIP_SKIP` how far into it to
583+ /// seek; ffmpeg decodes one frame, crops it to the block grid, and the
584+ /// encoder's reconstruction has to survive the same equality gate as the
585+ /// synthetic pictures — real video reaches contexts a test card does not.
586+ #[test]
587+ fn a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed() {
588+ let Ok(clip) = std::env::var("EC_AV1_CLIP") else {
589+ eprintln!(
590+ "SKIP a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed: \
591+ set EC_AV1_CLIP to a clip"
592+ );
593+ return;
594+ };
595+ if !have_ffmpeg() {
596+ eprintln!(
597+ "SKIP a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed: no ffmpeg"
598+ );
599+ return;
600+ }
601+ let skip = std::env::var("EC_AV1_CLIP_SKIP").unwrap_or_else(|_| "0".into());
602+ // A 4:2:0 frame cropped to whole 32x32 blocks, in a size that keeps the
603+ // test quick while still spanning many superblocks.
604+ let (width, height) = (640usize, 352usize);
605+ let out = Command::new("ffmpeg")
606+ .args(["-v", "error", "-ss", &skip, "-i", &clip, "-frames:v", "1"])
607+ .args(["-vf", &format!("scale={width}:{height}")])
608+ .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
609+ .output()
610+ .expect("ffmpeg failed to run");
611+ assert!(
612+ out.status.success(),
613+ "ffmpeg: {}",
614+ String::from_utf8_lossy(&out.stderr)
615+ );
616+ let (luma, chroma) = (width * height, width * height / 4);
617+ assert_eq!(
618+ out.stdout.len(),
619+ luma + 2 * chroma,
620+ "expected one 4:2:0 frame"
621+ );
622+ let picture = Picture {
623+ width,
624+ height,
625+ y: out.stdout[..luma].to_vec(),
626+ u: out.stdout[luma..luma + chroma].to_vec(),
627+ v: out.stdout[luma + chroma..].to_vec(),
628+ };
629+
630+ let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();
631+ let decoded = ffmpeg_decode(&encoded.stream, width, height);
632+ assert_eq!(decoded.y, encoded.reconstruction.y, "luma");
633+ assert_eq!(decoded.u, encoded.reconstruction.u, "U");
634+ assert_eq!(decoded.v, encoded.reconstruction.v, "V");
635+ eprintln!(
636+ "{} bytes, luma PSNR {:.2} dB",
637+ encoded.stream.len(),
638+ psnr(&decoded.y, &picture.y)
639+ );
640+ }
641+}
crates/ec-av1/src/lib.rsmodified+1 -0
@@ -14,6 +14,7 @@
1414
1515 pub mod bits;
1616 pub mod cdf;
17+pub mod encode;
1718 pub mod frame;
1819 pub mod msac;
1920 pub mod obu;
lanes/av1-picture-r1.report.mdadded+63 -0
@@ -0,0 +1,63 @@
1+# lane-av1-picture r1 — ec-av1 encodes a picture
2+
3+## What landed
4+
5+`crates/ec-av1/src/encode.rs`: a key-frame picture encoder.
6+
7+- `Picture` — an 8-bit planar 4:2:0 picture.
8+- `key_frame_headers(width, height, base_q_idx)` — the sequence and frame
9+ headers the tile writer's subset is coded under (one tile, TX_MODE_LARGEST,
10+ no in-loop filtering, no CDF adaptation).
11+- `encode_key_frame(&Picture, base_q_idx, deadzone) -> Encoded` — an AV1 stream
12+ plus the encoder's own reconstruction.
13+
14+Every block is 32x32 luma / 16x16 chroma, DC-predicted from the reconstruction
15+above and to its left exactly as the decoder will (`dc_predict`, spec 7.11.2),
16+residual through `forward_and_quantize`, reconstruction through
17+`dequant_and_inverse`. Superblocks are split into their four quadrants in the
18+order the decoder walks them.
19+
20+## Gates (`cargo test -p ec-av1`, 69 green)
21+
22+| test | what it holds |
23+|---|---|
24+| `ffmpeg_decodes_exactly_what_the_encoder_reconstructed` | 64x64, 96x64 and 160x96 test cards: **every sample of every plane** equals the encoder's reconstruction after an ffmpeg decode. Prediction reads the reconstruction, so one sample of drift would spread down and right — this is an equality, not a tolerance |
25+| `the_encoded_picture_is_the_one_that_went_in` | it is a reconstruction *of the right picture*: luma PSNR > 36 dB, chroma > 40 dB at q 100 |
26+| `fidelity_and_rate_move_with_the_quantizer` | bytes and PSNR both monotone in q (70/90/110) and in the deadzone (0.5/0.3/0.15) |
27+| `a_flat_picture_costs_almost_nothing` | a flat picture is under 100 bytes and every block after the first reconstructs its exact value |
28+| `a_picture_off_the_block_grid_is_refused` | off-grid sizes, a short plane and an out-of-band q are errors, not panics |
29+| `a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed` | the same equality gate on a frame of real video (`EC_AV1_CLIP`, `EC_AV1_CLIP_SKIP`) |
30+
31+## His data (640x352, q_idx 100, all sample-exact against ffmpeg)
32+
33+| clip | bytes | luma PSNR |
34+|---|---|---|
35+| `reela.mp4` @0s | 11 429 | 42.61 dB |
36+| OBS screen capture 2026-08-17 @5s | 33 674 | 38.45 dB |
37+| a 1080p AV1 film @5s | 32 366 | 39.26 dB |
38+
39+## Where that sits against libaom
40+
41+Same film frame, same size, libaom-av1 `-still-picture -cpu-used 4`:
42+
43+| crf | bytes | PSNR |
44+|---|---|---|
45+| 30 | 15 923 | 38.42 dB |
46+| 40 | 8 413 | 34.91 dB |
47+| 50 | 4 402 | 31.58 dB |
48+
49+Interpolating libaom to our 32.4 kB puts it near 41.7 dB against our 39.26 dB:
50+**about 2.4 dB behind at this rate.** That is the expected size of what is not
51+implemented yet rather than a defect — the encoder has one block size, one
52+transform type, DC prediction only, no rate-distortion decision and no CDF
53+adaptation. Each of those is a lane.
54+
55+## Not in this lane
56+
57+- block sizes other than 32x32, and the partition decision between them
58+- intra modes other than DC_PRED (the tile writer already codes all thirteen)
59+- transform types other than DCT_DCT, and transform size selection
60+- rate-distortion optimisation; the deadzone is a fixed parameter, unswept
61+- CDF adaptation (`disable_cdf_update` is set), CDEF, loop filter, loop
62+ restoration, superres
63+- inter frames, and pictures that are not a whole number of 32x32 blocks