forge
Explore
Log in

Don't you dare go Hollow

⚡ 10-bit HEVC hardware export 4x faster, output bit-identical: pipelined encode/decode-ahead, zero-copy P010 dmabuf for caption-free spans

Browse files at this commit

902be049b8c157e5c90097d99eb6849d2c18a1afAhmet Kaan GümüşParent: e1985fa
- hw encoder on its own thread; direct u16 shm copies (bytemuck)
- hw-child decode-ahead for wide frames; T_NEXT_DMA16 exports P010 to the encoder child
- spans split at caption/title boundaries; quiet spans stay on the GPU
- DMA header count read at the right offset (every hw decode had fallen to software)
- hw_fallback and hw_midgop_seek take the hardware seat: the failure hook no longer leaks across parallel tests
Cargo.lockmodified+2 -0
@@ -1933,6 +1933,7 @@ version = "0.1.0"
1933 dependencies = [1933 dependencies = [
1934 "ab_glyph",1934 "ab_glyph",
1935 "ab_glyph_rasterizer",1935 "ab_glyph_rasterizer",
1936+ "bytemuck",
1936 "ec-aac",1937 "ec-aac",
1937 "ec-ac3",1938 "ec-ac3",
1938 "ec-ass",1939 "ec-ass",
@@ -1986,6 +1987,7 @@ dependencies = [
1986 name = "engine-hw"1987 name = "engine-hw"
1987 version = "0.1.0"1988 version = "0.1.0"
1988 dependencies = [1989 dependencies = [
1990+ "bytemuck",
1989 "ec-hw",1991 "ec-hw",
1990 "ec-va",1992 "ec-va",
1991 "ec-vp8",1993 "ec-vp8",
crates/engine-hw/Cargo.tomlmodified+1 -0
@@ -16,6 +16,7 @@ name = "hw-child"
16 path = "src/bin/hw-child.rs"16 path = "src/bin/hw-child.rs"
17 17
18 [dependencies]18 [dependencies]
19+bytemuck = "1.25"
19 engine = { path = "../engine" }20 engine = { path = "../engine" }
20 # The decode seat: ec-hw drives the VA-API decoders, ec-va the display under it.21 # The decode seat: ec-hw drives the VA-API decoders, ec-va the display under it.
21 ec-hw = { path = "../../../edith_codecs/crates/ec-hw" }22 ec-hw = { path = "../../../edith_codecs/crates/ec-hw" }
crates/engine-hw/src/child.rsmodified+83 -13
@@ -54,12 +54,12 @@ use std::path::PathBuf;
54 54
55 use engine::hw::{DmaFrame, VhDma, meta_to_wire};55 use engine::hw::{DmaFrame, VhDma, meta_to_wire};
56 use engine::hwproc::{56 use engine::hwproc::{
57- DMA_BODY, K_DMA, K_PIXELS, Open, R_AU, R_ERR, R_NONE, Shm, T_DMA, T_DRAIN, T_ENCODE, T_GEOM,57+ 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,
58- T_NEXT, T_NEXT_DMA, T_SEEK, die_with_parent, recv_tag, send_msg, send_reply,58+ T_NEXT, T_NEXT_DMA, T_NEXT_DMA16, T_NEXT_WIDE, T_SEEK, die_with_parent, recv_tag, send_msg, send_reply,
59 };59 };
60 60
61 use crate::enc_ec::EcEncSession;61 use crate::enc_ec::EcEncSession;
62-use crate::{OpenSession, VA_FOURCC_NV12, query_caps};62+use crate::{OpenSession, VA_FOURCC_NV12, VA_FOURCC_P010, query_caps};
63 63
64 /// The entry point of the `hw-child` binary.64 /// The entry point of the `hw-child` binary.
65 pub fn main() {65 pub fn main() {
@@ -143,15 +143,40 @@ fn decode(sock: &mut UnixStream, args: &[OsString]) {
143 }143 }
144 drop(fd);144 drop(fd);
145 let mut staging = Staging { shm, capacity };145 let mut staging = Staging { shm, capacity };
146+ let mut ahead: Option<Result<bool, String>> = None;
147+ let mut wide_run = 0u32;
146 loop {148 loop {
147 let Ok((tag, _)) = recv_tag(sock) else {149 let Ok((tag, _)) = recv_tag(sock) else {
148 // The parent closed the socket: nothing left to decode for.150 // The parent closed the socket: nothing left to decode for.
149 return;151 return;
150 };152 };
153+ if tag != T_NEXT_WIDE {
154+ wide_run = 0;
155+ }
156+ if ahead.is_some() && tag != T_NEXT_WIDE {
157+ ahead = None;
158+ if tag != T_SEEK {
159+ if send_reply(sock, R_ERR, b"a wide picture was decoded ahead; only T_NEXT_WIDE or T_SEEK may follow", &[]).is_err() {
160+ return;
161+ }
162+ continue;
163+ }
164+ }
151 let answered = match tag {165 let answered = match tag {
152- T_NEXT | T_NEXT_DMA => {166+ T_NEXT_WIDE => {
167+ session.set_wide(true);
168+ let pumped = ahead.take().unwrap_or_else(|| session.next_frame(None));
169+ let answered = answer(sock, &mut session, &mut staging, pumped);
170+ wide_run += 1;
171+ if answered.is_ok() && wide_run >= 2 {
172+ ahead = Some(session.next_frame(None));
173+ }
174+ session.set_wide(false);
175+ answered
176+ }
177+ T_NEXT | T_NEXT_DMA | T_NEXT_DMA16 => {
153 let want = match tag {178 let want = match tag {
154- T_NEXT_DMA => {179+ T_NEXT_DMA | T_NEXT_DMA16 => {
155 let mut body = [0u8; 16];180 let mut body = [0u8; 16];
156 if sock.read_exact(&mut body).is_err() {181 if sock.read_exact(&mut body).is_err() {
157 return;182 return;
@@ -160,7 +185,7 @@ fn decode(sock: &mut UnixStream, args: &[OsString]) {
160 u32::from_le_bytes(body[4 * i..4 * i + 4].try_into().expect("four bytes"))185 u32::from_le_bytes(body[4 * i..4 * i + 4].try_into().expect("four bytes"))
161 };186 };
162 Some(VhDma {187 Some(VhDma {
163- fourcc: VA_FOURCC_NV12,188+ fourcc: if tag == T_NEXT_DMA16 { VA_FOURCC_P010 } else { VA_FOURCC_NV12 },
164 coded_width: word(0),189 coded_width: word(0),
165 coded_height: word(1),190 coded_height: word(1),
166 width: word(2),191 width: word(2),
@@ -170,7 +195,11 @@ fn decode(sock: &mut UnixStream, args: &[OsString]) {
170 }195 }
171 _ => None,196 _ => None,
172 };197 };
173- frame(sock, &mut session, &mut staging, want)198+ let wide = tag == T_NEXT_DMA16;
199+ session.set_wide(wide);
200+ let answered = frame(sock, &mut session, &mut staging, want);
201+ session.set_wide(false);
202+ answered
174 }203 }
175 T_SEEK => {204 T_SEEK => {
176 let mut body = [0u8; 4];205 let mut body = [0u8; 4];
@@ -198,7 +227,17 @@ fn frame(
198 staging: &mut Staging,227 staging: &mut Staging,
199 want: Option<VhDma>,228 want: Option<VhDma>,
200 ) -> std::io::Result<()> {229 ) -> std::io::Result<()> {
201- match session.next_frame(want) {230+ let pumped = session.next_frame(want);
231+ answer(sock, session, staging, pumped)
232+}
233+
234+fn answer(
235+ sock: &mut UnixStream,
236+ session: &mut OpenSession,
237+ staging: &mut Staging,
238+ pumped: Result<bool, String>,
239+) -> std::io::Result<()> {
240+ match pumped {
202 Ok(false) => send_reply(sock, R_NONE, &[], &[]),241 Ok(false) => send_reply(sock, R_NONE, &[], &[]),
203 Err(e) => send_reply(sock, R_ERR, e.as_bytes(), &[]),242 Err(e) => send_reply(sock, R_ERR, e.as_bytes(), &[]),
204 Ok(true) => match session.take_dma() {243 Ok(true) => match session.take_dma() {
@@ -239,8 +278,8 @@ fn send_pixels(
239 session: &OpenSession,278 session: &OpenSession,
240 staging: &mut Staging,279 staging: &mut Staging,
241 ) -> std::io::Result<()> {280 ) -> std::io::Result<()> {
242- let (picture, w, h) = session.picture();281+ let (picture, w, h, wide) = session.picture();
243- let needed = picture.len();282+ let needed: usize = picture.iter().map(|p| p.len()).sum();
244 let grown = if needed > staging.capacity {283 let grown = if needed > staging.capacity {
245 let (shm, fd) = Shm::create(needed)?;284 let (shm, fd) = Shm::create(needed)?;
246 staging.shm = shm;285 staging.shm = shm;
@@ -249,9 +288,9 @@ fn send_pixels(
249 } else {288 } else {
250 None289 None
251 };290 };
252- staging.shm.write_picture(&[picture])?;291+ staging.shm.write_picture(&picture)?;
253 let mut body = Vec::with_capacity(9);292 let mut body = Vec::with_capacity(9);
254- body.push(K_PIXELS);293+ body.push(if wide { K_PIXELS16 } else { K_PIXELS });
255 body.extend_from_slice(&w.to_le_bytes());294 body.extend_from_slice(&w.to_le_bytes());
256 body.extend_from_slice(&h.to_le_bytes());295 body.extend_from_slice(&h.to_le_bytes());
257 let attach: Vec<RawFd> = grown.iter().map(AsRawFd::as_raw_fd).collect();296 let attach: Vec<RawFd> = grown.iter().map(AsRawFd::as_raw_fd).collect();
@@ -348,6 +387,37 @@ fn encode(sock: &mut UnixStream, args: &[OsString]) {
348 return;387 return;
349 }388 }
350 }389 }
390+ T_ENCODE16 => {
391+ let mut head = [0u8; 9];
392+ if sock.read_exact(&mut head).is_err() {
393+ return;
394+ }
395+ reached(&At::Frame(coded));
396+ coded += 1;
397+ let width = u32::from_le_bytes(head[0..4].try_into().expect("four bytes"));
398+ let height = u32::from_le_bytes(head[4..8].try_into().expect("four bytes"));
399+ let force_key = head[8] != 0;
400+ let (w, h) = (width as usize, height as usize);
401+ let chroma = w.div_ceil(2) * h.div_ceil(2);
402+ let answer = match &mut seat {
403+ Seat::Real(encoder) => match (
404+ shm.read_u16(0, w * h),
405+ shm.read_u16(2 * w * h, chroma),
406+ shm.read_u16(2 * (w * h + chroma), chroma),
407+ ) {
408+ (Ok(y), Ok(u), Ok(v)) => {
409+ encoder
410+ .encode16_owned(y, u, v, force_key)
411+ .map(|()| encoder.next_au())
412+ }
413+ (Err(e), _, _) | (_, Err(e), _) | (_, _, Err(e)) => Err(format!("cannot read the staging buffer: {e}")),
414+ },
415+ Seat::Fake => Ok(None),
416+ };
417+ if !reply(sock, answer) {
418+ return;
419+ }
420+ }
351 T_DMA => {421 T_DMA => {
352 let mut head = [0u8; 46];422 let mut head = [0u8; 46];
353 if sock.read_exact(&mut head).is_err() {423 if sock.read_exact(&mut head).is_err() {
@@ -391,7 +461,7 @@ fn encode(sock: &mut UnixStream, args: &[OsString]) {
391 T_DRAIN => {461 T_DRAIN => {
392 reached(&At::Drain);462 reached(&At::Drain);
393 let answer = match &mut seat {463 let answer = match &mut seat {
394- Seat::Real(encoder) => Ok(encoder.next_au()),464+ Seat::Real(encoder) => encoder.flush().map(|()| encoder.next_au()),
395 Seat::Fake => Ok(None),465 Seat::Fake => Ok(None),
396 };466 };
397 if !reply(sock, answer) {467 if !reply(sock, answer) {
crates/engine-hw/src/enc_ec.rsmodified+73 -16
@@ -12,7 +12,7 @@ use std::os::fd::{AsFd, OwnedFd};
12 use std::rc::Rc;12 use std::rc::Rc;
13 13
14 use ec_hw::enc::{EncCodec, EncoderConfig, FrameMetadata, RateControlMode};14 use ec_hw::enc::{EncCodec, EncoderConfig, FrameMetadata, RateControlMode};
15-use ec_hw::{Encoder, H264Profile, I420};15+use ec_hw::{Encoder, H264Profile, I420, I420_16};
16 use ec_va::{PrimeLayer, PrimeObject, PrimeSurface};16 use ec_va::{PrimeLayer, PrimeObject, PrimeSurface};
17 17
18 use engine::hw::{DmaFrame, VhDma};18 use engine::hw::{DmaFrame, VhDma};
@@ -20,6 +20,8 @@ use engine::hwproc::SeatRate;
20 20
21 /// `DRM_FORMAT_NV12`, which is also `VA_FOURCC_NV12`: the four characters.21 /// `DRM_FORMAT_NV12`, which is also `VA_FOURCC_NV12`: the four characters.
22 const FOURCC_NV12: u32 = u32::from_le_bytes(*b"NV12");22 const FOURCC_NV12: u32 = u32::from_le_bytes(*b"NV12");
23+/// `DRM_FORMAT_P010`, which is also `VA_FOURCC_P010`.
24+const FOURCC_P010: u32 = u32::from_le_bytes(*b"P010");
23 25
24 /// One hardware encode session on `ec_hw`.26 /// One hardware encode session on `ec_hw`.
25 pub(crate) struct EcEncSession {27 pub(crate) struct EcEncSession {
@@ -36,6 +38,7 @@ pub(crate) struct EcEncSession {
36 ready: VecDeque<Vec<u8>>,38 ready: VecDeque<Vec<u8>>,
37 /// The access unit currently handed out, kept alive until the next call.39 /// The access unit currently handed out, kept alive until the next call.
38 out: Vec<u8>,40 out: Vec<u8>,
41+ ten_bit: bool,
39 }42 }
40 43
41 /// The `open` arguments, for any of the three codecs.44 /// The `open` arguments, for any of the three codecs.
@@ -52,6 +55,8 @@ pub(crate) struct EcOpen {
52 pub gop: Option<u32>,55 pub gop: Option<u32>,
53 /// Colour description for the VUI as `(primaries, transfer, matrix, full)`.56 /// Colour description for the VUI as `(primaries, transfer, matrix, full)`.
54 pub colour: Option<(u8, u8, u8, bool)>,57 pub colour: Option<(u8, u8, u8, bool)>,
58+ /// HEVC Main10: pictures go through [`EcEncSession::encode16`].
59+ pub ten_bit: bool,
55 }60 }
56 61
57 impl EcEncSession {62 impl EcEncSession {
@@ -66,6 +71,7 @@ impl EcEncSession {
66 intra_only,71 intra_only,
67 gop,72 gop,
68 colour,73 colour,
74+ ten_bit,
69 } = req;75 } = req;
70 // NV12 chroma is half resolution, so odd dimensions have no packing;76 // NV12 chroma is half resolution, so odd dimensions have no packing;
71 // radeonsi refuses encode contexts below 64x64 (measured).77 // radeonsi refuses encode contexts below 64x64 (measured).
@@ -105,6 +111,9 @@ impl EcEncSession {
105 if let Some((p, t, m, full)) = colour {111 if let Some((p, t, m, full)) = colour {
106 config = config.colour(p, t, m, full);112 config = config.colour(p, t, m, full);
107 }113 }
114+ if ten_bit {
115+ config = config.ten_bit();
116+ }
108 let display = ec_va::open().ok()?;117 let display = ec_va::open().ok()?;
109 let encoder = Encoder::new(&display, config).ok()?;118 let encoder = Encoder::new(&display, config).ok()?;
110 let coded = encoder.coded_size();119 let coded = encoder.coded_size();
@@ -117,9 +126,47 @@ impl EcEncSession {
117 timestamp: 0,126 timestamp: 0,
118 ready: VecDeque::new(),127 ready: VecDeque::new(),
119 out: Vec::new(),128 out: Vec::new(),
129+ ten_bit,
120 })130 })
121 }131 }
122 132
133+ pub(crate) fn encode16_owned(
134+ &mut self,
135+ mut y: Vec<u16>,
136+ mut u: Vec<u16>,
137+ mut v: Vec<u16>,
138+ force_keyframe: bool,
139+ ) -> Result<(), String> {
140+ let (w, h) = (self.width, self.height);
141+ let (cw, ch) = (w / 2, h / 2);
142+ if y.len() < w * h || u.len() < cw * ch || v.len() < cw * ch {
143+ return Err("encode input is not a packed I420 frame".into());
144+ }
145+ y.truncate(w * h);
146+ u.truncate(cw * ch);
147+ v.truncate(cw * ch);
148+ let picture = I420_16 {
149+ y,
150+ u,
151+ v,
152+ width: w as u32,
153+ height: h as u32,
154+ bit_depth: 10,
155+ };
156+ let meta = self.meta(force_keyframe);
157+ if let Some(coded) = self.encoder.submit_16(&picture, meta).map_err(|e| e.to_string())? {
158+ self.ready.push_back(coded.data);
159+ }
160+ Ok(())
161+ }
162+
163+ pub(crate) fn flush(&mut self) -> Result<(), String> {
164+ for coded in self.encoder.flush().map_err(|e| e.to_string())? {
165+ self.ready.push_back(coded.data);
166+ }
167+ Ok(())
168+ }
169+
123 /// The surface size the driver codes at, as the caller must describe it.170 /// The surface size the driver codes at, as the caller must describe it.
124 pub(crate) fn coded_size(&self) -> (u32, u32) {171 pub(crate) fn coded_size(&self) -> (u32, u32) {
125 self.coded172 self.coded
@@ -147,11 +194,9 @@ impl EcEncSession {
147 height: h as u32,194 height: h as u32,
148 };195 };
149 let meta = self.meta(force_keyframe);196 let meta = self.meta(force_keyframe);
150- let coded = self197+ if let Some(coded) = self.encoder.submit(&picture, meta).map_err(|e| e.to_string())? {
151- .encoder198+ self.ready.push_back(coded.data);
152- .encode(&picture, meta)199+ }
153- .map_err(|e| e.to_string())?;
154- self.ready.push_back(coded.data);
155 Ok(())200 Ok(())
156 }201 }
157 202
@@ -163,12 +208,24 @@ impl EcEncSession {
163 pub(crate) fn encode_dma(&mut self, frame: &DmaFrame, force_keyframe: bool) -> Result<(), String> {208 pub(crate) fn encode_dma(&mut self, frame: &DmaFrame, force_keyframe: bool) -> Result<(), String> {
164 let prime = prime_from_vhdma(&frame.desc, &frame.fds)?;209 let prime = prime_from_vhdma(&frame.desc, &frame.fds)?;
165 let surface = Rc::new(ec_va::import_prime(&self.display, &prime).map_err(|e| e.to_string())?);210 let surface = Rc::new(ec_va::import_prime(&self.display, &prime).map_err(|e| e.to_string())?);
211+ let display = (self.width as u32, self.height as u32);
166 let meta = self.meta(force_keyframe);212 let meta = self.meta(force_keyframe);
167- let coded = self213+ if self.ten_bit {
168- .encoder214+ if let Some(coded) = self
169- .encode_surface(&surface, (self.width as u32, self.height as u32), meta)215+ .encoder
170- .map_err(|e| e.to_string())?;216+ .submit_prime(surface, meta)
171- self.ready.push_back(coded.data);217+ .map_err(|e| e.to_string())?
218+ {
219+ self.ready.push_back(coded.data);
220+ }
221+ } else {
222+ self.flush()?;
223+ let coded = self
224+ .encoder
225+ .encode_surface(&surface, display, meta)
226+ .map_err(|e| e.to_string())?;
227+ self.ready.push_back(coded.data);
228+ }
172 Ok(())229 Ok(())
173 }230 }
174 231
@@ -190,13 +247,13 @@ impl EcEncSession {
190 }247 }
191 }248 }
192 249
193-/// Builds the PRIME descriptor for an NV12 picture the decoder holds.250+/// Builds the PRIME descriptor for an NV12 or P010 picture the decoder holds.
194 ///251 ///
195 /// Luma and chroma are either two objects (two descriptors) or one object252 /// Luma and chroma are either two objects (two descriptors) or one object
196 /// holding both at their own offsets, as the decoder's descriptor says.253 /// holding both at their own offsets, as the decoder's descriptor says.
197 fn prime_from_vhdma(desc: &VhDma, fds: &[OwnedFd]) -> Result<PrimeSurface, String> {254 fn prime_from_vhdma(desc: &VhDma, fds: &[OwnedFd]) -> Result<PrimeSurface, String> {
198- if fds.is_empty() || fds.len() > 2 || desc.fourcc != FOURCC_NV12 {255+ if fds.is_empty() || fds.len() > 2 || !matches!(desc.fourcc, FOURCC_NV12 | FOURCC_P010) {
199- return Err("DMA-BUF is not an NV12 picture on the GPU".into());256+ return Err("DMA-BUF is not an NV12 or P010 picture on the GPU".into());
200 }257 }
201 let (w, h) = (desc.coded_width, desc.coded_height);258 let (w, h) = (desc.coded_width, desc.coded_height);
202 let rows = [h, h / 2];259 let rows = [h, h / 2];
@@ -217,7 +274,7 @@ fn prime_from_vhdma(desc: &VhDma, fds: &[OwnedFd]) -> Result<PrimeSurface, Strin
217 *size = (*size).max(u32::try_from(end).map_err(|_| "DMA-BUF too large")?);274 *size = (*size).max(u32::try_from(end).map_err(|_| "DMA-BUF too large")?);
218 }275 }
219 let layer = PrimeLayer {276 let layer = PrimeLayer {
220- drm_format: FOURCC_NV12,277+ drm_format: desc.fourcc,
221 planes: vec![278 planes: vec![
222 (0, desc.offset[0], desc.stride[0]),279 (0, desc.offset[0], desc.stride[0]),
223 (280 (
@@ -228,7 +285,7 @@ fn prime_from_vhdma(desc: &VhDma, fds: &[OwnedFd]) -> Result<PrimeSurface, Strin
228 ],285 ],
229 };286 };
230 Ok(PrimeSurface {287 Ok(PrimeSurface {
231- fourcc: FOURCC_NV12,288+ fourcc: desc.fourcc,
232 width: w,289 width: w,
233 height: h,290 height: h,
234 objects,291 objects,
crates/engine-hw/src/lib.rsmodified+42 -6
@@ -131,6 +131,10 @@ struct Session {
131 out: Vec<u8>,131 out: Vec<u8>,
132 luma: usize,132 luma: usize,
133 chroma: usize,133 chroma: usize,
134+ /// Asked for this pump: a picture deeper than 8 bits is read back whole.
135+ wide: bool,
136+ out_wide: bool,
137+ out16: Option<ec_hw::I420_16>,
134 /// What the caller's encoder can read straight off the GPU, asked once per138 /// What the caller's encoder can read straight off the GPU, asked once per
135 /// [`vh_next_frame_dma`] call and `None` for every read-back caller.139 /// [`vh_next_frame_dma`] call and `None` for every read-back caller.
136 want: Option<VhDma>,140 want: Option<VhDma>,
@@ -194,6 +198,9 @@ impl Session {
194 out: Vec::new(),198 out: Vec::new(),
195 luma: 0,199 luma: 0,
196 chroma: 0,200 chroma: 0,
201+ wide: false,
202+ out_wide: false,
203+ out16: None,
197 want: None,204 want: None,
198 dma: None,205 dma: None,
199 held: VecDeque::new(),206 held: VecDeque::new(),
@@ -336,9 +343,9 @@ impl Session {
336 let [(obj0, off0, pitch0), (obj1, off1, pitch1)] = planes.as_slice() else {343 let [(obj0, off0, pitch0), (obj1, off1, pitch1)] = planes.as_slice() else {
337 return None;344 return None;
338 };345 };
346+ let fits = prime.width == want.coded_width && prime.height == want.coded_height;
339 if prime.fourcc != want.fourcc347 if prime.fourcc != want.fourcc
340- || prime.width != want.coded_width348+ || !fits
341- || prime.height != want.coded_height
342 || *obj0 != 0349 || *obj0 != 0
343 || *obj1 > 1350 || *obj1 > 1
344 || prime.objects.len() != *obj1 as usize + 1351 || prime.objects.len() != *obj1 as usize + 1
@@ -378,6 +385,17 @@ impl Session {
378 // The read-back goes through the driver's image copy (`vaGetImage`)385 // The read-back goes through the driver's image copy (`vaGetImage`)
379 // rather than a CPU map of the surface: on a discrete GPU that buffer386 // rather than a CPU map of the surface: on a discrete GPU that buffer
380 // lives in VRAM, and a CPU read of it runs over the PCIe BAR.387 // lives in VRAM, and a CPU read of it runs over the PCIe BAR.
388+ if self.wide && frame.bit_depth > 8 {
389+ let i420 = frame.to_i420_16().map_err(|e| e.to_string())?;
390+ self.luma = i420.y.len();
391+ self.chroma = i420.u.len();
392+ self.out_wide = true;
393+ self.meta.width = i420.width;
394+ self.meta.height = i420.height;
395+ self.out16 = Some(i420);
396+ return Ok(());
397+ }
398+ self.out_wide = false;
381 let i420 = frame.to_i420().map_err(|e| e.to_string())?;399 let i420 = frame.to_i420().map_err(|e| e.to_string())?;
382 self.luma = i420.y.len();400 self.luma = i420.y.len();
383 self.chroma = i420.u.len();401 self.chroma = i420.u.len();
@@ -392,8 +410,12 @@ impl Session {
392 410
393 /// The picture [`Session::pump`] or [`VpxSession::pump`] just delivered, as411 /// The picture [`Session::pump`] or [`VpxSession::pump`] just delivered, as
394 /// packed I420 (Y, then U, then V), with its width and height.412 /// packed I420 (Y, then U, then V), with its width and height.
395- fn picture(&self) -> (&[u8], u32, u32) {413+ fn picture(&self) -> ([&[u8]; 3], u32, u32, bool) {
396- (&self.out, self.meta.width, self.meta.height)414+ let parts = match (&self.out16, self.out_wide) {
415+ (Some(p), true) => [bytemuck::cast_slice(&p.y[..]), bytemuck::cast_slice(&p.u[..]), bytemuck::cast_slice(&p.v[..])],
416+ _ => [&self.out[..], &[][..], &[][..]],
417+ };
418+ (parts, self.meta.width, self.meta.height, self.out_wide)
397 }419 }
398 }420 }
399 421
@@ -476,10 +498,19 @@ impl OpenSession {
476 498
477 /// The picture the last successful [`OpenSession::next_frame`] delivered as499 /// The picture the last successful [`OpenSession::next_frame`] delivered as
478 /// read-back I420, with its width and height.500 /// read-back I420, with its width and height.
479- fn picture(&self) -> (&[u8], u32, u32) {501+ fn picture(&self) -> ([&[u8]; 3], u32, u32, bool) {
480 match self {502 match self {
481 Self::Vaapi(session) => session.picture(),503 Self::Vaapi(session) => session.picture(),
482- Self::Vpx(session) => session.picture(),504+ Self::Vpx(session) => {
505+ let (out, w, h) = session.picture();
506+ ([out, &[][..], &[][..]], w, h, false)
507+ }
508+ }
509+ }
510+
511+ fn set_wide(&mut self, wide: bool) {
512+ if let Self::Vaapi(session) = self {
513+ session.wide = wide;
483 }514 }
484 }515 }
485 516
@@ -822,6 +853,7 @@ pub(crate) fn open_encoder(open: &engine::hwproc::Open) -> Option<EcEncSession>
822 intra_only,853 intra_only,
823 gop: open.gop,854 gop: open.gop,
824 colour,855 colour,
856+ ten_bit: open.ten_bit,
825 })857 })
826 }858 }
827 859
@@ -871,6 +903,7 @@ mod tests {
871 intra_only: true,903 intra_only: true,
872 gop: None,904 gop: None,
873 colour: None,905 colour: None,
906+ ten_bit: false,
874 };907 };
875 // No VA-API on this machine: nothing to encode, nothing to claim.908 // No VA-API on this machine: nothing to encode, nothing to claim.
876 let Some(mut session) = EcEncSession::open(open) else {909 let Some(mut session) = EcEncSession::open(open) else {
@@ -881,6 +914,7 @@ mod tests {
881 session914 session
882 .encode(&luma, &chroma, &chroma, false)915 .encode(&luma, &chroma, &chroma, false)
883 .expect("the intra seat encodes a picture");916 .expect("the intra seat encodes a picture");
917+ session.flush().expect("flush");
884 let au = session.next_au().expect("one access unit").to_vec();918 let au = session.next_au().expect("one access unit").to_vec();
885 let au = au.as_slice();919 let au = au.as_slice();
886 assert_eq!(920 assert_eq!(
@@ -953,6 +987,7 @@ mod tests {
953 intra_only: true,987 intra_only: true,
954 gop: None,988 gop: None,
955 colour: None,989 colour: None,
990+ ten_bit: false,
956 };991 };
957 let Some(mut session) = EcEncSession::open(open) else {992 let Some(mut session) = EcEncSession::open(open) else {
958 return;993 return;
@@ -963,6 +998,7 @@ mod tests {
963 session998 session
964 .encode(&luma, &chroma, &chroma, false)999 .encode(&luma, &chroma, &chroma, false)
965 .expect("the intra seat encodes a picture");1000 .expect("the intra seat encodes a picture");
1001+ session.flush().expect("flush");
966 let au = session.next_au().expect("one access unit").to_vec();1002 let au = session.next_au().expect("one access unit").to_vec();
967 let au = au.as_slice();1003 let au = au.as_slice();
968 let kinds: Vec<u8> = au1004 let kinds: Vec<u8> = au
crates/engine/Cargo.tomlmodified+1 -0
@@ -9,6 +9,7 @@ doctest = false
9 9
10 # No UI dependency here, ever: the engine must stay reusable across front-ends.10 # No UI dependency here, ever: the engine must stay reusable across front-ends.
11 [dependencies]11 [dependencies]
12+bytemuck = "1.25"
12 # The WAV writer and reader, the family's own (`ec-riff`): RIFF for the usual13 # The WAV writer and reader, the family's own (`ec-riff`): RIFF for the usual
13 # sizes and RF64 past 4 GiB, WAVE_FORMAT_EXTENSIBLE for the layouts that need it.14 # sizes and RF64 past 4 GiB, WAVE_FORMAT_EXTENSIBLE for the layouts that need it.
14 # `ec-flac` encodes FLAC (RFC 9639), the family's own encoder.15 # `ec-flac` encodes FLAC (RFC 9639), the family's own encoder.
crates/engine/src/export.rsmodified+139 -37
@@ -1306,15 +1306,29 @@ fn audio_kbps_of(settings: &ExportSettings) -> u32 {
1306 /// to an encoder nobody picked. Every caller is before a file exists1306 /// to an encoder nobody picked. Every caller is before a file exists
1307 /// ([`Enc::open`] runs ahead of the muxer), which is what makes the refusal1307 /// ([`Enc::open`] runs ahead of the muxer), which is what makes the refusal
1308 /// free.1308 /// free.
1309-fn hw_seat(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result<Option<HwEncoder>> {1309+fn hw_seat(
1310+ meta: &VideoMeta,
1311+ settings: &ExportSettings,
1312+ ten_bit: bool,
1313+ colour: ColorDescription,
1314+) -> crate::Result<Option<HwEncoder>> {
1310 if settings.seat == EncoderSeat::Software || forced("VE_SW_ENC") {1315 if settings.seat == EncoderSeat::Software || forced("VE_SW_ENC") {
1311 return Ok(None);1316 return Ok(None);
1312 }1317 }
1313- let opened = open_hw_seat(meta, settings);1318+ if ten_bit && settings.format.is_hevc() && hdr_metadata(settings) {
1319+ if settings.seat == EncoderSeat::Hardware {
1320+ return Err("the hardware HEVC seat writes no mastering display or MaxCLL/MaxFALL SEI: \
1321+ drop that metadata, or pick Auto or Software"
1322+ .into());
1323+ }
1324+ return Ok(None);
1325+ }
1326+ let opened = open_hw_seat(meta, settings, ten_bit, colour);
1314 if opened.is_none() && settings.seat == EncoderSeat::Hardware {1327 if opened.is_none() && settings.seat == EncoderSeat::Hardware {
1315 return Err(format!(1328 return Err(format!(
1316- "hardware encoding was asked for and this machine has no VA-API seat for {}: \1329+ "hardware encoding was asked for and this machine has no VA-API seat for {}{}: \
1317 pick Auto or Software on the export card",1330 pick Auto or Software on the export card",
1331+ if ten_bit { "10-bit " } else { "" },
1318 settings.format.name()1332 settings.format.name()
1319 )1333 )
1320 .into());1334 .into());
@@ -1324,7 +1338,18 @@ fn hw_seat(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result<Option<
1324 1338
1325 /// The plugin half of [`hw_seat`]: what the driver gives for this codec and1339 /// The plugin half of [`hw_seat`]: what the driver gives for this codec and
1326 /// this picture, with no policy in it but the AV1 one.1340 /// this picture, with no policy in it but the AV1 one.
1327-fn open_hw_seat(meta: &VideoMeta, settings: &ExportSettings) -> Option<HwEncoder> {1341+/// Whether the export carries HDR static metadata, which only the software HEVC seat writes.
1342+fn hdr_metadata(settings: &ExportSettings) -> bool {
1343+ let hdr = &settings.hdr;
1344+ hdr.mastering_display.is_some() || hdr.max_cll.is_some() || hdr.max_fall.is_some()
1345+}
1346+
1347+fn open_hw_seat(
1348+ meta: &VideoMeta,
1349+ settings: &ExportSettings,
1350+ ten_bit: bool,
1351+ colour: ColorDescription,
1352+) -> Option<HwEncoder> {
1328 let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate).ok()?;1353 let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate).ok()?;
1329 let rate = rate_of(meta, settings);1354 let rate = rate_of(meta, settings);
1330 match settings.format {1355 match settings.format {
@@ -1341,7 +1366,8 @@ fn open_hw_seat(meta: &VideoMeta, settings: &ExportSettings) -> Option<HwEncoder
1341 fps_num,1366 fps_num,
1342 fps_den,1367 fps_den,
1343 rate,1368 rate,
1344- ColorDescription::output_sized(meta.width, meta.height),1369+ colour,
1370+ ten_bit,
1345 ),1371 ),
1346 format if format.is_hevc() => HwEncoder::open_hevc(1372 format if format.is_hevc() => HwEncoder::open_hevc(
1347 meta.width,1373 meta.width,
@@ -1349,8 +1375,9 @@ fn open_hw_seat(meta: &VideoMeta, settings: &ExportSettings) -> Option<HwEncoder
1349 fps_num,1375 fps_num,
1350 fps_den,1376 fps_den,
1351 rate,1377 rate,
1352- ColorDescription::output_sized(meta.width, meta.height),1378+ colour,
1353 gop_frames(meta, settings),1379 gop_frames(meta, settings),
1380+ ten_bit,
1354 ),1381 ),
1355 // Asked for by name only, for the reason [`Enc::open_av1`] states in1382 // Asked for by name only, for the reason [`Enc::open_av1`] states in
1356 // full: `Auto` takes the software encoder here and nowhere else. Both1383 // full: `Auto` takes the software encoder here and nowhere else. Both
@@ -1985,6 +2012,54 @@ fn export_spans(project: &Project, range: Option<(u32, u32)>) -> Vec<crate::proj
1985 2012
1986 /// The visible video lanes, bottom first: the last one is the topmost, the order2013 /// The visible video lanes, bottom first: the last one is the topmost, the order
1987 /// [`Project::composite_clip_at`] counts in.2014 /// [`Project::composite_clip_at`] counts in.
2015+fn split_spans(spans: Vec<crate::project::Span>, quiet: impl Fn(u32) -> bool) -> Vec<crate::project::Span> {
2016+ let mut out = Vec::with_capacity(spans.len());
2017+ for mut cur in spans {
2018+ let mut off = 1;
2019+ while off < cur.len {
2020+ if quiet(cur.start + off) != quiet(cur.start + off - 1)
2021+ && let Some(tail) = span_tail(&cur, off)
2022+ {
2023+ out.push(crate::project::Span { len: off, ..cur });
2024+ cur = tail;
2025+ off = 1;
2026+ continue;
2027+ }
2028+ off += 1;
2029+ }
2030+ out.push(cur);
2031+ }
2032+ out
2033+}
2034+
2035+fn span_tail(span: &crate::project::Span, cut: u32) -> Option<crate::project::Span> {
2036+ let mut tail = *span;
2037+ tail.start += cut;
2038+ tail.len -= cut;
2039+ tail.ramp = span.ramp.map(|r| r.advanced(cut));
2040+ if let Some((source, first)) = span.from {
2041+ let next = span.source_at(first, cut);
2042+ tail.from = Some((source, next));
2043+ if (0..tail.len).any(|o| tail.source_at(next, o) != span.source_at(first, cut + o)) {
2044+ return None;
2045+ }
2046+ }
2047+ Some(tail)
2048+}
2049+
2050+fn wide_yuv(bytes: &[u8], width: u32, height: u32) -> Yuv {
2051+ let (w, h) = (width as usize, height as usize);
2052+ let (luma, chroma) = (w * h, w.div_ceil(2) * h.div_ceil(2));
2053+ let unpack = crate::hwproc::unpack16;
2054+ Yuv::Wide {
2055+ y: unpack(&bytes[..2 * luma]),
2056+ u: unpack(&bytes[2 * luma..2 * (luma + chroma)]),
2057+ v: unpack(&bytes[2 * (luma + chroma)..2 * (luma + 2 * chroma)]),
2058+ width,
2059+ height,
2060+ }
2061+}
2062+
1988 fn visible_video_lanes(project: &Project) -> Vec<Lane> {2063 fn visible_video_lanes(project: &Project) -> Vec<Lane> {
1989 project2064 project
1990 .lanes()2065 .lanes()
@@ -3599,7 +3674,12 @@ pub fn planned_video(meta: &VideoMeta, settings: &ExportSettings) -> Option<&'st
3599 settings3674 settings
3600 .format3675 .format
3601 .has_video()3676 .has_video()
3602- .then(|| match hw_seat(meta, settings) {3677+ .then(|| match hw_seat(
3678+ meta,
3679+ settings,
3680+ settings.video_bit_depth == Some(10) || settings.hdr.transfer != HdrTransfer::Sdr,
3681+ ColorDescription::output_sized(meta.width, meta.height),
3682+ ) {
3603 Ok(hw) => video_label(settings.format, hw.is_some(), settings.intra_only),3683 Ok(hw) => video_label(settings.format, hw.is_some(), settings.intra_only),
3604 // The seat the settings demand and this machine has not: the very3684 // The seat the settings demand and this machine has not: the very
3605 // refusal [`start`] would settle with, said on the card instead.3685 // refusal [`start`] would settle with, said on the card instead.
@@ -5490,7 +5570,12 @@ fn run(
5490 // past it under a trailing caption -- and *which* lane a span comes from is5570 // past it under a trailing caption -- and *which* lane a span comes from is
5491 // `composite_spans_from`'s answer, the same one playback shows, so an5571 // `composite_spans_from`'s answer, the same one playback shows, so an
5492 // export is what was watched.5572 // export is what was watched.
5493- for span in export_spans(project, settings.range) {5573+ let spans = export_spans(project, settings.range);
5574+ let spans = match (&burn, ten_bit && matches!(encoder, Enc::HevcHw(_, _, true))) {
5575+ (Some(b), true) => split_spans(spans, |f| b.quiet(f, f + 1)),
5576+ _ => spans,
5577+ };
5578+ for span in spans {
5494 // Every clip reopens its own source file at its own in point; the5579 // Every clip reopens its own source file at its own in point; the
5495 // encoder is *not* reopened, so the export is one continuous stream5580 // encoder is *not* reopened, so the export is one continuous stream
5496 // whose GOP boundaries need not line up with the cuts -- nor with the5581 // whose GOP boundaries need not line up with the cuts -- nor with the
@@ -5528,7 +5613,7 @@ fn run(
5528 // the plugin hands back as pixels ([`HwSession::next_frame_dma`]).5613 // the plugin hands back as pixels ([`HwSession::next_frame_dma`]).
5529 let untouched = mapper.is_none()5614 let untouched = mapper.is_none()
5530 && keyed_color.is_none()5615 && keyed_color.is_none()
5531- && burn.is_none()5616+ && burn.as_ref().is_none_or(|b| ten_bit && b.quiet(span.start, span.end()))
5532 && remap_into(Some(color), false, out_color.matrix).is_none()5617 && remap_into(Some(color), false, out_color.matrix).is_none()
5533 && project5618 && project
5534 .composite_color_at(span.start)5619 .composite_color_at(span.start)
@@ -5886,7 +5971,7 @@ fn run(
5886 && pixel_aspect.is_square()5971 && pixel_aspect.is_square()
5887 && burn5972 && burn
5888 .as_ref()5973 .as_ref()
5889- .is_none_or(|b| b.cues.is_empty() && b.titles.is_empty())5974+ .is_none_or(|b| b.quiet(span.start + done_here, span.start + done_here + repeats))
5890 && (done_here..done_here + repeats)5975 && (done_here..done_here + repeats)
5891 .all(|off| picture_fade_at(project, span.start + off).is_none());5976 .all(|off| picture_fade_at(project, span.start + off).is_none());
5892 // A 10-bit export composes at 10 bits wherever the picture is touched at5977 // A 10-bit export composes at 10 bits wherever the picture is touched at
@@ -6490,6 +6575,12 @@ impl Burn {
6490 /// The picture at timeline frame `frame` with the titles on screen and the6575 /// The picture at timeline frame `frame` with the titles on screen and the
6491 /// caption drawn in, or `None` where nothing is on screen and the planes go6576 /// caption drawn in, or `None` where nothing is on screen and the planes go
6492 /// on untouched.6577 /// on untouched.
6578+ fn quiet(&self, from: u32, to: u32) -> bool {
6579+ (from..to).all(|f| {
6580+ cues_on_screen(&self.cues, f, self.fps).is_empty() && self.titles.iter().all(|t| t.motion_at(f).is_none())
6581+ })
6582+ }
6583+
6493 fn paint(6584 fn paint(
6494 &mut self,6585 &mut self,
6495 frame: u32,6586 frame: u32,
@@ -8277,7 +8368,7 @@ enum Enc {
8277 Av1Hw(HwEncoder),8368 Av1Hw(HwEncoder),
8278 /// HEVC on the GPU, through that same plugin -- and intra-only there too,8369 /// HEVC on the GPU, through that same plugin -- and intra-only there too,
8279 /// so this and [`Enc::Hevc`] write the same kind of file.8370 /// so this and [`Enc::Hevc`] write the same kind of file.
8280- HevcHw(HwEncoder, bool),8371+ HevcHw(HwEncoder, bool, bool),
8281 /// AV1 software at 10 bits: `rav1e`'s 16-bit context. A picture that passes8372 /// AV1 software at 10 bits: `rav1e`'s 16-bit context. A picture that passes
8282 /// through the span untouched arrives as 16-bit planes off the 10-bit decode8373 /// through the span untouched arrives as 16-bit planes off the 10-bit decode
8283 /// ([`Enc::encode_wide`]); an 8-bit picture (one composed on the way) is shifted8374 /// ([`Enc::encode_wide`]); an 8-bit picture (one composed on the way) is shifted
@@ -8369,7 +8460,7 @@ impl Enc {
8369 Self::Sw { .. } => video_label(Format::Mp4, false, false),8460 Self::Sw { .. } => video_label(Format::Mp4, false, false),
8370 Self::Av1Hw(_) => video_label(Format::Av1, true, false),8461 Self::Av1Hw(_) => video_label(Format::Av1, true, false),
8371 Self::Av1Sw { .. } | Self::Av1Sw16 { .. } => video_label(Format::Av1, false, false),8462 Self::Av1Sw { .. } | Self::Av1Sw16 { .. } => video_label(Format::Av1, false, false),
8372- Self::HevcHw(_, intra) => video_label(Format::Hevc, true, *intra),8463+ Self::HevcHw(_, intra, _) => video_label(Format::Hevc, true, *intra),
8373 Self::Hevc(_) => video_label(Format::Hevc, false, true),8464 Self::Hevc(_) => video_label(Format::Hevc, false, true),
8374 Self::HevcGop(_) => video_label(Format::Hevc, false, false),8465 Self::HevcGop(_) => video_label(Format::Hevc, false, false),
8375 Self::ProRes { .. } => video_label(Format::ProRes, false, true),8466 Self::ProRes { .. } => video_label(Format::ProRes, false, true),
@@ -8413,7 +8504,7 @@ impl Enc {
8413 // hand 24000/1001 over as a rounded 23.976, which is the same8504 // hand 24000/1001 over as a rounded 23.976, which is the same
8414 // truncation the container timing had.8505 // truncation the container timing had.
8415 crate::mux::frame_timing(meta.frame_rate)?;8506 crate::mux::frame_timing(meta.frame_rate)?;
8416- if let Some(hw) = hw_seat(meta, settings)? {8507+ if let Some(hw) = hw_seat(meta, settings, false, colour)? {
8417 if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export encoder: hardware (VA-API plugin)"); }8508 if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export encoder: hardware (VA-API plugin)"); }
8418 return Ok(Self::Hw(hw));8509 return Ok(Self::Hw(hw));
8419 }8510 }
@@ -8508,7 +8599,7 @@ impl Enc {
8508 // The 10-bit seat is software: the GPU encode is 8-bit only.8599 // The 10-bit seat is software: the GPU encode is 8-bit only.
8509 let hw = match ten_bit {8600 let hw = match ten_bit {
8510 true => None,8601 true => None,
8511- false => hw_seat(meta, settings)?,8602+ false => hw_seat(meta, settings, false, colour)?,
8512 };8603 };
8513 if let Some(hw) = hw {8604 if let Some(hw) = hw {
8514 if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export encoder: hardware AV1 (VA-API plugin)"); }8605 if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export encoder: hardware AV1 (VA-API plugin)"); }
@@ -8633,14 +8724,9 @@ impl Enc {
8633 )8724 )
8634 .into());8725 .into());
8635 }8726 }
8636- // The GPU seat is 8-bit only, so a 10-bit export is software.8727+ if let Some(hw) = hw_seat(meta, settings, ten_bit, colour)? {
8637- let hw = match ten_bit {
8638- true => None,
8639- false => hw_seat(meta, settings)?,
8640- };
8641- if let Some(hw) = hw {
8642 if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export encoder: hardware HEVC (VA-API plugin)"); }8728 if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export encoder: hardware HEVC (VA-API plugin)"); }
8643- return Ok(Self::HevcHw(hw, settings.intra_only));8729+ return Ok(Self::HevcHw(hw, settings.intra_only, ten_bit));
8644 }8730 }
8645 if !settings.intra_only {8731 if !settings.intra_only {
8646 if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export encoder: software HEVC I+P (ec-h265)"); }8732 if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export encoder: software HEVC I+P (ec-h265)"); }
@@ -8729,6 +8815,9 @@ impl Enc {
8729 *au = encoder.encode(&frame).map_err(|e| format!("ProRes encode: {e}"))?;8815 *au = encoder.encode(&frame).map_err(|e| format!("ProRes encode: {e}"))?;
8730 Ok(Some((&au[..], true)))8816 Ok(Some((&au[..], true)))
8731 }8817 }
8818+ Self::HevcHw(hw, intra, true) => Ok(hw
8819+ .encode16(y, u, v, width, height, *intra)?
8820+ .map(|au| (au, hevc_irap(au)))),
8732 Self::Hevc(hevc) if hevc.ten_bit => {8821 Self::Hevc(hevc) if hevc.ten_bit => {
8733 hevc.pending.push((le_bytes(y), le_bytes(u), le_bytes(v)));8822 hevc.pending.push((le_bytes(y), le_bytes(u), le_bytes(v)));
8734 if hevc.pending.len() >= hevc.lanes.len() {8823 if hevc.pending.len() >= hevc.lanes.len() {
@@ -8740,11 +8829,12 @@ impl Enc {
8740 }8829 }
8741 }8830 }
8742 8831
8743- /// Whether this is a software HEVC seat coding at 10 bits.8832+ /// Whether this is an HEVC seat coding at 10 bits.
8744 fn hevc_ten_bit(&self) -> bool {8833 fn hevc_ten_bit(&self) -> bool {
8745 match self {8834 match self {
8746 Self::HevcGop(gop) => gop.ten_bit,8835 Self::HevcGop(gop) => gop.ten_bit,
8747 Self::Hevc(hevc) => hevc.ten_bit,8836 Self::Hevc(hevc) => hevc.ten_bit,
8837+ Self::HevcHw(_, _, ten) => *ten,
8748 _ => false,8838 _ => false,
8749 }8839 }
8750 }8840 }
@@ -8829,7 +8919,7 @@ impl Enc {
8829 collect_av1(context, ready)?;8919 collect_av1(context, ready)?;
8830 Ok(pop_av1(ready, au))8920 Ok(pop_av1(ready, au))
8831 }8921 }
8832- Self::HevcHw(hw, intra) => Ok(hw8922+ Self::HevcHw(hw, intra, _) => Ok(hw
8833 .encode(y, u, v, width, height, *intra)?8923 .encode(y, u, v, width, height, *intra)?
8834 .map(|au| (au, hevc_irap(au)))),8924 .map(|au| (au, hevc_irap(au)))),
8835 Self::Hevc(hevc) => {8925 Self::Hevc(hevc) => {
@@ -8883,7 +8973,10 @@ impl Enc {
8883 /// ([`crate::hwproc`]), which is a round trip on its socket.8973 /// ([`crate::hwproc`]), which is a round trip on its socket.
8884 fn dma_want(&mut self, meta: &VideoMeta) -> Option<crate::hw::DmaWant> {8974 fn dma_want(&mut self, meta: &VideoMeta) -> Option<crate::hw::DmaWant> {
8885 match self {8975 match self {
8886- Self::Hw(hw) | Self::HevcHw(hw, _) => hw.dma_want(meta.width, meta.height),8976+ Self::Hw(hw) | Self::HevcHw(hw, _, false) => hw.dma_want(meta.width, meta.height),
8977+ Self::HevcHw(hw, _, true) => hw
8978+ .dma_want(meta.width, meta.height)
8979+ .map(|want| crate::hw::DmaWant { ten_bit: true, ..want }),
8887 _ => None,8980 _ => None,
8888 }8981 }
8889 }8982 }
@@ -8902,7 +8995,7 @@ impl Enc {
8902 fn encode_dma(&mut self, dma: &DmaFrame, intra: bool) -> crate::Result<Option<(&[u8], bool)>> {8995 fn encode_dma(&mut self, dma: &DmaFrame, intra: bool) -> crate::Result<Option<(&[u8], bool)>> {
8903 match self {8996 match self {
8904 Self::Hw(hw) => Ok(hw.encode_dma(dma, intra)?.map(|au| (au, intra))),8997 Self::Hw(hw) => Ok(hw.encode_dma(dma, intra)?.map(|au| (au, intra))),
8905- Self::HevcHw(hw, intra) => Ok(hw.encode_dma(dma, *intra)?.map(|au| (au, hevc_irap(au)))),8998+ Self::HevcHw(hw, intra, _) => Ok(hw.encode_dma(dma, *intra)?.map(|au| (au, hevc_irap(au)))),
8906 // Unreachable through [`Enc::dma_want`], which is the only thing8999 // Unreachable through [`Enc::dma_want`], which is the only thing
8907 // that puts a span's decoder on this path.9000 // that puts a span's decoder on this path.
8908 _ => Err("this encoder takes pictures as bytes, not as buffers".into()),9001 _ => Err("this encoder takes pictures as bytes, not as buffers".into()),
@@ -8943,7 +9036,7 @@ impl Enc {
8943 }9036 }
8944 Ok(pop_av1(ready, au))9037 Ok(pop_av1(ready, au))
8945 }9038 }
8946- Self::HevcHw(hw, _) => Ok(hw.drain()?.map(|au| (au, hevc_irap(au)))),9039+ Self::HevcHw(hw, ..) => Ok(hw.drain()?.map(|au| (au, hevc_irap(au)))),
8947 // The tail batch: fewer frames than lanes, coded on as many9040 // The tail batch: fewer frames than lanes, coded on as many
8948 // encoders as there are frames left.9041 // encoders as there are frames left.
8949 Self::Hevc(hevc) => {9042 Self::Hevc(hevc) => {
@@ -9398,9 +9491,8 @@ fn source_sdr_colour(colours: &[ColorDescription]) -> Option<ColorDescription> {
9398 9491
9399 /// Whether a software export is written at 10 bits: the setting where it names a9492 /// Whether a software export is written at 10 bits: the setting where it names a
9400 /// depth, the source's own where it does not. AV1 and HEVC have the choice --9493 /// depth, the source's own where it does not. AV1 and HEVC have the choice --
9401-/// H.264 is 8-bit here -- and a depth the file cannot be is refused. The HEVC9494+/// H.264 is 8-bit here -- and a depth the file cannot be is refused. A 10-bit
9402-/// hardware seat is 8-bit, so a 10-bit HEVC export falls back to software9495+/// HEVC export takes the hardware seat (Main10) where there is one ([`open_hevc`]).
9403-/// ([`open_hevc`]).
9404 fn wide_ten_bit(9496 fn wide_ten_bit(
9405 settings: &ExportSettings,9497 settings: &ExportSettings,
9406 source_ten_bit: impl FnOnce() -> bool,9498 source_ten_bit: impl FnOnce() -> bool,
@@ -10102,13 +10194,16 @@ fn decode_stream(
10102 wide: bool,10194 wide: bool,
10103 deint: Deinterlace,10195 deint: Deinterlace,
10104 ) -> Option<Kept> {10196 ) -> Option<Kept> {
10105- // A 10-bit export decodes in software: the hardware seat hands 8-bit planes.10197+ // A 10-bit export asks the hardware seat for whole 10-bit pictures ([`Pictures::Hw`]).
10106- let opened = match forced("VE_SW") || wide {10198+ let opened = match forced("VE_SW") {
10107 // The decode door's own gate ([`crate::decode::open_hw`]): a VP9 4:2:2 or 4:4:410199 // The decode door's own gate ([`crate::decode::open_hw`]): a VP9 4:2:2 or 4:4:4
10108 // stream is never offered to the GPU, which would refuse it on stderr.10200 // stream is never offered to the GPU, which would refuse it on stderr.
10109- false => crate::decode::open_hw(path, start_frame).map(|hw| Pictures::Hw(Box::new(hw))),10201+ false => crate::decode::open_hw(path, start_frame).map(|hw| Pictures::Hw(Box::new(hw), wide)),
10110 true => None,10202 true => None,
10111 };10203 };
10204+ if std::env::var_os("EDITH_DEBUG").is_some() {
10205+ eprintln!("export decode: {}{}", if opened.is_some() { "hardware" } else { "software" }, if wide { ", 10-bit" } else { "" });
10206+ }
10112 // Pictures decoded ahead of the span that a parked decoder still holds.10207 // Pictures decoded ahead of the span that a parked decoder still holds.
10113 let (mut decoder, mut backlog) = match opened {10208 let (mut decoder, mut backlog) = match opened {
10114 Some(hw) => (hw, VecDeque::new()),10209 Some(hw) => (hw, VecDeque::new()),
@@ -10150,7 +10245,7 @@ fn decode_stream(
10150 None => decoder.next(want),10245 None => decoder.next(want),
10151 };10246 };
10152 let next = match next {10247 let next = match next {
10153- Ok(None) if decoded == 0 && matches!(decoder, Pictures::Hw(_)) => {10248+ Ok(None) if decoded == 0 && matches!(decoder, Pictures::Hw(..)) => {
10154 Err("hardware gave no picture from the start frame".into())10249 Err("hardware gave no picture from the start frame".into())
10155 }10250 }
10156 other => other,10251 other => other,
@@ -10162,7 +10257,7 @@ fn decode_stream(
10162 return None;10257 return None;
10163 }10258 }
10164 Err(e) => {10259 Err(e) => {
10165- if matches!(decoder, Pictures::Hw(_)) {10260+ if matches!(decoder, Pictures::Hw(..)) {
10166 // Before the first picture, or after some: either way the10261 // Before the first picture, or after some: either way the
10167 // software seat takes the span from the first picture not yet10262 // software seat takes the span from the first picture not yet
10168 // sent (`decoded` is 0 in the first case), so nothing is10263 // sent (`decoded` is 0 in the first case), so nothing is
@@ -10198,7 +10293,8 @@ fn decode_stream(
10198 10293
10199 /// The stream decoders, on the thread that opened them.10294 /// The stream decoders, on the thread that opened them.
10200 enum Pictures {10295 enum Pictures {
10201- Hw(Box<HwSession>),10296+ /// With whether the export is 10-bit, which asks for whole 10-bit pictures.
10297+ Hw(Box<HwSession>, bool),
10202 /// `ec-h264`, on this thread.10298 /// `ec-h264`, on this thread.
10203 Sw(Box<SwDecoder>),10299 Sw(Box<SwDecoder>),
10204 /// `ec-av1`, on a thread of its own -- see [`Av1Stream`].10300 /// `ec-av1`, on a thread of its own -- see [`Av1Stream`].
@@ -10225,14 +10321,20 @@ impl Pictures {
10225 /// buys the decode and the encode their overlap.10321 /// buys the decode and the encode their overlap.
10226 fn next(&mut self, want: Option<DmaWant>) -> crate::Result<Option<Yuv>> {10322 fn next(&mut self, want: Option<DmaWant>) -> crate::Result<Option<Yuv>> {
10227 match (self, want) {10323 match (self, want) {
10228- (Self::Hw(hw), Some(want)) => Ok(match hw.next_frame_dma(want)? {10324+ (Self::Hw(hw, true), None) => Ok(match hw.next_frame_wide()? {
10325+ Some(crate::hw::HwFrame::Wide(bytes, width, height)) => Some(wide_yuv(bytes, width, height)),
10326+ Some(crate::hw::HwFrame::Narrow((y, u, v, width, height))) => Some(Yuv::pixels(y, u, v, width, height)),
10327+ None => None,
10328+ }),
10329+ (Self::Hw(hw, _), Some(want)) => Ok(match hw.next_frame_dma(want)? {
10229 Some(HwPicture::Dma(dma)) => Some(Yuv::Dma(dma)),10330 Some(HwPicture::Dma(dma)) => Some(Yuv::Dma(dma)),
10331+ Some(HwPicture::Wide(bytes, width, height)) => Some(wide_yuv(bytes, width, height)),
10230 Some(HwPicture::Pixels(y, u, v, width, height)) => {10332 Some(HwPicture::Pixels(y, u, v, width, height)) => {
10231 Some(Yuv::pixels(y, u, v, width, height))10333 Some(Yuv::pixels(y, u, v, width, height))
10232 }10334 }
10233 None => None,10335 None => None,
10234 }),10336 }),
10235- (Self::Hw(hw), None) => Ok(hw10337+ (Self::Hw(hw, _), None) => Ok(hw
10236 .next_frame()?10338 .next_frame()?
10237 .map(|(y, u, v, width, height)| Yuv::pixels(y, u, v, width, height))),10339 .map(|(y, u, v, width, height)| Yuv::pixels(y, u, v, width, height))),
10238 (Self::Av1(av1), _) => av1.next(),10340 (Self::Av1(av1), _) => av1.next(),
crates/engine/src/hw.rsmodified+302 -15
@@ -16,16 +16,19 @@
16 //! Pictures still on the GPU cross as DRM-PRIME descriptors over `SCM_RIGHTS`16 //! Pictures still on the GPU cross as DRM-PRIME descriptors over `SCM_RIGHTS`
17 //! and are never copied through the socket.17 //! and are never copied through the socket.
18 18
19+use std::collections::VecDeque;
19 use std::ffi::OsString;20 use std::ffi::OsString;
20 use std::os::fd::OwnedFd;21 use std::os::fd::OwnedFd;
21 use std::path::Path;22 use std::path::Path;
22 use std::process::Child;23 use std::process::Child;
23 use std::sync::OnceLock;24 use std::sync::OnceLock;
25+use std::sync::mpsc::{self, Receiver, Sender, SyncSender, TryRecvError};
26+use std::thread::JoinHandle;
24 27
25 use crate::colorspace::ColorDescription;28 use crate::colorspace::ColorDescription;
26 use crate::hwproc::{29 use crate::hwproc::{
27- DMA_BODY, HW_LOST, K_DMA, K_PIXELS, Lost, Open, R_AU, R_ERR, R_NONE, Remote, Seat, SeatRate, Shm,30+ DMA_BODY, HW_LOST, K_DMA, K_PIXELS, K_PIXELS16, Lost, Open, R_AU, R_ERR, R_NONE, Remote, Seat, SeatRate, Shm,
28- T_NEXT, T_NEXT_DMA, T_SEEK, recv_reply, send_msg, spawn_child,31+ T_NEXT, T_NEXT_DMA, T_NEXT_DMA16, T_NEXT_WIDE, T_SEEK, pack16, recv_reply, send_msg, spawn_child,
29 };32 };
30 33
31 #[cfg(test)]34 #[cfg(test)]
@@ -246,6 +249,8 @@ pub struct HwSession {
246 body: Vec<u8>,249 body: Vec<u8>,
247 /// The last picture read out of `shm`, packed I420.250 /// The last picture read out of `shm`, packed I420.
248 pixels: Vec<u8>,251 pixels: Vec<u8>,
252+ /// Whether `pixels` holds 16-bit LE samples (`K_PIXELS16`).
253+ pixels_wide: bool,
249 /// Set the moment the child is known gone, so every later call refuses in254 /// Set the moment the child is known gone, so every later call refuses in
250 /// the same words instead of waiting on a socket nobody holds.255 /// the same words instead of waiting on a socket nobody holds.
251 lost: Option<String>,256 lost: Option<String>,
@@ -295,6 +300,7 @@ impl HwSession {
295 meta,300 meta,
296 body,301 body,
297 pixels: Vec::new(),302 pixels: Vec::new(),
303+ pixels_wide: false,
298 lost: None,304 lost: None,
299 fail_after: injected_failure(),305 fail_after: injected_failure(),
300 delivered: 0,306 delivered: 0,
@@ -342,6 +348,21 @@ impl HwSession {
342 }348 }
343 }349 }
344 350
351+ /// The next picture for a 10-bit consumer: a picture deeper than 8 bits comes
352+ /// back whole ([`HwFrame::Wide`]), an 8-bit one as ordinary planes.
353+ pub fn next_frame_wide(&mut self) -> crate::Result<Option<HwFrame<'_>>> {
354+ self.inject()?;
355+ match self.fetch(T_NEXT_WIDE, &[])? {
356+ None => Ok(None),
357+ Some(Fetched::Pixels) if self.pixels_wide => {
358+ let (w, h) = (self.meta.width, self.meta.height);
359+ Ok(Some(HwFrame::Wide(&self.pixels[..2 * i420_bytes(w, h)], w, h)))
360+ }
361+ Some(Fetched::Pixels) => Ok(Some(HwFrame::Narrow(self.planes()))),
362+ Some(Fetched::Dma(_)) => Err("the decoder handed over a GPU buffer nobody asked for".into()),
363+ }
364+ }
365+
345 /// The next picture *without reading it back* where the caller's encoder can366 /// The next picture *without reading it back* where the caller's encoder can
346 /// take the buffer the decoder wrote into -- which is what `want` describes.367 /// take the buffer the decoder wrote into -- which is what `want` describes.
347 /// Anything the child cannot hand over that way comes back as pixels368 /// Anything the child cannot hand over that way comes back as pixels
@@ -356,9 +377,13 @@ impl HwSession {
356 for value in [want.coded_width, want.coded_height, want.width, want.height] {377 for value in [want.coded_width, want.coded_height, want.width, want.height] {
357 body.extend_from_slice(&value.to_le_bytes());378 body.extend_from_slice(&value.to_le_bytes());
358 }379 }
359- match self.fetch(T_NEXT_DMA, &body)? {380+ match self.fetch(if want.ten_bit { T_NEXT_DMA16 } else { T_NEXT_DMA }, &body)? {
360 None => Ok(None),381 None => Ok(None),
361 Some(Fetched::Dma(frame)) => Ok(Some(HwPicture::Dma(frame))),382 Some(Fetched::Dma(frame)) => Ok(Some(HwPicture::Dma(frame))),
383+ Some(Fetched::Pixels) if self.pixels_wide => {
384+ let (w, h) = (self.meta.width, self.meta.height);
385+ Ok(Some(HwPicture::Wide(&self.pixels[..2 * i420_bytes(w, h)], w, h)))
386+ }
362 Some(Fetched::Pixels) => {387 Some(Fetched::Pixels) => {
363 let (y, u, v, width, height) = self.planes();388 let (y, u, v, width, height) = self.planes();
364 Ok(Some(HwPicture::Pixels(y, u, v, width, height)))389 Ok(Some(HwPicture::Pixels(y, u, v, width, height)))
@@ -375,11 +400,12 @@ impl HwSession {
375 }400 }
376 let reply = self.body.clone();401 let reply = self.body.clone();
377 match reply.first().copied() {402 match reply.first().copied() {
378- Some(K_PIXELS) if tag == R_AU => {403+ Some(kind @ (K_PIXELS | K_PIXELS16)) if tag == R_AU => {
379 let bad = || -> crate::Error { "the decoder sent a short picture header".into() };404 let bad = || -> crate::Error { "the decoder sent a short picture header".into() };
380 let width = le_u32(&reply, 1).ok_or_else(bad)?;405 let width = le_u32(&reply, 1).ok_or_else(bad)?;
381 let height = le_u32(&reply, 5).ok_or_else(bad)?;406 let height = le_u32(&reply, 5).ok_or_else(bad)?;
382- let needed = i420_bytes(width, height);407+ self.pixels_wide = kind == K_PIXELS16;
408+ let needed = i420_bytes(width, height) * if self.pixels_wide { 2 } else { 1 };
383 if let Some(fd) = fds.pop() {409 if let Some(fd) = fds.pop() {
384 // The child made a bigger staging buffer for this frame.410 // The child made a bigger staging buffer for this frame.
385 self.shm = Shm::from_fd(fd, needed);411 self.shm = Shm::from_fd(fd, needed);
@@ -396,9 +422,9 @@ impl HwSession {
396 }422 }
397 Some(K_DMA) if tag == R_AU => {423 Some(K_DMA) if tag == R_AU => {
398 let desc = dma_from_wire(&reply).ok_or("the decoder sent a short GPU buffer header")?;424 let desc = dma_from_wire(&reply).ok_or("the decoder sent a short GPU buffer header")?;
399- let count = usize::from(reply[DMA_BODY - 1]);425+ let count = usize::from(*reply.get(DMA_BODY).ok_or("the decoder sent a short GPU buffer header")?);
400 if fds.len() != count || !(1..=2).contains(&count) {426 if fds.len() != count || !(1..=2).contains(&count) {
401- return Err("the decoder's GPU buffer came without its descriptors".into());427+ return Err(format!("the decoder's GPU buffer came without its descriptors ({} of {count})", fds.len()).into());
402 }428 }
403 self.meta.width = desc.width;429 self.meta.width = desc.width;
404 self.meta.height = desc.height;430 self.meta.height = desc.height;
@@ -473,12 +499,21 @@ pub struct DmaWant {
473 pub coded_height: u32,499 pub coded_height: u32,
474 pub width: u32,500 pub width: u32,
475 pub height: u32,501 pub height: u32,
502+ pub ten_bit: bool,
503+}
504+
505+/// One picture out of [`HwSession::next_frame_wide`]: 8-bit planes, or packed
506+/// I420 of 16-bit LE samples with its width and height.
507+pub enum HwFrame<'a> {
508+ Narrow(Planes<'a>),
509+ Wide(&'a [u8], u32, u32),
476 }510 }
477 511
478 /// One picture out of [`HwSession::next_frame_dma`]: still on the GPU, or read512 /// One picture out of [`HwSession::next_frame_dma`]: still on the GPU, or read
479 /// back like every other frame.513 /// back like every other frame.
480 pub enum HwPicture<'a> {514 pub enum HwPicture<'a> {
481 Pixels(&'a [u8], &'a [u8], &'a [u8], u32, u32),515 Pixels(&'a [u8], &'a [u8], &'a [u8], u32, u32),
516+ Wide(&'a [u8], u32, u32),
482 Dma(DmaFrame),517 Dma(DmaFrame),
483 }518 }
484 519
@@ -487,7 +522,96 @@ pub enum HwPicture<'a> {
487 ///522 ///
488 /// The API is the one it always was, call for call, so nothing in the export523 /// The API is the one it always was, call for call, so nothing in the export
489 /// loop knows which side of a process boundary the encoder is on.524 /// loop knows which side of a process boundary the encoder is on.
490-pub struct HwEncoder(Remote);525+pub struct HwEncoder {
526+ remote: Option<Remote>,
527+ pipe: Option<Pipe>,
528+ backlog: VecDeque<Vec<u8>>,
529+ au: Vec<u8>,
530+ spare: Vec<Vec<u8>>,
531+ failed: Option<crate::Error>,
532+}
533+
534+/// A finished job: its access unit, if any, copied out, and the job's buffer
535+/// back for reuse.
536+type Done = (crate::Result<Option<Vec<u8>>>, Vec<u8>);
537+
538+enum Job {
539+ Eight {
540+ bytes: Vec<u8>,
541+ y: usize,
542+ u: usize,
543+ width: u32,
544+ height: u32,
545+ key: bool,
546+ },
547+ Ten {
548+ bytes: Vec<u8>,
549+ width: u32,
550+ height: u32,
551+ key: bool,
552+ },
553+}
554+
555+/// The worker thread that owns the [`Remote`] while jobs are in flight.
556+struct Pipe {
557+ jobs: SyncSender<Job>,
558+ done: Receiver<Done>,
559+ worker: JoinHandle<Remote>,
560+ queued: usize,
561+}
562+
563+impl Pipe {
564+ fn start(remote: Remote) -> crate::Result<Self> {
565+ let (jobs, inbox) = mpsc::sync_channel(2);
566+ let (outbox, done) = mpsc::channel();
567+ let worker = std::thread::Builder::new()
568+ .name("hw-encode".to_owned())
569+ .spawn(move || serve(remote, inbox, outbox))?;
570+ Ok(Self {
571+ jobs,
572+ done,
573+ worker,
574+ queued: 0,
575+ })
576+ }
577+}
578+
579+fn serve(mut remote: Remote, inbox: Receiver<Job>, outbox: Sender<Done>) -> Remote {
580+ for job in inbox {
581+ let (result, bytes) = match job {
582+ Job::Eight {
583+ bytes,
584+ y,
585+ u,
586+ width,
587+ height,
588+ key,
589+ } => {
590+ let (ys, rest) = bytes.split_at(y);
591+ let (us, vs) = rest.split_at(u);
592+ let result = remote
593+ .encode(ys, us, vs, width, height, key)
594+ .map(|au| au.map(<[u8]>::to_vec));
595+ (result, bytes)
596+ }
597+ Job::Ten {
598+ bytes,
599+ width,
600+ height,
601+ key,
602+ } => {
603+ let result = remote
604+ .encode16_le(&bytes, width, height, key)
605+ .map(|au| au.map(<[u8]>::to_vec));
606+ (result, bytes)
607+ }
608+ };
609+ if outbox.send((result, bytes)).is_err() {
610+ break;
611+ }
612+ }
613+ remote
614+}
491 615
492 impl HwEncoder {616 impl HwEncoder {
493 /// H.264 at `width`x`height`, `fps_num / fps_den` frames per second, coded617 /// H.264 at `width`x`height`, `fps_num / fps_den` frames per second, coded
@@ -505,6 +629,7 @@ impl HwEncoder {
505 rate,629 rate,
506 ColorDescription::default(),630 ColorDescription::default(),
507 gop,631 gop,
632+ false,
508 )633 )
509 }634 }
510 635
@@ -523,6 +648,7 @@ impl HwEncoder {
523 rate,648 rate,
524 ColorDescription::default(),649 ColorDescription::default(),
525 None,650 None,
651+ false,
526 )652 )
527 }653 }
528 654
@@ -539,12 +665,14 @@ impl HwEncoder {
539 rate,665 rate,
540 ColorDescription::default(),666 ColorDescription::default(),
541 gop,667 gop,
668+ false,
542 )669 )
543 }670 }
544 671
545 /// The same, coding HEVC. `colour` is what the SPS will say the samples672 /// The same, coding HEVC. `colour` is what the SPS will say the samples
546 /// mean, and it is taken at the open because the parameter sets are written673 /// mean, and it is taken at the open because the parameter sets are written
547 /// when the sequence starts.674 /// when the sequence starts.
675+ #[allow(clippy::too_many_arguments)]
548 pub fn open_hevc(676 pub fn open_hevc(
549 width: u32,677 width: u32,
550 height: u32,678 height: u32,
@@ -553,8 +681,9 @@ impl HwEncoder {
553 rate: SeatRate,681 rate: SeatRate,
554 colour: ColorDescription,682 colour: ColorDescription,
555 gop: Option<u32>,683 gop: Option<u32>,
684+ ten_bit: bool,
556 ) -> Option<Self> {685 ) -> Option<Self> {
557- Self::seated(Seat::Hevc, width, height, fps_num, fps_den, rate, colour, gop)686+ Self::seated(Seat::Hevc, width, height, fps_num, fps_den, rate, colour, gop, ten_bit)
558 }687 }
559 688
560 /// The HEVC seat, **intra-only**: every picture an IDR, as [`Self::open_intra`]689 /// The HEVC seat, **intra-only**: every picture an IDR, as [`Self::open_intra`]
@@ -566,8 +695,9 @@ impl HwEncoder {
566 fps_den: u32,695 fps_den: u32,
567 rate: SeatRate,696 rate: SeatRate,
568 colour: ColorDescription,697 colour: ColorDescription,
698+ ten_bit: bool,
569 ) -> Option<Self> {699 ) -> Option<Self> {
570- Self::seated(Seat::HevcIntra, width, height, fps_num, fps_den, rate, colour, None)700+ Self::seated(Seat::HevcIntra, width, height, fps_num, fps_den, rate, colour, None, ten_bit)
571 }701 }
572 702
573 #[allow(clippy::too_many_arguments)]703 #[allow(clippy::too_many_arguments)]
@@ -580,6 +710,7 @@ impl HwEncoder {
580 rate: SeatRate,710 rate: SeatRate,
581 colour: ColorDescription,711 colour: ColorDescription,
582 gop: Option<u32>,712 gop: Option<u32>,
713+ ten_bit: bool,
583 ) -> Option<Self> {714 ) -> Option<Self> {
584 let open = Open {715 let open = Open {
585 seat,716 seat,
@@ -590,10 +721,18 @@ impl HwEncoder {
590 rate,721 rate,
591 colour,722 colour,
592 gop,723 gop,
724+ ten_bit,
593 };725 };
594 // No child binary beside the executable means no hardware seat at all:726 // No child binary beside the executable means no hardware seat at all:
595 // `Remote::spawn` answers `None` before a process is forked.727 // `Remote::spawn` answers `None` before a process is forked.
596- Remote::spawn(open).map(Self)728+ Remote::spawn(open).map(|remote| Self {
729+ remote: Some(remote),
730+ pipe: None,
731+ backlog: VecDeque::new(),
732+ au: Vec::new(),
733+ spare: Vec::new(),
734+ failed: None,
735+ })
597 }736 }
598 737
599 /// Feeds one tightly packed I420 picture. `Ok(None)` means the encoder has738 /// Feeds one tightly packed I420 picture. `Ok(None)` means the encoder has
@@ -616,30 +755,178 @@ impl HwEncoder {
616 if y.len() < w * h || u.len() < cw * ch || v.len() < cw * ch {755 if y.len() < w * h || u.len() < cw * ch || v.len() < cw * ch {
617 return Err("encode input is not a packed I420 frame".into());756 return Err("encode input is not a packed I420 frame".into());
618 }757 }
619- self.0.encode(y, u, v, width, height, force_key)758+ let mut bytes = self.spare.pop().unwrap_or_default();
759+ bytes.clear();
760+ bytes.extend_from_slice(y);
761+ bytes.extend_from_slice(u);
762+ bytes.extend_from_slice(v);
763+ self.submit(Job::Eight {
764+ bytes,
765+ y: y.len(),
766+ u: u.len(),
767+ width,
768+ height,
769+ key: force_key,
770+ })?;
771+ self.collect_ready()?;
772+ Ok(self.pop())
773+ }
774+
775+ /// Feeds one tightly packed 10-bit I420 picture (samples in the low 10 bits).
776+ pub fn encode16(
777+ &mut self,
778+ y: &[u16],
779+ u: &[u16],
780+ v: &[u16],
781+ width: u32,
782+ height: u32,
783+ force_key: bool,
784+ ) -> crate::Result<Option<&[u8]>> {
785+ let (w, h) = (width as usize, height as usize);
786+ let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
787+ if y.len() < w * h || u.len() < cw * ch || v.len() < cw * ch {
788+ return Err("encode input is not a packed I420 frame".into());
789+ }
790+ let mut bytes = self.spare.pop().unwrap_or_default();
791+ pack16(&y[..w * h], &u[..cw * ch], &v[..cw * ch], &mut bytes);
792+ self.submit(Job::Ten {
793+ bytes,
794+ width,
795+ height,
796+ key: force_key,
797+ })?;
798+ self.collect_ready()?;
799+ Ok(self.pop())
620 }800 }
621 801
622 /// What a decoded buffer must look like to reach this encoder without a802 /// What a decoded buffer must look like to reach this encoder without a
623 /// copy, or `None` where the child has no zero-copy door at all.803 /// copy, or `None` where the child has no zero-copy door at all.
624 pub fn dma_want(&mut self, width: u32, height: u32) -> Option<DmaWant> {804 pub fn dma_want(&mut self, width: u32, height: u32) -> Option<DmaWant> {
625- let (coded_width, coded_height) = self.0.dma_geometry()?;805+ let remote = match self.settled() {
806+ Ok(remote) => remote,
807+ Err(e) => {
808+ self.failed = Some(e);
809+ return None;
810+ }
811+ };
812+ let (coded_width, coded_height) = remote.dma_geometry()?;
626 Some(DmaWant {813 Some(DmaWant {
627 coded_width,814 coded_width,
628 coded_height,815 coded_height,
629 width,816 width,
630 height,817 height,
818+ ten_bit: false,
631 })819 })
632 }820 }
633 821
634 /// Feeds one picture the decoder left on the GPU. The descriptors go over822 /// Feeds one picture the decoder left on the GPU. The descriptors go over
635 /// with the message, so the buffer itself never moves.823 /// with the message, so the buffer itself never moves.
636 pub fn encode_dma(&mut self, dma: &DmaFrame, force_key: bool) -> crate::Result<Option<&[u8]>> {824 pub fn encode_dma(&mut self, dma: &DmaFrame, force_key: bool) -> crate::Result<Option<&[u8]>> {
637- self.0.encode_dma(dma, force_key)825+ let au = self.settled()?.encode_dma(dma, force_key)?.map(<[u8]>::to_vec);
826+ if let Some(au) = au {
827+ self.backlog.push_back(au);
828+ }
829+ Ok(self.pop())
638 }830 }
639 831
640 /// Flushes the encoder; call until it returns `Ok(None)`.832 /// Flushes the encoder; call until it returns `Ok(None)`.
641 pub fn drain(&mut self) -> crate::Result<Option<&[u8]>> {833 pub fn drain(&mut self) -> crate::Result<Option<&[u8]>> {
642- self.0.drain()834+ self.settle()?;
835+ if !self.backlog.is_empty() {
836+ return Ok(self.pop());
837+ }
838+ let remote = self.remote.as_mut().ok_or("the hardware encoder was lost")?;
839+ let Some(au) = remote.drain()? else {
840+ return Ok(None);
841+ };
842+ self.au.clear();
843+ self.au.extend_from_slice(au);
844+ Ok(Some(&self.au))
845+ }
846+
847+ fn submit(&mut self, job: Job) -> crate::Result<()> {
848+ if let Some(e) = self.failed.take() {
849+ return Err(e);
850+ }
851+ if self.pipe.is_none() {
852+ let remote = self.remote.take().ok_or("the hardware encoder was lost")?;
853+ self.pipe = Some(Pipe::start(remote)?);
854+ }
855+ let pipe = self.pipe.as_mut().ok_or("the hw encode pipe is missing")?;
856+ pipe.jobs.send(job).map_err(|_| "the hw encode worker panicked")?;
857+ pipe.queued += 1;
858+ Ok(())
859+ }
860+
861+ fn collect_ready(&mut self) -> crate::Result<()> {
862+ loop {
863+ let Some(pipe) = self.pipe.as_mut() else {
864+ return Ok(());
865+ };
866+ let finished = match pipe.done.try_recv() {
867+ Ok(finished) => finished,
868+ Err(TryRecvError::Empty) => return Ok(()),
869+ Err(TryRecvError::Disconnected) => return Err("the hw encode worker panicked".into()),
870+ };
871+ pipe.queued -= 1;
872+ self.finish(finished)?;
873+ }
874+ }
875+
876+ fn finish(&mut self, (result, bytes): Done) -> crate::Result<()> {
877+ if self.spare.len() < 3 {
878+ self.spare.push(bytes);
879+ }
880+ if let Some(au) = result? {
881+ self.backlog.push_back(au);
882+ }
883+ Ok(())
884+ }
885+
886+ /// Waits for every queued job, keeps their access units in order, and takes
887+ /// the [`Remote`] back from the worker. The first error is returned.
888+ fn settle(&mut self) -> crate::Result<()> {
889+ if let Some(e) = self.failed.take() {
890+ return Err(e);
891+ }
892+ let Some(pipe) = self.pipe.take() else {
893+ return Ok(());
894+ };
895+ let Pipe {
896+ jobs,
897+ done,
898+ worker,
899+ mut queued,
900+ } = pipe;
901+ drop(jobs);
902+ let mut first: Option<crate::Error> = None;
903+ while queued > 0 {
904+ let Ok(finished) = done.recv() else {
905+ break;
906+ };
907+ queued -= 1;
908+ if let Err(e) = self.finish(finished) {
909+ first = first.or(Some(e));
910+ }
911+ }
912+ match worker.join() {
913+ Ok(remote) => self.remote = Some(remote),
914+ Err(_) => first = first.or(Some("the hw encode worker panicked".into())),
915+ }
916+ match first {
917+ Some(e) => Err(e),
918+ None => Ok(()),
919+ }
920+ }
921+
922+ fn settled(&mut self) -> crate::Result<&mut Remote> {
923+ self.settle()?;
924+ self.remote.as_mut().ok_or_else(|| "the hardware encoder was lost".into())
925+ }
926+
927+ fn pop(&mut self) -> Option<&[u8]> {
928+ self.au = self.backlog.pop_front()?;
929+ Some(&self.au)
643 }930 }
644 }931 }
645 932
crates/engine/src/hwproc.rsmodified+104 -12
@@ -137,6 +137,8 @@ pub struct Open {
137 pub colour: ColorDescription,137 pub colour: ColorDescription,
138 /// Pictures between key frames; `None` is the seat's own two seconds.138 /// Pictures between key frames; `None` is the seat's own two seconds.
139 pub gop: Option<u32>,139 pub gop: Option<u32>,
140+ /// Code at 10 bits (HEVC Main10): pictures arrive as 16-bit LE samples.
141+ pub ten_bit: bool,
140 }142 }
141 143
142 impl Open {144 impl Open {
@@ -170,6 +172,7 @@ impl Open {
170 SeatRate::ConstantQp(qp) => [1, u64::from(qp)],172 SeatRate::ConstantQp(qp) => [1, u64::from(qp)],
171 }.map(|v| v.to_string()))173 }.map(|v| v.to_string()))
172 .chain(std::iter::once(self.gop.unwrap_or(0).to_string()))174 .chain(std::iter::once(self.gop.unwrap_or(0).to_string()))
175+ .chain(std::iter::once(u8::from(self.ten_bit).to_string()))
173 .collect()176 .collect()
174 }177 }
175 178
@@ -207,6 +210,7 @@ impl Open {
207 0 => None,210 0 => None,
208 gop => Some(gop),211 gop => Some(gop),
209 },212 },
213+ ten_bit: n(11)? != 0,
210 })214 })
211 }215 }
212 216
@@ -215,7 +219,8 @@ impl Open {
215 /// canvas size for the whole file.219 /// canvas size for the whole file.
216 pub fn frame_bytes(&self) -> usize {220 pub fn frame_bytes(&self) -> usize {
217 let (w, h) = (self.width as usize, self.height as usize);221 let (w, h) = (self.width as usize, self.height as usize);
218- w * h + 2 * (w.div_ceil(2) * h.div_ceil(2))222+ let samples = w * h + 2 * (w.div_ceil(2) * h.div_ceil(2));
223+ if self.ten_bit { samples * 2 } else { samples }
219 }224 }
220 }225 }
221 226
@@ -224,12 +229,16 @@ pub const T_ENCODE: u8 = 1;
224 pub const T_DMA: u8 = 2;229 pub const T_DMA: u8 = 2;
225 pub const T_DRAIN: u8 = 3;230 pub const T_DRAIN: u8 = 3;
226 pub const T_GEOM: u8 = 4;231 pub const T_GEOM: u8 = 4;
232+pub const T_ENCODE16: u8 = 8;
227 // Requests, parent to child (decode seat). `T_NEXT` has no body, `T_NEXT_DMA`233 // Requests, parent to child (decode seat). `T_NEXT` has no body, `T_NEXT_DMA`
228 // carries `coded_width, coded_height, width, height` as u32 LE, `T_SEEK` the234 // carries `coded_width, coded_height, width, height` as u32 LE, `T_SEEK` the
229 // 1-based target sample as u32 LE.235 // 1-based target sample as u32 LE.
230 pub const T_NEXT: u8 = 5;236 pub const T_NEXT: u8 = 5;
231 pub const T_NEXT_DMA: u8 = 6;237 pub const T_NEXT_DMA: u8 = 6;
232 pub const T_SEEK: u8 = 7;238 pub const T_SEEK: u8 = 7;
239+/// `T_NEXT`, but a picture deeper than 8 bits comes back as `K_PIXELS16`.
240+pub const T_NEXT_WIDE: u8 = 9;
241+pub const T_NEXT_DMA16: u8 = 10;
233 // Replies, child to parent. `R_NONE` carries no body; `R_AU` and `R_ERR` carry242 // Replies, child to parent. `R_NONE` carries no body; `R_AU` and `R_ERR` carry
234 // a u32 LE length and that many bytes. Descriptors ride on the tag byte.243 // a u32 LE length and that many bytes. Descriptors ride on the tag byte.
235 pub const R_NONE: u8 = 0;244 pub const R_NONE: u8 = 0;
@@ -241,6 +250,8 @@ pub const R_ERR: u8 = 2;
241 // descriptors ride on the tag byte, one per plane object).250 // descriptors ride on the tag byte, one per plane object).
242 pub const K_PIXELS: u8 = 0;251 pub const K_PIXELS: u8 = 0;
243 pub const K_DMA: u8 = 1;252 pub const K_DMA: u8 = 1;
253+/// As `K_PIXELS`, with 16-bit LE samples at 10-bit scale.
254+pub const K_PIXELS16: u8 = 2;
244 /// The `K_DMA` descriptor after its kind byte: fourcc u32, modifier u64, coded255 /// The `K_DMA` descriptor after its kind byte: fourcc u32, modifier u64, coded
245 /// width and height, picture width and height, two offsets and two strides as256 /// width and height, picture width and height, two offsets and two strides as
246 /// u32 each, then the number of descriptors (1 or 2) as one byte.257 /// u32 each, then the number of descriptors (1 or 2) as one byte.
@@ -302,11 +313,22 @@ impl Shm {
302 "a read past the end of the staging buffer",313 "a read past the end of the staging buffer",
303 ));314 ));
304 }315 }
305- into.clear();
306 into.resize(len, 0);316 into.resize(len, 0);
307 self.file.read_exact_at(into, 0)317 self.file.read_exact_at(into, 0)
308 }318 }
309 319
320+ pub fn read_u16(&self, offset: usize, count: usize) -> std::io::Result<Vec<u16>> {
321+ if offset + 2 * count > self.len {
322+ return Err(std::io::Error::new(
323+ std::io::ErrorKind::InvalidInput,
324+ "a read past the end of the staging buffer",
325+ ));
326+ }
327+ let mut out = vec![0u16; count];
328+ self.file.read_exact_at(bytemuck::cast_slice_mut(&mut out), offset as u64)?;
329+ Ok(out)
330+ }
331+
310 /// Reads the first `len` bytes of the buffer into an owned one.332 /// Reads the first `len` bytes of the buffer into an owned one.
311 pub fn read_bytes(&self, len: usize) -> std::io::Result<Vec<u8>> {333 pub fn read_bytes(&self, len: usize) -> std::io::Result<Vec<u8>> {
312 if len > self.len {334 if len > self.len {
@@ -331,14 +353,18 @@ pub fn send_msg(sock: &UnixStream, bytes: &[u8], fds: &[RawFd]) -> std::io::Resu
331 debug_assert!(!bytes.is_empty(), "ancillary data rides on a real byte");353 debug_assert!(!bytes.is_empty(), "ancillary data rides on a real byte");
332 let rights = [ControlMessage::ScmRights(fds)];354 let rights = [ControlMessage::ScmRights(fds)];
333 let control: &[ControlMessage] = if fds.is_empty() { &[] } else { &rights };355 let control: &[ControlMessage] = if fds.is_empty() { &[] } else { &rights };
334- let sent = sendmsg::<UnixAddr>(356+ let sent = loop {
335- sock.as_raw_fd(),357+ match sendmsg::<UnixAddr>(
336- &[IoSlice::new(bytes)],358+ sock.as_raw_fd(),
337- control,359+ &[IoSlice::new(bytes)],
338- MsgFlags::MSG_NOSIGNAL,360+ control,
339- None,361+ MsgFlags::MSG_NOSIGNAL,
340- )362+ None,
341- .map_err(std::io::Error::from)?;363+ ) {
364+ Err(nix::errno::Errno::EINTR) => continue,
365+ other => break other.map_err(std::io::Error::from)?,
366+ }
367+ };
342 // Messages here are tens of bytes and a socket buffer is kilobytes, so a368 // Messages here are tens of bytes and a socket buffer is kilobytes, so a
343 // short send means the peer is gone rather than that we should loop.369 // short send means the peer is gone rather than that we should loop.
344 if sent != bytes.len() {370 if sent != bytes.len() {
@@ -360,8 +386,12 @@ pub fn recv_tag(sock: &UnixStream) -> std::io::Result<(u8, Vec<OwnedFd>)> {
360 // Room for four descriptors; the most anything here sends is two.386 // Room for four descriptors; the most anything here sends is two.
361 let mut space = [MaybeUninit::uninit(); rustix::cmsg_space!(ScmRights(4))];387 let mut space = [MaybeUninit::uninit(); rustix::cmsg_space!(ScmRights(4))];
362 let mut control = RecvAncillaryBuffer::new(&mut space);388 let mut control = RecvAncillaryBuffer::new(&mut space);
363- let received = rustix::net::recvmsg(sock, &mut iov, &mut control, RecvFlags::CMSG_CLOEXEC)389+ let received = loop {
364- .map_err(std::io::Error::from)?;390+ match rustix::net::recvmsg(sock, &mut iov, &mut control, RecvFlags::CMSG_CLOEXEC) {
391+ Err(rustix::io::Errno::INTR) => continue,
392+ other => break other.map_err(std::io::Error::from)?,
393+ }
394+ };
365 if received.bytes == 0 {395 if received.bytes == 0 {
366 return Err(std::io::Error::new(396 return Err(std::io::Error::new(
367 std::io::ErrorKind::UnexpectedEof,397 std::io::ErrorKind::UnexpectedEof,
@@ -523,6 +553,24 @@ pub fn faked() -> bool {
523 crate::envcfg::var_os("VE_HW_TEST_FAKE").is_some()553 crate::envcfg::var_os("VE_HW_TEST_FAKE").is_some()
524 }554 }
525 555
556+/// Packs Y, U and V samples as 16-bit LE, back to back, into `out`.
557+const _: () = assert!(cfg!(target_endian = "little"));
558+
559+pub fn pack16(y: &[u16], u: &[u16], v: &[u16], out: &mut Vec<u8>) {
560+ out.clear();
561+ out.reserve(2 * (y.len() + u.len() + v.len()));
562+ for plane in [y, u, v] {
563+ out.extend_from_slice(bytemuck::cast_slice(plane));
564+ }
565+}
566+
567+pub fn unpack16(bytes: &[u8]) -> Vec<u16> {
568+ let n = bytes.len() / 2;
569+ let mut out = vec![0u16; n];
570+ bytemuck::cast_slice_mut(&mut out).copy_from_slice(&bytes[..2 * n]);
571+ out
572+}
573+
526 /// A hardware encode session living in another process.574 /// A hardware encode session living in another process.
527 pub struct Remote {575 pub struct Remote {
528 child: Child,576 child: Child,
@@ -672,6 +720,49 @@ impl Remote {
672 self.round_trip(&msg, &[])720 self.round_trip(&msg, &[])
673 }721 }
674 722
723+ /// Feeds one 10-bit picture (samples in the low 10 bits) through the shared mapping.
724+ pub fn encode16(
725+ &mut self,
726+ y: &[u16],
727+ u: &[u16],
728+ v: &[u16],
729+ width: u32,
730+ height: u32,
731+ force_key: bool,
732+ ) -> crate::Result<Option<&[u8]>> {
733+ let mut bytes = Vec::new();
734+ pack16(y, u, v, &mut bytes);
735+ self.encode16_le(&bytes, width, height, force_key)
736+ }
737+
738+ /// Feeds one picture already packed as 16-bit LE samples, Y then U then V.
739+ pub fn encode16_le(
740+ &mut self,
741+ bytes: &[u8],
742+ width: u32,
743+ height: u32,
744+ force_key: bool,
745+ ) -> crate::Result<Option<&[u8]>> {
746+ let Some(shm) = self.shm.as_ref() else {
747+ return Err("the staging buffer was never opened".to_owned().into());
748+ };
749+ if bytes.len() > shm.capacity() {
750+ return Err(format!(
751+ "a {width}x{height} picture does not fit the staging buffer opened for {}x{}",
752+ self.open.width, self.open.height
753+ )
754+ .into());
755+ }
756+ if let Err(e) = shm.write_picture(&[bytes]) {
757+ return Err(format!("cannot stage the picture: {e}").into());
758+ }
759+ let mut msg = vec![T_ENCODE16];
760+ msg.extend_from_slice(&width.to_le_bytes());
761+ msg.extend_from_slice(&height.to_le_bytes());
762+ msg.push(u8::from(force_key));
763+ self.round_trip(&msg, &[])
764+ }
765+
675 /// Feeds one picture the decoder left on the GPU. The descriptors go over766 /// Feeds one picture the decoder left on the GPU. The descriptors go over
676 /// with the message, so the buffer itself never moves.767 /// with the message, so the buffer itself never moves.
677 pub fn encode_dma(&mut self, frame: &DmaFrame, force_key: bool) -> crate::Result<Option<&[u8]>> {768 pub fn encode_dma(&mut self, frame: &DmaFrame, force_key: bool) -> crate::Result<Option<&[u8]>> {
@@ -818,6 +909,7 @@ mod tests {
818 full_range: true,909 full_range: true,
819 },910 },
820 gop: Some(15),911 gop: Some(15),
912+ ten_bit: false,
821 };913 };
822 let back = Open::from_argv(&open.argv()).expect("parse");914 let back = Open::from_argv(&open.argv()).expect("parse");
823 assert!(back.seat == Seat::Hevc);915 assert!(back.seat == Seat::Hevc);
crates/engine/tests/hw_encode.rsmodified+1 -1
@@ -269,7 +269,7 @@ fn a_decoded_buffer_is_encoded_without_ever_being_read_back() {
269 stream.extend_from_slice(au);269 stream.extend_from_slice(au);
270 }270 }
271 }271 }
272- Some(HwPicture::Pixels(..)) => panic!("frame {index} was read back after all"),272+ Some(HwPicture::Pixels(..) | HwPicture::Wide(..)) => panic!("frame {index} was read back after all"),
273 None => panic!("the fixture ran out at frame {index}"),273 None => panic!("the fixture ran out at frame {index}"),
274 }274 }
275 }275 }
crates/engine/tests/it/export_ten_bit.rsmodified+46 -0
@@ -473,3 +473,49 @@ fn a_bt2020_sdr_ten_bit_source_exports_with_its_own_colour() {
473 }473 }
474 let _ = std::fs::remove_dir_all(&dir);474 let _ = std::fs::remove_dir_all(&dir);
475 }475 }
476+
477+#[test]
478+fn a_ten_bit_hevc_export_takes_the_hardware_seat_at_a_constant_qp() {
479+ let (Some(encoder), true, true) = (source_encoder(), have("ffmpeg"), have("ffprobe")) else {
480+ eprintln!("no ffmpeg with a source encoder: skipping");
481+ return;
482+ };
483+ let dir = scratch("ten-bit-hevc-hw");
484+ let source = dir.join("source10.mkv");
485+ let made = Command::new("ffmpeg")
486+ .args(["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=size=640x480:rate=25:duration=1"])
487+ .args(["-pix_fmt", "yuv420p10le"])
488+ .args(codec_args(encoder))
489+ .arg(&source)
490+ .status()
491+ .is_ok_and(|s| s.success());
492+ assert!(made, "ffmpeg makes the 10-bit source");
493+ let session = PlaybackSession::open(&source).expect("open the source");
494+ let out = dir.join("ten.mp4");
495+ let settings = ExportSettings {
496+ format: Format::HevcMp4,
497+ video_bit_depth: Some(10),
498+ seat: engine::export::EncoderSeat::Hardware,
499+ qp: Some(12),
500+ ..Default::default()
501+ };
502+ let handle = session.export_to_with(&out, &settings);
503+ let started = Instant::now();
504+ while !handle.is_finished() {
505+ assert!(started.elapsed() < Duration::from_secs(600), "the export did not finish in 600 s");
506+ std::thread::sleep(Duration::from_millis(20));
507+ }
508+ match handle.result().expect("an outcome") {
509+ Err(e) if e.to_string().contains("no VA-API seat") => {
510+ eprintln!("no 10-bit HEVC hardware seat here: {e}");
511+ return;
512+ }
513+ other => other.expect("the export"),
514+ };
515+ assert_eq!(pix_fmt(&out), "yuv420p10le");
516+ assert_eq!(profile(&out), "Main 10");
517+ let psnr = psnr_10(&decoded(&source, "yuv420p10le"), &decoded(&out, "yuv420p10le"));
518+ eprintln!("hardware HEVC Main 10 at qp 12: {psnr:.2} dB");
519+ assert!(psnr > 40.0, "{psnr:.2} dB against the source");
520+ let _ = std::fs::remove_dir_all(&dir);
521+}
crates/engine/tests/it/hw_fallback.rsmodified+1 -0
@@ -30,6 +30,7 @@ fn span(path: &PathBuf, start: u32, end: u32) -> Vec<(u32, Vec<u8>)> {
30 30
31 #[test]31 #[test]
32 fn a_hardware_error_mid_span_continues_in_software_with_the_same_frames() {32 fn a_hardware_error_mid_span_continues_in_software_with_the_same_frames() {
33+ let _seat = crate::seat::hardware();
33 hwchild::require();34 hwchild::require();
34 for (name, start, end, fail_after) in [35 for (name, start, end, fail_after) in [
35 ("test_25fps.mp4", 0, 50, 17),36 ("test_25fps.mp4", 0, 50, 17),
crates/engine/tests/it/hw_midgop_seek.rsmodified+1 -0
@@ -53,6 +53,7 @@ fn take(hw: &mut HwSession, count: usize) -> Vec<Picture> {
53 /// Asserts that a fresh open at each target, and a seek on a live session to53 /// Asserts that a fresh open at each target, and a seek on a live session to
54 /// each target, hands back the sequential decode's pictures exactly.54 /// each target, hands back the sequential decode's pictures exactly.
55 fn check_midgop(name: &str, targets: &[usize]) {55 fn check_midgop(name: &str, targets: &[usize]) {
56+ let _seat = crate::seat::hardware();
56 // `require()` has already panicked if a render node exists without57 // `require()` has already panicked if a render node exists without
57 // `hw-child`, so a session that does not open here means no usable VA-API58 // `hw-child`, so a session that does not open here means no usable VA-API
58 // driver or profile: a skip, as on a machine with no GPU.59 // driver or profile: a skip, as on a machine with no GPU.