forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

dump_yuv.rs206 lines, 9.2 KiBHistoryRawDownload
1//! Decode one OBU stream and write every frame's planes as raw planar video
2//! (`<out-prefix>.f<N>.yuv`), at the sample depth **the stream's own sequence
3//! header carries**: 8-bit as one byte per sample, 10/12-bit as little-endian
4//! `u16`. That is the layout `ffmpeg -pix_fmt yuv420p{,10,12}le -f rawvideo`
5//! and `aomdec --rawvideo` write, so a byte-exact `cmp` against either is
6//! meaningful.
7//!
8//! It is the high-bit-depth companion to `EC_AV1_PREFILT_DUMP`, whose `as u8`
9//! narrowing throws away exactly the bits a 10-bit mismatch lives in
10//! (lane-rect1d r1 found its defect by diffing this against
11//! `ffmpeg -pix_fmt yuv420p10le -f rawvideo`).
12//!
13//! ```text
14//! cargo run -p ec-av1 --example dump_yuv -- s.obu /tmp/ours
15//! ffmpeg -v error -i s.obu -pix_fmt yuv420p10le -f rawvideo /tmp/ref.yuv
16//! cmp /tmp/ours.f0.yuv /tmp/ref.yuv
17//! ```
18//!
19//! The depth is NEVER taken from the file name, the output extension, or the
20//! `-pix_fmt` of a reference tool: it is parsed out of the sequence header
21//! (spec 5.5.2 `color_config.bit_depth`) before a single byte is written. The
22//! old version packed every sample as `u16` unconditionally, so pointing it at
23//! an 8-bit stream silently produced a file TWICE the size of the oracle's,
24//! and the size mismatch read like a decoder bug. `--depth N` is accepted for
25//! the case where you already know what the stream is, and is ASSERTED against
26//! the parsed header: a mismatch names both depths and the consequence it
27//! would have caused, and writes nothing.
28//!
29//! `i` in `<out-prefix>.f<i>.yuv` indexes `decode_stream`'s output, which is
30//! DISPLAY order and SHOWN frames only -- hidden alt-refs are never emitted.
31//! Every other `.f{N}` in this crate (EC_AV1_FINAL_DUMP,
32//! EC_AV1_DECODE_ORDER_DUMP, EC_AV1_PREFILT_DUMP) uses a DECODE index, so this
33//! file does NOT line up with an aomdec dump past frame 0 on a stream with
34//! altref. Compare against ffmpeg rawvideo, or against aomdec via
35//! `decode_all_frames_vs_oracle`.
36fn main() {
37 let argv: Vec<String> = std::env::args().skip(1).collect();
38 let (Some(path), Some(out)) = (argv.first().cloned(), argv.get(1).cloned()) else {
39 eprintln!("usage: dump_yuv <stream.obu> <out-prefix> [--depth 8|10|12]");
40 std::process::exit(2);
41 };
42 // An ASSERTED expectation, not a switch: the packing always follows the
43 // parsed header, and a wrong `--depth` is a hard error before any file.
44 let mut claimed_depth: Option<u8> = None;
45 let mut rest = argv[2.min(argv.len())..].iter();
46 while let Some(arg) = rest.next() {
47 let value = arg
48 .strip_prefix("--depth=")
49 .map(str::to_string)
50 .or_else(|| (arg == "--depth").then(|| rest.next().cloned()).flatten());
51 let Some(value) = value else {
52 eprintln!("dump_yuv: unknown argument `{arg}`");
53 eprintln!("usage: dump_yuv <stream.obu> <out-prefix> [--depth 8|10|12]");
54 std::process::exit(2);
55 };
56 let Ok(depth) = value.parse::<u8>() else {
57 eprintln!("dump_yuv: --depth `{value}` is not a bit depth (8, 10 or 12)");
58 std::process::exit(2);
59 };
60 if claimed_depth.is_some() {
61 eprintln!("dump_yuv: --depth given twice; the depth is asserted, not a switch");
62 std::process::exit(2);
63 }
64 claimed_depth = Some(depth);
65 }
66 let data = match std::fs::read(&path) {
67 Ok(data) => data,
68 Err(e) => {
69 eprintln!("{path}: {e}");
70 std::process::exit(2);
71 }
72 };
73
74 // The stream's OWN header, read before the decode so a depth mismatch is
75 // reported instead of a file. Scans OBU by OBU because the sequence header
76 // need not be the first OBU (decode_probe walks it the same way).
77 let mut parser = ec_av1_syntax::Av1Parser::new();
78 let mut pos = 0usize;
79 while pos < data.len() && parser.sequence_header().is_none() {
80 let Ok(obu) = parser.parse_obu(&data[pos..]) else {
81 break;
82 };
83 pos += obu.total_size.max(1);
84 }
85 let Some(seq) = parser.sequence_header() else {
86 eprintln!(
87 "dump_yuv: {path}: no sequence header parsed, so the sample depth is unknown. \
88 Refusing to guess: packing u16 blind is what wrote a 2x-size file for every 8-bit \
89 stream. Re-checkout the stream (an IVF container parses as zero frames too), or pass \
90 a raw OBU stream."
91 );
92 std::process::exit(1);
93 };
94 let cfg = &seq.color_config;
95 let bit_depth = cfg.bit_depth;
96 if let Some(claimed) = claimed_depth
97 && claimed != bit_depth {
98 let theirs = if bit_depth == 8 {
99 format!(
100 "aomdec --rawvideo / ffmpeg -pix_fmt yuv420p ({} bytes per sample, \
101 W*H*3/2 for 4:2:0)",
102 1
103 )
104 } else {
105 format!(
106 "aomdec --rawvideo / ffmpeg -pix_fmt yuv420p{}le ({} bytes per sample, \
107 W*H*3 for 4:2:0)",
108 bit_depth, 2
109 )
110 };
111 eprintln!(
112 "dump_yuv: {path}: --depth {claimed} contradicts the stream's own sequence \
113 header, which carries bit_depth {bit_depth} (seq_profile {}, \
114 subsampling {}/{}, mono_chrome {}). Writing {claimed}-bit would emit \
115 {} bytes per sample against the oracle's {theirs}, so every `cmp` would fail on \
116 size alone and read like a decoder defect. Nothing was written.",
117 seq.seq_profile,
118 cfg.subsampling_x,
119 cfg.subsampling_y,
120 cfg.mono_chrome,
121 if claimed == 8 { 1 } else { 2 },
122 );
123 std::process::exit(1);
124 }
125 // 8 bit -> one byte per sample; anything above -> little-endian u16, which
126 // is what both oracles emit for `*p10le` / `*p12le` (they never pack to
127 // the bit depth itself, they use a full 16-bit container).
128 let bytes_per_sample = if bit_depth == 8 { 1 } else { 2 };
129 // Spec 5.5.3 `subsampling_{x,y}`: 1/1 IS 4:2:0 (measured on this crate's own
130 // 8-bit 192x128 fixture, which parses 1/1 and yields 36864 samples for a
131 // 192x128 frame = W*H*3/2), 0/0 is 4:4:4, 1/0 is 4:2:2, 0/1 is 4:4:0.
132 let chroma = match (cfg.mono_chrome, cfg.subsampling_x, cfg.subsampling_y) {
133 (true, _, _) => "gray",
134 (false, 0, 0) => "yuv444p",
135 (false, 0, 1) => "yuv440p",
136 (false, 1, 0) => "yuv422p",
137 _ => "yuv420p",
138 };
139 let pix_fmt = match (chroma, bit_depth) {
140 (c, 8) => c.to_string(),
141 ("gray", _) => "gray16le".to_string(),
142 (c, 10) => format!("{c}10le"),
143 (c, 12) => format!("{c}12le"),
144 (c, d) => format!("{c}{d}le"),
145 };
146 let max = (1u32 << bit_depth) - 1;
147 println!(
148 "sequence header: bit_depth {bit_depth} -> {bytes_per_sample} byte(s) per sample, \
149 seq_profile {}, subsampling {}/{}, mono_chrome {}; ffmpeg -pix_fmt {pix_fmt}",
150 seq.seq_profile, cfg.subsampling_x, cfg.subsampling_y, cfg.mono_chrome,
151 );
152
153 let frames = match ec_av1::stream::decode_stream(&data) {
154 Ok(frames) => frames,
155 Err(e) => {
156 eprintln!("{path}: {e}");
157 std::process::exit(1);
158 }
159 };
160 for (i, f) in frames.iter().enumerate() {
161 let planes: &[&Vec<u16>] = if cfg.mono_chrome {
162 &[&f.y]
163 } else {
164 &[&f.y, &f.u, &f.v]
165 };
166 // The OTHER half of the depth contract: samples that do not fit the
167 // container we are about to write. A `s as u8` on a 10-bit plane (or a
168 // u16 on a depth we packed narrow) is exactly the bit loss this tool
169 // exists to rule out, so it is an error, not a truncation.
170 if let Some((plane_name, sample)) = [("Y", &f.y), ("U", &f.u), ("V", &f.v)]
171 .into_iter()
172 .take(if cfg.mono_chrome { 1 } else { 3 })
173 .find_map(|(name, plane)| plane.iter().max().map(|&s| (name, s)))
174 && u32::from(sample) > max {
175 eprintln!(
176 "dump_yuv: {path}: frame {i} plane {plane_name} carries sample {sample} above \
177 the {bit_depth}-bit maximum {max} -- the decoded output does not match the \
178 sequence header it was decoded under, and packing it would silently drop the \
179 high bits. Nothing was written."
180 );
181 std::process::exit(1);
182 }
183 let samples: usize = planes.iter().map(|p| p.len()).sum();
184 let mut buf = Vec::with_capacity(samples * bytes_per_sample);
185 for plane in planes {
186 if bytes_per_sample == 1 {
187 buf.extend(plane.iter().map(|&s| s as u8));
188 } else {
189 for &s in plane.iter() {
190 buf.extend_from_slice(&s.to_le_bytes());
191 }
192 }
193 }
194 let name = format!("{out}.f{i}.yuv");
195 if let Err(e) = std::fs::write(&name, &buf) {
196 eprintln!("{name}: {e}");
197 std::process::exit(2);
198 }
199 println!(
200 "frame {i}: {}x{} -> {name} ({samples} samples, {} bytes, {pix_fmt})",
201 f.width,
202 f.height,
203 buf.len(),
204 );
205 }
206}