use std::path::{Path, PathBuf}; use ec_core::frame::{PixelFormat, VideoFrame}; use ec_h264::{Decoder, NalOutcome}; pub(super) fn layout(f: PixelFormat) -> (usize, usize, usize) { match f { PixelFormat::I444 => (1, 1, 1), PixelFormat::I410 => (2, 1, 1), PixelFormat::I422 => (1, 2, 1), PixelFormat::I210 => (2, 2, 1), PixelFormat::I420 => (1, 2, 2), PixelFormat::I010 => (2, 2, 2), other => panic!("unexpected output format {other:?}"), } } pub(super) fn frame_bytes(frame: &VideoFrame) -> Vec { let (bps, dx, dy) = layout(frame.format); let (w, h) = (frame.width as usize, frame.height as usize); let (cw, ch) = (w.div_ceil(dx), h.div_ceil(dy)); let mut out = Vec::new(); for (plane, (pw, ph)) in frame.planes.iter().zip([(w, h), (cw, ch), (cw, ch)]) { for y in 0..ph { out.extend_from_slice(plane.row(y, pw * bps).expect("plane row")); } } out } pub(super) fn decode_all(bytes: &[u8]) -> Result>, ec_h264::Error> { let mut dec = Decoder::new(); let mut frames = Vec::new(); for nal in ec_h264_syntax::AnnexBIter::new(bytes) { if dec.push_nal(nal)? == NalOutcome::PictureBoundary { dec.end_picture()?; dec.push_nal(nal)?; } while let Some(f) = dec.next_frame() { frames.push(frame_bytes(&f)); } } dec.flush()?; while let Some(f) = dec.next_frame() { frames.push(frame_bytes(&f)); } Ok(frames) } pub(super) fn scratch(tag: &str) -> PathBuf { let dir = std::env::temp_dir().join(format!( "ec-h264-{tag}-{}-{:?}", std::process::id(), std::thread::current().id() )); std::fs::create_dir_all(&dir).unwrap(); dir } pub(super) fn ffmpeg_frames(stream: &Path, pix_fmt: &str, frame_len: usize) -> Option> { let out = ec_testkit::ffmpeg() .args(["-v", "error", "-i"]) .arg(stream) .args(["-f", "rawvideo", "-pix_fmt", pix_fmt, "-"]) .output() .ok()?; (out.status.success() && !out.stdout.is_empty() && out.stdout.len() % frame_len == 0) .then_some(out.stdout) } pub(super) fn escape(rbsp: &[u8]) -> Vec { let mut out = Vec::with_capacity(rbsp.len() + 8); let mut zeros = 0; for &b in rbsp { if zeros >= 2 && b <= 3 { out.push(3); zeros = 0; } out.push(b); zeros = if b == 0 { zeros + 1 } else { 0 }; } out } pub(super) fn find_stream(dir: &Path) -> Option { let mut fallback = None; for entry in std::fs::read_dir(dir).ok()? { let p = entry.ok()?.path(); let ext = p.extension()?.to_str()?.to_ascii_lowercase(); if matches!(ext.as_str(), "jsv" | "264" | "avc" | "26l" | "h264" | "jvt") { return Some(p); } if ext == "bit" { fallback = Some(p); } } fallback } pub(super) fn ffmpeg_pix_frames(stream: &Path, pix_fmt: &str) -> Option> { let out = ec_testkit::ffmpeg() .args(["-v", "error", "-f", "h264", "-i"]) .arg(stream) .args(["-f", "rawvideo", "-pix_fmt", pix_fmt, "-"]) .output() .ok()?; (out.status.success() && !out.stdout.is_empty()).then_some(out.stdout) }