From 032b56155092f6803b74e9e0bf89937332d0025f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Mon, 16 Nov 2026 00:04:24 +0300 Subject: [PATCH] edith-sink: raw RGBA stdin to VA-API h264/hevc/av1 mp4; ec-dsp rgb BT.709 converter; ec-mp4 codec config helpers --- Cargo.lock | 11 ++ crates/ec-dsp/src/lib.rs | 1 + crates/ec-dsp/src/rgb.rs | 149 +++++++++++++++ crates/ec-mp4/src/config.rs | 171 +++++++++++++++++ crates/ec-mp4/src/lib.rs | 8 +- tools/edith-sink/Cargo.toml | 17 ++ tools/edith-sink/src/main.rs | 354 +++++++++++++++++++++++++++++++++++ 7 files changed, 708 insertions(+), 3 deletions(-) create mode 100644 crates/ec-dsp/src/rgb.rs create mode 100644 crates/ec-mp4/src/config.rs create mode 100644 tools/edith-sink/Cargo.toml create mode 100644 tools/edith-sink/src/main.rs diff --git a/Cargo.lock b/Cargo.lock index d91fca38..634c54e6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -746,6 +746,17 @@ dependencies = [ "ec-core", ] +[[package]] +name = "edith-sink" +version = "0.1.0" +dependencies = [ + "ec-core", + "ec-dsp", + "ec-hw", + "ec-mp4", + "ec-va", +] + [[package]] name = "either" version = "1.17.0" diff --git a/crates/ec-dsp/src/lib.rs b/crates/ec-dsp/src/lib.rs index e202b3a2..f77c2932 100644 --- a/crates/ec-dsp/src/lib.rs +++ b/crates/ec-dsp/src/lib.rs @@ -44,6 +44,7 @@ pub mod dct; pub mod fft; pub mod mdct; pub mod remap; +pub mod rgb; pub mod window; pub use dct::{Dct, Dct4}; diff --git a/crates/ec-dsp/src/rgb.rs b/crates/ec-dsp/src/rgb.rs new file mode 100644 index 00000000..de87e6fc --- /dev/null +++ b/crates/ec-dsp/src/rgb.rs @@ -0,0 +1,149 @@ +//! RGB to YUV conversion. + +/// Packed sRGB RGBA8 to planar BT.709 limited-range I420 with MPEG-2 left chroma siting. Alpha is ignored; `width` and `height` must be even. +pub fn rgba_to_i420_709( + rgba: &[u8], + width: usize, + height: usize, + y: &mut [u8], + u: &mut [u8], + v: &mut [u8], +) { + assert!(width.is_multiple_of(2) && height.is_multiple_of(2), "width and height must be even"); + assert_eq!(rgba.len(), width * height * 4); + assert_eq!(y.len(), width * height); + let (cw, ch) = (width / 2, height / 2); + assert_eq!(u.len(), cw * ch); + assert_eq!(v.len(), cw * ch); + if ch == 0 { + return; + } + + let k = Coeffs::bt709(); + let threads = std::thread::available_parallelism() + .map_or(1, |n| n.get()) + .min(8) + .min(ch); + let rows = ch.div_ceil(threads); + let band = rows * 2 * width; + + std::thread::scope(|s| { + let bands = rgba + .chunks(band * 4) + .zip(y.chunks_mut(band)) + .zip(u.chunks_mut(rows * cw)) + .zip(v.chunks_mut(rows * cw)); + for (((src, y), u), v) in bands { + let k = &k; + s.spawn(move || convert_band(src, width, k, y, u, v)); + } + }); +} + +struct Coeffs { + y: [i32; 3], + cb: [i32; 3], + cr: [i32; 3], +} + +impl Coeffs { + fn bt709() -> Self { + let kr = 0.2126; + let kb = 0.0722; + let kg = 1.0 - kr - kb; + let ky = 219.0 / 255.0; + let kc = 224.0 / 255.0; + let q = |c: f64| (c * 65536.0).round() as i32; + Self { + y: [q(ky * kr), q(ky * kg), q(ky * kb)], + cb: [ + q(-kc * kr / (2.0 * (1.0 - kb))), + q(-kc * kg / (2.0 * (1.0 - kb))), + q(kc / 2.0), + ], + cr: [ + q(kc / 2.0), + q(-kc * kg / (2.0 * (1.0 - kr))), + q(-kc * kb / (2.0 * (1.0 - kr))), + ], + } + } +} + +fn convert_band( + rgba: &[u8], + width: usize, + k: &Coeffs, + y: &mut [u8], + u: &mut [u8], + v: &mut [u8], +) { + let cw = width / 2; + let mut cb = vec![0i32; width]; + let mut cr = vec![0i32; width]; + let pairs = rgba + .chunks_exact(2 * width * 4) + .zip(y.chunks_exact_mut(2 * width)) + .zip(u.chunks_exact_mut(cw)) + .zip(v.chunks_exact_mut(cw)); + for (((pair, luma), u), v) in pairs { + let (top, bottom) = pair.split_at(width * 4); + let (y0, y1) = luma.split_at_mut(width); + cb.fill(0); + cr.fill(0); + pixel_row(top, y0, &mut cb, &mut cr, k); + pixel_row(bottom, y1, &mut cb, &mut cr, k); + subsample(&cb, u); + subsample(&cr, v); + } +} + +fn pixel_row(rgba: &[u8], y: &mut [u8], cb: &mut [i32], cr: &mut [i32], k: &Coeffs) { + let px = rgba.as_chunks::<4>().0; + for (((&[r, g, b, _], y), cb), cr) in px + .iter() + .zip(y.iter_mut()) + .zip(cb.iter_mut()) + .zip(cr.iter_mut()) + { + let (r, g, b) = (i32::from(r), i32::from(g), i32::from(b)); + let luma = k.y[0] * r + k.y[1] * g + k.y[2] * b; + *y = (((luma + 0x8000) >> 16) + 16).clamp(0, 255) as u8; + *cb += k.cb[0] * r + k.cb[1] * g + k.cb[2] * b; + *cr += k.cr[0] * r + k.cr[1] * g + k.cr[2] * b; + } +} + +fn subsample(sums: &[i32], out: &mut [u8]) { + const HALF: i32 = 1 << 18; + let fin = |acc: i32| (((acc + HALF) >> 19) + 128).clamp(0, 255) as u8; + out[0] = fin(3 * sums[0] + sums[1]); + for (o, w) in out[1..].iter_mut().zip(sums[1..].windows(3).step_by(2)) { + *o = fin(w[0] + 2 * w[1] + w[2]); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn four_by_two_matches_hand_values() { + let white = [255, 255, 255, 255]; + let red = [255, 0, 0, 255]; + let black = [0, 0, 0, 255]; + let rgba: Vec = [white, white, red, red, black, black, black, black] + .into_iter() + .flatten() + .collect(); + let (mut y, mut u, mut v) = (vec![0u8; 8], vec![0u8; 2], vec![0u8; 2]); + rgba_to_i420_709(&rgba, 4, 2, &mut y, &mut u, &mut v); + let close = |got: u8, want: i32| (i32::from(got) - want).abs() <= 1; + for (got, want) in y.iter().zip([235, 235, 63, 63, 16, 16, 16, 16]) { + assert!(close(*got, want), "y {got} vs {want}"); + } + assert!(close(u[0], 128) && close(v[0], 128)); + assert!(close(u[1], 118), "u {}", u[1]); + assert!(close(v[1], 170), "v {}", v[1]); + } +} diff --git a/crates/ec-mp4/src/config.rs b/crates/ec-mp4/src/config.rs new file mode 100644 index 00000000..b1d08ad6 --- /dev/null +++ b/crates/ec-mp4/src/config.rs @@ -0,0 +1,171 @@ +//! Turns encoder output (Annex-B) into mp4 samples and sample-entry config records. + +const NAL_IDR: u8 = 5; +const NAL_SEI: u8 = 6; +const NAL_SPS: u8 = 7; +const NAL_PPS: u8 = 8; +const NAL_AUD: u8 = 9; + +const HEVC_VPS: u8 = 32; +const HEVC_SPS: u8 = 33; +const HEVC_PPS: u8 = 34; +const HEVC_AUD: u8 = 35; + +const AV1C_HEAD: [u8; 4] = [0x81, 0x1F, 0x0C, 0x00]; + +/// An H.264 sample, whether it is an IDR, and its first SPS and PPS when present. +pub type H264Split = (Vec, bool, Option<(Vec, Vec)>); + +/// Splits an H.264 Annex-B access unit into a length-prefixed sample. +/// +/// SPS, PPS, AUD and SEI are stripped from the sample. `None` when the unit holds no coded slice. +pub fn h264_split_annex_b(annex_b: &[u8]) -> Option { + let nals = split_annex_b(annex_b); + let first = |kind: u8| nals.iter().copied().find(|n| nal_type(n) == kind); + let params = match (first(NAL_SPS), first(NAL_PPS)) { + (Some(sps), Some(pps)) => Some((sps.to_vec(), pps.to_vec())), + _ => None, + }; + let mut out = Vec::with_capacity(annex_b.len()); + let mut is_idr = false; + for nal in nals { + match nal_type(nal) { + NAL_SPS | NAL_PPS | NAL_AUD | NAL_SEI => continue, + NAL_IDR => is_idr = true, + _ => {} + } + out.extend_from_slice(&(nal.len() as u32).to_be_bytes()); + out.extend_from_slice(nal); + } + (!out.is_empty()).then_some((out, is_idr, params)) +} + +/// An H.264 `AVCDecoderConfigurationRecord` for one SPS and one PPS, with four-byte NAL length prefixes. +pub fn avcc_record(sps: &[u8], pps: &[u8]) -> Vec { + let profile = sps.get(1..4).unwrap_or(&[0, 0, 0]); + let mut out = vec![1, profile[0], profile[1], profile[2], 0xFF, 0xE1]; + out.extend_from_slice(&(sps.len() as u16).to_be_bytes()); + out.extend_from_slice(sps); + out.push(1); + out.extend_from_slice(&(pps.len() as u16).to_be_bytes()); + out.extend_from_slice(pps); + out +} + +/// An HEVC `HEVCDecoderConfigurationRecord` built from the VPS, SPS and PPS of an Annex-B access unit. +/// +/// `None` when the unit lacks a VPS, SPS or PPS. +pub fn hvcc_record(annex_b: &[u8], ten_bit: bool) -> Option> { + let nals = split_annex_b(annex_b); + let of = |kind: u8| nals.iter().copied().find(|n| hevc_nal_type(n) == kind); + let (vps, sps) = (of(HEVC_VPS)?, of(HEVC_SPS)?); + let ppss: Vec<&[u8]> = nals + .iter() + .copied() + .filter(|n| hevc_nal_type(n) == HEVC_PPS) + .collect(); + if ppss.is_empty() { + return None; + } + let rbsp = unescape(sps.get(2..)?); + let mut rec = vec![1u8]; + rec.extend_from_slice(rbsp.get(1..13)?); + rec.extend_from_slice(&[0xF0, 0x00]); + rec.push(0xFC); + rec.push(0xFC | 1); + let depth = if ten_bit { 0xFA } else { 0xF8 }; + rec.push(depth); + rec.push(depth); + rec.extend_from_slice(&0u16.to_be_bytes()); + rec.push(0b0000_1111); + rec.push(3); + for (kind, units) in [ + (HEVC_VPS, vec![vps]), + (HEVC_SPS, vec![sps]), + (HEVC_PPS, ppss), + ] { + rec.push(0x80 | kind); + rec.extend_from_slice(&(units.len() as u16).to_be_bytes()); + for nal in units { + rec.extend_from_slice(&(nal.len() as u16).to_be_bytes()); + rec.extend_from_slice(nal); + } + } + Some(rec) +} + +/// Splits an HEVC Annex-B access unit into a length-prefixed sample, dropping VPS, SPS, PPS and AUD. +/// +/// `None` when the unit holds no NAL left to write. +pub fn annex_b_to_hvcc(annex_b: &[u8]) -> Option> { + let mut out = Vec::with_capacity(annex_b.len()); + for nal in split_annex_b(annex_b) { + if matches!( + hevc_nal_type(nal), + HEVC_VPS | HEVC_SPS | HEVC_PPS | HEVC_AUD + ) { + continue; + } + out.extend_from_slice(&(nal.len() as u32).to_be_bytes()); + out.extend_from_slice(nal); + } + (!out.is_empty()).then_some(out) +} + +/// An `av1C` record: the four fixed bytes, then the sequence header OBU as the config OBUs. +pub fn av1c_record(ten_bit: bool, config_obus: &[u8]) -> Vec { + let mut head = AV1C_HEAD; + if ten_bit { + head[2] |= 0x40; + } + let mut out = head.to_vec(); + out.extend_from_slice(config_obus); + out +} + +fn hevc_nal_type(nal: &[u8]) -> u8 { + nal.first().map_or(0xFF, |b| (b >> 1) & 0x3F) +} + +fn unescape(nal: &[u8]) -> Vec { + let mut out = Vec::with_capacity(nal.len()); + for (i, &byte) in nal.iter().enumerate() { + if byte == 3 && i >= 2 && nal[i - 1] == 0 && nal[i - 2] == 0 { + continue; + } + out.push(byte); + } + out +} + +fn split_annex_b(src: &[u8]) -> Vec<&[u8]> { + let mut nals = Vec::new(); + let mut start = None; + let mut i = 0; + while i + 2 < src.len() { + if src[i] == 0 && src[i + 1] == 0 && src[i + 2] == 1 { + if let Some(s) = start { + push_nal(&mut nals, &src[s..i]); + } + i += 3; + start = Some(i); + } else { + i += 1; + } + } + if let Some(s) = start { + push_nal(&mut nals, &src[s..]); + } + nals +} + +fn push_nal<'a>(nals: &mut Vec<&'a [u8]>, nal: &'a [u8]) { + let end = nal.iter().rposition(|&b| b != 0).map_or(0, |p| p + 1); + if end > 0 { + nals.push(&nal[..end]); + } +} + +fn nal_type(nal: &[u8]) -> u8 { + nal.first().map_or(0, |b| b & 0x1F) +} diff --git a/crates/ec-mp4/src/lib.rs b/crates/ec-mp4/src/lib.rs index 8a694841..e1fadf23 100644 --- a/crates/ec-mp4/src/lib.rs +++ b/crates/ec-mp4/src/lib.rs @@ -41,9 +41,9 @@ //! [`Mp4Muxer`] for what that costs and what it buys. //! //! What this crate deliberately does *not* do: convert between Annex-B and -//! length-prefixed samples. An mp4 sample is the codec's own bytes and this -//! writes what it is given — the bitstream-format question belongs to the codec -//! crates, not to the container. +//! length-prefixed samples inside the muxer. An mp4 sample is the codec's own +//! bytes and [`Mp4Muxer`] writes what it is given; [`config`] holds the helpers +//! that turn encoder output into those bytes and their sample-entry records. //! //! No async, no unsafe, no external dependencies. @@ -56,6 +56,8 @@ mod demux; mod esds; mod mux; +pub mod config; + pub use demux::{Edit, Mp4Demuxer, Sample, TrackInfo}; pub use esds::{Esds, object_type}; pub use mux::Mp4Muxer; diff --git a/tools/edith-sink/Cargo.toml b/tools/edith-sink/Cargo.toml new file mode 100644 index 00000000..38c48a78 --- /dev/null +++ b/tools/edith-sink/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "edith-sink" +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true +publish = false + +[dependencies] +ec-core.workspace = true +ec-dsp.workspace = true +ec-hw.workspace = true +ec-mp4.workspace = true +ec-va.workspace = true + +[lints.rust] +unsafe_code = "forbid" diff --git a/tools/edith-sink/src/main.rs b/tools/edith-sink/src/main.rs new file mode 100644 index 00000000..86934252 --- /dev/null +++ b/tools/edith-sink/src/main.rs @@ -0,0 +1,354 @@ +use std::fs::File; +use std::io::{self, BufWriter, Read}; +use std::path::{Path, PathBuf}; +use std::process::ExitCode; +use std::str::FromStr; +use std::sync::mpsc::{self, Receiver, SyncSender}; +use std::thread; + +use ec_core::{Buf, ColorInfo, CodecId, CodecParameters, Muxer, Packet, StreamInfo, TimeBase}; +use ec_dsp::rgb::rgba_to_i420_709; +use ec_hw::{CodedFrame, EncCodec, Encoder, EncoderConfig, FrameMetadata, I420, RateControlMode}; +use ec_mp4::Mp4Muxer; +use ec_mp4::config::{annex_b_to_hvcc, av1c_record, avcc_record, h264_split_annex_b, hvcc_record}; + +type Res = Result; + +const OBU_SEQUENCE_HEADER: u8 = 1; +const OBU_TEMPORAL_DELIMITER: u8 = 2; + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Codec { + H264, + Hevc, + Av1, +} + +impl Codec { + fn enc(self) -> EncCodec { + match self { + Codec::H264 => EncCodec::H264, + Codec::Hevc => EncCodec::H265, + Codec::Av1 => EncCodec::Av1, + } + } +} + +struct Args { + width: u32, + height: u32, + rate: u32, + codec: Codec, + qp: u32, + dev: Option, + out: PathBuf, +} + +fn value(it: &mut impl Iterator, flag: &str) -> Res { + it.next().ok_or_else(|| format!("{flag} needs a value")) +} + +fn number(text: &str, flag: &str) -> Res { + text.parse().map_err(|_| format!("{flag}: bad number {text}")) +} + +fn parse_args() -> Res { + let mut size = None; + let mut rate = 30; + let mut codec = Codec::Hevc; + let mut qp = 16; + let mut dev = None; + let mut out = None; + let mut it = std::env::args().skip(1); + while let Some(flag) = it.next() { + match flag.as_str() { + "-s" => { + let text = value(&mut it, &flag)?; + let (w, h) = text + .split_once('x') + .ok_or_else(|| format!("-s: expected WxH, got {text}"))?; + size = Some((number(w, "-s")?, number(h, "-s")?)); + } + "-r" => rate = number(&value(&mut it, &flag)?, "-r")?, + "--qp" => qp = number(&value(&mut it, &flag)?, "--qp")?, + "--codec" => { + codec = match value(&mut it, &flag)?.as_str() { + "hevc" => Codec::Hevc, + "h264" => Codec::H264, + "av1" => Codec::Av1, + other => return Err(format!("unknown codec {other}")), + } + } + "--dev" => dev = Some(PathBuf::from(value(&mut it, &flag)?)), + "-o" => out = Some(PathBuf::from(value(&mut it, &flag)?)), + other => return Err(format!("unknown argument {other}")), + } + } + let (width, height) = size.ok_or("missing -s WxH")?; + let out = out.ok_or("missing -o FILE")?; + if width == 0 || height == 0 || width % 2 != 0 || height % 2 != 0 { + return Err("size must be non-zero and even".into()); + } + if rate == 0 { + return Err("-r must be positive".into()); + } + if qp > 51 { + return Err("--qp must be 0..51".into()); + } + Ok(Args { + width, + height, + rate, + codec, + qp, + dev, + out, + }) +} + +fn blank(width: u32, height: u32) -> I420 { + let (w, h) = (width as usize, height as usize); + let chroma = (w / 2) * (h / 2); + I420 { + y: vec![0; w * h], + u: vec![0; chroma], + v: vec![0; chroma], + width, + height, + } +} + +fn read_frame(src: &mut impl Read, buf: &mut [u8], index: u64) -> Res { + let mut filled = 0; + while filled < buf.len() { + match src.read(&mut buf[filled..]) { + Ok(0) => break, + Ok(n) => filled += n, + Err(e) if e.kind() == io::ErrorKind::Interrupted => {} + Err(e) => return Err(format!("stdin: {e}")), + } + } + match filled { + 0 => Ok(false), + n if n == buf.len() => Ok(true), + n => Err(format!( + "partial frame {index}: {n} of {} bytes", + buf.len() + )), + } +} + +fn read_frames( + width: u32, + height: u32, + tx: SyncSender, + recycled: Receiver, +) -> Res { + let (w, h) = (width as usize, height as usize); + let mut stdin = io::stdin().lock(); + let mut rgba = vec![0u8; w * h * 4]; + let mut count = 0u64; + while read_frame(&mut stdin, &mut rgba, count)? { + let mut frame = recycled + .try_recv() + .unwrap_or_else(|_| blank(width, height)); + rgba_to_i420_709(&rgba, w, h, &mut frame.y, &mut frame.u, &mut frame.v); + if tx.send(frame).is_err() { + break; + } + count += 1; + } + if count == 0 { + return Err("no frames on stdin".into()); + } + Ok(count) +} + +fn leb128(bytes: &[u8]) -> Res<(usize, usize)> { + let mut value = 0u64; + for (i, &b) in bytes.iter().take(8).enumerate() { + value |= u64::from(b & 0x7F) << (7 * i); + if (b & 0x80) == 0 { + let size = usize::try_from(value).map_err(|e| e.to_string())?; + return Ok((size, i + 1)); + } + } + Err("bad AV1 leb128 size".into()) +} + +fn av1_obus(data: &[u8]) -> Res> { + let mut out = Vec::new(); + let mut at = 0; + while at < data.len() { + let head = data[at]; + let kind = (head >> 3) & 0x0F; + if (head & 0x02) == 0 { + return Err("AV1 OBU without a size field".into()); + } + let mut pos = at + 1 + usize::from((head & 0x04) != 0); + let (size, used) = leb128(data.get(pos..).unwrap_or(&[]))?; + pos += used; + let end = pos + .checked_add(size) + .filter(|&end| end <= data.len()) + .ok_or("truncated AV1 OBU")?; + out.push((kind, &data[at..end])); + at = end; + } + Ok(out) +} + +fn config_record(codec: Codec, data: &[u8]) -> Res<(CodecId, Vec)> { + match codec { + Codec::H264 => { + let (_, _, params) = h264_split_annex_b(data).ok_or("first frame has no slice")?; + let (sps, pps) = params.ok_or("first frame has no SPS/PPS")?; + Ok((CodecId::H264, avcc_record(&sps, &pps))) + } + Codec::Hevc => { + let record = hvcc_record(data, false).ok_or("first frame has no VPS/SPS/PPS")?; + Ok((CodecId::H265, record)) + } + Codec::Av1 => { + let seq = av1_obus(data)? + .into_iter() + .find(|(kind, _)| *kind == OBU_SEQUENCE_HEADER) + .map(|(_, obu)| obu) + .ok_or("first frame has no sequence header")?; + Ok((CodecId::Av1, av1c_record(false, seq))) + } + } +} + +fn sample_of(codec: Codec, data: &[u8]) -> Res> { + match codec { + Codec::H264 => h264_split_annex_b(data) + .map(|(sample, _, _)| sample) + .ok_or_else(|| "coded frame has no slice".into()), + Codec::Hevc => annex_b_to_hvcc(data).ok_or_else(|| "coded frame has no NAL".into()), + Codec::Av1 => Ok(av1_obus(data)? + .into_iter() + .filter(|(kind, _)| *kind != OBU_TEMPORAL_DELIMITER) + .flat_map(|(_, obu)| obu.iter().copied()) + .collect()), + } +} + +fn open_sink( + out: &Path, + codec: Codec, + args: &Args, + first: &CodedFrame, +) -> Res<(Mp4Muxer>, u32)> { + let (codec_id, extradata) = config_record(codec, &first.data)?; + let file = File::create(out).map_err(|e| format!("{}: {e}", out.display()))?; + let mut mux = Mp4Muxer::new(BufWriter::new(file)).map_err(|e| e.to_string())?; + let mut params = CodecParameters::new(codec_id); + params.extradata = Some(Buf::from(extradata)); + if let ec_core::MediaParameters::Video(video) = &mut params.media { + video.width = args.width; + video.height = args.height; + video.frame_rate = Some(TimeBase::new(i64::from(args.rate), 1)); + } + let info = StreamInfo::new(0, TimeBase::new(1, i64::from(args.rate)), params); + let stream = mux.add_stream(info).map_err(|e| e.to_string())?; + mux.set_color( + stream, + ColorInfo { + primaries: 1, + transfer: 1, + matrix: 1, + full_range: false, + }, + ) + .map_err(|e| e.to_string())?; + Ok((mux, stream)) +} + +struct Partial<'a>(Option<&'a Path>); + +impl Drop for Partial<'_> { + fn drop(&mut self) { + if let Some(path) = self.0 { + let _ = std::fs::remove_file(path); + } + } +} + +fn run() -> Res { + let args = parse_args()?; + let display = match &args.dev { + Some(path) => ec_va::open_path(path), + None => ec_va::open(), + } + .map_err(|e| e.to_string())?; + + let qp = if args.codec == Codec::Av1 { + args.qp * 255 / 51 + } else { + args.qp + }; + let mut config = EncoderConfig::new(args.codec.enc(), args.width, args.height) + .colour(1, 1, 1, false); + config.framerate = (args.rate, 1); + config.gop_size = args.rate; + config.rate_control = RateControlMode::ConstantQp { qp }; + let mut encoder = Encoder::new(&display, config).map_err(|e| e.to_string())?; + + let (frame_tx, frame_rx) = mpsc::sync_channel::(2); + let (recycle_tx, recycle_rx) = mpsc::channel::(); + let (width, height) = (args.width, args.height); + let reader = thread::spawn(move || read_frames(width, height, frame_tx, recycle_rx)); + + let mut sink: Option<(Mp4Muxer>, u32)> = None; + let mut partial = Partial(None); + for (index, frame) in frame_rx.iter().enumerate() { + let index = index as i64; + let coded = encoder + .encode( + &frame, + FrameMetadata { + timestamp: index, + force_keyframe: false, + }, + ) + .map_err(|e| e.to_string())?; + let _ = recycle_tx.send(frame); + if sink.is_none() { + sink = Some(open_sink(&args.out, args.codec, &args, &coded)?); + partial.0 = Some(&args.out); + } + let (mux, stream) = sink.as_mut().ok_or("no output stream")?; + let mut packet = Packet::new( + *stream, + TimeBase::new(1, i64::from(args.rate)), + sample_of(args.codec, &coded.data)?, + ); + packet.pts = Some(index); + packet.dts = Some(index); + packet.duration = Some(1); + packet.flags.keyframe = coded.is_keyframe; + mux.write_packet(&packet).map_err(|e| e.to_string())?; + } + + let frames = reader + .join() + .map_err(|_| "reader thread panicked".to_string())??; + let (mut mux, _) = sink.ok_or("no output stream")?; + mux.finish().map_err(|e| e.to_string())?; + partial.0 = None; + Ok(frames) +} + +fn main() -> ExitCode { + match run() { + Ok(frames) => { + eprintln!("edith-sink: {frames} frames"); + ExitCode::SUCCESS + } + Err(e) => { + eprintln!("edith-sink: {e}"); + ExitCode::FAILURE + } + } +}