diff --git a/Cargo.lock b/Cargo.lock index 67cdd37..be7309d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1933,6 +1933,7 @@ version = "0.1.0" dependencies = [ "ab_glyph", "ab_glyph_rasterizer", + "bytemuck", "ec-aac", "ec-ac3", "ec-ass", @@ -1986,6 +1987,7 @@ dependencies = [ name = "engine-hw" version = "0.1.0" dependencies = [ + "bytemuck", "ec-hw", "ec-va", "ec-vp8", diff --git a/crates/engine-hw/Cargo.toml b/crates/engine-hw/Cargo.toml index 95b0b19..5bb3bfe 100644 --- a/crates/engine-hw/Cargo.toml +++ b/crates/engine-hw/Cargo.toml @@ -16,6 +16,7 @@ name = "hw-child" path = "src/bin/hw-child.rs" [dependencies] +bytemuck = "1.25" engine = { path = "../engine" } # The decode seat: ec-hw drives the VA-API decoders, ec-va the display under it. ec-hw = { path = "../../../edith_codecs/crates/ec-hw" } diff --git a/crates/engine-hw/src/child.rs b/crates/engine-hw/src/child.rs index e31b125..a71fd13 100644 --- a/crates/engine-hw/src/child.rs +++ b/crates/engine-hw/src/child.rs @@ -54,12 +54,12 @@ use std::path::PathBuf; use engine::hw::{DmaFrame, VhDma, meta_to_wire}; use engine::hwproc::{ - DMA_BODY, K_DMA, K_PIXELS, Open, R_AU, R_ERR, R_NONE, Shm, T_DMA, T_DRAIN, T_ENCODE, T_GEOM, - T_NEXT, T_NEXT_DMA, T_SEEK, die_with_parent, recv_tag, send_msg, send_reply, + DMA_BODY, K_DMA, K_PIXELS, K_PIXELS16, Open, R_AU, R_ERR, R_NONE, Shm, T_DMA, T_DRAIN, T_ENCODE, T_ENCODE16, T_GEOM, + T_NEXT, T_NEXT_DMA, T_NEXT_DMA16, T_NEXT_WIDE, T_SEEK, die_with_parent, recv_tag, send_msg, send_reply, }; use crate::enc_ec::EcEncSession; -use crate::{OpenSession, VA_FOURCC_NV12, query_caps}; +use crate::{OpenSession, VA_FOURCC_NV12, VA_FOURCC_P010, query_caps}; /// The entry point of the `hw-child` binary. pub fn main() { @@ -143,15 +143,40 @@ fn decode(sock: &mut UnixStream, args: &[OsString]) { } drop(fd); let mut staging = Staging { shm, capacity }; + let mut ahead: Option> = None; + let mut wide_run = 0u32; loop { let Ok((tag, _)) = recv_tag(sock) else { // The parent closed the socket: nothing left to decode for. return; }; + if tag != T_NEXT_WIDE { + wide_run = 0; + } + if ahead.is_some() && tag != T_NEXT_WIDE { + ahead = None; + if tag != T_SEEK { + if send_reply(sock, R_ERR, b"a wide picture was decoded ahead; only T_NEXT_WIDE or T_SEEK may follow", &[]).is_err() { + return; + } + continue; + } + } let answered = match tag { - T_NEXT | T_NEXT_DMA => { + T_NEXT_WIDE => { + session.set_wide(true); + let pumped = ahead.take().unwrap_or_else(|| session.next_frame(None)); + let answered = answer(sock, &mut session, &mut staging, pumped); + wide_run += 1; + if answered.is_ok() && wide_run >= 2 { + ahead = Some(session.next_frame(None)); + } + session.set_wide(false); + answered + } + T_NEXT | T_NEXT_DMA | T_NEXT_DMA16 => { let want = match tag { - T_NEXT_DMA => { + T_NEXT_DMA | T_NEXT_DMA16 => { let mut body = [0u8; 16]; if sock.read_exact(&mut body).is_err() { return; @@ -160,7 +185,7 @@ fn decode(sock: &mut UnixStream, args: &[OsString]) { u32::from_le_bytes(body[4 * i..4 * i + 4].try_into().expect("four bytes")) }; Some(VhDma { - fourcc: VA_FOURCC_NV12, + fourcc: if tag == T_NEXT_DMA16 { VA_FOURCC_P010 } else { VA_FOURCC_NV12 }, coded_width: word(0), coded_height: word(1), width: word(2), @@ -170,7 +195,11 @@ fn decode(sock: &mut UnixStream, args: &[OsString]) { } _ => None, }; - frame(sock, &mut session, &mut staging, want) + let wide = tag == T_NEXT_DMA16; + session.set_wide(wide); + let answered = frame(sock, &mut session, &mut staging, want); + session.set_wide(false); + answered } T_SEEK => { let mut body = [0u8; 4]; @@ -198,7 +227,17 @@ fn frame( staging: &mut Staging, want: Option, ) -> std::io::Result<()> { - match session.next_frame(want) { + let pumped = session.next_frame(want); + answer(sock, session, staging, pumped) +} + +fn answer( + sock: &mut UnixStream, + session: &mut OpenSession, + staging: &mut Staging, + pumped: Result, +) -> std::io::Result<()> { + match pumped { Ok(false) => send_reply(sock, R_NONE, &[], &[]), Err(e) => send_reply(sock, R_ERR, e.as_bytes(), &[]), Ok(true) => match session.take_dma() { @@ -239,8 +278,8 @@ fn send_pixels( session: &OpenSession, staging: &mut Staging, ) -> std::io::Result<()> { - let (picture, w, h) = session.picture(); - let needed = picture.len(); + let (picture, w, h, wide) = session.picture(); + let needed: usize = picture.iter().map(|p| p.len()).sum(); let grown = if needed > staging.capacity { let (shm, fd) = Shm::create(needed)?; staging.shm = shm; @@ -249,9 +288,9 @@ fn send_pixels( } else { None }; - staging.shm.write_picture(&[picture])?; + staging.shm.write_picture(&picture)?; let mut body = Vec::with_capacity(9); - body.push(K_PIXELS); + body.push(if wide { K_PIXELS16 } else { K_PIXELS }); body.extend_from_slice(&w.to_le_bytes()); body.extend_from_slice(&h.to_le_bytes()); let attach: Vec = grown.iter().map(AsRawFd::as_raw_fd).collect(); @@ -348,6 +387,37 @@ fn encode(sock: &mut UnixStream, args: &[OsString]) { return; } } + T_ENCODE16 => { + let mut head = [0u8; 9]; + if sock.read_exact(&mut head).is_err() { + return; + } + reached(&At::Frame(coded)); + coded += 1; + let width = u32::from_le_bytes(head[0..4].try_into().expect("four bytes")); + let height = u32::from_le_bytes(head[4..8].try_into().expect("four bytes")); + let force_key = head[8] != 0; + let (w, h) = (width as usize, height as usize); + let chroma = w.div_ceil(2) * h.div_ceil(2); + let answer = match &mut seat { + Seat::Real(encoder) => match ( + shm.read_u16(0, w * h), + shm.read_u16(2 * w * h, chroma), + shm.read_u16(2 * (w * h + chroma), chroma), + ) { + (Ok(y), Ok(u), Ok(v)) => { + encoder + .encode16_owned(y, u, v, force_key) + .map(|()| encoder.next_au()) + } + (Err(e), _, _) | (_, Err(e), _) | (_, _, Err(e)) => Err(format!("cannot read the staging buffer: {e}")), + }, + Seat::Fake => Ok(None), + }; + if !reply(sock, answer) { + return; + } + } T_DMA => { let mut head = [0u8; 46]; if sock.read_exact(&mut head).is_err() { @@ -391,7 +461,7 @@ fn encode(sock: &mut UnixStream, args: &[OsString]) { T_DRAIN => { reached(&At::Drain); let answer = match &mut seat { - Seat::Real(encoder) => Ok(encoder.next_au()), + Seat::Real(encoder) => encoder.flush().map(|()| encoder.next_au()), Seat::Fake => Ok(None), }; if !reply(sock, answer) { diff --git a/crates/engine-hw/src/enc_ec.rs b/crates/engine-hw/src/enc_ec.rs index 23d02e5..1ace824 100644 --- a/crates/engine-hw/src/enc_ec.rs +++ b/crates/engine-hw/src/enc_ec.rs @@ -12,7 +12,7 @@ use std::os::fd::{AsFd, OwnedFd}; use std::rc::Rc; use ec_hw::enc::{EncCodec, EncoderConfig, FrameMetadata, RateControlMode}; -use ec_hw::{Encoder, H264Profile, I420}; +use ec_hw::{Encoder, H264Profile, I420, I420_16}; use ec_va::{PrimeLayer, PrimeObject, PrimeSurface}; use engine::hw::{DmaFrame, VhDma}; @@ -20,6 +20,8 @@ use engine::hwproc::SeatRate; /// `DRM_FORMAT_NV12`, which is also `VA_FOURCC_NV12`: the four characters. const FOURCC_NV12: u32 = u32::from_le_bytes(*b"NV12"); +/// `DRM_FORMAT_P010`, which is also `VA_FOURCC_P010`. +const FOURCC_P010: u32 = u32::from_le_bytes(*b"P010"); /// One hardware encode session on `ec_hw`. pub(crate) struct EcEncSession { @@ -36,6 +38,7 @@ pub(crate) struct EcEncSession { ready: VecDeque>, /// The access unit currently handed out, kept alive until the next call. out: Vec, + ten_bit: bool, } /// The `open` arguments, for any of the three codecs. @@ -52,6 +55,8 @@ pub(crate) struct EcOpen { pub gop: Option, /// Colour description for the VUI as `(primaries, transfer, matrix, full)`. pub colour: Option<(u8, u8, u8, bool)>, + /// HEVC Main10: pictures go through [`EcEncSession::encode16`]. + pub ten_bit: bool, } impl EcEncSession { @@ -66,6 +71,7 @@ impl EcEncSession { intra_only, gop, colour, + ten_bit, } = req; // NV12 chroma is half resolution, so odd dimensions have no packing; // radeonsi refuses encode contexts below 64x64 (measured). @@ -105,6 +111,9 @@ impl EcEncSession { if let Some((p, t, m, full)) = colour { config = config.colour(p, t, m, full); } + if ten_bit { + config = config.ten_bit(); + } let display = ec_va::open().ok()?; let encoder = Encoder::new(&display, config).ok()?; let coded = encoder.coded_size(); @@ -117,9 +126,47 @@ impl EcEncSession { timestamp: 0, ready: VecDeque::new(), out: Vec::new(), + ten_bit, }) } + pub(crate) fn encode16_owned( + &mut self, + mut y: Vec, + mut u: Vec, + mut v: Vec, + force_keyframe: bool, + ) -> Result<(), String> { + let (w, h) = (self.width, self.height); + let (cw, ch) = (w / 2, h / 2); + if y.len() < w * h || u.len() < cw * ch || v.len() < cw * ch { + return Err("encode input is not a packed I420 frame".into()); + } + y.truncate(w * h); + u.truncate(cw * ch); + v.truncate(cw * ch); + let picture = I420_16 { + y, + u, + v, + width: w as u32, + height: h as u32, + bit_depth: 10, + }; + let meta = self.meta(force_keyframe); + if let Some(coded) = self.encoder.submit_16(&picture, meta).map_err(|e| e.to_string())? { + self.ready.push_back(coded.data); + } + Ok(()) + } + + pub(crate) fn flush(&mut self) -> Result<(), String> { + for coded in self.encoder.flush().map_err(|e| e.to_string())? { + self.ready.push_back(coded.data); + } + Ok(()) + } + /// The surface size the driver codes at, as the caller must describe it. pub(crate) fn coded_size(&self) -> (u32, u32) { self.coded @@ -147,11 +194,9 @@ impl EcEncSession { height: h as u32, }; let meta = self.meta(force_keyframe); - let coded = self - .encoder - .encode(&picture, meta) - .map_err(|e| e.to_string())?; - self.ready.push_back(coded.data); + if let Some(coded) = self.encoder.submit(&picture, meta).map_err(|e| e.to_string())? { + self.ready.push_back(coded.data); + } Ok(()) } @@ -163,12 +208,24 @@ impl EcEncSession { pub(crate) fn encode_dma(&mut self, frame: &DmaFrame, force_keyframe: bool) -> Result<(), String> { let prime = prime_from_vhdma(&frame.desc, &frame.fds)?; let surface = Rc::new(ec_va::import_prime(&self.display, &prime).map_err(|e| e.to_string())?); + let display = (self.width as u32, self.height as u32); let meta = self.meta(force_keyframe); - let coded = self - .encoder - .encode_surface(&surface, (self.width as u32, self.height as u32), meta) - .map_err(|e| e.to_string())?; - self.ready.push_back(coded.data); + if self.ten_bit { + if let Some(coded) = self + .encoder + .submit_prime(surface, meta) + .map_err(|e| e.to_string())? + { + self.ready.push_back(coded.data); + } + } else { + self.flush()?; + let coded = self + .encoder + .encode_surface(&surface, display, meta) + .map_err(|e| e.to_string())?; + self.ready.push_back(coded.data); + } Ok(()) } @@ -190,13 +247,13 @@ impl EcEncSession { } } -/// Builds the PRIME descriptor for an NV12 picture the decoder holds. +/// Builds the PRIME descriptor for an NV12 or P010 picture the decoder holds. /// /// Luma and chroma are either two objects (two descriptors) or one object /// holding both at their own offsets, as the decoder's descriptor says. fn prime_from_vhdma(desc: &VhDma, fds: &[OwnedFd]) -> Result { - if fds.is_empty() || fds.len() > 2 || desc.fourcc != FOURCC_NV12 { - return Err("DMA-BUF is not an NV12 picture on the GPU".into()); + if fds.is_empty() || fds.len() > 2 || !matches!(desc.fourcc, FOURCC_NV12 | FOURCC_P010) { + return Err("DMA-BUF is not an NV12 or P010 picture on the GPU".into()); } let (w, h) = (desc.coded_width, desc.coded_height); let rows = [h, h / 2]; @@ -217,7 +274,7 @@ fn prime_from_vhdma(desc: &VhDma, fds: &[OwnedFd]) -> Result Result, luma: usize, chroma: usize, + /// Asked for this pump: a picture deeper than 8 bits is read back whole. + wide: bool, + out_wide: bool, + out16: Option, /// What the caller's encoder can read straight off the GPU, asked once per /// [`vh_next_frame_dma`] call and `None` for every read-back caller. want: Option, @@ -194,6 +198,9 @@ impl Session { out: Vec::new(), luma: 0, chroma: 0, + wide: false, + out_wide: false, + out16: None, want: None, dma: None, held: VecDeque::new(), @@ -336,9 +343,9 @@ impl Session { let [(obj0, off0, pitch0), (obj1, off1, pitch1)] = planes.as_slice() else { return None; }; + let fits = prime.width == want.coded_width && prime.height == want.coded_height; if prime.fourcc != want.fourcc - || prime.width != want.coded_width - || prime.height != want.coded_height + || !fits || *obj0 != 0 || *obj1 > 1 || prime.objects.len() != *obj1 as usize + 1 @@ -378,6 +385,17 @@ impl Session { // The read-back goes through the driver's image copy (`vaGetImage`) // rather than a CPU map of the surface: on a discrete GPU that buffer // lives in VRAM, and a CPU read of it runs over the PCIe BAR. + if self.wide && frame.bit_depth > 8 { + let i420 = frame.to_i420_16().map_err(|e| e.to_string())?; + self.luma = i420.y.len(); + self.chroma = i420.u.len(); + self.out_wide = true; + self.meta.width = i420.width; + self.meta.height = i420.height; + self.out16 = Some(i420); + return Ok(()); + } + self.out_wide = false; let i420 = frame.to_i420().map_err(|e| e.to_string())?; self.luma = i420.y.len(); self.chroma = i420.u.len(); @@ -392,8 +410,12 @@ impl Session { /// The picture [`Session::pump`] or [`VpxSession::pump`] just delivered, as /// packed I420 (Y, then U, then V), with its width and height. - fn picture(&self) -> (&[u8], u32, u32) { - (&self.out, self.meta.width, self.meta.height) + fn picture(&self) -> ([&[u8]; 3], u32, u32, bool) { + let parts = match (&self.out16, self.out_wide) { + (Some(p), true) => [bytemuck::cast_slice(&p.y[..]), bytemuck::cast_slice(&p.u[..]), bytemuck::cast_slice(&p.v[..])], + _ => [&self.out[..], &[][..], &[][..]], + }; + (parts, self.meta.width, self.meta.height, self.out_wide) } } @@ -476,10 +498,19 @@ impl OpenSession { /// The picture the last successful [`OpenSession::next_frame`] delivered as /// read-back I420, with its width and height. - fn picture(&self) -> (&[u8], u32, u32) { + fn picture(&self) -> ([&[u8]; 3], u32, u32, bool) { match self { Self::Vaapi(session) => session.picture(), - Self::Vpx(session) => session.picture(), + Self::Vpx(session) => { + let (out, w, h) = session.picture(); + ([out, &[][..], &[][..]], w, h, false) + } + } + } + + fn set_wide(&mut self, wide: bool) { + if let Self::Vaapi(session) = self { + session.wide = wide; } } @@ -822,6 +853,7 @@ pub(crate) fn open_encoder(open: &engine::hwproc::Open) -> Option intra_only, gop: open.gop, colour, + ten_bit: open.ten_bit, }) } @@ -871,6 +903,7 @@ mod tests { intra_only: true, gop: None, colour: None, + ten_bit: false, }; // No VA-API on this machine: nothing to encode, nothing to claim. let Some(mut session) = EcEncSession::open(open) else { @@ -881,6 +914,7 @@ mod tests { session .encode(&luma, &chroma, &chroma, false) .expect("the intra seat encodes a picture"); + session.flush().expect("flush"); let au = session.next_au().expect("one access unit").to_vec(); let au = au.as_slice(); assert_eq!( @@ -953,6 +987,7 @@ mod tests { intra_only: true, gop: None, colour: None, + ten_bit: false, }; let Some(mut session) = EcEncSession::open(open) else { return; @@ -963,6 +998,7 @@ mod tests { session .encode(&luma, &chroma, &chroma, false) .expect("the intra seat encodes a picture"); + session.flush().expect("flush"); let au = session.next_au().expect("one access unit").to_vec(); let au = au.as_slice(); let kinds: Vec = au diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index a742788..7b83991 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -9,6 +9,7 @@ doctest = false # No UI dependency here, ever: the engine must stay reusable across front-ends. [dependencies] +bytemuck = "1.25" # The WAV writer and reader, the family's own (`ec-riff`): RIFF for the usual # sizes and RF64 past 4 GiB, WAVE_FORMAT_EXTENSIBLE for the layouts that need it. # `ec-flac` encodes FLAC (RFC 9639), the family's own encoder. diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index 7a04e7c..092c53b 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -1306,15 +1306,29 @@ fn audio_kbps_of(settings: &ExportSettings) -> u32 { /// to an encoder nobody picked. Every caller is before a file exists /// ([`Enc::open`] runs ahead of the muxer), which is what makes the refusal /// free. -fn hw_seat(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result> { +fn hw_seat( + meta: &VideoMeta, + settings: &ExportSettings, + ten_bit: bool, + colour: ColorDescription, +) -> crate::Result> { if settings.seat == EncoderSeat::Software || forced("VE_SW_ENC") { return Ok(None); } - let opened = open_hw_seat(meta, settings); + if ten_bit && settings.format.is_hevc() && hdr_metadata(settings) { + if settings.seat == EncoderSeat::Hardware { + return Err("the hardware HEVC seat writes no mastering display or MaxCLL/MaxFALL SEI: \ + drop that metadata, or pick Auto or Software" + .into()); + } + return Ok(None); + } + let opened = open_hw_seat(meta, settings, ten_bit, colour); if opened.is_none() && settings.seat == EncoderSeat::Hardware { return Err(format!( - "hardware encoding was asked for and this machine has no VA-API seat for {}: \ + "hardware encoding was asked for and this machine has no VA-API seat for {}{}: \ pick Auto or Software on the export card", + if ten_bit { "10-bit " } else { "" }, settings.format.name() ) .into()); @@ -1324,7 +1338,18 @@ fn hw_seat(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result Option { +/// Whether the export carries HDR static metadata, which only the software HEVC seat writes. +fn hdr_metadata(settings: &ExportSettings) -> bool { + let hdr = &settings.hdr; + hdr.mastering_display.is_some() || hdr.max_cll.is_some() || hdr.max_fall.is_some() +} + +fn open_hw_seat( + meta: &VideoMeta, + settings: &ExportSettings, + ten_bit: bool, + colour: ColorDescription, +) -> Option { let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate).ok()?; let rate = rate_of(meta, settings); match settings.format { @@ -1341,7 +1366,8 @@ fn open_hw_seat(meta: &VideoMeta, settings: &ExportSettings) -> Option HwEncoder::open_hevc( meta.width, @@ -1349,8 +1375,9 @@ fn open_hw_seat(meta: &VideoMeta, settings: &ExportSettings) -> Option) -> Vec, quiet: impl Fn(u32) -> bool) -> Vec { + let mut out = Vec::with_capacity(spans.len()); + for mut cur in spans { + let mut off = 1; + while off < cur.len { + if quiet(cur.start + off) != quiet(cur.start + off - 1) + && let Some(tail) = span_tail(&cur, off) + { + out.push(crate::project::Span { len: off, ..cur }); + cur = tail; + off = 1; + continue; + } + off += 1; + } + out.push(cur); + } + out +} + +fn span_tail(span: &crate::project::Span, cut: u32) -> Option { + let mut tail = *span; + tail.start += cut; + tail.len -= cut; + tail.ramp = span.ramp.map(|r| r.advanced(cut)); + if let Some((source, first)) = span.from { + let next = span.source_at(first, cut); + tail.from = Some((source, next)); + if (0..tail.len).any(|o| tail.source_at(next, o) != span.source_at(first, cut + o)) { + return None; + } + } + Some(tail) +} + +fn wide_yuv(bytes: &[u8], width: u32, height: u32) -> Yuv { + let (w, h) = (width as usize, height as usize); + let (luma, chroma) = (w * h, w.div_ceil(2) * h.div_ceil(2)); + let unpack = crate::hwproc::unpack16; + Yuv::Wide { + y: unpack(&bytes[..2 * luma]), + u: unpack(&bytes[2 * luma..2 * (luma + chroma)]), + v: unpack(&bytes[2 * (luma + chroma)..2 * (luma + 2 * chroma)]), + width, + height, + } +} + fn visible_video_lanes(project: &Project) -> Vec { project .lanes() @@ -3599,7 +3674,12 @@ pub fn planned_video(meta: &VideoMeta, settings: &ExportSettings) -> Option<&'st settings .format .has_video() - .then(|| match hw_seat(meta, settings) { + .then(|| match hw_seat( + meta, + settings, + settings.video_bit_depth == Some(10) || settings.hdr.transfer != HdrTransfer::Sdr, + ColorDescription::output_sized(meta.width, meta.height), + ) { Ok(hw) => video_label(settings.format, hw.is_some(), settings.intra_only), // The seat the settings demand and this machine has not: the very // refusal [`start`] would settle with, said on the card instead. @@ -5490,7 +5570,12 @@ fn run( // past it under a trailing caption -- and *which* lane a span comes from is // `composite_spans_from`'s answer, the same one playback shows, so an // export is what was watched. - for span in export_spans(project, settings.range) { + let spans = export_spans(project, settings.range); + let spans = match (&burn, ten_bit && matches!(encoder, Enc::HevcHw(_, _, true))) { + (Some(b), true) => split_spans(spans, |f| b.quiet(f, f + 1)), + _ => spans, + }; + for span in spans { // Every clip reopens its own source file at its own in point; the // encoder is *not* reopened, so the export is one continuous stream // whose GOP boundaries need not line up with the cuts -- nor with the @@ -5528,7 +5613,7 @@ fn run( // the plugin hands back as pixels ([`HwSession::next_frame_dma`]). let untouched = mapper.is_none() && keyed_color.is_none() - && burn.is_none() + && burn.as_ref().is_none_or(|b| ten_bit && b.quiet(span.start, span.end())) && remap_into(Some(color), false, out_color.matrix).is_none() && project .composite_color_at(span.start) @@ -5886,7 +5971,7 @@ fn run( && pixel_aspect.is_square() && burn .as_ref() - .is_none_or(|b| b.cues.is_empty() && b.titles.is_empty()) + .is_none_or(|b| b.quiet(span.start + done_here, span.start + done_here + repeats)) && (done_here..done_here + repeats) .all(|off| picture_fade_at(project, span.start + off).is_none()); // A 10-bit export composes at 10 bits wherever the picture is touched at @@ -6490,6 +6575,12 @@ impl Burn { /// The picture at timeline frame `frame` with the titles on screen and the /// caption drawn in, or `None` where nothing is on screen and the planes go /// on untouched. + fn quiet(&self, from: u32, to: u32) -> bool { + (from..to).all(|f| { + cues_on_screen(&self.cues, f, self.fps).is_empty() && self.titles.iter().all(|t| t.motion_at(f).is_none()) + }) + } + fn paint( &mut self, frame: u32, @@ -8277,7 +8368,7 @@ enum Enc { Av1Hw(HwEncoder), /// HEVC on the GPU, through that same plugin -- and intra-only there too, /// so this and [`Enc::Hevc`] write the same kind of file. - HevcHw(HwEncoder, bool), + HevcHw(HwEncoder, bool, bool), /// AV1 software at 10 bits: `rav1e`'s 16-bit context. A picture that passes /// through the span untouched arrives as 16-bit planes off the 10-bit decode /// ([`Enc::encode_wide`]); an 8-bit picture (one composed on the way) is shifted @@ -8369,7 +8460,7 @@ impl Enc { Self::Sw { .. } => video_label(Format::Mp4, false, false), Self::Av1Hw(_) => video_label(Format::Av1, true, false), Self::Av1Sw { .. } | Self::Av1Sw16 { .. } => video_label(Format::Av1, false, false), - Self::HevcHw(_, intra) => video_label(Format::Hevc, true, *intra), + Self::HevcHw(_, intra, _) => video_label(Format::Hevc, true, *intra), Self::Hevc(_) => video_label(Format::Hevc, false, true), Self::HevcGop(_) => video_label(Format::Hevc, false, false), Self::ProRes { .. } => video_label(Format::ProRes, false, true), @@ -8413,7 +8504,7 @@ impl Enc { // hand 24000/1001 over as a rounded 23.976, which is the same // truncation the container timing had. crate::mux::frame_timing(meta.frame_rate)?; - if let Some(hw) = hw_seat(meta, settings)? { + if let Some(hw) = hw_seat(meta, settings, false, colour)? { if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export encoder: hardware (VA-API plugin)"); } return Ok(Self::Hw(hw)); } @@ -8508,7 +8599,7 @@ impl Enc { // The 10-bit seat is software: the GPU encode is 8-bit only. let hw = match ten_bit { true => None, - false => hw_seat(meta, settings)?, + false => hw_seat(meta, settings, false, colour)?, }; if let Some(hw) = hw { if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export encoder: hardware AV1 (VA-API plugin)"); } @@ -8633,14 +8724,9 @@ impl Enc { ) .into()); } - // The GPU seat is 8-bit only, so a 10-bit export is software. - let hw = match ten_bit { - true => None, - false => hw_seat(meta, settings)?, - }; - if let Some(hw) = hw { + if let Some(hw) = hw_seat(meta, settings, ten_bit, colour)? { if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export encoder: hardware HEVC (VA-API plugin)"); } - return Ok(Self::HevcHw(hw, settings.intra_only)); + return Ok(Self::HevcHw(hw, settings.intra_only, ten_bit)); } if !settings.intra_only { if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export encoder: software HEVC I+P (ec-h265)"); } @@ -8729,6 +8815,9 @@ impl Enc { *au = encoder.encode(&frame).map_err(|e| format!("ProRes encode: {e}"))?; Ok(Some((&au[..], true))) } + Self::HevcHw(hw, intra, true) => Ok(hw + .encode16(y, u, v, width, height, *intra)? + .map(|au| (au, hevc_irap(au)))), Self::Hevc(hevc) if hevc.ten_bit => { hevc.pending.push((le_bytes(y), le_bytes(u), le_bytes(v))); if hevc.pending.len() >= hevc.lanes.len() { @@ -8740,11 +8829,12 @@ impl Enc { } } - /// Whether this is a software HEVC seat coding at 10 bits. + /// Whether this is an HEVC seat coding at 10 bits. fn hevc_ten_bit(&self) -> bool { match self { Self::HevcGop(gop) => gop.ten_bit, Self::Hevc(hevc) => hevc.ten_bit, + Self::HevcHw(_, _, ten) => *ten, _ => false, } } @@ -8829,7 +8919,7 @@ impl Enc { collect_av1(context, ready)?; Ok(pop_av1(ready, au)) } - Self::HevcHw(hw, intra) => Ok(hw + Self::HevcHw(hw, intra, _) => Ok(hw .encode(y, u, v, width, height, *intra)? .map(|au| (au, hevc_irap(au)))), Self::Hevc(hevc) => { @@ -8883,7 +8973,10 @@ impl Enc { /// ([`crate::hwproc`]), which is a round trip on its socket. fn dma_want(&mut self, meta: &VideoMeta) -> Option { match self { - Self::Hw(hw) | Self::HevcHw(hw, _) => hw.dma_want(meta.width, meta.height), + Self::Hw(hw) | Self::HevcHw(hw, _, false) => hw.dma_want(meta.width, meta.height), + Self::HevcHw(hw, _, true) => hw + .dma_want(meta.width, meta.height) + .map(|want| crate::hw::DmaWant { ten_bit: true, ..want }), _ => None, } } @@ -8902,7 +8995,7 @@ impl Enc { fn encode_dma(&mut self, dma: &DmaFrame, intra: bool) -> crate::Result> { match self { Self::Hw(hw) => Ok(hw.encode_dma(dma, intra)?.map(|au| (au, intra))), - Self::HevcHw(hw, intra) => Ok(hw.encode_dma(dma, *intra)?.map(|au| (au, hevc_irap(au)))), + Self::HevcHw(hw, intra, _) => Ok(hw.encode_dma(dma, *intra)?.map(|au| (au, hevc_irap(au)))), // Unreachable through [`Enc::dma_want`], which is the only thing // that puts a span's decoder on this path. _ => Err("this encoder takes pictures as bytes, not as buffers".into()), @@ -8943,7 +9036,7 @@ impl Enc { } Ok(pop_av1(ready, au)) } - Self::HevcHw(hw, _) => Ok(hw.drain()?.map(|au| (au, hevc_irap(au)))), + Self::HevcHw(hw, ..) => Ok(hw.drain()?.map(|au| (au, hevc_irap(au)))), // The tail batch: fewer frames than lanes, coded on as many // encoders as there are frames left. Self::Hevc(hevc) => { @@ -9398,9 +9491,8 @@ fn source_sdr_colour(colours: &[ColorDescription]) -> Option { /// Whether a software export is written at 10 bits: the setting where it names a /// depth, the source's own where it does not. AV1 and HEVC have the choice -- -/// H.264 is 8-bit here -- and a depth the file cannot be is refused. The HEVC -/// hardware seat is 8-bit, so a 10-bit HEVC export falls back to software -/// ([`open_hevc`]). +/// H.264 is 8-bit here -- and a depth the file cannot be is refused. A 10-bit +/// HEVC export takes the hardware seat (Main10) where there is one ([`open_hevc`]). fn wide_ten_bit( settings: &ExportSettings, source_ten_bit: impl FnOnce() -> bool, @@ -10102,13 +10194,16 @@ fn decode_stream( wide: bool, deint: Deinterlace, ) -> Option { - // A 10-bit export decodes in software: the hardware seat hands 8-bit planes. - let opened = match forced("VE_SW") || wide { + // A 10-bit export asks the hardware seat for whole 10-bit pictures ([`Pictures::Hw`]). + let opened = match forced("VE_SW") { // The decode door's own gate ([`crate::decode::open_hw`]): a VP9 4:2:2 or 4:4:4 // stream is never offered to the GPU, which would refuse it on stderr. - false => crate::decode::open_hw(path, start_frame).map(|hw| Pictures::Hw(Box::new(hw))), + false => crate::decode::open_hw(path, start_frame).map(|hw| Pictures::Hw(Box::new(hw), wide)), true => None, }; + if std::env::var_os("EDITH_DEBUG").is_some() { + eprintln!("export decode: {}{}", if opened.is_some() { "hardware" } else { "software" }, if wide { ", 10-bit" } else { "" }); + } // Pictures decoded ahead of the span that a parked decoder still holds. let (mut decoder, mut backlog) = match opened { Some(hw) => (hw, VecDeque::new()), @@ -10150,7 +10245,7 @@ fn decode_stream( None => decoder.next(want), }; let next = match next { - Ok(None) if decoded == 0 && matches!(decoder, Pictures::Hw(_)) => { + Ok(None) if decoded == 0 && matches!(decoder, Pictures::Hw(..)) => { Err("hardware gave no picture from the start frame".into()) } other => other, @@ -10162,7 +10257,7 @@ fn decode_stream( return None; } Err(e) => { - if matches!(decoder, Pictures::Hw(_)) { + if matches!(decoder, Pictures::Hw(..)) { // Before the first picture, or after some: either way the // software seat takes the span from the first picture not yet // sent (`decoded` is 0 in the first case), so nothing is @@ -10198,7 +10293,8 @@ fn decode_stream( /// The stream decoders, on the thread that opened them. enum Pictures { - Hw(Box), + /// With whether the export is 10-bit, which asks for whole 10-bit pictures. + Hw(Box, bool), /// `ec-h264`, on this thread. Sw(Box), /// `ec-av1`, on a thread of its own -- see [`Av1Stream`]. @@ -10225,14 +10321,20 @@ impl Pictures { /// buys the decode and the encode their overlap. fn next(&mut self, want: Option) -> crate::Result> { match (self, want) { - (Self::Hw(hw), Some(want)) => Ok(match hw.next_frame_dma(want)? { + (Self::Hw(hw, true), None) => Ok(match hw.next_frame_wide()? { + Some(crate::hw::HwFrame::Wide(bytes, width, height)) => Some(wide_yuv(bytes, width, height)), + Some(crate::hw::HwFrame::Narrow((y, u, v, width, height))) => Some(Yuv::pixels(y, u, v, width, height)), + None => None, + }), + (Self::Hw(hw, _), Some(want)) => Ok(match hw.next_frame_dma(want)? { Some(HwPicture::Dma(dma)) => Some(Yuv::Dma(dma)), + Some(HwPicture::Wide(bytes, width, height)) => Some(wide_yuv(bytes, width, height)), Some(HwPicture::Pixels(y, u, v, width, height)) => { Some(Yuv::pixels(y, u, v, width, height)) } None => None, }), - (Self::Hw(hw), None) => Ok(hw + (Self::Hw(hw, _), None) => Ok(hw .next_frame()? .map(|(y, u, v, width, height)| Yuv::pixels(y, u, v, width, height))), (Self::Av1(av1), _) => av1.next(), diff --git a/crates/engine/src/hw.rs b/crates/engine/src/hw.rs index d796e11..ff57a0f 100644 --- a/crates/engine/src/hw.rs +++ b/crates/engine/src/hw.rs @@ -16,16 +16,19 @@ //! Pictures still on the GPU cross as DRM-PRIME descriptors over `SCM_RIGHTS` //! and are never copied through the socket. +use std::collections::VecDeque; use std::ffi::OsString; use std::os::fd::OwnedFd; use std::path::Path; use std::process::Child; use std::sync::OnceLock; +use std::sync::mpsc::{self, Receiver, Sender, SyncSender, TryRecvError}; +use std::thread::JoinHandle; use crate::colorspace::ColorDescription; use crate::hwproc::{ - DMA_BODY, HW_LOST, K_DMA, K_PIXELS, Lost, Open, R_AU, R_ERR, R_NONE, Remote, Seat, SeatRate, Shm, - T_NEXT, T_NEXT_DMA, T_SEEK, recv_reply, send_msg, spawn_child, + DMA_BODY, HW_LOST, K_DMA, K_PIXELS, K_PIXELS16, Lost, Open, R_AU, R_ERR, R_NONE, Remote, Seat, SeatRate, Shm, + T_NEXT, T_NEXT_DMA, T_NEXT_DMA16, T_NEXT_WIDE, T_SEEK, pack16, recv_reply, send_msg, spawn_child, }; #[cfg(test)] @@ -246,6 +249,8 @@ pub struct HwSession { body: Vec, /// The last picture read out of `shm`, packed I420. pixels: Vec, + /// Whether `pixels` holds 16-bit LE samples (`K_PIXELS16`). + pixels_wide: bool, /// Set the moment the child is known gone, so every later call refuses in /// the same words instead of waiting on a socket nobody holds. lost: Option, @@ -295,6 +300,7 @@ impl HwSession { meta, body, pixels: Vec::new(), + pixels_wide: false, lost: None, fail_after: injected_failure(), delivered: 0, @@ -342,6 +348,21 @@ impl HwSession { } } + /// The next picture for a 10-bit consumer: a picture deeper than 8 bits comes + /// back whole ([`HwFrame::Wide`]), an 8-bit one as ordinary planes. + pub fn next_frame_wide(&mut self) -> crate::Result>> { + self.inject()?; + match self.fetch(T_NEXT_WIDE, &[])? { + None => Ok(None), + Some(Fetched::Pixels) if self.pixels_wide => { + let (w, h) = (self.meta.width, self.meta.height); + Ok(Some(HwFrame::Wide(&self.pixels[..2 * i420_bytes(w, h)], w, h))) + } + Some(Fetched::Pixels) => Ok(Some(HwFrame::Narrow(self.planes()))), + Some(Fetched::Dma(_)) => Err("the decoder handed over a GPU buffer nobody asked for".into()), + } + } + /// The next picture *without reading it back* where the caller's encoder can /// take the buffer the decoder wrote into -- which is what `want` describes. /// Anything the child cannot hand over that way comes back as pixels @@ -356,9 +377,13 @@ impl HwSession { for value in [want.coded_width, want.coded_height, want.width, want.height] { body.extend_from_slice(&value.to_le_bytes()); } - match self.fetch(T_NEXT_DMA, &body)? { + match self.fetch(if want.ten_bit { T_NEXT_DMA16 } else { T_NEXT_DMA }, &body)? { None => Ok(None), Some(Fetched::Dma(frame)) => Ok(Some(HwPicture::Dma(frame))), + Some(Fetched::Pixels) if self.pixels_wide => { + let (w, h) = (self.meta.width, self.meta.height); + Ok(Some(HwPicture::Wide(&self.pixels[..2 * i420_bytes(w, h)], w, h))) + } Some(Fetched::Pixels) => { let (y, u, v, width, height) = self.planes(); Ok(Some(HwPicture::Pixels(y, u, v, width, height))) @@ -375,11 +400,12 @@ impl HwSession { } let reply = self.body.clone(); match reply.first().copied() { - Some(K_PIXELS) if tag == R_AU => { + Some(kind @ (K_PIXELS | K_PIXELS16)) if tag == R_AU => { let bad = || -> crate::Error { "the decoder sent a short picture header".into() }; let width = le_u32(&reply, 1).ok_or_else(bad)?; let height = le_u32(&reply, 5).ok_or_else(bad)?; - let needed = i420_bytes(width, height); + self.pixels_wide = kind == K_PIXELS16; + let needed = i420_bytes(width, height) * if self.pixels_wide { 2 } else { 1 }; if let Some(fd) = fds.pop() { // The child made a bigger staging buffer for this frame. self.shm = Shm::from_fd(fd, needed); @@ -396,9 +422,9 @@ impl HwSession { } Some(K_DMA) if tag == R_AU => { let desc = dma_from_wire(&reply).ok_or("the decoder sent a short GPU buffer header")?; - let count = usize::from(reply[DMA_BODY - 1]); + let count = usize::from(*reply.get(DMA_BODY).ok_or("the decoder sent a short GPU buffer header")?); if fds.len() != count || !(1..=2).contains(&count) { - return Err("the decoder's GPU buffer came without its descriptors".into()); + return Err(format!("the decoder's GPU buffer came without its descriptors ({} of {count})", fds.len()).into()); } self.meta.width = desc.width; self.meta.height = desc.height; @@ -473,12 +499,21 @@ pub struct DmaWant { pub coded_height: u32, pub width: u32, pub height: u32, + pub ten_bit: bool, +} + +/// One picture out of [`HwSession::next_frame_wide`]: 8-bit planes, or packed +/// I420 of 16-bit LE samples with its width and height. +pub enum HwFrame<'a> { + Narrow(Planes<'a>), + Wide(&'a [u8], u32, u32), } /// One picture out of [`HwSession::next_frame_dma`]: still on the GPU, or read /// back like every other frame. pub enum HwPicture<'a> { Pixels(&'a [u8], &'a [u8], &'a [u8], u32, u32), + Wide(&'a [u8], u32, u32), Dma(DmaFrame), } @@ -487,7 +522,96 @@ pub enum HwPicture<'a> { /// /// The API is the one it always was, call for call, so nothing in the export /// loop knows which side of a process boundary the encoder is on. -pub struct HwEncoder(Remote); +pub struct HwEncoder { + remote: Option, + pipe: Option, + backlog: VecDeque>, + au: Vec, + spare: Vec>, + failed: Option, +} + +/// A finished job: its access unit, if any, copied out, and the job's buffer +/// back for reuse. +type Done = (crate::Result>>, Vec); + +enum Job { + Eight { + bytes: Vec, + y: usize, + u: usize, + width: u32, + height: u32, + key: bool, + }, + Ten { + bytes: Vec, + width: u32, + height: u32, + key: bool, + }, +} + +/// The worker thread that owns the [`Remote`] while jobs are in flight. +struct Pipe { + jobs: SyncSender, + done: Receiver, + worker: JoinHandle, + queued: usize, +} + +impl Pipe { + fn start(remote: Remote) -> crate::Result { + let (jobs, inbox) = mpsc::sync_channel(2); + let (outbox, done) = mpsc::channel(); + let worker = std::thread::Builder::new() + .name("hw-encode".to_owned()) + .spawn(move || serve(remote, inbox, outbox))?; + Ok(Self { + jobs, + done, + worker, + queued: 0, + }) + } +} + +fn serve(mut remote: Remote, inbox: Receiver, outbox: Sender) -> Remote { + for job in inbox { + let (result, bytes) = match job { + Job::Eight { + bytes, + y, + u, + width, + height, + key, + } => { + let (ys, rest) = bytes.split_at(y); + let (us, vs) = rest.split_at(u); + let result = remote + .encode(ys, us, vs, width, height, key) + .map(|au| au.map(<[u8]>::to_vec)); + (result, bytes) + } + Job::Ten { + bytes, + width, + height, + key, + } => { + let result = remote + .encode16_le(&bytes, width, height, key) + .map(|au| au.map(<[u8]>::to_vec)); + (result, bytes) + } + }; + if outbox.send((result, bytes)).is_err() { + break; + } + } + remote +} impl HwEncoder { /// H.264 at `width`x`height`, `fps_num / fps_den` frames per second, coded @@ -505,6 +629,7 @@ impl HwEncoder { rate, ColorDescription::default(), gop, + false, ) } @@ -523,6 +648,7 @@ impl HwEncoder { rate, ColorDescription::default(), None, + false, ) } @@ -539,12 +665,14 @@ impl HwEncoder { rate, ColorDescription::default(), gop, + false, ) } /// The same, coding HEVC. `colour` is what the SPS will say the samples /// mean, and it is taken at the open because the parameter sets are written /// when the sequence starts. + #[allow(clippy::too_many_arguments)] pub fn open_hevc( width: u32, height: u32, @@ -553,8 +681,9 @@ impl HwEncoder { rate: SeatRate, colour: ColorDescription, gop: Option, + ten_bit: bool, ) -> Option { - Self::seated(Seat::Hevc, width, height, fps_num, fps_den, rate, colour, gop) + Self::seated(Seat::Hevc, width, height, fps_num, fps_den, rate, colour, gop, ten_bit) } /// The HEVC seat, **intra-only**: every picture an IDR, as [`Self::open_intra`] @@ -566,8 +695,9 @@ impl HwEncoder { fps_den: u32, rate: SeatRate, colour: ColorDescription, + ten_bit: bool, ) -> Option { - Self::seated(Seat::HevcIntra, width, height, fps_num, fps_den, rate, colour, None) + Self::seated(Seat::HevcIntra, width, height, fps_num, fps_den, rate, colour, None, ten_bit) } #[allow(clippy::too_many_arguments)] @@ -580,6 +710,7 @@ impl HwEncoder { rate: SeatRate, colour: ColorDescription, gop: Option, + ten_bit: bool, ) -> Option { let open = Open { seat, @@ -590,10 +721,18 @@ impl HwEncoder { rate, colour, gop, + ten_bit, }; // No child binary beside the executable means no hardware seat at all: // `Remote::spawn` answers `None` before a process is forked. - Remote::spawn(open).map(Self) + Remote::spawn(open).map(|remote| Self { + remote: Some(remote), + pipe: None, + backlog: VecDeque::new(), + au: Vec::new(), + spare: Vec::new(), + failed: None, + }) } /// Feeds one tightly packed I420 picture. `Ok(None)` means the encoder has @@ -616,30 +755,178 @@ impl HwEncoder { if y.len() < w * h || u.len() < cw * ch || v.len() < cw * ch { return Err("encode input is not a packed I420 frame".into()); } - self.0.encode(y, u, v, width, height, force_key) + let mut bytes = self.spare.pop().unwrap_or_default(); + bytes.clear(); + bytes.extend_from_slice(y); + bytes.extend_from_slice(u); + bytes.extend_from_slice(v); + self.submit(Job::Eight { + bytes, + y: y.len(), + u: u.len(), + width, + height, + key: force_key, + })?; + self.collect_ready()?; + Ok(self.pop()) + } + + /// Feeds one tightly packed 10-bit I420 picture (samples in the low 10 bits). + pub fn encode16( + &mut self, + y: &[u16], + u: &[u16], + v: &[u16], + width: u32, + height: u32, + force_key: bool, + ) -> crate::Result> { + let (w, h) = (width as usize, height as usize); + let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); + if y.len() < w * h || u.len() < cw * ch || v.len() < cw * ch { + return Err("encode input is not a packed I420 frame".into()); + } + let mut bytes = self.spare.pop().unwrap_or_default(); + pack16(&y[..w * h], &u[..cw * ch], &v[..cw * ch], &mut bytes); + self.submit(Job::Ten { + bytes, + width, + height, + key: force_key, + })?; + self.collect_ready()?; + Ok(self.pop()) } /// What a decoded buffer must look like to reach this encoder without a /// copy, or `None` where the child has no zero-copy door at all. pub fn dma_want(&mut self, width: u32, height: u32) -> Option { - let (coded_width, coded_height) = self.0.dma_geometry()?; + let remote = match self.settled() { + Ok(remote) => remote, + Err(e) => { + self.failed = Some(e); + return None; + } + }; + let (coded_width, coded_height) = remote.dma_geometry()?; Some(DmaWant { coded_width, coded_height, width, height, + ten_bit: false, }) } /// Feeds one picture the decoder left on the GPU. The descriptors go over /// with the message, so the buffer itself never moves. pub fn encode_dma(&mut self, dma: &DmaFrame, force_key: bool) -> crate::Result> { - self.0.encode_dma(dma, force_key) + let au = self.settled()?.encode_dma(dma, force_key)?.map(<[u8]>::to_vec); + if let Some(au) = au { + self.backlog.push_back(au); + } + Ok(self.pop()) } /// Flushes the encoder; call until it returns `Ok(None)`. pub fn drain(&mut self) -> crate::Result> { - self.0.drain() + self.settle()?; + if !self.backlog.is_empty() { + return Ok(self.pop()); + } + let remote = self.remote.as_mut().ok_or("the hardware encoder was lost")?; + let Some(au) = remote.drain()? else { + return Ok(None); + }; + self.au.clear(); + self.au.extend_from_slice(au); + Ok(Some(&self.au)) + } + + fn submit(&mut self, job: Job) -> crate::Result<()> { + if let Some(e) = self.failed.take() { + return Err(e); + } + if self.pipe.is_none() { + let remote = self.remote.take().ok_or("the hardware encoder was lost")?; + self.pipe = Some(Pipe::start(remote)?); + } + let pipe = self.pipe.as_mut().ok_or("the hw encode pipe is missing")?; + pipe.jobs.send(job).map_err(|_| "the hw encode worker panicked")?; + pipe.queued += 1; + Ok(()) + } + + fn collect_ready(&mut self) -> crate::Result<()> { + loop { + let Some(pipe) = self.pipe.as_mut() else { + return Ok(()); + }; + let finished = match pipe.done.try_recv() { + Ok(finished) => finished, + Err(TryRecvError::Empty) => return Ok(()), + Err(TryRecvError::Disconnected) => return Err("the hw encode worker panicked".into()), + }; + pipe.queued -= 1; + self.finish(finished)?; + } + } + + fn finish(&mut self, (result, bytes): Done) -> crate::Result<()> { + if self.spare.len() < 3 { + self.spare.push(bytes); + } + if let Some(au) = result? { + self.backlog.push_back(au); + } + Ok(()) + } + + /// Waits for every queued job, keeps their access units in order, and takes + /// the [`Remote`] back from the worker. The first error is returned. + fn settle(&mut self) -> crate::Result<()> { + if let Some(e) = self.failed.take() { + return Err(e); + } + let Some(pipe) = self.pipe.take() else { + return Ok(()); + }; + let Pipe { + jobs, + done, + worker, + mut queued, + } = pipe; + drop(jobs); + let mut first: Option = None; + while queued > 0 { + let Ok(finished) = done.recv() else { + break; + }; + queued -= 1; + if let Err(e) = self.finish(finished) { + first = first.or(Some(e)); + } + } + match worker.join() { + Ok(remote) => self.remote = Some(remote), + Err(_) => first = first.or(Some("the hw encode worker panicked".into())), + } + match first { + Some(e) => Err(e), + None => Ok(()), + } + } + + fn settled(&mut self) -> crate::Result<&mut Remote> { + self.settle()?; + self.remote.as_mut().ok_or_else(|| "the hardware encoder was lost".into()) + } + + fn pop(&mut self) -> Option<&[u8]> { + self.au = self.backlog.pop_front()?; + Some(&self.au) } } diff --git a/crates/engine/src/hwproc.rs b/crates/engine/src/hwproc.rs index 37041d3..a393adc 100644 --- a/crates/engine/src/hwproc.rs +++ b/crates/engine/src/hwproc.rs @@ -137,6 +137,8 @@ pub struct Open { pub colour: ColorDescription, /// Pictures between key frames; `None` is the seat's own two seconds. pub gop: Option, + /// Code at 10 bits (HEVC Main10): pictures arrive as 16-bit LE samples. + pub ten_bit: bool, } impl Open { @@ -170,6 +172,7 @@ impl Open { SeatRate::ConstantQp(qp) => [1, u64::from(qp)], }.map(|v| v.to_string())) .chain(std::iter::once(self.gop.unwrap_or(0).to_string())) + .chain(std::iter::once(u8::from(self.ten_bit).to_string())) .collect() } @@ -207,6 +210,7 @@ impl Open { 0 => None, gop => Some(gop), }, + ten_bit: n(11)? != 0, }) } @@ -215,7 +219,8 @@ impl Open { /// canvas size for the whole file. pub fn frame_bytes(&self) -> usize { let (w, h) = (self.width as usize, self.height as usize); - w * h + 2 * (w.div_ceil(2) * h.div_ceil(2)) + let samples = w * h + 2 * (w.div_ceil(2) * h.div_ceil(2)); + if self.ten_bit { samples * 2 } else { samples } } } @@ -224,12 +229,16 @@ pub const T_ENCODE: u8 = 1; pub const T_DMA: u8 = 2; pub const T_DRAIN: u8 = 3; pub const T_GEOM: u8 = 4; +pub const T_ENCODE16: u8 = 8; // Requests, parent to child (decode seat). `T_NEXT` has no body, `T_NEXT_DMA` // carries `coded_width, coded_height, width, height` as u32 LE, `T_SEEK` the // 1-based target sample as u32 LE. pub const T_NEXT: u8 = 5; pub const T_NEXT_DMA: u8 = 6; pub const T_SEEK: u8 = 7; +/// `T_NEXT`, but a picture deeper than 8 bits comes back as `K_PIXELS16`. +pub const T_NEXT_WIDE: u8 = 9; +pub const T_NEXT_DMA16: u8 = 10; // Replies, child to parent. `R_NONE` carries no body; `R_AU` and `R_ERR` carry // a u32 LE length and that many bytes. Descriptors ride on the tag byte. pub const R_NONE: u8 = 0; @@ -241,6 +250,8 @@ pub const R_ERR: u8 = 2; // descriptors ride on the tag byte, one per plane object). pub const K_PIXELS: u8 = 0; pub const K_DMA: u8 = 1; +/// As `K_PIXELS`, with 16-bit LE samples at 10-bit scale. +pub const K_PIXELS16: u8 = 2; /// The `K_DMA` descriptor after its kind byte: fourcc u32, modifier u64, coded /// width and height, picture width and height, two offsets and two strides as /// u32 each, then the number of descriptors (1 or 2) as one byte. @@ -302,11 +313,22 @@ impl Shm { "a read past the end of the staging buffer", )); } - into.clear(); into.resize(len, 0); self.file.read_exact_at(into, 0) } + pub fn read_u16(&self, offset: usize, count: usize) -> std::io::Result> { + if offset + 2 * count > self.len { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidInput, + "a read past the end of the staging buffer", + )); + } + let mut out = vec![0u16; count]; + self.file.read_exact_at(bytemuck::cast_slice_mut(&mut out), offset as u64)?; + Ok(out) + } + /// Reads the first `len` bytes of the buffer into an owned one. pub fn read_bytes(&self, len: usize) -> std::io::Result> { if len > self.len { @@ -331,14 +353,18 @@ pub fn send_msg(sock: &UnixStream, bytes: &[u8], fds: &[RawFd]) -> std::io::Resu debug_assert!(!bytes.is_empty(), "ancillary data rides on a real byte"); let rights = [ControlMessage::ScmRights(fds)]; let control: &[ControlMessage] = if fds.is_empty() { &[] } else { &rights }; - let sent = sendmsg::( - sock.as_raw_fd(), - &[IoSlice::new(bytes)], - control, - MsgFlags::MSG_NOSIGNAL, - None, - ) - .map_err(std::io::Error::from)?; + let sent = loop { + match sendmsg::( + sock.as_raw_fd(), + &[IoSlice::new(bytes)], + control, + MsgFlags::MSG_NOSIGNAL, + None, + ) { + Err(nix::errno::Errno::EINTR) => continue, + other => break other.map_err(std::io::Error::from)?, + } + }; // Messages here are tens of bytes and a socket buffer is kilobytes, so a // short send means the peer is gone rather than that we should loop. if sent != bytes.len() { @@ -360,8 +386,12 @@ pub fn recv_tag(sock: &UnixStream) -> std::io::Result<(u8, Vec)> { // Room for four descriptors; the most anything here sends is two. let mut space = [MaybeUninit::uninit(); rustix::cmsg_space!(ScmRights(4))]; let mut control = RecvAncillaryBuffer::new(&mut space); - let received = rustix::net::recvmsg(sock, &mut iov, &mut control, RecvFlags::CMSG_CLOEXEC) - .map_err(std::io::Error::from)?; + let received = loop { + match rustix::net::recvmsg(sock, &mut iov, &mut control, RecvFlags::CMSG_CLOEXEC) { + Err(rustix::io::Errno::INTR) => continue, + other => break other.map_err(std::io::Error::from)?, + } + }; if received.bytes == 0 { return Err(std::io::Error::new( std::io::ErrorKind::UnexpectedEof, @@ -523,6 +553,24 @@ pub fn faked() -> bool { crate::envcfg::var_os("VE_HW_TEST_FAKE").is_some() } +/// Packs Y, U and V samples as 16-bit LE, back to back, into `out`. +const _: () = assert!(cfg!(target_endian = "little")); + +pub fn pack16(y: &[u16], u: &[u16], v: &[u16], out: &mut Vec) { + out.clear(); + out.reserve(2 * (y.len() + u.len() + v.len())); + for plane in [y, u, v] { + out.extend_from_slice(bytemuck::cast_slice(plane)); + } +} + +pub fn unpack16(bytes: &[u8]) -> Vec { + let n = bytes.len() / 2; + let mut out = vec![0u16; n]; + bytemuck::cast_slice_mut(&mut out).copy_from_slice(&bytes[..2 * n]); + out +} + /// A hardware encode session living in another process. pub struct Remote { child: Child, @@ -672,6 +720,49 @@ impl Remote { self.round_trip(&msg, &[]) } + /// Feeds one 10-bit picture (samples in the low 10 bits) through the shared mapping. + pub fn encode16( + &mut self, + y: &[u16], + u: &[u16], + v: &[u16], + width: u32, + height: u32, + force_key: bool, + ) -> crate::Result> { + let mut bytes = Vec::new(); + pack16(y, u, v, &mut bytes); + self.encode16_le(&bytes, width, height, force_key) + } + + /// Feeds one picture already packed as 16-bit LE samples, Y then U then V. + pub fn encode16_le( + &mut self, + bytes: &[u8], + width: u32, + height: u32, + force_key: bool, + ) -> crate::Result> { + let Some(shm) = self.shm.as_ref() else { + return Err("the staging buffer was never opened".to_owned().into()); + }; + if bytes.len() > shm.capacity() { + return Err(format!( + "a {width}x{height} picture does not fit the staging buffer opened for {}x{}", + self.open.width, self.open.height + ) + .into()); + } + if let Err(e) = shm.write_picture(&[bytes]) { + return Err(format!("cannot stage the picture: {e}").into()); + } + let mut msg = vec![T_ENCODE16]; + msg.extend_from_slice(&width.to_le_bytes()); + msg.extend_from_slice(&height.to_le_bytes()); + msg.push(u8::from(force_key)); + self.round_trip(&msg, &[]) + } + /// Feeds one picture the decoder left on the GPU. The descriptors go over /// with the message, so the buffer itself never moves. pub fn encode_dma(&mut self, frame: &DmaFrame, force_key: bool) -> crate::Result> { @@ -818,6 +909,7 @@ mod tests { full_range: true, }, gop: Some(15), + ten_bit: false, }; let back = Open::from_argv(&open.argv()).expect("parse"); assert!(back.seat == Seat::Hevc); diff --git a/crates/engine/tests/hw_encode.rs b/crates/engine/tests/hw_encode.rs index 4261d8d..ec9c516 100644 --- a/crates/engine/tests/hw_encode.rs +++ b/crates/engine/tests/hw_encode.rs @@ -269,7 +269,7 @@ fn a_decoded_buffer_is_encoded_without_ever_being_read_back() { stream.extend_from_slice(au); } } - Some(HwPicture::Pixels(..)) => panic!("frame {index} was read back after all"), + Some(HwPicture::Pixels(..) | HwPicture::Wide(..)) => panic!("frame {index} was read back after all"), None => panic!("the fixture ran out at frame {index}"), } } diff --git a/crates/engine/tests/it/export_ten_bit.rs b/crates/engine/tests/it/export_ten_bit.rs index 3f1fd0e..72a68d7 100644 --- a/crates/engine/tests/it/export_ten_bit.rs +++ b/crates/engine/tests/it/export_ten_bit.rs @@ -473,3 +473,49 @@ fn a_bt2020_sdr_ten_bit_source_exports_with_its_own_colour() { } let _ = std::fs::remove_dir_all(&dir); } + +#[test] +fn a_ten_bit_hevc_export_takes_the_hardware_seat_at_a_constant_qp() { + let (Some(encoder), true, true) = (source_encoder(), have("ffmpeg"), have("ffprobe")) else { + eprintln!("no ffmpeg with a source encoder: skipping"); + return; + }; + let dir = scratch("ten-bit-hevc-hw"); + let source = dir.join("source10.mkv"); + let made = Command::new("ffmpeg") + .args(["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=size=640x480:rate=25:duration=1"]) + .args(["-pix_fmt", "yuv420p10le"]) + .args(codec_args(encoder)) + .arg(&source) + .status() + .is_ok_and(|s| s.success()); + assert!(made, "ffmpeg makes the 10-bit source"); + let session = PlaybackSession::open(&source).expect("open the source"); + let out = dir.join("ten.mp4"); + let settings = ExportSettings { + format: Format::HevcMp4, + video_bit_depth: Some(10), + seat: engine::export::EncoderSeat::Hardware, + qp: Some(12), + ..Default::default() + }; + let handle = session.export_to_with(&out, &settings); + let started = Instant::now(); + while !handle.is_finished() { + assert!(started.elapsed() < Duration::from_secs(600), "the export did not finish in 600 s"); + std::thread::sleep(Duration::from_millis(20)); + } + match handle.result().expect("an outcome") { + Err(e) if e.to_string().contains("no VA-API seat") => { + eprintln!("no 10-bit HEVC hardware seat here: {e}"); + return; + } + other => other.expect("the export"), + }; + assert_eq!(pix_fmt(&out), "yuv420p10le"); + assert_eq!(profile(&out), "Main 10"); + let psnr = psnr_10(&decoded(&source, "yuv420p10le"), &decoded(&out, "yuv420p10le")); + eprintln!("hardware HEVC Main 10 at qp 12: {psnr:.2} dB"); + assert!(psnr > 40.0, "{psnr:.2} dB against the source"); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/engine/tests/it/hw_fallback.rs b/crates/engine/tests/it/hw_fallback.rs index 7a653f0..31739d7 100644 --- a/crates/engine/tests/it/hw_fallback.rs +++ b/crates/engine/tests/it/hw_fallback.rs @@ -30,6 +30,7 @@ fn span(path: &PathBuf, start: u32, end: u32) -> Vec<(u32, Vec)> { #[test] fn a_hardware_error_mid_span_continues_in_software_with_the_same_frames() { + let _seat = crate::seat::hardware(); hwchild::require(); for (name, start, end, fail_after) in [ ("test_25fps.mp4", 0, 50, 17), diff --git a/crates/engine/tests/it/hw_midgop_seek.rs b/crates/engine/tests/it/hw_midgop_seek.rs index c2ca9cf..7821e43 100644 --- a/crates/engine/tests/it/hw_midgop_seek.rs +++ b/crates/engine/tests/it/hw_midgop_seek.rs @@ -53,6 +53,7 @@ fn take(hw: &mut HwSession, count: usize) -> Vec { /// Asserts that a fresh open at each target, and a seek on a live session to /// each target, hands back the sequential decode's pictures exactly. fn check_midgop(name: &str, targets: &[usize]) { + let _seat = crate::seat::hardware(); // `require()` has already panicked if a render node exists without // `hw-child`, so a session that does not open here means no usable VA-API // driver or profile: a skip, as on a machine with no GPU.