forge
Explore
Log in

Don't you dare go Hollow

edith-sink: raw RGBA stdin to VA-API h264/hevc/av1 mp4; ec-dsp rgb BT.709 converter; ec-mp4 codec config helpers

Browse files at this commit

032b56155092f6803b74e9e0bf89937332d0025fAhmet Kaan GümüşParent: f849ee9
Cargo.lockmodified+11 -0
@@ -746,6 +746,17 @@ dependencies = [
746 "ec-core",746 "ec-core",
747 ]747 ]
748 748
749+[[package]]
750+name = "edith-sink"
751+version = "0.1.0"
752+dependencies = [
753+ "ec-core",
754+ "ec-dsp",
755+ "ec-hw",
756+ "ec-mp4",
757+ "ec-va",
758+]
759+
749 [[package]]760 [[package]]
750 name = "either"761 name = "either"
751 version = "1.17.0"762 version = "1.17.0"
crates/ec-dsp/src/lib.rsmodified+1 -0
@@ -44,6 +44,7 @@ pub mod dct;
44 pub mod fft;44 pub mod fft;
45 pub mod mdct;45 pub mod mdct;
46 pub mod remap;46 pub mod remap;
47+pub mod rgb;
47 pub mod window;48 pub mod window;
48 49
49 pub use dct::{Dct, Dct4};50 pub use dct::{Dct, Dct4};
crates/ec-dsp/src/rgb.rsadded+149 -0
@@ -0,0 +1,149 @@
1+//! RGB to YUV conversion.
2+
3+/// 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.
4+pub fn rgba_to_i420_709(
5+ rgba: &[u8],
6+ width: usize,
7+ height: usize,
8+ y: &mut [u8],
9+ u: &mut [u8],
10+ v: &mut [u8],
11+) {
12+ assert!(width.is_multiple_of(2) && height.is_multiple_of(2), "width and height must be even");
13+ assert_eq!(rgba.len(), width * height * 4);
14+ assert_eq!(y.len(), width * height);
15+ let (cw, ch) = (width / 2, height / 2);
16+ assert_eq!(u.len(), cw * ch);
17+ assert_eq!(v.len(), cw * ch);
18+ if ch == 0 {
19+ return;
20+ }
21+
22+ let k = Coeffs::bt709();
23+ let threads = std::thread::available_parallelism()
24+ .map_or(1, |n| n.get())
25+ .min(8)
26+ .min(ch);
27+ let rows = ch.div_ceil(threads);
28+ let band = rows * 2 * width;
29+
30+ std::thread::scope(|s| {
31+ let bands = rgba
32+ .chunks(band * 4)
33+ .zip(y.chunks_mut(band))
34+ .zip(u.chunks_mut(rows * cw))
35+ .zip(v.chunks_mut(rows * cw));
36+ for (((src, y), u), v) in bands {
37+ let k = &k;
38+ s.spawn(move || convert_band(src, width, k, y, u, v));
39+ }
40+ });
41+}
42+
43+struct Coeffs {
44+ y: [i32; 3],
45+ cb: [i32; 3],
46+ cr: [i32; 3],
47+}
48+
49+impl Coeffs {
50+ fn bt709() -> Self {
51+ let kr = 0.2126;
52+ let kb = 0.0722;
53+ let kg = 1.0 - kr - kb;
54+ let ky = 219.0 / 255.0;
55+ let kc = 224.0 / 255.0;
56+ let q = |c: f64| (c * 65536.0).round() as i32;
57+ Self {
58+ y: [q(ky * kr), q(ky * kg), q(ky * kb)],
59+ cb: [
60+ q(-kc * kr / (2.0 * (1.0 - kb))),
61+ q(-kc * kg / (2.0 * (1.0 - kb))),
62+ q(kc / 2.0),
63+ ],
64+ cr: [
65+ q(kc / 2.0),
66+ q(-kc * kg / (2.0 * (1.0 - kr))),
67+ q(-kc * kb / (2.0 * (1.0 - kr))),
68+ ],
69+ }
70+ }
71+}
72+
73+fn convert_band(
74+ rgba: &[u8],
75+ width: usize,
76+ k: &Coeffs,
77+ y: &mut [u8],
78+ u: &mut [u8],
79+ v: &mut [u8],
80+) {
81+ let cw = width / 2;
82+ let mut cb = vec![0i32; width];
83+ let mut cr = vec![0i32; width];
84+ let pairs = rgba
85+ .chunks_exact(2 * width * 4)
86+ .zip(y.chunks_exact_mut(2 * width))
87+ .zip(u.chunks_exact_mut(cw))
88+ .zip(v.chunks_exact_mut(cw));
89+ for (((pair, luma), u), v) in pairs {
90+ let (top, bottom) = pair.split_at(width * 4);
91+ let (y0, y1) = luma.split_at_mut(width);
92+ cb.fill(0);
93+ cr.fill(0);
94+ pixel_row(top, y0, &mut cb, &mut cr, k);
95+ pixel_row(bottom, y1, &mut cb, &mut cr, k);
96+ subsample(&cb, u);
97+ subsample(&cr, v);
98+ }
99+}
100+
101+fn pixel_row(rgba: &[u8], y: &mut [u8], cb: &mut [i32], cr: &mut [i32], k: &Coeffs) {
102+ let px = rgba.as_chunks::<4>().0;
103+ for (((&[r, g, b, _], y), cb), cr) in px
104+ .iter()
105+ .zip(y.iter_mut())
106+ .zip(cb.iter_mut())
107+ .zip(cr.iter_mut())
108+ {
109+ let (r, g, b) = (i32::from(r), i32::from(g), i32::from(b));
110+ let luma = k.y[0] * r + k.y[1] * g + k.y[2] * b;
111+ *y = (((luma + 0x8000) >> 16) + 16).clamp(0, 255) as u8;
112+ *cb += k.cb[0] * r + k.cb[1] * g + k.cb[2] * b;
113+ *cr += k.cr[0] * r + k.cr[1] * g + k.cr[2] * b;
114+ }
115+}
116+
117+fn subsample(sums: &[i32], out: &mut [u8]) {
118+ const HALF: i32 = 1 << 18;
119+ let fin = |acc: i32| (((acc + HALF) >> 19) + 128).clamp(0, 255) as u8;
120+ out[0] = fin(3 * sums[0] + sums[1]);
121+ for (o, w) in out[1..].iter_mut().zip(sums[1..].windows(3).step_by(2)) {
122+ *o = fin(w[0] + 2 * w[1] + w[2]);
123+ }
124+}
125+
126+#[cfg(test)]
127+mod tests {
128+ use super::*;
129+
130+ #[test]
131+ fn four_by_two_matches_hand_values() {
132+ let white = [255, 255, 255, 255];
133+ let red = [255, 0, 0, 255];
134+ let black = [0, 0, 0, 255];
135+ let rgba: Vec<u8> = [white, white, red, red, black, black, black, black]
136+ .into_iter()
137+ .flatten()
138+ .collect();
139+ let (mut y, mut u, mut v) = (vec![0u8; 8], vec![0u8; 2], vec![0u8; 2]);
140+ rgba_to_i420_709(&rgba, 4, 2, &mut y, &mut u, &mut v);
141+ let close = |got: u8, want: i32| (i32::from(got) - want).abs() <= 1;
142+ for (got, want) in y.iter().zip([235, 235, 63, 63, 16, 16, 16, 16]) {
143+ assert!(close(*got, want), "y {got} vs {want}");
144+ }
145+ assert!(close(u[0], 128) && close(v[0], 128));
146+ assert!(close(u[1], 118), "u {}", u[1]);
147+ assert!(close(v[1], 170), "v {}", v[1]);
148+ }
149+}
crates/ec-mp4/src/config.rsadded+171 -0
@@ -0,0 +1,171 @@
1+//! Turns encoder output (Annex-B) into mp4 samples and sample-entry config records.
2+
3+const NAL_IDR: u8 = 5;
4+const NAL_SEI: u8 = 6;
5+const NAL_SPS: u8 = 7;
6+const NAL_PPS: u8 = 8;
7+const NAL_AUD: u8 = 9;
8+
9+const HEVC_VPS: u8 = 32;
10+const HEVC_SPS: u8 = 33;
11+const HEVC_PPS: u8 = 34;
12+const HEVC_AUD: u8 = 35;
13+
14+const AV1C_HEAD: [u8; 4] = [0x81, 0x1F, 0x0C, 0x00];
15+
16+/// An H.264 sample, whether it is an IDR, and its first SPS and PPS when present.
17+pub type H264Split = (Vec<u8>, bool, Option<(Vec<u8>, Vec<u8>)>);
18+
19+/// Splits an H.264 Annex-B access unit into a length-prefixed sample.
20+///
21+/// SPS, PPS, AUD and SEI are stripped from the sample. `None` when the unit holds no coded slice.
22+pub fn h264_split_annex_b(annex_b: &[u8]) -> Option<H264Split> {
23+ let nals = split_annex_b(annex_b);
24+ let first = |kind: u8| nals.iter().copied().find(|n| nal_type(n) == kind);
25+ let params = match (first(NAL_SPS), first(NAL_PPS)) {
26+ (Some(sps), Some(pps)) => Some((sps.to_vec(), pps.to_vec())),
27+ _ => None,
28+ };
29+ let mut out = Vec::with_capacity(annex_b.len());
30+ let mut is_idr = false;
31+ for nal in nals {
32+ match nal_type(nal) {
33+ NAL_SPS | NAL_PPS | NAL_AUD | NAL_SEI => continue,
34+ NAL_IDR => is_idr = true,
35+ _ => {}
36+ }
37+ out.extend_from_slice(&(nal.len() as u32).to_be_bytes());
38+ out.extend_from_slice(nal);
39+ }
40+ (!out.is_empty()).then_some((out, is_idr, params))
41+}
42+
43+/// An H.264 `AVCDecoderConfigurationRecord` for one SPS and one PPS, with four-byte NAL length prefixes.
44+pub fn avcc_record(sps: &[u8], pps: &[u8]) -> Vec<u8> {
45+ let profile = sps.get(1..4).unwrap_or(&[0, 0, 0]);
46+ let mut out = vec![1, profile[0], profile[1], profile[2], 0xFF, 0xE1];
47+ out.extend_from_slice(&(sps.len() as u16).to_be_bytes());
48+ out.extend_from_slice(sps);
49+ out.push(1);
50+ out.extend_from_slice(&(pps.len() as u16).to_be_bytes());
51+ out.extend_from_slice(pps);
52+ out
53+}
54+
55+/// An HEVC `HEVCDecoderConfigurationRecord` built from the VPS, SPS and PPS of an Annex-B access unit.
56+///
57+/// `None` when the unit lacks a VPS, SPS or PPS.
58+pub fn hvcc_record(annex_b: &[u8], ten_bit: bool) -> Option<Vec<u8>> {
59+ let nals = split_annex_b(annex_b);
60+ let of = |kind: u8| nals.iter().copied().find(|n| hevc_nal_type(n) == kind);
61+ let (vps, sps) = (of(HEVC_VPS)?, of(HEVC_SPS)?);
62+ let ppss: Vec<&[u8]> = nals
63+ .iter()
64+ .copied()
65+ .filter(|n| hevc_nal_type(n) == HEVC_PPS)
66+ .collect();
67+ if ppss.is_empty() {
68+ return None;
69+ }
70+ let rbsp = unescape(sps.get(2..)?);
71+ let mut rec = vec![1u8];
72+ rec.extend_from_slice(rbsp.get(1..13)?);
73+ rec.extend_from_slice(&[0xF0, 0x00]);
74+ rec.push(0xFC);
75+ rec.push(0xFC | 1);
76+ let depth = if ten_bit { 0xFA } else { 0xF8 };
77+ rec.push(depth);
78+ rec.push(depth);
79+ rec.extend_from_slice(&0u16.to_be_bytes());
80+ rec.push(0b0000_1111);
81+ rec.push(3);
82+ for (kind, units) in [
83+ (HEVC_VPS, vec![vps]),
84+ (HEVC_SPS, vec![sps]),
85+ (HEVC_PPS, ppss),
86+ ] {
87+ rec.push(0x80 | kind);
88+ rec.extend_from_slice(&(units.len() as u16).to_be_bytes());
89+ for nal in units {
90+ rec.extend_from_slice(&(nal.len() as u16).to_be_bytes());
91+ rec.extend_from_slice(nal);
92+ }
93+ }
94+ Some(rec)
95+}
96+
97+/// Splits an HEVC Annex-B access unit into a length-prefixed sample, dropping VPS, SPS, PPS and AUD.
98+///
99+/// `None` when the unit holds no NAL left to write.
100+pub fn annex_b_to_hvcc(annex_b: &[u8]) -> Option<Vec<u8>> {
101+ let mut out = Vec::with_capacity(annex_b.len());
102+ for nal in split_annex_b(annex_b) {
103+ if matches!(
104+ hevc_nal_type(nal),
105+ HEVC_VPS | HEVC_SPS | HEVC_PPS | HEVC_AUD
106+ ) {
107+ continue;
108+ }
109+ out.extend_from_slice(&(nal.len() as u32).to_be_bytes());
110+ out.extend_from_slice(nal);
111+ }
112+ (!out.is_empty()).then_some(out)
113+}
114+
115+/// An `av1C` record: the four fixed bytes, then the sequence header OBU as the config OBUs.
116+pub fn av1c_record(ten_bit: bool, config_obus: &[u8]) -> Vec<u8> {
117+ let mut head = AV1C_HEAD;
118+ if ten_bit {
119+ head[2] |= 0x40;
120+ }
121+ let mut out = head.to_vec();
122+ out.extend_from_slice(config_obus);
123+ out
124+}
125+
126+fn hevc_nal_type(nal: &[u8]) -> u8 {
127+ nal.first().map_or(0xFF, |b| (b >> 1) & 0x3F)
128+}
129+
130+fn unescape(nal: &[u8]) -> Vec<u8> {
131+ let mut out = Vec::with_capacity(nal.len());
132+ for (i, &byte) in nal.iter().enumerate() {
133+ if byte == 3 && i >= 2 && nal[i - 1] == 0 && nal[i - 2] == 0 {
134+ continue;
135+ }
136+ out.push(byte);
137+ }
138+ out
139+}
140+
141+fn split_annex_b(src: &[u8]) -> Vec<&[u8]> {
142+ let mut nals = Vec::new();
143+ let mut start = None;
144+ let mut i = 0;
145+ while i + 2 < src.len() {
146+ if src[i] == 0 && src[i + 1] == 0 && src[i + 2] == 1 {
147+ if let Some(s) = start {
148+ push_nal(&mut nals, &src[s..i]);
149+ }
150+ i += 3;
151+ start = Some(i);
152+ } else {
153+ i += 1;
154+ }
155+ }
156+ if let Some(s) = start {
157+ push_nal(&mut nals, &src[s..]);
158+ }
159+ nals
160+}
161+
162+fn push_nal<'a>(nals: &mut Vec<&'a [u8]>, nal: &'a [u8]) {
163+ let end = nal.iter().rposition(|&b| b != 0).map_or(0, |p| p + 1);
164+ if end > 0 {
165+ nals.push(&nal[..end]);
166+ }
167+}
168+
169+fn nal_type(nal: &[u8]) -> u8 {
170+ nal.first().map_or(0, |b| b & 0x1F)
171+}
crates/ec-mp4/src/lib.rsmodified+5 -3
@@ -41,9 +41,9 @@
41 //! [`Mp4Muxer`] for what that costs and what it buys.41 //! [`Mp4Muxer`] for what that costs and what it buys.
42 //!42 //!
43 //! What this crate deliberately does *not* do: convert between Annex-B and43 //! What this crate deliberately does *not* do: convert between Annex-B and
44-//! length-prefixed samples. An mp4 sample is the codec's own bytes and this44+//! length-prefixed samples inside the muxer. An mp4 sample is the codec's own
45-//! writes what it is given — the bitstream-format question belongs to the codec45+//! bytes and [`Mp4Muxer`] writes what it is given; [`config`] holds the helpers
46-//! crates, not to the container.46+//! that turn encoder output into those bytes and their sample-entry records.
47 //!47 //!
48 //! No async, no unsafe, no external dependencies.48 //! No async, no unsafe, no external dependencies.
49 49
@@ -56,6 +56,8 @@ mod demux;
56 mod esds;56 mod esds;
57 mod mux;57 mod mux;
58 58
59+pub mod config;
60+
59 pub use demux::{Edit, Mp4Demuxer, Sample, TrackInfo};61 pub use demux::{Edit, Mp4Demuxer, Sample, TrackInfo};
60 pub use esds::{Esds, object_type};62 pub use esds::{Esds, object_type};
61 pub use mux::Mp4Muxer;63 pub use mux::Mp4Muxer;
tools/edith-sink/Cargo.tomladded+17 -0
@@ -0,0 +1,17 @@
1+[package]
2+name = "edith-sink"
3+version.workspace = true
4+edition.workspace = true
5+license.workspace = true
6+authors.workspace = true
7+publish = false
8+
9+[dependencies]
10+ec-core.workspace = true
11+ec-dsp.workspace = true
12+ec-hw.workspace = true
13+ec-mp4.workspace = true
14+ec-va.workspace = true
15+
16+[lints.rust]
17+unsafe_code = "forbid"
tools/edith-sink/src/main.rsadded+354 -0
@@ -0,0 +1,354 @@
1+use std::fs::File;
2+use std::io::{self, BufWriter, Read};
3+use std::path::{Path, PathBuf};
4+use std::process::ExitCode;
5+use std::str::FromStr;
6+use std::sync::mpsc::{self, Receiver, SyncSender};
7+use std::thread;
8+
9+use ec_core::{Buf, ColorInfo, CodecId, CodecParameters, Muxer, Packet, StreamInfo, TimeBase};
10+use ec_dsp::rgb::rgba_to_i420_709;
11+use ec_hw::{CodedFrame, EncCodec, Encoder, EncoderConfig, FrameMetadata, I420, RateControlMode};
12+use ec_mp4::Mp4Muxer;
13+use ec_mp4::config::{annex_b_to_hvcc, av1c_record, avcc_record, h264_split_annex_b, hvcc_record};
14+
15+type Res<T> = Result<T, String>;
16+
17+const OBU_SEQUENCE_HEADER: u8 = 1;
18+const OBU_TEMPORAL_DELIMITER: u8 = 2;
19+
20+#[derive(Clone, Copy, PartialEq, Eq)]
21+enum Codec {
22+ H264,
23+ Hevc,
24+ Av1,
25+}
26+
27+impl Codec {
28+ fn enc(self) -> EncCodec {
29+ match self {
30+ Codec::H264 => EncCodec::H264,
31+ Codec::Hevc => EncCodec::H265,
32+ Codec::Av1 => EncCodec::Av1,
33+ }
34+ }
35+}
36+
37+struct Args {
38+ width: u32,
39+ height: u32,
40+ rate: u32,
41+ codec: Codec,
42+ qp: u32,
43+ dev: Option<PathBuf>,
44+ out: PathBuf,
45+}
46+
47+fn value(it: &mut impl Iterator<Item = String>, flag: &str) -> Res<String> {
48+ it.next().ok_or_else(|| format!("{flag} needs a value"))
49+}
50+
51+fn number<T: FromStr>(text: &str, flag: &str) -> Res<T> {
52+ text.parse().map_err(|_| format!("{flag}: bad number {text}"))
53+}
54+
55+fn parse_args() -> Res<Args> {
56+ let mut size = None;
57+ let mut rate = 30;
58+ let mut codec = Codec::Hevc;
59+ let mut qp = 16;
60+ let mut dev = None;
61+ let mut out = None;
62+ let mut it = std::env::args().skip(1);
63+ while let Some(flag) = it.next() {
64+ match flag.as_str() {
65+ "-s" => {
66+ let text = value(&mut it, &flag)?;
67+ let (w, h) = text
68+ .split_once('x')
69+ .ok_or_else(|| format!("-s: expected WxH, got {text}"))?;
70+ size = Some((number(w, "-s")?, number(h, "-s")?));
71+ }
72+ "-r" => rate = number(&value(&mut it, &flag)?, "-r")?,
73+ "--qp" => qp = number(&value(&mut it, &flag)?, "--qp")?,
74+ "--codec" => {
75+ codec = match value(&mut it, &flag)?.as_str() {
76+ "hevc" => Codec::Hevc,
77+ "h264" => Codec::H264,
78+ "av1" => Codec::Av1,
79+ other => return Err(format!("unknown codec {other}")),
80+ }
81+ }
82+ "--dev" => dev = Some(PathBuf::from(value(&mut it, &flag)?)),
83+ "-o" => out = Some(PathBuf::from(value(&mut it, &flag)?)),
84+ other => return Err(format!("unknown argument {other}")),
85+ }
86+ }
87+ let (width, height) = size.ok_or("missing -s WxH")?;
88+ let out = out.ok_or("missing -o FILE")?;
89+ if width == 0 || height == 0 || width % 2 != 0 || height % 2 != 0 {
90+ return Err("size must be non-zero and even".into());
91+ }
92+ if rate == 0 {
93+ return Err("-r must be positive".into());
94+ }
95+ if qp > 51 {
96+ return Err("--qp must be 0..51".into());
97+ }
98+ Ok(Args {
99+ width,
100+ height,
101+ rate,
102+ codec,
103+ qp,
104+ dev,
105+ out,
106+ })
107+}
108+
109+fn blank(width: u32, height: u32) -> I420 {
110+ let (w, h) = (width as usize, height as usize);
111+ let chroma = (w / 2) * (h / 2);
112+ I420 {
113+ y: vec![0; w * h],
114+ u: vec![0; chroma],
115+ v: vec![0; chroma],
116+ width,
117+ height,
118+ }
119+}
120+
121+fn read_frame(src: &mut impl Read, buf: &mut [u8], index: u64) -> Res<bool> {
122+ let mut filled = 0;
123+ while filled < buf.len() {
124+ match src.read(&mut buf[filled..]) {
125+ Ok(0) => break,
126+ Ok(n) => filled += n,
127+ Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
128+ Err(e) => return Err(format!("stdin: {e}")),
129+ }
130+ }
131+ match filled {
132+ 0 => Ok(false),
133+ n if n == buf.len() => Ok(true),
134+ n => Err(format!(
135+ "partial frame {index}: {n} of {} bytes",
136+ buf.len()
137+ )),
138+ }
139+}
140+
141+fn read_frames(
142+ width: u32,
143+ height: u32,
144+ tx: SyncSender<I420>,
145+ recycled: Receiver<I420>,
146+) -> Res<u64> {
147+ let (w, h) = (width as usize, height as usize);
148+ let mut stdin = io::stdin().lock();
149+ let mut rgba = vec![0u8; w * h * 4];
150+ let mut count = 0u64;
151+ while read_frame(&mut stdin, &mut rgba, count)? {
152+ let mut frame = recycled
153+ .try_recv()
154+ .unwrap_or_else(|_| blank(width, height));
155+ rgba_to_i420_709(&rgba, w, h, &mut frame.y, &mut frame.u, &mut frame.v);
156+ if tx.send(frame).is_err() {
157+ break;
158+ }
159+ count += 1;
160+ }
161+ if count == 0 {
162+ return Err("no frames on stdin".into());
163+ }
164+ Ok(count)
165+}
166+
167+fn leb128(bytes: &[u8]) -> Res<(usize, usize)> {
168+ let mut value = 0u64;
169+ for (i, &b) in bytes.iter().take(8).enumerate() {
170+ value |= u64::from(b & 0x7F) << (7 * i);
171+ if (b & 0x80) == 0 {
172+ let size = usize::try_from(value).map_err(|e| e.to_string())?;
173+ return Ok((size, i + 1));
174+ }
175+ }
176+ Err("bad AV1 leb128 size".into())
177+}
178+
179+fn av1_obus(data: &[u8]) -> Res<Vec<(u8, &[u8])>> {
180+ let mut out = Vec::new();
181+ let mut at = 0;
182+ while at < data.len() {
183+ let head = data[at];
184+ let kind = (head >> 3) & 0x0F;
185+ if (head & 0x02) == 0 {
186+ return Err("AV1 OBU without a size field".into());
187+ }
188+ let mut pos = at + 1 + usize::from((head & 0x04) != 0);
189+ let (size, used) = leb128(data.get(pos..).unwrap_or(&[]))?;
190+ pos += used;
191+ let end = pos
192+ .checked_add(size)
193+ .filter(|&end| end <= data.len())
194+ .ok_or("truncated AV1 OBU")?;
195+ out.push((kind, &data[at..end]));
196+ at = end;
197+ }
198+ Ok(out)
199+}
200+
201+fn config_record(codec: Codec, data: &[u8]) -> Res<(CodecId, Vec<u8>)> {
202+ match codec {
203+ Codec::H264 => {
204+ let (_, _, params) = h264_split_annex_b(data).ok_or("first frame has no slice")?;
205+ let (sps, pps) = params.ok_or("first frame has no SPS/PPS")?;
206+ Ok((CodecId::H264, avcc_record(&sps, &pps)))
207+ }
208+ Codec::Hevc => {
209+ let record = hvcc_record(data, false).ok_or("first frame has no VPS/SPS/PPS")?;
210+ Ok((CodecId::H265, record))
211+ }
212+ Codec::Av1 => {
213+ let seq = av1_obus(data)?
214+ .into_iter()
215+ .find(|(kind, _)| *kind == OBU_SEQUENCE_HEADER)
216+ .map(|(_, obu)| obu)
217+ .ok_or("first frame has no sequence header")?;
218+ Ok((CodecId::Av1, av1c_record(false, seq)))
219+ }
220+ }
221+}
222+
223+fn sample_of(codec: Codec, data: &[u8]) -> Res<Vec<u8>> {
224+ match codec {
225+ Codec::H264 => h264_split_annex_b(data)
226+ .map(|(sample, _, _)| sample)
227+ .ok_or_else(|| "coded frame has no slice".into()),
228+ Codec::Hevc => annex_b_to_hvcc(data).ok_or_else(|| "coded frame has no NAL".into()),
229+ Codec::Av1 => Ok(av1_obus(data)?
230+ .into_iter()
231+ .filter(|(kind, _)| *kind != OBU_TEMPORAL_DELIMITER)
232+ .flat_map(|(_, obu)| obu.iter().copied())
233+ .collect()),
234+ }
235+}
236+
237+fn open_sink(
238+ out: &Path,
239+ codec: Codec,
240+ args: &Args,
241+ first: &CodedFrame,
242+) -> Res<(Mp4Muxer<BufWriter<File>>, u32)> {
243+ let (codec_id, extradata) = config_record(codec, &first.data)?;
244+ let file = File::create(out).map_err(|e| format!("{}: {e}", out.display()))?;
245+ let mut mux = Mp4Muxer::new(BufWriter::new(file)).map_err(|e| e.to_string())?;
246+ let mut params = CodecParameters::new(codec_id);
247+ params.extradata = Some(Buf::from(extradata));
248+ if let ec_core::MediaParameters::Video(video) = &mut params.media {
249+ video.width = args.width;
250+ video.height = args.height;
251+ video.frame_rate = Some(TimeBase::new(i64::from(args.rate), 1));
252+ }
253+ let info = StreamInfo::new(0, TimeBase::new(1, i64::from(args.rate)), params);
254+ let stream = mux.add_stream(info).map_err(|e| e.to_string())?;
255+ mux.set_color(
256+ stream,
257+ ColorInfo {
258+ primaries: 1,
259+ transfer: 1,
260+ matrix: 1,
261+ full_range: false,
262+ },
263+ )
264+ .map_err(|e| e.to_string())?;
265+ Ok((mux, stream))
266+}
267+
268+struct Partial<'a>(Option<&'a Path>);
269+
270+impl Drop for Partial<'_> {
271+ fn drop(&mut self) {
272+ if let Some(path) = self.0 {
273+ let _ = std::fs::remove_file(path);
274+ }
275+ }
276+}
277+
278+fn run() -> Res<u64> {
279+ let args = parse_args()?;
280+ let display = match &args.dev {
281+ Some(path) => ec_va::open_path(path),
282+ None => ec_va::open(),
283+ }
284+ .map_err(|e| e.to_string())?;
285+
286+ let qp = if args.codec == Codec::Av1 {
287+ args.qp * 255 / 51
288+ } else {
289+ args.qp
290+ };
291+ let mut config = EncoderConfig::new(args.codec.enc(), args.width, args.height)
292+ .colour(1, 1, 1, false);
293+ config.framerate = (args.rate, 1);
294+ config.gop_size = args.rate;
295+ config.rate_control = RateControlMode::ConstantQp { qp };
296+ let mut encoder = Encoder::new(&display, config).map_err(|e| e.to_string())?;
297+
298+ let (frame_tx, frame_rx) = mpsc::sync_channel::<I420>(2);
299+ let (recycle_tx, recycle_rx) = mpsc::channel::<I420>();
300+ let (width, height) = (args.width, args.height);
301+ let reader = thread::spawn(move || read_frames(width, height, frame_tx, recycle_rx));
302+
303+ let mut sink: Option<(Mp4Muxer<BufWriter<File>>, u32)> = None;
304+ let mut partial = Partial(None);
305+ for (index, frame) in frame_rx.iter().enumerate() {
306+ let index = index as i64;
307+ let coded = encoder
308+ .encode(
309+ &frame,
310+ FrameMetadata {
311+ timestamp: index,
312+ force_keyframe: false,
313+ },
314+ )
315+ .map_err(|e| e.to_string())?;
316+ let _ = recycle_tx.send(frame);
317+ if sink.is_none() {
318+ sink = Some(open_sink(&args.out, args.codec, &args, &coded)?);
319+ partial.0 = Some(&args.out);
320+ }
321+ let (mux, stream) = sink.as_mut().ok_or("no output stream")?;
322+ let mut packet = Packet::new(
323+ *stream,
324+ TimeBase::new(1, i64::from(args.rate)),
325+ sample_of(args.codec, &coded.data)?,
326+ );
327+ packet.pts = Some(index);
328+ packet.dts = Some(index);
329+ packet.duration = Some(1);
330+ packet.flags.keyframe = coded.is_keyframe;
331+ mux.write_packet(&packet).map_err(|e| e.to_string())?;
332+ }
333+
334+ let frames = reader
335+ .join()
336+ .map_err(|_| "reader thread panicked".to_string())??;
337+ let (mut mux, _) = sink.ok_or("no output stream")?;
338+ mux.finish().map_err(|e| e.to_string())?;
339+ partial.0 = None;
340+ Ok(frames)
341+}
342+
343+fn main() -> ExitCode {
344+ match run() {
345+ Ok(frames) => {
346+ eprintln!("edith-sink: {frames} frames");
347+ ExitCode::SUCCESS
348+ }
349+ Err(e) => {
350+ eprintln!("edith-sink: {e}");
351+ ExitCode::FAILURE
352+ }
353+ }
354+}