ec-hw: 10-bit HEVC encode, pipelined submit/flush, prime submit, CBR/VBR closed-loop rate correction; remove edith-sink
Browse files at this commitccbbd43cdd4da1af882fd26651b403d6362937e9Parent: d346e458 changed files +469 -484
- Cargo.lock +0 -11
- crates/ec-hw/src/enc/headers.rs +8 -3
- crates/ec-hw/src/enc/hevc.rs +16 -20
- crates/ec-hw/src/enc/mod.rs +329 -45
- crates/ec-hw/src/lib.rs +4 -4
- crates/ec-hw/tests/gpu.rs +112 -14
- tools/edith-sink/Cargo.toml +0 -17
- tools/edith-sink/src/main.rs +0 -370
Cargo.lockmodified+0 -11
| @@ -746,17 +746,6 @@ dependencies = [ | ||
| 746 | 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 | - | |
| 760 | 749 | [[package]] |
| 761 | 750 | name = "either" |
| 762 | 751 | version = "1.17.0" |
crates/ec-hw/src/enc/headers.rsmodified+8 -3
| @@ -229,11 +229,16 @@ pub(super) mod hevc { | ||
| 229 | 229 | pub(in crate::enc) time_scale: u32, |
| 230 | 230 | pub(in crate::enc) init_qp: u8, |
| 231 | 231 | pub(in crate::enc) colour: Option<Colour>, |
| 232 | + pub(in crate::enc) bit_depth: u8, | |
| 232 | 233 | } |
| 233 | 234 | |
| 234 | 235 | /// The VPS, SPS and PPS, in that order. |
| 235 | 236 | 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 | + }; | |
| 237 | 242 | let vps = Vps { |
| 238 | 243 | id: 0, |
| 239 | 244 | ptl, |
| @@ -255,8 +260,8 @@ pub(super) mod hevc { | ||
| 255 | 260 | top: 0, |
| 256 | 261 | bottom: (p.coded_height - p.height) / 2, |
| 257 | 262 | }, |
| 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), | |
| 260 | 265 | log2_max_poc_lsb_minus4: 8, |
| 261 | 266 | max_dec_pic_buffering_minus1: 1, |
| 262 | 267 | max_num_reorder_pics: 0, |
crates/ec-hw/src/enc/hevc.rsmodified+16 -20
| @@ -57,8 +57,9 @@ pub(super) fn parameters( | ||
| 57 | 57 | let vui_num_units_in_tick = config.framerate.1.max(1); |
| 58 | 58 | let vui_time_scale = config.framerate.0.max(1); |
| 59 | 59 | |
| 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); | |
| 62 | 63 | // vui_timing_info_present_flag. |
| 63 | 64 | let vui = HevcEncVuiFields::new(0, 0, 0, 1, 0, 0, 0, 0, 0, 0); |
| 64 | 65 | let scc = HevcEncSeqSccFields::new(0); |
| @@ -67,7 +68,7 @@ pub(super) fn parameters( | ||
| 67 | 68 | // parameters say, and `num_ctu_in_slice` below has to count the same |
| 68 | 69 | // blocks the hardware does. |
| 69 | 70 | let seq = EncSequenceParameterBufferHEVC::new( |
| 70 | - 1, | |
| 71 | + if config.bit_depth == 10 { 2 } else { 1 }, | |
| 71 | 72 | general_level_idc, |
| 72 | 73 | 0, |
| 73 | 74 | intra_period, |
| @@ -98,7 +99,9 @@ pub(super) fn parameters( | ||
| 98 | 99 | 0, |
| 99 | 100 | &scc, |
| 100 | 101 | ); |
| 101 | - out.push(BufferType::EncSequenceParameter(EncSequenceParameter::HEVC(seq))); | |
| 102 | + out.push(BufferType::EncSequenceParameter( | |
| 103 | + EncSequenceParameter::HEVC(seq), | |
| 104 | + )); | |
| 102 | 105 | |
| 103 | 106 | let pic_init_qp = match config.rate_control { |
| 104 | 107 | RateControlMode::ConstantQp { qp } => qp.clamp(1, 51) as u8, |
| @@ -166,7 +169,9 @@ pub(super) fn parameters( | ||
| 166 | 169 | 0, |
| 167 | 170 | &pic_scc, |
| 168 | 171 | ); |
| 169 | - out.push(BufferType::EncPictureParameter(EncPictureParameter::HEVC(pic))); | |
| 172 | + out.push(BufferType::EncPictureParameter(EncPictureParameter::HEVC( | |
| 173 | + pic, | |
| 174 | + ))); | |
| 170 | 175 | |
| 171 | 176 | // CTBs are 64x64 by the sequence parameters above. |
| 172 | 177 | let ctbs = coded_w.div_ceil(64) * coded_h.div_ceil(64); |
| @@ -177,20 +182,8 @@ pub(super) fn parameters( | ||
| 177 | 182 | } |
| 178 | 183 | // last_slice_of_pic_flag, slice_sao_luma/chroma, and the reference override |
| 179 | 184 | // 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); | |
| 194 | 187 | let slice = EncSliceParameterBufferHEVC::new( |
| 195 | 188 | 0, |
| 196 | 189 | ctbs, |
| @@ -231,6 +224,7 @@ pub(super) fn parameters( | ||
| 231 | 224 | time_scale: vui_time_scale, |
| 232 | 225 | init_qp: pic_init_qp, |
| 233 | 226 | colour: config.colour, |
| 227 | + bit_depth: config.bit_depth, | |
| 234 | 228 | }; |
| 235 | 229 | let (vps, sps, pps) = hevc_headers::parameter_sets(&header_params); |
| 236 | 230 | if keyframe { |
| @@ -243,7 +237,9 @@ pub(super) fn parameters( | ||
| 243 | 237 | // only when a slice header accompanies them, so dropping it costs the |
| 244 | 238 | // stream its VPS, SPS and PPS (measured 2026-08-14). |
| 245 | 239 | 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 | + ))); | |
| 247 | 243 | Ok(()) |
| 248 | 244 | } |
| 249 | 245 |
crates/ec-hw/src/enc/mod.rsmodified+329 -45
| @@ -36,17 +36,18 @@ | ||
| 36 | 36 | |
| 37 | 37 | #![allow(dead_code)] // the header writers wait for the encoder port |
| 38 | 38 | |
| 39 | +use std::collections::VecDeque; | |
| 39 | 40 | use std::rc::Rc; |
| 40 | 41 | |
| 41 | 42 | use ec_va::caps::{Entrypoint, Profile}; |
| 43 | +use ec_va::va::SurfaceMemoryDescriptor; | |
| 42 | 44 | use ec_va::va::{ |
| 43 | 45 | BufferType, EncMiscParameter, EncMiscParameterFrameRate, EncMiscParameterHRD, |
| 44 | 46 | 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, | |
| 48 | 50 | }; |
| 49 | -use ec_va::va::SurfaceMemoryDescriptor; | |
| 50 | 51 | use ec_va::{CapReport, Config, ConfigAttrib, Context, Display, Surface, SurfaceSpec, Vpp}; |
| 51 | 52 | |
| 52 | 53 | use crate::error::{Error, Result}; |
| @@ -111,6 +112,9 @@ impl H264Profile { | ||
| 111 | 112 | /// The rate window the request is spread over, in milliseconds (`window_size`). |
| 112 | 113 | const RATE_WINDOW_MS: u32 = 1000; |
| 113 | 114 | |
| 115 | +/// Pictures the pipelined path keeps in flight before the oldest is read back. | |
| 116 | +const DEPTH: usize = 3; | |
| 117 | + | |
| 114 | 118 | /// The HRD buffer for a GOP of `gop_size` pictures, in milliseconds of the |
| 115 | 119 | /// requested bitrate. |
| 116 | 120 | /// |
| @@ -136,6 +140,26 @@ fn hrd_buffer_ms(gop_size: u32) -> u32 { | ||
| 136 | 140 | if gop_size < 10 { 20 } else { RATE_WINDOW_MS } |
| 137 | 141 | } |
| 138 | 142 | |
| 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 | + | |
| 139 | 163 | /// How the driver should spend bits. |
| 140 | 164 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 141 | 165 | pub enum RateControlMode { |
| @@ -264,7 +288,7 @@ impl EncoderConfig { | ||
| 264 | 288 | } |
| 265 | 289 | } |
| 266 | 290 | |
| 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`]. | |
| 268 | 292 | pub fn ten_bit(mut self) -> EncoderConfig { |
| 269 | 293 | self.bit_depth = 10; |
| 270 | 294 | self |
| @@ -306,6 +330,16 @@ pub struct CodedFrame { | ||
| 306 | 330 | pub is_keyframe: bool, |
| 307 | 331 | } |
| 308 | 332 | |
| 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 | + | |
| 309 | 343 | /// A hardware encoder. |
| 310 | 344 | /// A hardware encoder. |
| 311 | 345 | pub struct Encoder { |
| @@ -325,6 +359,7 @@ pub struct Encoder { | ||
| 325 | 359 | tunings: Tunings, |
| 326 | 360 | /// Set when the rate control parameters have to be resent. |
| 327 | 361 | tunings_dirty: bool, |
| 362 | + rc: RateFeedback, | |
| 328 | 363 | profile: Profile, |
| 329 | 364 | /// P010 -> NV12 GPU-resident conversion pipeline for [`Encoder::encode_frame`] |
| 330 | 365 | /// on a source that is not the encoder's own format or size; built lazily, |
| @@ -336,6 +371,8 @@ pub struct Encoder { | ||
| 336 | 371 | /// to never hand out one still in flight. |
| 337 | 372 | vpp_surfaces: Vec<Rc<Surface>>, |
| 338 | 373 | vpp_next: usize, |
| 374 | + /// Pictures submitted by [`Encoder::submit`], oldest first, not yet read back. | |
| 375 | + pending: VecDeque<InFlight<()>>, | |
| 339 | 376 | } |
| 340 | 377 | |
| 341 | 378 | impl Encoder { |
| @@ -352,20 +389,19 @@ impl Encoder { | ||
| 352 | 389 | } |
| 353 | 390 | if config.bit_depth != 8 && config.bit_depth != 10 { |
| 354 | 391 | 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", | |
| 356 | 393 | config.bit_depth |
| 357 | 394 | ))); |
| 358 | 395 | } |
| 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 { | |
| 362 | 397 | 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 \ | |
| 364 | 399 | configures are 8-bit", |
| 365 | 400 | )); |
| 366 | 401 | } |
| 367 | 402 | let (profile, block) = match config.codec { |
| 368 | 403 | EncCodec::H264 => (config.h264_profile.va_profile(), 16), |
| 404 | + EncCodec::H265 if config.bit_depth == 10 => (Profile::HEVCMain10, 32), | |
| 369 | 405 | EncCodec::H265 => (Profile::HEVCMain, 32), |
| 370 | 406 | EncCodec::Av1 => (Profile::AV1Profile0, 64), |
| 371 | 407 | }; |
| @@ -428,9 +464,12 @@ impl Encoder { | ||
| 428 | 464 | ], |
| 429 | 465 | )?; |
| 430 | 466 | 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 | + } | |
| 434 | 473 | let context = ec_va::picture::create_context( |
| 435 | 474 | display, |
| 436 | 475 | &config_id, |
| @@ -455,10 +494,12 @@ impl Encoder { | ||
| 455 | 494 | gop_position: 0, |
| 456 | 495 | idr_count: 0, |
| 457 | 496 | tunings_dirty: true, |
| 497 | + rc: RateFeedback::default(), | |
| 458 | 498 | profile, |
| 459 | 499 | vpp: None, |
| 460 | 500 | vpp_surfaces: Vec::new(), |
| 461 | 501 | vpp_next: 0, |
| 502 | + pending: VecDeque::new(), | |
| 462 | 503 | }) |
| 463 | 504 | } |
| 464 | 505 | |
| @@ -471,10 +512,16 @@ impl Encoder { | ||
| 471 | 512 | pub fn tune(&mut self, tunings: Tunings) { |
| 472 | 513 | self.tunings = tunings; |
| 473 | 514 | self.tunings_dirty = true; |
| 515 | + self.rc = RateFeedback::default(); | |
| 474 | 516 | } |
| 475 | 517 | |
| 476 | 518 | /// Encode one frame and return its coded bytes. |
| 477 | 519 | 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 | + } | |
| 478 | 525 | if self.config.bit_depth != 8 { |
| 479 | 526 | return Err(Error::config(format!( |
| 480 | 527 | "encode: this encoder is configured for {} bits; call encode_16", |
| @@ -490,11 +537,115 @@ impl Encoder { | ||
| 490 | 537 | self.encode_settled(Rc::clone(input.surface()), meta) |
| 491 | 538 | } |
| 492 | 539 | |
| 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 | + | |
| 493 | 639 | /// Encode one 10-bit frame; the [`Encoder::encode`] of a 10-bit encoder. |
| 494 | 640 | /// |
| 495 | 641 | /// 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. | |
| 497 | 643 | 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 | + } | |
| 498 | 649 | if self.config.bit_depth != 10 { |
| 499 | 650 | return Err(Error::config(format!( |
| 500 | 651 | "encode_16: this encoder is configured for {} bits; call encode", |
| @@ -525,6 +676,11 @@ impl Encoder { | ||
| 525 | 676 | /// only means anything on the display that created it. |
| 526 | 677 | /// - `frame`'s bit depth is neither 8 nor 10. |
| 527 | 678 | 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 | + } | |
| 528 | 684 | if frame.bit_depth != 8 && frame.bit_depth != 10 { |
| 529 | 685 | return Err(Error::unsupported( |
| 530 | 686 | format!("encode_frame of a {}-bit source", frame.bit_depth), |
| @@ -558,6 +714,11 @@ impl Encoder { | ||
| 558 | 714 | display_size: (u32, u32), |
| 559 | 715 | meta: FrameMetadata, |
| 560 | 716 | ) -> Result<CodedFrame> { |
| 717 | + if !self.pending.is_empty() { | |
| 718 | + return Err(Error::config( | |
| 719 | + "encode_surface: pipelined frames pending; call flush first", | |
| 720 | + )); | |
| 721 | + } | |
| 561 | 722 | if surface.size() != self.coded_size { |
| 562 | 723 | let converted = self.vpp_into_pool(surface, display_size)?; |
| 563 | 724 | self.encode_settled(converted, meta) |
| @@ -582,11 +743,7 @@ impl Encoder { | ||
| 582 | 743 | /// Builds the VPP pipeline and its two-surface pool on first use, painting |
| 583 | 744 | /// the pool black so any padding beyond `display_size` a region copy never |
| 584 | 745 | /// 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> { | |
| 590 | 747 | if self.vpp.is_none() { |
| 591 | 748 | let spec = surface_spec(self.config.bit_depth, self.coded_size); |
| 592 | 749 | let display = Rc::clone(self.context.display()); |
| @@ -603,10 +760,20 @@ impl Encoder { | ||
| 603 | 760 | self.vpp_surfaces = surfaces.into_iter().map(Rc::new).collect(); |
| 604 | 761 | self.vpp = Some(vpp); |
| 605 | 762 | } |
| 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()?; | |
| 606 | 772 | let dest = Rc::clone(&self.vpp_surfaces[self.vpp_next]); |
| 607 | 773 | 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 { | |
| 610 | 777 | Ok(vpp.convert(source, dest)?) |
| 611 | 778 | } else { |
| 612 | 779 | let rect = (0, 0, display_size.0, display_size.1); |
| @@ -614,14 +781,23 @@ impl Encoder { | ||
| 614 | 781 | } |
| 615 | 782 | } |
| 616 | 783 | |
| 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. | |
| 620 | 786 | fn encode_settled<D: SurfaceMemoryDescriptor>( |
| 621 | 787 | &mut self, |
| 622 | 788 | source: Rc<ec_va::va::Surface<D>>, |
| 623 | 789 | meta: FrameMetadata, |
| 624 | 790 | ) -> 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>> { | |
| 625 | 801 | if crate::reset::gpu_reset_epoch() != self.born_epoch { |
| 626 | 802 | return Err(Error::hw_reset( |
| 627 | 803 | "the GPU was reset after this encoder was created; its context is lost", |
| @@ -657,7 +833,33 @@ impl Encoder { | ||
| 657 | 833 | } |
| 658 | 834 | |
| 659 | 835 | 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; | |
| 661 | 863 | drop(picture); |
| 662 | 864 | |
| 663 | 865 | let mut data = { |
| @@ -674,6 +876,7 @@ impl Encoder { | ||
| 674 | 876 | if data.is_empty() { |
| 675 | 877 | return Err(Error::config("the encoder produced an empty coded buffer")); |
| 676 | 878 | } |
| 879 | + self.track_rate(data.len()); | |
| 677 | 880 | if self.config.codec == EncCodec::Av1 { |
| 678 | 881 | // Every AV1 temporal unit begins with a temporal delimiter (5.6), |
| 679 | 882 | // and this driver emits none: its coded buffer starts at the |
| @@ -682,21 +885,52 @@ impl Encoder { | ||
| 682 | 885 | // here rather than left to the caller. |
| 683 | 886 | data.splice(0..0, [0x12u8, 0x00]); |
| 684 | 887 | } |
| 685 | - // The coded buffer is no longer read once it is copied out. | |
| 686 | 888 | 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); | |
| 693 | 890 | Ok(CodedFrame { |
| 694 | 891 | data, |
| 695 | - timestamp: meta.timestamp, | |
| 892 | + timestamp, | |
| 696 | 893 | is_keyframe: keyframe, |
| 697 | 894 | }) |
| 698 | 895 | } |
| 699 | 896 | |
| 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 | + | |
| 700 | 934 | /// The misc parameter buffers that carry rate control, resent when tuned. |
| 701 | 935 | fn rate_control_buffers(&mut self) -> Result<Vec<BufferType>> { |
| 702 | 936 | if !self.tunings_dirty { |
| @@ -708,9 +942,9 @@ impl Encoder { | ||
| 708 | 942 | // becomes a 1.5x ceiling at 66%. |
| 709 | 943 | let (initial_qp, min_qp, max_qp, bits, target, quality) = match self.config.rate_control { |
| 710 | 944 | 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), | |
| 712 | 946 | 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) | |
| 714 | 948 | } |
| 715 | 949 | RateControlMode::Qvbr { quality } => (0, 0, 0, self.tunings.bitrate, 100, quality), |
| 716 | 950 | }; |
| @@ -742,7 +976,7 @@ impl Encoder { | ||
| 742 | 976 | out.push(BufferType::EncMiscParameter(EncMiscParameter::FrameRate( |
| 743 | 977 | EncMiscParameterFrameRate::new(packed, 0), |
| 744 | 978 | ))); |
| 745 | - if bits > 0 { | |
| 979 | + if bits > 0 && !std::mem::take(&mut self.rc.steered) { | |
| 746 | 980 | // The buffer starts full. Starting at three quarters full cost a |
| 747 | 981 | // quarter of a window of budget: radeonsi then spent 12.5% under the |
| 748 | 982 | // 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 { | ||
| 832 | 1066 | /// cros-libva writes a mutated image back to the surface when the image is |
| 833 | 1067 | /// dropped (`vaPutImage`), so `fill` runs against the image's own bytes and |
| 834 | 1068 | /// the write-back happens at the end of this function. |
| 835 | -fn write_surface( | |
| 1069 | +fn write_surface<D: SurfaceMemoryDescriptor>( | |
| 836 | 1070 | display: &Display, |
| 837 | - surface: &Surface, | |
| 1071 | + surface: &ec_va::va::Surface<D>, | |
| 838 | 1072 | fourcc: u32, |
| 839 | 1073 | size: (u32, u32), |
| 840 | 1074 | fill: impl FnOnce(&VAImage, &mut [u8]), |
| 841 | 1075 | ) -> 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 | + } | |
| 842 | 1083 | let format = ec_va::surface::image_format(display, fourcc)?; |
| 843 | 1084 | let mut image = ec_va::surface::create_image(surface, format, size, size)?; |
| 844 | 1085 | let layout = *image.image(); |
| @@ -847,12 +1088,7 @@ fn write_surface( | ||
| 847 | 1088 | } |
| 848 | 1089 | |
| 849 | 1090 | /// 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<()> { | |
| 856 | 1092 | let display: &Display = context.display(); |
| 857 | 1093 | let (w, h) = (frame.width as usize, frame.height as usize); |
| 858 | 1094 | 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: | ||
| 899 | 1135 | (u16::from(eight) << 6).to_le_bytes().to_vec() |
| 900 | 1136 | } |
| 901 | 1137 | }; |
| 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 | + ] { | |
| 903 | 1142 | let pitch = layout.pitches[plane] as usize; |
| 904 | 1143 | let base = layout.offsets[plane] as usize; |
| 905 | 1144 | let unit = samples(value); |
| @@ -916,6 +1155,51 @@ fn fill_black(display: &Display, surface: &Surface, size: (u32, u32), bit_depth: | ||
| 916 | 1155 | }) |
| 917 | 1156 | } |
| 918 | 1157 | |
| 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 | + | |
| 919 | 1203 | /// Upload one 10-bit frame into a surface as P010: samples move from the low |
| 920 | 1204 | /// ten bits of the caller's `u16` into P010's top ten. |
| 921 | 1205 | fn upload_16( |
crates/ec-hw/src/lib.rsmodified+4 -4
| @@ -25,11 +25,11 @@ | ||
| 25 | 25 | //! call [`Frame::to_i420_16`] instead — that is the lossless path that keeps |
| 26 | 26 | //! all ten bits. |
| 27 | 27 | //! |
| 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 | |
| 29 | 29 | //! 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. | |
| 33 | 33 | //! |
| 34 | 34 | //! # Shape |
| 35 | 35 | //! |
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 | ||
| 1218 | 1218 | /// What ffprobe calls the stream's pixel format — for an AV1 stream that is |
| 1219 | 1219 | /// libdav1d reporting the sequence header's `high_bitdepth`, read by a decoder |
| 1220 | 1220 | /// 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> { | |
| 1222 | 1222 | let out = Command::new("ffprobe") |
| 1223 | 1223 | .args([ |
| 1224 | 1224 | "-v", |
| @@ -1230,7 +1230,7 @@ fn ffprobe_pix_fmt(path: &Path) -> Option<String> { | ||
| 1230 | 1230 | "-of", |
| 1231 | 1231 | "default=nw=1:nk=1", |
| 1232 | 1232 | "-f", |
| 1233 | - "obu", | |
| 1233 | + format, | |
| 1234 | 1234 | ]) |
| 1235 | 1235 | .arg(path) |
| 1236 | 1236 | .output() |
| @@ -1241,12 +1241,13 @@ fn ffprobe_pix_fmt(path: &Path) -> Option<String> { | ||
| 1241 | 1241 | /// Encode 10-bit planes and return the bitstream. |
| 1242 | 1242 | fn encode_stream_16( |
| 1243 | 1243 | display: &Rc<Display>, |
| 1244 | + codec: EncCodec, | |
| 1244 | 1245 | planes: &[I420_16], |
| 1245 | 1246 | qp: u32, |
| 1246 | 1247 | rate_control: RateControlMode, |
| 1247 | 1248 | ) -> Result<Vec<u8>, ec_hw::Error> { |
| 1248 | 1249 | 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(); | |
| 1250 | 1251 | config.gop_size = 60; |
| 1251 | 1252 | config.framerate = (24, 1); |
| 1252 | 1253 | config.rate_control = match rate_control { |
| @@ -1268,6 +1269,52 @@ fn encode_stream_16( | ||
| 1268 | 1269 | Ok(out) |
| 1269 | 1270 | } |
| 1270 | 1271 | |
| 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 | + | |
| 1271 | 1318 | /// 10-bit AV1 hardware encode, proved by two decoders and by two readings of |
| 1272 | 1319 | /// the stream's bit depth. |
| 1273 | 1320 | /// |
| @@ -1289,6 +1336,7 @@ fn av1_10bit_encode_agrees_between_two_decoders() { | ||
| 1289 | 1336 | let (width, height) = (planes[0].width, planes[0].height); |
| 1290 | 1337 | let data = match encode_stream_16( |
| 1291 | 1338 | &display, |
| 1339 | + EncCodec::Av1, | |
| 1292 | 1340 | &planes, |
| 1293 | 1341 | 90, |
| 1294 | 1342 | RateControlMode::ConstantQp { qp: 90 }, |
| @@ -1303,19 +1351,13 @@ fn av1_10bit_encode_agrees_between_two_decoders() { | ||
| 1303 | 1351 | std::fs::write(&path, &data).expect("write the coded stream"); |
| 1304 | 1352 | |
| 1305 | 1353 | assert_eq!( |
| 1306 | - ffprobe_pix_fmt(&path).as_deref(), | |
| 1354 | + ffprobe_pix_fmt(&path, "obu").as_deref(), | |
| 1307 | 1355 | Some("yuv420p10le"), |
| 1308 | 1356 | "the coded stream's sequence header does not say 10-bit" |
| 1309 | 1357 | ); |
| 1310 | 1358 | |
| 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()); | |
| 1319 | 1361 | let mut config = EncoderConfig::new(EncCodec::Av1, width, height).ten_bit(); |
| 1320 | 1362 | config.rate_control = RateControlMode::ConstantQp { qp: 90 }; |
| 1321 | 1363 | let mut ten = Encoder::new(&display, config).expect("a 10-bit AV1 encoder"); |
| @@ -1551,8 +1593,13 @@ fn av1_10bit_bd_row_vs_software() { | ||
| 1551 | 1593 | |
| 1552 | 1594 | let mut ours = Vec::new(); |
| 1553 | 1595 | 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 | + ) { | |
| 1556 | 1603 | Ok(data) => data, |
| 1557 | 1604 | Err(e) => { |
| 1558 | 1605 | eprintln!("skipped: 10-bit AV1 encode unavailable ({e})"); |
| @@ -1990,6 +2037,7 @@ fn av1_encode_speed() { | ||
| 1990 | 2037 | let start = Instant::now(); |
| 1991 | 2038 | match encode_stream_16( |
| 1992 | 2039 | &display, |
| 2040 | + EncCodec::Av1, | |
| 1993 | 2041 | &planes, |
| 1994 | 2042 | 90, |
| 1995 | 2043 | RateControlMode::ConstantQp { qp: 90 }, |
| @@ -3599,3 +3647,53 @@ fn a_broken_gop_is_refused_on_every_codec() { | ||
| 3599 | 3647 | println!("{codec:?} {name}: refused: {}", refusal.unwrap_or_default()); |
| 3600 | 3648 | } |
| 3601 | 3649 | } |
| 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 | -} |