forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust381.5 MiB2fb2a9cTahinli12 hours ago4264 commits

encode.rs550 lines, 24.4 KiBHistoryRawDownload
1//! The ProRes encoder: ffmpeg decodes what we write exactly as ec-prores does, frame sizes sit on
2//! Apple's rates, quality matches or beats ffmpeg's `prores_ks`, the .mov probes right.
3//! All media is synthetic.
4
5mod common;
6use std::io::Cursor;
7
8use common::*;
9use ec_core::frame::{ColorInfo, PixelFormat, Plane, VideoFrame};
10use ec_core::registry::{CodecId, Demuxer, Encoder, Muxer, StreamInfo};
11use ec_core::timebase::TimeBase;
12use ec_core::Packet;
13use ec_mp4::{Mp4Demuxer, Mp4Muxer};
14use ec_prores::{nominal_frame_bytes, EncoderConfig, Profile, ProResEncoder};
15
16const ALL: [Profile; 6] =
17 [Profile::Proxy, Profile::Lt, Profile::Standard, Profile::Hq, Profile::P4444, Profile::P4444Xq];
18
19fn xorshift(s: &mut u64) -> u64 {
20 *s ^= *s << 13;
21 *s ^= *s >> 7;
22 *s ^= *s << 17;
23 *s
24}
25
26/// Synthetic picture: smooth gradients and rings plus `noise` (peak, 10-bit units), as planar
27/// little-endian 16-bit samples in `bits` (10 or 12) with planes Y, U, V.
28fn synth(w: usize, h: usize, is_444: bool, bits: u32, noise: i32, seed: u64) -> Vec<Vec<u16>> {
29 let mut s = seed | 1;
30 let cw = if is_444 { w } else { w.div_ceil(2) };
31 let scale = 1i32 << (bits - 10);
32 let mut planes = Vec::new();
33 for p in 0..3 {
34 let (pw, ph) = if p == 0 { (w, h) } else { (cw, h) };
35 let mut v = Vec::with_capacity(pw * ph);
36 for y in 0..ph {
37 for x in 0..pw {
38 let (fx, fy) = (x as f64 / pw as f64, y as f64 / ph as f64);
39 let base = match p {
40 0 => 200.0 + 500.0 * fx + 150.0 * (fy * 9.0).sin() + 90.0 * (((fx - 0.5).powi(2) + (fy - 0.5).powi(2)) * 90.0).sin(),
41 1 => 512.0 + 150.0 * (fx * 4.0).cos() - 80.0 * fy,
42 _ => 512.0 - 120.0 * (fy * 5.0).sin() + 60.0 * fx,
43 };
44 let n = if noise > 0 { (xorshift(&mut s) % (2 * noise as u64 + 1)) as i32 - noise } else { 0 };
45 v.push((((base as i32 + n).clamp(16, 1000)) * scale) as u16);
46 }
47 }
48 planes.push(v);
49 }
50 planes
51}
52
53fn to_frame(planes: &[Vec<u16>], w: usize, h: usize, fmt: PixelFormat) -> VideoFrame {
54 let geo = fmt.plane_geometry(w as u32, h as u32);
55 let ps = planes
56 .iter()
57 .zip(&geo)
58 .map(|(p, g)| {
59 let bytes: Vec<u8> = if fmt.bytes_per_component() == 2 {
60 p.iter().flat_map(|v| v.to_le_bytes()).collect()
61 } else {
62 p.iter().map(|&v| v as u8).collect()
63 };
64 Plane::new(bytes, g.0)
65 })
66 .collect();
67 VideoFrame::try_new(fmt, w as u32, h as u32, ps).unwrap()
68}
69
70fn fmt_for(p: Profile) -> PixelFormat {
71 if p.is_444() { PixelFormat::I412 } else { PixelFormat::I210 }
72}
73
74fn encoder(p: Profile, w: usize, h: usize) -> ProResEncoder {
75 let mut cfg = EncoderConfig::new(p, w as u32, h as u32);
76 cfg.color = ColorInfo { primaries: 1, transfer: 1, matrix: 1, full_range: false };
77 ProResEncoder::new(cfg).unwrap()
78}
79
80fn mux(enc: &ProResEncoder, frames: &[Vec<u8>], w: usize, h: usize) -> Vec<u8> {
81 let tb = TimeBase::try_new(1001, 30000).unwrap();
82 let mut m = Mp4Muxer::with_brands(Cursor::new(Vec::new()), *b"qt ", &[*b"qt "]).unwrap();
83 let mut params = enc.codec_parameters().clone();
84 if let ec_core::registry::MediaParameters::Video(v) = &mut params.media {
85 v.width = w as u32;
86 v.height = h as u32;
87 }
88 let s = m.add_stream(StreamInfo::new(0, tb, params)).unwrap();
89 for (i, f) in frames.iter().enumerate() {
90 let mut p = Packet::new(s, tb, f.clone());
91 p.pts = Some(i as i64);
92 p.dts = Some(i as i64);
93 p.duration = Some(1);
94 p.flags.keyframe = true;
95 m.write_packet(&p).unwrap();
96 }
97 m.finish().unwrap();
98 m.into_inner().into_inner()
99}
100
101/// Tight little-endian planes of a decoded frame.
102fn tight(f: &ec_core::frame::VideoFrame) -> Vec<u8> {
103 let (w, h) = (f.width as usize, f.height as usize);
104 let (sx, sy) = f.format.chroma_shift();
105 let mut v = Vec::new();
106 for (i, pl) in f.planes.iter().enumerate() {
107 let (pw, ph) = if i == 0 { (w, h) } else { (w.div_ceil(1 << sx), h.div_ceil(1 << sy)) };
108 for y in 0..ph {
109 v.extend_from_slice(&pl.data[y * pl.stride..y * pl.stride + pw * 2]);
110 }
111 }
112 v
113}
114
115fn psnr(a: &[u8], b: &[u8], peak: f64) -> f64 {
116 assert_eq!(a.len(), b.len());
117 let mut se = 0f64;
118 for (x, y) in a.as_chunks::<2>().0.iter().zip(b.as_chunks::<2>().0) {
119 let d = f64::from(u16::from_le_bytes([x[0], x[1]])) - f64::from(u16::from_le_bytes([y[0], y[1]]));
120 se += d * d;
121 }
122 let mse = se / (a.len() / 2) as f64;
123 if mse == 0.0 { 99.0 } else { 10.0 * (peak * peak / mse).log10() }
124}
125
126fn raw_of(planes: &[Vec<u16>]) -> Vec<u8> {
127 planes.iter().flatten().flat_map(|v| v.to_le_bytes()).collect()
128}
129
130fn pix(p: Profile) -> &'static str {
131 if p.is_444() { "yuv444p12le" } else { "yuv422p10le" }
132}
133
134#[test]
135fn ffmpeg_and_ec_prores_decode_every_profile_identically() {
136 let dir = scratch("enc-rt");
137 for (i, p) in ALL.into_iter().enumerate() {
138 // Odd size: padding macroblocks on both axes, 3 slice widths in a row.
139 let (w, h) = (331, 75);
140 let planes = synth(w, h, p.is_444(), if p.is_444() { 12 } else { 10 }, 10, 7 + i as u64);
141 let enc = encoder(p, w, h);
142 let f = enc.encode(&to_frame(&planes, w, h, fmt_for(p))).unwrap();
143 let mov = mux(&enc, &[f.clone(), f], w, h);
144 let path = dir.join(format!("{}.mov", String::from_utf8_lossy(&p.fourcc())));
145 std::fs::write(&path, &mov).unwrap();
146 let ours = decode_ours(&mov, 1).unwrap();
147 assert_eq!(ours.len(), 2);
148 let mut ours_raw = tight(&ours[0].video);
149 ours_raw.extend(tight(&ours[1].video));
150 let theirs = raw_ffmpeg(&format!("enc-rt-{i}"), &path, pix(p)).unwrap();
151 assert_eq!(first_diff(&ours_raw, &theirs), None, "{p:?}: ffmpeg and ec-prores disagree");
152 let peak = if p.is_444() { 4095.0 } else { 1023.0 };
153 let q = psnr(&raw_of(&planes), &theirs[..theirs.len() / 2], peak);
154 assert!(q > 34.0, "{p:?}: PSNR {q:.1} dB against the source");
155 // Same bytes with a different thread count.
156 let mut cfg = enc.config().clone();
157 cfg.threads = 1;
158 let one = ProResEncoder::new(cfg).unwrap().encode(&to_frame(&planes, w, h, fmt_for(p))).unwrap();
159 assert_eq!(one, packets(&mov)[0], "{p:?}: output depends on the thread count");
160 }
161}
162
163#[test]
164fn eight_bit_input_is_widened() {
165 let (w, h) = (96, 48);
166 let planes = synth(w, h, false, 10, 8, 3);
167 let p8: Vec<Vec<u16>> = planes.iter().map(|p| p.iter().map(|&v| v >> 2).collect()).collect();
168 let enc = encoder(Profile::Hq, w, h);
169 let f = enc.encode(&to_frame(&p8, w, h, PixelFormat::I422)).unwrap();
170 let dec = decoder(1).decode(&f).unwrap();
171 let want: Vec<u8> = p8.iter().flatten().flat_map(|&v| (u16::from(v as u8) * 4 + u16::from(v as u8 >> 6)).to_le_bytes()).collect();
172 assert!(psnr(&tight(&dec), &want, 1023.0) > 45.0);
173 // A 4:4:4 picture into a 4:2:2 profile is refused, not guessed at.
174 let p444 = synth(w, h, true, 10, 0, 1);
175 assert!(enc.encode(&to_frame(&p444, w, h, PixelFormat::I410)).is_err());
176}
177
178#[test]
179fn frame_sizes_sit_on_apples_rates() {
180 // Dense noise saturates the budget; HD: 8160 macroblocks, UHD: 32400.
181 for (w, h) in [(1920usize, 1080usize), (3840, 2160)] {
182 for p in ALL {
183 if w == 3840 && !matches!(p, Profile::Hq | Profile::Lt | Profile::P4444) {
184 continue;
185 }
186 let planes = synth(w, h, p.is_444(), if p.is_444() { 12 } else { 10 }, 70, 11);
187 let enc = encoder(p, w, h);
188 let n = enc.encode(&to_frame(&planes, w, h, fmt_for(p))).unwrap().len() as f64;
189 let nominal = nominal_frame_bytes(p, w.div_ceil(16) * h.div_ceil(16)) as f64;
190 let ratio = n / nominal;
191 eprintln!("{p:?} {w}x{h}: {n} bytes, nominal {nominal}, ratio {ratio:.3}");
192 assert!((0.9..=1.1).contains(&ratio), "{p:?} {w}x{h}: ratio {ratio:.3}");
193 if w == 1920 {
194 // Apple's 1080p29.97 rates, Mbit/s.
195 let mbps = match p {
196 Profile::Proxy => 45.0,
197 Profile::Lt => 102.0,
198 Profile::Standard => 147.0,
199 Profile::Hq => 220.0,
200 Profile::P4444 => 330.0,
201 Profile::P4444Xq => 500.0,
202 };
203 let apple = mbps * 1e6 / 29.97 / 8.0;
204 assert!((0.9..=1.1).contains(&(n / apple)), "{p:?}: {:.3} of Apple's 1080p rate", n / apple);
205 } else {
206 // Apple's UHD 29.97 rates.
207 let mbps = match p {
208 Profile::Lt => 328.0,
209 Profile::Hq => 707.0,
210 _ => 1060.0,
211 };
212 let apple = mbps * 1e6 / 29.97 / 8.0;
213 assert!((0.9..=1.1).contains(&(n / apple)), "{p:?}: {:.3} of Apple's 2160p rate", n / apple);
214 }
215 }
216 }
217}
218
219#[test]
220fn encoder_trait_and_mov_probe() {
221 let dir = scratch("enc-probe");
222 let (w, h) = (192, 108);
223 for p in ALL {
224 let planes = synth(w, h, p.is_444(), if p.is_444() { 12 } else { 10 }, 10, 5);
225 let mut enc = encoder(p, w, h);
226 assert_eq!(enc.codec_parameters().codec, CodecId::ProRes);
227 let mut frames = Vec::new();
228 for i in 0..3 {
229 let mut v = to_frame(&planes, w, h, fmt_for(p));
230 v.pts = Some(ec_core::timebase::Timestamp::new(i, TimeBase::try_new(1001, 30000).unwrap()));
231 enc.send_frame(&ec_core::frame::Frame::Video(v)).unwrap();
232 let pk = enc.receive_packet().unwrap();
233 assert!(pk.flags.keyframe);
234 assert_eq!(pk.pts, Some(i));
235 frames.push(pk.data.to_vec());
236 }
237 let mov = mux(&enc, &frames, w, h);
238 for needle in [&p.fourcc()[..], b"fiel", b"colr", b"pasp"] {
239 assert!(mov.windows(4).any(|x| x == needle), "{p:?}: missing {:?}", String::from_utf8_lossy(needle));
240 }
241 assert!(!mov.windows(4).any(|x| x == b"avcC" || x == b"esds"), "{p:?}: a config box");
242 let path = dir.join(format!("{}.mov", String::from_utf8_lossy(&p.fourcc())));
243 std::fs::write(&path, &mov).unwrap();
244 let out = ec_testkit::ffprobe()
245 .args(["-v", "error", "-select_streams", "v:0", "-show_entries"])
246 .arg("stream=codec_name,profile,pix_fmt,field_order,color_space,color_transfer,color_primaries,codec_tag_string,width,height,nb_frames")
247 .args(["-of", "default=nw=1"])
248 .arg(&path)
249 .output()
250 .unwrap();
251 let t = String::from_utf8_lossy(&out.stdout).to_string();
252 let want_profile = match p {
253 Profile::Proxy => "Proxy",
254 Profile::Lt => "LT",
255 Profile::Standard => "Standard",
256 Profile::Hq => "HQ",
257 Profile::P4444 => "4444",
258 Profile::P4444Xq => "XQ",
259 };
260 for line in [
261 "codec_name=prores".to_string(),
262 format!("profile={want_profile}"),
263 format!("pix_fmt={}", if p.is_444() { "yuv444p12le" } else { "yuv422p10le" }),
264 "field_order=progressive".into(),
265 "color_space=bt709".into(),
266 "color_transfer=bt709".into(),
267 "color_primaries=bt709".into(),
268 format!("codec_tag_string={}", String::from_utf8_lossy(&p.fourcc())),
269 format!("width={w}"),
270 format!("height={h}"),
271 "nb_frames=3".into(),
272 ] {
273 assert!(t.lines().any(|l| l == line), "{p:?}: ffprobe lacks `{line}` in:\n{t}");
274 }
275 // Our demuxer reads it back.
276 let dm = Mp4Demuxer::new(Cursor::new(mov)).unwrap();
277 assert_eq!(dm.streams()[0].params.codec, CodecId::ProRes);
278 }
279}
280
281/// Mean PSNR of ours and prores_ks on a lavfi source: ours must be within 0.5 dB (or better).
282fn psnr_vs_prores_ks(generator: &str, post: &str, tag: &str) {
283 let dir = scratch(tag);
284 let (w, h) = (1920usize, 1080usize);
285 for (p, num, pf) in [
286 (Profile::Proxy, "0", "yuv422p10le"),
287 (Profile::Lt, "1", "yuv422p10le"),
288 (Profile::Standard, "2", "yuv422p10le"),
289 (Profile::Hq, "3", "yuv422p10le"),
290 (Profile::P4444, "4", "yuv444p10le"),
291 ] {
292 let raw = dir.join("src.raw");
293 let fmt = if p.is_444() { "yuv444p10le" } else { pf };
294 assert!(run(&["-f", "lavfi", "-i", &format!("{generator}=size={w}x{h}:rate=25{post}"), "-frames:v", "2", "-pix_fmt", fmt, "-f", "rawvideo", raw.to_str().unwrap()]));
295 let data = std::fs::read(&raw).unwrap();
296 let fsize = data.len() / 2;
297 // ffmpeg's encoder.
298 let refmov = dir.join("ref.mov");
299 assert!(run(&["-f", "rawvideo", "-pix_fmt", fmt, "-s", &format!("{w}x{h}"), "-i", raw.to_str().unwrap(), "-c:v", "prores_ks", "-profile", num, "-pix_fmt", fmt, refmov.to_str().unwrap()]));
300 let ref_dec = raw_ffmpeg(&format!("{tag}-ref"), &refmov, fmt).unwrap();
301 // Ours (10-bit 4:4:4 input is I410: a 4444 stream decodes at 12 bits, so compare at 12).
302 let enc = encoder(p, w, h);
303 let infmt = if p.is_444() { PixelFormat::I410 } else { PixelFormat::I210 };
304 let mut frames = Vec::new();
305 for f in 0..2 {
306 let chunk = &data[f * fsize..(f + 1) * fsize];
307 let geo = infmt.plane_geometry(w as u32, h as u32);
308 let mut off = 0;
309 let mut planes = Vec::new();
310 for g in &geo {
311 planes.push(Plane::new(chunk[off..off + g.0 * g.1].to_vec(), g.0));
312 off += g.0 * g.1;
313 }
314 frames.push(enc.encode(&VideoFrame::try_new(infmt, w as u32, h as u32, planes).unwrap()).unwrap());
315 }
316 let ours_mov = dir.join("ours.mov");
317 std::fs::write(&ours_mov, mux(&enc, &frames, w, h)).unwrap();
318 let ours_dec = raw_ffmpeg(&format!("{tag}-ours"), &ours_mov, fmt).unwrap();
319 let ref_bytes = std::fs::metadata(&refmov).unwrap().len() as f64 / 2.0;
320 let ours_bytes = frames[0].len() as f64;
321 // 4444 decodes in ffmpeg as 10-bit when asked for yuv444p10le: same scale as the source.
322 let a = psnr(&data, &ours_dec, 1023.0);
323 let b = psnr(&data, &ref_dec, 1023.0);
324 eprintln!("{tag} {p:?}: ours {a:.2} dB ({ours_bytes:.0} B) prores_ks {b:.2} dB ({ref_bytes:.0} B)");
325 assert!(a >= b - 0.5, "{tag} {p:?}: ours {a:.2} dB, prores_ks {b:.2} dB");
326 }
327}
328
329#[test]
330fn quality_matches_prores_ks_testsrc2() {
331 psnr_vs_prores_ks("testsrc2", "", "q-testsrc2");
332}
333
334#[test]
335fn quality_matches_prores_ks_mandelbrot() {
336 psnr_vs_prores_ks("mandelbrot", "", "q-mandel");
337}
338
339#[test]
340fn quality_matches_prores_ks_noisy() {
341 psnr_vs_prores_ks("testsrc2", ",noise=alls=12:allf=t", "q-noisy");
342}
343
344#[test]
345fn random_small_sizes_round_trip() {
346 let mut s = 0x9E3779B97F4A7C15u64;
347 let mut dec = decoder(1);
348 for case in 0..120 {
349 let p = ALL[(xorshift(&mut s) % 6) as usize];
350 let (w, h) = match case % 6 {
351 0 => (1 + (xorshift(&mut s) % 16) as usize, 1 + (xorshift(&mut s) % 16) as usize), // one macroblock
352 1 => (16, 16),
353 _ => (1 + (xorshift(&mut s) % 150) as usize, 1 + (xorshift(&mut s) % 70) as usize),
354 };
355 let bits = if p.is_444() { 12 } else { 10 };
356 let noise = (xorshift(&mut s) % 20) as i32;
357 let planes = synth(w, h, p.is_444(), bits, noise, xorshift(&mut s));
358 let mut cfg = EncoderConfig::new(p, w as u32, h as u32);
359 cfg.threads = 1 + (xorshift(&mut s) % 6) as usize;
360 let enc = ProResEncoder::new(cfg).unwrap();
361 let f = enc.encode(&to_frame(&planes, w, h, fmt_for(p))).unwrap();
362 let d = dec.decode_full(&f).unwrap_or_else(|e| panic!("case {case} {p:?} {w}x{h}: {e}"));
363 assert_eq!((d.video.width as usize, d.video.height as usize), (w, h), "case {case}");
364 assert_eq!(d.video.format, fmt_for(p));
365 let q = psnr(&tight(&d.video), &raw_of(&planes), if p.is_444() { 4095.0 } else { 1023.0 });
366 assert!(q > 40.0, "case {case} {p:?} {w}x{h} noise {noise}: PSNR {q:.1}");
367 }
368}
369
370#[test]
371fn encode_speed_1080p_hq() {
372 let (w, h) = (1920, 1080);
373 let planes = synth(w, h, false, 10, 12, 21);
374 let frame = to_frame(&planes, w, h, PixelFormat::I210);
375 let enc = encoder(Profile::Hq, w, h);
376 enc.encode(&frame).unwrap();
377 let t0 = std::time::Instant::now();
378 let n = 20;
379 for _ in 0..n {
380 std::hint::black_box(enc.encode(&frame).unwrap());
381 }
382 let fps = n as f64 / t0.elapsed().as_secs_f64();
383 eprintln!("1080p HQ encode, {} threads: {fps:.1} fps", enc.config().threads);
384 if let Some(min) = std::env::var("EC_PRORES_ENC_MIN_FPS").ok().and_then(|v| v.parse::<f64>().ok()) {
385 assert!(fps >= min, "{fps:.1} fps < {min}");
386 }
387}
388
389fn probe(path: &std::path::Path, entry: &str) -> String {
390 let out = ec_testkit::ffprobe()
391 .args(["-v", "error", "-select_streams", "v:0", "-show_entries", &format!("stream={entry}"), "-of", "default=nw=1:nk=1"])
392 .arg(path)
393 .output()
394 .expect("ffprobe");
395 String::from_utf8_lossy(&out.stdout).trim().to_string()
396}
397
398fn probe_frame(path: &std::path::Path, entry: &str) -> String {
399 let out = ec_testkit::ffprobe()
400 .args(["-v", "error", "-select_streams", "v:0", "-show_frames", "-read_intervals", "%+#1", "-show_entries", &format!("frame={entry}"), "-of", "default=nw=1:nk=1"])
401 .arg(path)
402 .output()
403 .expect("ffprobe");
404 String::from_utf8_lossy(&out.stdout).trim().to_string()
405}
406
407#[test]
408fn interlaced_every_profile_ffmpeg_and_ours_agree() {
409 use ec_core::frame::Interlace;
410 let dir = scratch("enc-field");
411 for (i, p) in ALL.into_iter().enumerate() {
412 for (order, field_order) in [(Interlace::TopFieldFirst, "tt"), (Interlace::BottomFieldFirst, "bb")] {
413 // Odd height: the two fields differ in height; odd width: a ragged macroblock column.
414 let (w, h) = (331, 75);
415 let planes = synth(w, h, p.is_444(), if p.is_444() { 12 } else { 10 }, 10, 21 + i as u64);
416 let enc = encoder(p, w, h);
417 let mut frame = to_frame(&planes, w, h, fmt_for(p));
418 frame.interlace = order;
419 let f = enc.encode(&frame).unwrap();
420 let mov = mux(&enc, std::slice::from_ref(&f), w, h);
421 let path = dir.join(format!("{}-{field_order}.mov", String::from_utf8_lossy(&p.fourcc())));
422 std::fs::write(&path, &mov).unwrap();
423 // The stream-level field_order comes from the container (a `fiel` atom the mov muxer
424 // does not write); the decoded frames carry the order from the ProRes frame header.
425 let fo = probe_frame(&path, "interlaced_frame,top_field_first");
426 let want_tff = if field_order == "tt" { "1" } else { "0" };
427 assert_eq!(fo.replace('\n', " "), format!("1 {want_tff}"), "{p:?}: ffprobe frame field order");
428 let ours = decode_ours(&mov, 1).unwrap();
429 assert_eq!(ours[0].video.interlace, order);
430 let theirs = raw_ffmpeg(&format!("enc-field-{i}"), &path, pix(p)).unwrap();
431 assert_eq!(first_diff(&tight(&ours[0].video), &theirs), None, "{p:?} {order:?}: ffmpeg and ec-prores disagree");
432 let peak = if p.is_444() { 4095.0 } else { 1023.0 };
433 let q = psnr(&raw_of(&planes), &theirs, peak);
434 assert!(q > 34.0, "{p:?} {order:?}: PSNR {q:.1} dB against the source");
435 // Thread count does not change the bytes.
436 let mut cfg = enc.config().clone();
437 cfg.threads = 1;
438 assert_eq!(ProResEncoder::new(cfg).unwrap().encode(&frame).unwrap(), f);
439 }
440 }
441}
442
443#[test]
444fn interlaced_fields_are_coded_separately() {
445 use ec_core::frame::Interlace;
446 // Two very different fields: a progressive coding would smear them, field coding keeps both.
447 let (w, h) = (128, 64);
448 let mut planes = synth(w, h, false, 10, 0, 5);
449 for y in 0..h {
450 if y % 2 == 1 {
451 for x in 0..w {
452 planes[0][y * w + x] = if (x / 8) % 2 == 0 { 900 } else { 150 };
453 }
454 }
455 }
456 let enc = encoder(Profile::Hq, w, h);
457 let mut frame = to_frame(&planes, w, h, PixelFormat::I210);
458 let prog = enc.encode(&frame).unwrap();
459 frame.interlace = Interlace::TopFieldFirst;
460 let field = enc.encode(&frame).unwrap();
461 let want = raw_of(&planes);
462 let qp = psnr(&tight(&decoder(1).decode(&prog).unwrap()), &want, 1023.0);
463 let qf = psnr(&tight(&decoder(1).decode(&field).unwrap()), &want, 1023.0);
464 eprintln!("progressive {qp:.1} dB, field {qf:.1} dB");
465 assert!(qf > qp, "field coding should help on field-different content");
466}
467
468/// Alpha test pattern: smooth ramps, flat runs, hard edges and noise, 16-bit full scale.
469fn alpha_pattern(w: usize, h: usize, seed: u64) -> Vec<u16> {
470 let mut s = seed | 1;
471 let mut v = Vec::with_capacity(w * h);
472 for y in 0..h {
473 for x in 0..w {
474 let a = match (y / 16 + x / 40) % 4 {
475 0 => 0xFFFFu32,
476 1 => (x * 65535 / w) as u32,
477 2 => 0,
478 _ => (xorshift(&mut s) & 0xFFFF) as u32,
479 };
480 let edge = if (x + y) % 97 < 3 { 0x8000 } else { a };
481 v.push(edge as u16);
482 }
483 }
484 v
485}
486
487#[test]
488fn alpha_4444_round_trips_and_ffmpeg_agrees() {
489 use ec_core::frame::Interlace;
490 use ec_prores::AlphaPlane;
491 let dir = scratch("enc-alpha");
492 let mut n = 0;
493 for p in [Profile::P4444, Profile::P4444Xq] {
494 for bits in [8u8, 16] {
495 for order in [Interlace::Progressive, Interlace::BottomFieldFirst] {
496 n += 1;
497 let (w, h) = (203, 67);
498 let planes = synth(w, h, true, 12, 10, 40 + n);
499 let a16 = alpha_pattern(w, h, 9 + n);
500 let mut cfg = EncoderConfig::new(p, w as u32, h as u32);
501 cfg.alpha_bits = bits;
502 let enc = ProResEncoder::new(cfg).unwrap();
503 let mut frame = to_frame(&planes, w, h, PixelFormat::I412);
504 frame.interlace = order;
505 let ap = AlphaPlane { width: w as u32, height: h as u32, stride: w, data: a16.clone() };
506 let f = enc.encode_with_alpha(&frame, Some(&ap)).unwrap();
507 let mov = mux(&enc, std::slice::from_ref(&f), w, h);
508 let path = dir.join(format!("a{n}.mov"));
509 std::fs::write(&path, &mov).unwrap();
510 let pf = probe(&path, "pix_fmt");
511 assert!(pf.starts_with("yuva444p1"), "{p:?} alpha {bits}: ffprobe pix_fmt {pf}");
512 // Our decode: alpha is exact (16-bit) or the 8-bit value replicated.
513 let ours = decode_ours(&mov, 1).unwrap();
514 let got = ours[0].alpha.as_ref().expect("alpha plane");
515 for y in 0..h {
516 for x in 0..w {
517 let a = a16[y * w + x];
518 let want = if bits == 16 { a } else { (a & 0xFF00) | (a >> 8) };
519 assert_eq!(got.data[y * got.stride + x], want, "{p:?} alpha {bits} {order:?} at {x},{y}");
520 }
521 }
522 // ffmpeg decodes the same planes and alpha as we do.
523 let theirs = raw_ffmpeg(&format!("enc-alpha-{n}"), &path, "yuva444p12le").unwrap();
524 assert_eq!(first_diff(&raw_ours(&ours), &theirs), None, "{p:?} alpha {bits} {order:?}: ffmpeg and ec-prores disagree");
525 let ysz = w * h * 2 * 3;
526 let q = psnr(&raw_of(&planes), &theirs[..ysz], 4095.0);
527 assert!(q > 34.0, "{p:?} alpha {bits} {order:?}: PSNR {q:.1} dB");
528 // Without an alpha plane the coded alpha is opaque.
529 let opaque = enc.encode(&frame).unwrap();
530 let d = decoder(1).decode_full(&opaque).unwrap();
531 assert!(d.alpha.unwrap().data.iter().all(|&a| a == 0xFFFF));
532 }
533 }
534 }
535}
536
537#[test]
538fn alpha_config_is_validated() {
539 use ec_prores::AlphaPlane;
540 let mut cfg = EncoderConfig::new(Profile::Hq, 64, 32);
541 cfg.alpha_bits = 8;
542 assert!(ProResEncoder::new(cfg).is_err(), "alpha on a 4:2:2 profile");
543 let mut cfg = EncoderConfig::new(Profile::P4444, 64, 32);
544 cfg.alpha_bits = 12;
545 assert!(ProResEncoder::new(cfg).is_err(), "12-bit alpha");
546 let enc = encoder(Profile::P4444, 64, 32);
547 let planes = synth(64, 32, true, 12, 0, 1);
548 let ap = AlphaPlane { width: 64, height: 32, stride: 64, data: vec![0; 64 * 32] };
549 assert!(enc.encode_with_alpha(&to_frame(&planes, 64, 32, PixelFormat::I412), Some(&ap)).is_err(), "alpha without alpha_bits");
550}