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