forge
Explore
Log in

Don't you dare go Hollow

ec-hw: 10-bit HEVC encode, pipelined submit/flush, prime submit, CBR/VBR closed-loop rate correction; remove edith-sink

Browse files at this commit

ccbbd43cdd4da1af882fd26651b403d6362937e9Ahmet Kaan GümüşParent: d346e45
- submit/submit_16/submit_prime + flush: DEPTH-3 pipelined encode, pool zero-filled
- submit_prime: GPU copy of an imported surface into a pool surface, padding zeroed (bit-identical to the CPU upload path)
- rate control: once-a-second bias + debt correction; mesa 26.2.6 / fw 20261019 overshoot 12-19% on detailed content (ffmpeg vaapi too)
- edith-sink removed: the MCP export path covers it
Cargo.lockmodified+0 -11
@@ -746,17 +746,6 @@ dependencies = [
746746 "ec-core",
747747 ]
748748
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-
760749 [[package]]
761750 name = "either"
762751 version = "1.17.0"
crates/ec-hw/src/enc/headers.rsmodified+8 -3
@@ -229,11 +229,16 @@ pub(super) mod hevc {
229229 pub(in crate::enc) time_scale: u32,
230230 pub(in crate::enc) init_qp: u8,
231231 pub(in crate::enc) colour: Option<Colour>,
232+ pub(in crate::enc) bit_depth: u8,
232233 }
233234
234235 /// The VPS, SPS and PPS, in that order.
235236 pub(in crate::enc) fn parameter_sets(p: &Params) -> (Vps, Sps, Pps) {
236- let ptl = ProfileTierLevel::main(p.level_idc);
237+ let ptl = if p.bit_depth == 10 {
238+ ProfileTierLevel::main10(p.level_idc)
239+ } else {
240+ ProfileTierLevel::main(p.level_idc)
241+ };
237242 let vps = Vps {
238243 id: 0,
239244 ptl,
@@ -255,8 +260,8 @@ pub(super) mod hevc {
255260 top: 0,
256261 bottom: (p.coded_height - p.height) / 2,
257262 },
258- bit_depth_luma_minus8: 0,
259- bit_depth_chroma_minus8: 0,
263+ bit_depth_luma_minus8: u32::from(p.bit_depth - 8),
264+ bit_depth_chroma_minus8: u32::from(p.bit_depth - 8),
260265 log2_max_poc_lsb_minus4: 8,
261266 max_dec_pic_buffering_minus1: 1,
262267 max_num_reorder_pics: 0,
crates/ec-hw/src/enc/hevc.rsmodified+16 -20
@@ -57,8 +57,9 @@ pub(super) fn parameters(
5757 let vui_num_units_in_tick = config.framerate.1.max(1);
5858 let vui_time_scale = config.framerate.0.max(1);
5959
60- // chroma_format_idc 1, bit depths 8, strong intra smoothing, AMP, SAO.
61- let seq_fields = HEVCEncSeqFields::new(1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0);
60+ let depth_minus8 = u32::from(config.bit_depth - 8);
61+ let seq_fields =
62+ HEVCEncSeqFields::new(1, 0, depth_minus8, depth_minus8, 0, 1, 1, 1, 0, 0, 0, 0, 0);
6263 // vui_timing_info_present_flag.
6364 let vui = HevcEncVuiFields::new(0, 0, 0, 1, 0, 0, 0, 0, 0, 0);
6465 let scc = HevcEncSeqSccFields::new(0);
@@ -67,7 +68,7 @@ pub(super) fn parameters(
6768 // parameters say, and `num_ctu_in_slice` below has to count the same
6869 // blocks the hardware does.
6970 let seq = EncSequenceParameterBufferHEVC::new(
70- 1,
71+ if config.bit_depth == 10 { 2 } else { 1 },
7172 general_level_idc,
7273 0,
7374 intra_period,
@@ -98,7 +99,9 @@ pub(super) fn parameters(
9899 0,
99100 &scc,
100101 );
101- out.push(BufferType::EncSequenceParameter(EncSequenceParameter::HEVC(seq)));
102+ out.push(BufferType::EncSequenceParameter(
103+ EncSequenceParameter::HEVC(seq),
104+ ));
102105
103106 let pic_init_qp = match config.rate_control {
104107 RateControlMode::ConstantQp { qp } => qp.clamp(1, 51) as u8,
@@ -166,7 +169,9 @@ pub(super) fn parameters(
166169 0,
167170 &pic_scc,
168171 );
169- out.push(BufferType::EncPictureParameter(EncPictureParameter::HEVC(pic)));
172+ out.push(BufferType::EncPictureParameter(EncPictureParameter::HEVC(
173+ pic,
174+ )));
170175
171176 // CTBs are 64x64 by the sequence parameters above.
172177 let ctbs = coded_w.div_ceil(64) * coded_h.div_ceil(64);
@@ -177,20 +182,8 @@ pub(super) fn parameters(
177182 }
178183 // last_slice_of_pic_flag, slice_sao_luma/chroma, and the reference override
179184 // on P pictures. The loop filter across slices stays off, matching the PPS.
180- let slice_fields = HevcEncSliceFields::new(
181- 1,
182- 0,
183- 0,
184- 0,
185- 1,
186- 1,
187- u32::from(!keyframe),
188- 0,
189- 0,
190- 0,
191- 0,
192- 0,
193- );
185+ let slice_fields =
186+ HevcEncSliceFields::new(1, 0, 0, 0, 1, 1, u32::from(!keyframe), 0, 0, 0, 0, 0);
194187 let slice = EncSliceParameterBufferHEVC::new(
195188 0,
196189 ctbs,
@@ -231,6 +224,7 @@ pub(super) fn parameters(
231224 time_scale: vui_time_scale,
232225 init_qp: pic_init_qp,
233226 colour: config.colour,
227+ bit_depth: config.bit_depth,
234228 };
235229 let (vps, sps, pps) = hevc_headers::parameter_sets(&header_params);
236230 if keyframe {
@@ -243,7 +237,9 @@ pub(super) fn parameters(
243237 // only when a slice header accompanies them, so dropping it costs the
244238 // stream its VPS, SPS and PPS (measured 2026-08-14).
245239 encoder.push_packed(&hevc_headers::packed_slice(&sps, &pps, keyframe, poc), out)?;
246- out.push(BufferType::EncSliceParameter(EncSliceParameter::HEVC(slice)));
240+ out.push(BufferType::EncSliceParameter(EncSliceParameter::HEVC(
241+ slice,
242+ )));
247243 Ok(())
248244 }
249245
crates/ec-hw/src/enc/mod.rsmodified+329 -45
@@ -36,17 +36,18 @@
3636
3737 #![allow(dead_code)] // the header writers wait for the encoder port
3838
39+use std::collections::VecDeque;
3940 use std::rc::Rc;
4041
4142 use ec_va::caps::{Entrypoint, Profile};
43+use ec_va::va::SurfaceMemoryDescriptor;
4244 use ec_va::va::{
4345 BufferType, EncMiscParameter, EncMiscParameterFrameRate, EncMiscParameterHRD,
4446 EncMiscParameterRateControl, EncPackedHeaderParameter, EncPackedHeaderType, RcFlags,
45- VAConfigAttribType, VAImage, VA_ENC_PACKED_HEADER_PICTURE, VA_ENC_PACKED_HEADER_SEQUENCE,
46- VA_ENC_PACKED_HEADER_SLICE, VA_FOURCC_NV12, VA_FOURCC_P010, VA_RT_FORMAT_YUV420,
47- VA_RT_FORMAT_YUV420_10, VA_SURFACE_ATTRIB_USAGE_HINT_ENCODER,
47+ VA_ENC_PACKED_HEADER_PICTURE, VA_ENC_PACKED_HEADER_SEQUENCE, VA_ENC_PACKED_HEADER_SLICE,
48+ VA_FOURCC_NV12, VA_FOURCC_P010, VA_RT_FORMAT_YUV420, VA_RT_FORMAT_YUV420_10,
49+ VA_SURFACE_ATTRIB_USAGE_HINT_ENCODER, VAConfigAttribType, VAImage,
4850 };
49-use ec_va::va::SurfaceMemoryDescriptor;
5051 use ec_va::{CapReport, Config, ConfigAttrib, Context, Display, Surface, SurfaceSpec, Vpp};
5152
5253 use crate::error::{Error, Result};
@@ -111,6 +112,9 @@ impl H264Profile {
111112 /// The rate window the request is spread over, in milliseconds (`window_size`).
112113 const RATE_WINDOW_MS: u32 = 1000;
113114
115+/// Pictures the pipelined path keeps in flight before the oldest is read back.
116+const DEPTH: usize = 3;
117+
114118 /// The HRD buffer for a GOP of `gop_size` pictures, in milliseconds of the
115119 /// requested bitrate.
116120 ///
@@ -136,6 +140,26 @@ fn hrd_buffer_ms(gop_size: u32) -> u32 {
136140 if gop_size < 10 { 20 } else { RATE_WINDOW_MS }
137141 }
138142
143+/// Closed-loop correction of the driver's rate control, which lands off the ask
144+/// on detailed content (testsrc2: +12..19% on mesa 26.2.6, ffmpeg's VA-API
145+/// encoders too): once a second the bitrate sent is rescaled by the measured
146+/// bias, plus whatever was over- or under-spent so far.
147+#[derive(Debug, Clone, Copy)]
148+struct RateFeedback {
149+ scale: f64,
150+ spent: f64,
151+ frames: u32,
152+ window: f64,
153+ window_frames: u32,
154+ steered: bool,
155+}
156+
157+impl Default for RateFeedback {
158+ fn default() -> Self {
159+ RateFeedback { scale: 1.0, spent: 0.0, frames: 0, window: 0.0, window_frames: 0, steered: false }
160+ }
161+}
162+
139163 /// How the driver should spend bits.
140164 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
141165 pub enum RateControlMode {
@@ -264,7 +288,7 @@ impl EncoderConfig {
264288 }
265289 }
266290
267- /// Encode at 10 bits (AV1 only); see [`EncoderConfig::bit_depth`].
291+ /// Encode at 10 bits (H.265 Main10 or AV1); see [`EncoderConfig::bit_depth`].
268292 pub fn ten_bit(mut self) -> EncoderConfig {
269293 self.bit_depth = 10;
270294 self
@@ -306,6 +330,16 @@ pub struct CodedFrame {
306330 pub is_keyframe: bool,
307331 }
308332
333+/// A picture submitted but not yet read back.
334+struct InFlight<D: SurfaceMemoryDescriptor> {
335+ picture: ec_va::picture::Picture<ec_va::picture::PictureEnd, Rc<ec_va::va::Surface<D>>>,
336+ coded: ec_va::picture::EncCodedBuffer,
337+ source: Rc<ec_va::va::Surface<D>>,
338+ leases: Vec<Rc<PooledSurface>>,
339+ timestamp: i64,
340+ keyframe: bool,
341+}
342+
309343 /// A hardware encoder.
310344 /// A hardware encoder.
311345 pub struct Encoder {
@@ -325,6 +359,7 @@ pub struct Encoder {
325359 tunings: Tunings,
326360 /// Set when the rate control parameters have to be resent.
327361 tunings_dirty: bool,
362+ rc: RateFeedback,
328363 profile: Profile,
329364 /// P010 -> NV12 GPU-resident conversion pipeline for [`Encoder::encode_frame`]
330365 /// on a source that is not the encoder's own format or size; built lazily,
@@ -336,6 +371,8 @@ pub struct Encoder {
336371 /// to never hand out one still in flight.
337372 vpp_surfaces: Vec<Rc<Surface>>,
338373 vpp_next: usize,
374+ /// Pictures submitted by [`Encoder::submit`], oldest first, not yet read back.
375+ pending: VecDeque<InFlight<()>>,
339376 }
340377
341378 impl Encoder {
@@ -352,20 +389,19 @@ impl Encoder {
352389 }
353390 if config.bit_depth != 8 && config.bit_depth != 10 {
354391 return Err(Error::config(format!(
355- "encoder bit depth {} : this crate encodes 8-bit, or 10-bit AV1",
392+ "encoder bit depth {} : this crate encodes 8-bit, or 10-bit H.265/AV1",
356393 config.bit_depth
357394 )));
358395 }
359- if config.bit_depth == 10 && config.codec != EncCodec::Av1 {
360- // Not a driver refusal: H264High and HEVCMain are 8-bit profiles by
361- // definition, and this crate configures no other.
396+ if config.bit_depth == 10 && config.codec == EncCodec::H264 {
362397 return Err(Error::config(
363- "10-bit encode is AV1 only here: the H.264 and H.265 profiles this crate \
398+ "10-bit encode is H.265 and AV1 only here: the H.264 profiles this crate \
364399 configures are 8-bit",
365400 ));
366401 }
367402 let (profile, block) = match config.codec {
368403 EncCodec::H264 => (config.h264_profile.va_profile(), 16),
404+ EncCodec::H265 if config.bit_depth == 10 => (Profile::HEVCMain10, 32),
369405 EncCodec::H265 => (Profile::HEVCMain, 32),
370406 EncCodec::Av1 => (Profile::AV1Profile0, 64),
371407 };
@@ -428,9 +464,12 @@ impl Encoder {
428464 ],
429465 )?;
430466 let spec = surface_spec(config.bit_depth, coded_size);
431- // Input, reconstruction, one reference, and slack for the driver to
432- // keep a submission in flight.
433- let surfaces = ec_va::create_pool(display, &spec, 8)?;
467+ // Input, reconstruction, one reference, and slack for the pictures
468+ // the pipelined path keeps in flight.
469+ let surfaces = ec_va::create_pool(display, &spec, 12)?;
470+ for s in &surfaces {
471+ fill_zero(display, s, coded_size, config.bit_depth)?;
472+ }
434473 let context = ec_va::picture::create_context(
435474 display,
436475 &config_id,
@@ -455,10 +494,12 @@ impl Encoder {
455494 gop_position: 0,
456495 idr_count: 0,
457496 tunings_dirty: true,
497+ rc: RateFeedback::default(),
458498 profile,
459499 vpp: None,
460500 vpp_surfaces: Vec::new(),
461501 vpp_next: 0,
502+ pending: VecDeque::new(),
462503 })
463504 }
464505
@@ -471,10 +512,16 @@ impl Encoder {
471512 pub fn tune(&mut self, tunings: Tunings) {
472513 self.tunings = tunings;
473514 self.tunings_dirty = true;
515+ self.rc = RateFeedback::default();
474516 }
475517
476518 /// Encode one frame and return its coded bytes.
477519 pub fn encode(&mut self, frame: &I420, meta: FrameMetadata) -> Result<CodedFrame> {
520+ if !self.pending.is_empty() {
521+ return Err(Error::config(
522+ "encode: pipelined frames pending; call flush first",
523+ ));
524+ }
478525 if self.config.bit_depth != 8 {
479526 return Err(Error::config(format!(
480527 "encode: this encoder is configured for {} bits; call encode_16",
@@ -490,11 +537,115 @@ impl Encoder {
490537 self.encode_settled(Rc::clone(input.surface()), meta)
491538 }
492539
540+ /// Submit one frame without waiting for it; the oldest pending frame comes back
541+ /// once more than [`DEPTH`] are in flight.
542+ pub fn submit(&mut self, frame: &I420, meta: FrameMetadata) -> Result<Option<CodedFrame>> {
543+ if self.config.bit_depth != 8 {
544+ return Err(Error::config(format!(
545+ "submit: this encoder is configured for {} bits; call submit_16",
546+ self.config.bit_depth
547+ )));
548+ }
549+ self.check_size(frame.width, frame.height)?;
550+ let input = self
551+ .pool
552+ .acquire()
553+ .ok_or_else(|| Error::config("submit: every surface is still in use"))?;
554+ upload(&self.context, frame, input.surface(), self.coded_size)?;
555+ self.push_pipelined(input, meta)
556+ }
557+
558+ /// The [`Encoder::submit`] of a 10-bit encoder.
559+ pub fn submit_16(
560+ &mut self,
561+ frame: &I420_16,
562+ meta: FrameMetadata,
563+ ) -> Result<Option<CodedFrame>> {
564+ if self.config.bit_depth != 10 {
565+ return Err(Error::config(format!(
566+ "submit_16: this encoder is configured for {} bits; call submit",
567+ self.config.bit_depth
568+ )));
569+ }
570+ self.check_size(frame.width, frame.height)?;
571+ let input = self
572+ .pool
573+ .acquire()
574+ .ok_or_else(|| Error::config("submit_16: every surface is still in use"))?;
575+ upload_16(&self.context, frame, input.surface(), self.coded_size)?;
576+ self.push_pipelined(input, meta)
577+ }
578+
579+ /// Read back every pending frame, oldest first.
580+ pub fn flush(&mut self) -> Result<Vec<CodedFrame>> {
581+ let mut out = Vec::with_capacity(self.pending.len());
582+ while let Some(f) = self.pending.pop_front() {
583+ out.push(self.finish(f)?);
584+ }
585+ Ok(out)
586+ }
587+
588+ fn push_pipelined(
589+ &mut self,
590+ input: Rc<PooledSurface>,
591+ meta: FrameMetadata,
592+ ) -> Result<Option<CodedFrame>> {
593+ let source = Rc::clone(input.surface());
594+ let in_flight = self.submit_settled(source, meta, vec![input])?;
595+ self.pending.push_back(in_flight);
596+ if self.pending.len() > DEPTH {
597+ self.retire_oldest()
598+ } else {
599+ Ok(None)
600+ }
601+ }
602+
603+ /// Pipelined encode of an imported surface of the encoder's coded size: a GPU copy
604+ /// into a pool surface whose padding is then zeroed, matching the CPU upload path.
605+ pub fn submit_prime(
606+ &mut self,
607+ surface: Rc<ec_va::va::Surface<ec_va::surface::PrimeImport>>,
608+ meta: FrameMetadata,
609+ ) -> Result<Option<CodedFrame>> {
610+ if surface.size() != self.coded_size {
611+ return Err(Error::config(format!(
612+ "submit_prime: a {:?} surface for a {:?} encoder",
613+ surface.size(),
614+ self.coded_size
615+ )));
616+ }
617+ let input = self
618+ .pool
619+ .acquire()
620+ .ok_or_else(|| Error::config("submit_prime: every surface is still in use"))?;
621+ self.vpp()?.convert(&surface, Rc::clone(input.surface()))?;
622+ zero_padding(
623+ self.context.display(),
624+ input.surface(),
625+ self.config.bit_depth,
626+ (self.config.width, self.config.height),
627+ self.coded_size,
628+ )?;
629+ self.push_pipelined(input, meta)
630+ }
631+
632+ fn retire_oldest(&mut self) -> Result<Option<CodedFrame>> {
633+ match self.pending.pop_front() {
634+ Some(f) => self.finish(f).map(Some),
635+ None => Ok(None),
636+ }
637+ }
638+
493639 /// Encode one 10-bit frame; the [`Encoder::encode`] of a 10-bit encoder.
494640 ///
495641 /// Samples are 0..1023 in the low ten bits of each `u16`, shifted into
496- /// P010's top ten bits on upload. Only a 10-bit (AV1) encoder takes this path.
642+ /// P010's top ten bits on upload. Only a 10-bit (H.265/AV1) encoder takes this path.
497643 pub fn encode_16(&mut self, frame: &I420_16, meta: FrameMetadata) -> Result<CodedFrame> {
644+ if !self.pending.is_empty() {
645+ return Err(Error::config(
646+ "encode_16: pipelined frames pending; call flush first",
647+ ));
648+ }
498649 if self.config.bit_depth != 10 {
499650 return Err(Error::config(format!(
500651 "encode_16: this encoder is configured for {} bits; call encode",
@@ -525,6 +676,11 @@ impl Encoder {
525676 /// only means anything on the display that created it.
526677 /// - `frame`'s bit depth is neither 8 nor 10.
527678 pub fn encode_frame(&mut self, frame: &Frame, meta: FrameMetadata) -> Result<CodedFrame> {
679+ if !self.pending.is_empty() {
680+ return Err(Error::config(
681+ "encode_frame: pipelined frames pending; call flush first",
682+ ));
683+ }
528684 if frame.bit_depth != 8 && frame.bit_depth != 10 {
529685 return Err(Error::unsupported(
530686 format!("encode_frame of a {}-bit source", frame.bit_depth),
@@ -558,6 +714,11 @@ impl Encoder {
558714 display_size: (u32, u32),
559715 meta: FrameMetadata,
560716 ) -> Result<CodedFrame> {
717+ if !self.pending.is_empty() {
718+ return Err(Error::config(
719+ "encode_surface: pipelined frames pending; call flush first",
720+ ));
721+ }
561722 if surface.size() != self.coded_size {
562723 let converted = self.vpp_into_pool(surface, display_size)?;
563724 self.encode_settled(converted, meta)
@@ -582,11 +743,7 @@ impl Encoder {
582743 /// Builds the VPP pipeline and its two-surface pool on first use, painting
583744 /// the pool black so any padding beyond `display_size` a region copy never
584745 /// touches is deterministic.
585- fn vpp_into_pool<D: SurfaceMemoryDescriptor>(
586- &mut self,
587- source: &ec_va::va::Surface<D>,
588- display_size: (u32, u32),
589- ) -> Result<Rc<Surface>> {
746+ fn vpp(&mut self) -> Result<&Vpp> {
590747 if self.vpp.is_none() {
591748 let spec = surface_spec(self.config.bit_depth, self.coded_size);
592749 let display = Rc::clone(self.context.display());
@@ -603,10 +760,20 @@ impl Encoder {
603760 self.vpp_surfaces = surfaces.into_iter().map(Rc::new).collect();
604761 self.vpp = Some(vpp);
605762 }
763+ Ok(self.vpp.as_ref().expect("just built above if it was None"))
764+ }
765+
766+ fn vpp_into_pool<D: SurfaceMemoryDescriptor>(
767+ &mut self,
768+ source: &ec_va::va::Surface<D>,
769+ display_size: (u32, u32),
770+ ) -> Result<Rc<Surface>> {
771+ self.vpp()?;
606772 let dest = Rc::clone(&self.vpp_surfaces[self.vpp_next]);
607773 self.vpp_next = (self.vpp_next + 1) % self.vpp_surfaces.len();
608- let vpp = self.vpp.as_ref().expect("just built above if it was None");
609- if display_size == self.coded_size {
774+ let whole = display_size == self.coded_size;
775+ let vpp = self.vpp()?;
776+ if whole {
610777 Ok(vpp.convert(source, dest)?)
611778 } else {
612779 let rect = (0, 0, display_size.0, display_size.1);
@@ -614,14 +781,23 @@ impl Encoder {
614781 }
615782 }
616783
617- /// Shared submission path for [`Encoder::encode`], [`Encoder::encode_frame`]
618- /// and [`Encoder::encode_surface`]: everything after the source surface is
619- /// settled.
784+ /// Shared synchronous path for [`Encoder::encode`], [`Encoder::encode_frame`]
785+ /// and [`Encoder::encode_surface`]: submit, then read back at once.
620786 fn encode_settled<D: SurfaceMemoryDescriptor>(
621787 &mut self,
622788 source: Rc<ec_va::va::Surface<D>>,
623789 meta: FrameMetadata,
624790 ) -> Result<CodedFrame> {
791+ let in_flight = self.submit_settled(source, meta, Vec::new())?;
792+ self.finish(in_flight)
793+ }
794+
795+ fn submit_settled<D: SurfaceMemoryDescriptor>(
796+ &mut self,
797+ source: Rc<ec_va::va::Surface<D>>,
798+ meta: FrameMetadata,
799+ mut leases: Vec<Rc<PooledSurface>>,
800+ ) -> Result<InFlight<D>> {
625801 if crate::reset::gpu_reset_epoch() != self.born_epoch {
626802 return Err(Error::hw_reset(
627803 "the GPU was reset after this encoder was created; its context is lost",
@@ -657,7 +833,33 @@ impl Encoder {
657833 }
658834
659835 let picture = ec_va::picture::submit(&self.context, Rc::clone(&source), buffers)?;
660- crate::reset::sync_watched(&source)?;
836+ if let Some(previous) = self.reference.replace(recon) {
837+ leases.push(previous);
838+ }
839+ if keyframe {
840+ self.idr_count = self.idr_count.wrapping_add(1);
841+ }
842+ self.gop_position = if keyframe { 1 } else { self.gop_position + 1 };
843+ Ok(InFlight {
844+ picture,
845+ coded,
846+ source,
847+ leases,
848+ timestamp: meta.timestamp,
849+ keyframe,
850+ })
851+ }
852+
853+ fn finish<D: SurfaceMemoryDescriptor>(&mut self, f: InFlight<D>) -> Result<CodedFrame> {
854+ crate::reset::sync_watched(&f.source)?;
855+ let InFlight {
856+ picture,
857+ coded,
858+ leases,
859+ timestamp,
860+ keyframe,
861+ ..
862+ } = f;
661863 drop(picture);
662864
663865 let mut data = {
@@ -674,6 +876,7 @@ impl Encoder {
674876 if data.is_empty() {
675877 return Err(Error::config("the encoder produced an empty coded buffer"));
676878 }
879+ self.track_rate(data.len());
677880 if self.config.codec == EncCodec::Av1 {
678881 // Every AV1 temporal unit begins with a temporal delimiter (5.6),
679882 // and this driver emits none: its coded buffer starts at the
@@ -682,21 +885,52 @@ impl Encoder {
682885 // here rather than left to the caller.
683886 data.splice(0..0, [0x12u8, 0x00]);
684887 }
685- // The coded buffer is no longer read once it is copied out.
686888 drop(coded);
687-
688- self.reference = Some(recon);
689- if keyframe {
690- self.idr_count = self.idr_count.wrapping_add(1);
691- }
692- self.gop_position = if keyframe { 1 } else { self.gop_position + 1 };
889+ drop(leases);
693890 Ok(CodedFrame {
694891 data,
695- timestamp: meta.timestamp,
892+ timestamp,
696893 is_keyframe: keyframe,
697894 })
698895 }
699896
897+ fn steered_bitrate(&self) -> u32 {
898+ (f64::from(self.tunings.bitrate) * self.rc.scale) as u32
899+ }
900+
901+ fn track_rate(&mut self, bytes: usize) {
902+ if !matches!(
903+ self.config.rate_control,
904+ RateControlMode::ConstantBitrate | RateControlMode::VariableBitrate
905+ ) {
906+ return;
907+ }
908+ let (num, den) = self.tunings.framerate;
909+ let fps = f64::from(num.max(1)) / f64::from(den.max(1));
910+ let rate = f64::from(self.tunings.bitrate);
911+ let per_frame = rate / fps;
912+ let rc = &mut self.rc;
913+ let bits = bytes as f64 * 8.0;
914+ rc.spent += bits;
915+ rc.frames += 1;
916+ rc.window += bits;
917+ rc.window_frames += 1;
918+ if f64::from(rc.window_frames) < fps.round().max(1.0) {
919+ return;
920+ }
921+ let asked = rc.scale * per_frame * f64::from(rc.window_frames);
922+ let bias = rc.window / asked;
923+ let debt = f64::from(rc.frames) * per_frame - rc.spent;
924+ let scale = ((rate + debt) / rate / bias).clamp(0.5, 1.5);
925+ rc.window = 0.0;
926+ rc.window_frames = 0;
927+ if (scale / rc.scale - 1.0).abs() > 0.02 {
928+ rc.scale = scale;
929+ rc.steered = true;
930+ self.tunings_dirty = true;
931+ }
932+ }
933+
700934 /// The misc parameter buffers that carry rate control, resent when tuned.
701935 fn rate_control_buffers(&mut self) -> Result<Vec<BufferType>> {
702936 if !self.tunings_dirty {
@@ -708,9 +942,9 @@ impl Encoder {
708942 // becomes a 1.5x ceiling at 66%.
709943 let (initial_qp, min_qp, max_qp, bits, target, quality) = match self.config.rate_control {
710944 RateControlMode::ConstantQp { qp } => (qp, qp, qp, 0, 100, 0),
711- RateControlMode::ConstantBitrate => (0, 0, 0, self.tunings.bitrate, 100, 0),
945+ RateControlMode::ConstantBitrate => (0, 0, 0, self.steered_bitrate(), 100, 0),
712946 RateControlMode::VariableBitrate => {
713- (0, 0, 0, self.tunings.bitrate.saturating_mul(3) / 2, 66, 0)
947+ (0, 0, 0, self.steered_bitrate().saturating_mul(3) / 2, 66, 0)
714948 }
715949 RateControlMode::Qvbr { quality } => (0, 0, 0, self.tunings.bitrate, 100, quality),
716950 };
@@ -742,7 +976,7 @@ impl Encoder {
742976 out.push(BufferType::EncMiscParameter(EncMiscParameter::FrameRate(
743977 EncMiscParameterFrameRate::new(packed, 0),
744978 )));
745- if bits > 0 {
979+ if bits > 0 && !std::mem::take(&mut self.rc.steered) {
746980 // The buffer starts full. Starting at three quarters full cost a
747981 // quarter of a window of budget: radeonsi then spent 12.5% under the
748982 // ask on a 2 s clip, and the gap is exactly that quarter over the
@@ -832,13 +1066,20 @@ fn fourcc(bit_depth: u8) -> u32 {
8321066 /// cros-libva writes a mutated image back to the surface when the image is
8331067 /// dropped (`vaPutImage`), so `fill` runs against the image's own bytes and
8341068 /// the write-back happens at the end of this function.
835-fn write_surface(
1069+fn write_surface<D: SurfaceMemoryDescriptor>(
8361070 display: &Display,
837- surface: &Surface,
1071+ surface: &ec_va::va::Surface<D>,
8381072 fourcc: u32,
8391073 size: (u32, u32),
8401074 fill: impl FnOnce(&VAImage, &mut [u8]),
8411075 ) -> Result<()> {
1076+ if let Ok(mut image) = ec_va::va::Image::derive_from(surface, size)
1077+ && image.image().format.fourcc == fourcc
1078+ {
1079+ let layout = *image.image();
1080+ fill(&layout, AsMut::<[u8]>::as_mut(&mut image));
1081+ return Ok(());
1082+ }
8421083 let format = ec_va::surface::image_format(display, fourcc)?;
8431084 let mut image = ec_va::surface::create_image(surface, format, size, size)?;
8441085 let layout = *image.image();
@@ -847,12 +1088,7 @@ fn write_surface(
8471088 }
8481089
8491090 /// Upload one frame into a surface as NV12.
850-fn upload(
851- context: &Rc<Context>,
852- frame: &I420,
853- surface: &Surface,
854- coded: (u32, u32),
855-) -> Result<()> {
1091+fn upload(context: &Rc<Context>, frame: &I420, surface: &Surface, coded: (u32, u32)) -> Result<()> {
8561092 let display: &Display = context.display();
8571093 let (w, h) = (frame.width as usize, frame.height as usize);
8581094 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
@@ -899,7 +1135,10 @@ fn fill_black(display: &Display, surface: &Surface, size: (u32, u32), bit_depth:
8991135 (u16::from(eight) << 6).to_le_bytes().to_vec()
9001136 }
9011137 };
902- for (plane, value, rows) in [(0usize, 16u8, size.1 as usize), (1, 128, size.1 as usize / 2)] {
1138+ for (plane, value, rows) in [
1139+ (0usize, 16u8, size.1 as usize),
1140+ (1, 128, size.1 as usize / 2),
1141+ ] {
9031142 let pitch = layout.pitches[plane] as usize;
9041143 let base = layout.offsets[plane] as usize;
9051144 let unit = samples(value);
@@ -916,6 +1155,51 @@ fn fill_black(display: &Display, surface: &Surface, size: (u32, u32), bit_depth:
9161155 })
9171156 }
9181157
1158+fn fill_zero(display: &Display, surface: &Surface, size: (u32, u32), bit_depth: u8) -> Result<()> {
1159+ write_surface(display, surface, fourcc(bit_depth), size, |_, data| {
1160+ data.fill(0)
1161+ })
1162+}
1163+
1164+fn zero_padding<D: SurfaceMemoryDescriptor>(
1165+ display: &Display,
1166+ surface: &ec_va::va::Surface<D>,
1167+ bit_depth: u8,
1168+ (w, h): (u32, u32),
1169+ coded: (u32, u32),
1170+) -> Result<()> {
1171+ if (w, h) == coded {
1172+ return Ok(());
1173+ }
1174+ let (fourcc, px) = if bit_depth > 8 {
1175+ (VA_FOURCC_P010, 2)
1176+ } else {
1177+ (VA_FOURCC_NV12, 1)
1178+ };
1179+ let (w, h, cw, ch) = (
1180+ w as usize * px,
1181+ h as usize,
1182+ coded.0 as usize * px,
1183+ coded.1 as usize,
1184+ );
1185+ write_surface(display, surface, fourcc, coded, |layout, data| {
1186+ for (plane, rows, last, start) in [
1187+ (0, h, ch, w),
1188+ (1, h.div_ceil(2), ch / 2, w.next_multiple_of(2 * px)),
1189+ ] {
1190+ let pitch = layout.pitches[plane] as usize;
1191+ let base = layout.offsets[plane] as usize;
1192+ for row in 0..last {
1193+ let from = if row < rows { start } else { 0 };
1194+ if let Some(dst) = data.get_mut(base + row * pitch + from..base + row * pitch + cw)
1195+ {
1196+ dst.fill(0);
1197+ }
1198+ }
1199+ }
1200+ })
1201+}
1202+
9191203 /// Upload one 10-bit frame into a surface as P010: samples move from the low
9201204 /// ten bits of the caller's `u16` into P010's top ten.
9211205 fn upload_16(
crates/ec-hw/src/lib.rsmodified+4 -4
@@ -25,11 +25,11 @@
2525 //! call [`Frame::to_i420_16`] instead — that is the lossless path that keeps
2626 //! all ten bits.
2727 //!
28-//! Encoding is 10-bit too, for AV1: `EncoderConfig::ten_bit()` allocates P010
28+//! Encoding is 10-bit too, for H.265 (Main10) and AV1: `EncoderConfig::ten_bit()` allocates P010
2929 //! surfaces and takes its pixels through [`Encoder::encode_16`] (or straight
30-//! from a 10-bit [`Frame`], with no conversion at all). H.264 and H.265 stay
31-//! 8-bit here, because High and Main — the profiles this crate configures —
32-//! are 8-bit profiles.
30+//! from a 10-bit [`Frame`], with no conversion at all). H.264 stays
31+//! 8-bit here, because the profiles this crate configures for it
32+//! are 8-bit.
3333 //!
3434 //! # Shape
3535 //!
crates/ec-hw/tests/gpu.rsmodified+112 -14
@@ -1218,7 +1218,7 @@ fn raw_frames_16(y4m: &Path, width: u32, height: u32, frames: u32) -> Option<Vec
12181218 /// What ffprobe calls the stream's pixel format — for an AV1 stream that is
12191219 /// libdav1d reporting the sequence header's `high_bitdepth`, read by a decoder
12201220 /// that shares no code with the writer above.
1221-fn ffprobe_pix_fmt(path: &Path) -> Option<String> {
1221+fn ffprobe_pix_fmt(path: &Path, format: &str) -> Option<String> {
12221222 let out = Command::new("ffprobe")
12231223 .args([
12241224 "-v",
@@ -1230,7 +1230,7 @@ fn ffprobe_pix_fmt(path: &Path) -> Option<String> {
12301230 "-of",
12311231 "default=nw=1:nk=1",
12321232 "-f",
1233- "obu",
1233+ format,
12341234 ])
12351235 .arg(path)
12361236 .output()
@@ -1241,12 +1241,13 @@ fn ffprobe_pix_fmt(path: &Path) -> Option<String> {
12411241 /// Encode 10-bit planes and return the bitstream.
12421242 fn encode_stream_16(
12431243 display: &Rc<Display>,
1244+ codec: EncCodec,
12441245 planes: &[I420_16],
12451246 qp: u32,
12461247 rate_control: RateControlMode,
12471248 ) -> Result<Vec<u8>, ec_hw::Error> {
12481249 let (width, height) = (planes[0].width, planes[0].height);
1249- let mut config = EncoderConfig::new(EncCodec::Av1, width, height).ten_bit();
1250+ let mut config = EncoderConfig::new(codec, width, height).ten_bit();
12501251 config.gop_size = 60;
12511252 config.framerate = (24, 1);
12521253 config.rate_control = match rate_control {
@@ -1268,6 +1269,52 @@ fn encode_stream_16(
12681269 Ok(out)
12691270 }
12701271
1272+#[test]
1273+fn hevc_main10_encode_round_trips() {
1274+ let Some(display) = display() else { return };
1275+ let dir = std::env::temp_dir().join("ec-hw-hevc-10bit");
1276+ let _ = std::fs::create_dir_all(&dir);
1277+ let Some((_, _, planes)) = ten_bit_source(&dir, 10) else {
1278+ eprintln!("skipped: no 10-bit source could be built");
1279+ return;
1280+ };
1281+ let (width, height) = (planes[0].width, planes[0].height);
1282+ let data = match encode_stream_16(
1283+ &display,
1284+ EncCodec::H265,
1285+ &planes,
1286+ 26,
1287+ RateControlMode::ConstantQp { qp: 26 },
1288+ ) {
1289+ Ok(data) => data,
1290+ Err(e) => {
1291+ eprintln!("skipped: 10-bit HEVC encode unavailable ({e})");
1292+ return;
1293+ }
1294+ };
1295+ let path = dir.join("hw-10bit.hevc");
1296+ std::fs::write(&path, &data).expect("write the coded stream");
1297+ assert_eq!(
1298+ ffprobe_pix_fmt(&path, "hevc").as_deref(),
1299+ Some("yuv420p10le")
1300+ );
1301+ let mut reference =
1302+ Reference::open(&path, width, height, true).expect("ffmpeg opens the stream");
1303+ let mut worst = f64::INFINITY;
1304+ for (i, source) in planes.iter().enumerate() {
1305+ let theirs = reference
1306+ .next(width, height)
1307+ .unwrap_or_else(|| panic!("ffmpeg has no frame {i}"));
1308+ let db = psnr(&theirs, &Planes::from_16bit(source));
1309+ assert!(db > 30.0, "frame {i}: {db:.2} dB from the 10-bit source");
1310+ worst = worst.min(db);
1311+ }
1312+ println!(
1313+ "HEVC Main10 encode {width}x{height}: {} bytes, worst frame {worst:.2} dB",
1314+ data.len()
1315+ );
1316+}
1317+
12711318 /// 10-bit AV1 hardware encode, proved by two decoders and by two readings of
12721319 /// the stream's bit depth.
12731320 ///
@@ -1289,6 +1336,7 @@ fn av1_10bit_encode_agrees_between_two_decoders() {
12891336 let (width, height) = (planes[0].width, planes[0].height);
12901337 let data = match encode_stream_16(
12911338 &display,
1339+ EncCodec::Av1,
12921340 &planes,
12931341 90,
12941342 RateControlMode::ConstantQp { qp: 90 },
@@ -1303,19 +1351,13 @@ fn av1_10bit_encode_agrees_between_two_decoders() {
13031351 std::fs::write(&path, &data).expect("write the coded stream");
13041352
13051353 assert_eq!(
1306- ffprobe_pix_fmt(&path).as_deref(),
1354+ ffprobe_pix_fmt(&path, "obu").as_deref(),
13071355 Some("yuv420p10le"),
13081356 "the coded stream's sequence header does not say 10-bit"
13091357 );
13101358
1311- // The two refusals this depth added, exercised rather than asserted in
1312- // prose: 10-bit H.265 (High and Main are 8-bit profiles, so this crate
1313- // never asks the driver), and 8-bit pixels handed to a 10-bit encoder.
1314- let ten_bit_hevc = EncoderConfig::new(EncCodec::H265, width, height).ten_bit();
1315- assert!(
1316- Encoder::new(&display, ten_bit_hevc).is_err(),
1317- "a 10-bit HEVC encoder was built out of an 8-bit profile"
1318- );
1359+ let ten_bit_h264 = EncoderConfig::new(EncCodec::H264, width, height).ten_bit();
1360+ assert!(Encoder::new(&display, ten_bit_h264).is_err());
13191361 let mut config = EncoderConfig::new(EncCodec::Av1, width, height).ten_bit();
13201362 config.rate_control = RateControlMode::ConstantQp { qp: 90 };
13211363 let mut ten = Encoder::new(&display, config).expect("a 10-bit AV1 encoder");
@@ -1551,8 +1593,13 @@ fn av1_10bit_bd_row_vs_software() {
15511593
15521594 let mut ours = Vec::new();
15531595 for qp in [180u32, 140, 100, 60] {
1554- let data = match encode_stream_16(&display, &planes, qp, RateControlMode::ConstantQp { qp })
1555- {
1596+ let data = match encode_stream_16(
1597+ &display,
1598+ EncCodec::Av1,
1599+ &planes,
1600+ qp,
1601+ RateControlMode::ConstantQp { qp },
1602+ ) {
15561603 Ok(data) => data,
15571604 Err(e) => {
15581605 eprintln!("skipped: 10-bit AV1 encode unavailable ({e})");
@@ -1990,6 +2037,7 @@ fn av1_encode_speed() {
19902037 let start = Instant::now();
19912038 match encode_stream_16(
19922039 &display,
2040+ EncCodec::Av1,
19932041 &planes,
19942042 90,
19952043 RateControlMode::ConstantQp { qp: 90 },
@@ -3599,3 +3647,53 @@ fn a_broken_gop_is_refused_on_every_codec() {
35993647 println!("{codec:?} {name}: refused: {}", refusal.unwrap_or_default());
36003648 }
36013649 }
3650+
3651+#[test]
3652+fn ten_bit_prime_submit_matches_the_cpu_path() {
3653+ let Some(file) = std::env::var_os("EC_HEVC10").map(PathBuf::from) else {
3654+ return;
3655+ };
3656+ let Some(display) = display() else { return };
3657+ let data = std::fs::read(file).expect("fixture is readable");
3658+ let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens");
3659+ let mut size = (0, 0);
3660+ decode_stream(&mut decoder, Codec::H265, &data, 1, |f| {
3661+ size = f.display_size
3662+ })
3663+ .expect("decode");
3664+ let mut cfg = EncoderConfig::new(EncCodec::H265, size.0, size.1).ten_bit();
3665+ cfg.rate_control = RateControlMode::ConstantQp { qp: 22 };
3666+ let mut zc = Encoder::new(&display, cfg).expect("encoder");
3667+ let mut cpu = Encoder::new(&display, cfg).expect("encoder");
3668+ let (mut a, mut b) = (Vec::new(), Vec::new());
3669+ let mut t = 0;
3670+ let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens");
3671+ decode_stream(&mut decoder, Codec::H265, &data, 8, |frame| {
3672+ let meta = FrameMetadata {
3673+ timestamp: t,
3674+ force_keyframe: false,
3675+ };
3676+ t += 1;
3677+ let prime = frame.export_prime().expect("export");
3678+ let imported = Rc::new(ec_va::import_prime(&display, &prime).expect("import"));
3679+ if let Some(c) = zc.submit_prime(imported, meta).expect("submit_prime") {
3680+ a.extend(c.data);
3681+ }
3682+ if let Some(c) = cpu
3683+ .submit_16(&frame.to_i420_16().expect("readback"), meta)
3684+ .expect("submit_16")
3685+ {
3686+ b.extend(c.data);
3687+ }
3688+ })
3689+ .expect("decode");
3690+ a.extend(zc.flush().expect("flush").into_iter().flat_map(|c| c.data));
3691+ b.extend(cpu.flush().expect("flush").into_iter().flat_map(|c| c.data));
3692+ assert!(!a.is_empty());
3693+ assert!(
3694+ a == b,
3695+ "zero-copy and CPU 10-bit streams differ ({} vs {} bytes)",
3696+ a.len(),
3697+ b.len()
3698+ );
3699+}
tools/edith-sink/Cargo.tomldeleted+0 -17
@@ -1,17 +0,0 @@
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.rsdeleted+0 -370
@@ -1,370 +0,0 @@
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 quiet_libva() -> Option<ExitCode> {
344- if std::env::var_os("LIBVA_MESSAGING_LEVEL").is_some() {
345- return None;
346- }
347- let exe = std::env::current_exe().ok()?;
348- let status = std::process::Command::new(exe)
349- .args(std::env::args_os().skip(1))
350- .env("LIBVA_MESSAGING_LEVEL", "1")
351- .status()
352- .ok()?;
353- Some(ExitCode::from(u8::try_from(status.code().unwrap_or(1)).unwrap_or(1)))
354-}
355-
356-fn main() -> ExitCode {
357- if let Some(code) = quiet_libva() {
358- return code;
359- }
360- match run() {
361- Ok(frames) => {
362- eprintln!("edith-sink: {frames} frames");
363- ExitCode::SUCCESS
364- }
365- Err(e) => {
366- eprintln!("edith-sink: {e}");
367- ExitCode::FAILURE
368- }
369- }
370-}