The picture the GPU decoded is the picture it encodes
Browse files at this commit366171bcaba613700f235adc1782d4355fd3bdbcParent: 267d45b- perf
- the picture the GPU decoded is the picture it encodes
4 changed files +806 -93
- crates/engine-hw/src/lib.rs +311 -3
- crates/engine/src/export.rs +218 -87
- crates/engine/src/hw.rs +200 -2
- crates/engine/tests/hw_encode.rs +77 -1
crates/engine-hw/src/lib.rsmodified+311 -3
| @@ -12,6 +12,7 @@ | |||
| 12 | 12 | ||
| 13 | use std::collections::VecDeque; | 13 | use std::collections::VecDeque; |
| 14 | use std::ffi::{CStr, c_char, c_void}; | 14 | use std::ffi::{CStr, c_char, c_void}; |
| 15 | +use std::os::fd::IntoRawFd; | ||
| 15 | use std::panic::{AssertUnwindSafe, catch_unwind}; | 16 | use std::panic::{AssertUnwindSafe, catch_unwind}; |
| 16 | use std::path::{Path, PathBuf}; | 17 | use std::path::{Path, PathBuf}; |
| 17 | use std::rc::Rc; | 18 | use std::rc::Rc; |
| @@ -49,7 +50,7 @@ use cros_codecs::{Fourcc, FrameLayout, PlaneLayout, Resolution}; | |||
| 49 | use gbm::{BufferObjectFlags, Format as GbmFormat}; | 50 | use gbm::{BufferObjectFlags, Format as GbmFormat}; |
| 50 | 51 | ||
| 51 | use engine::demux::{Codec, Demuxer}; | 52 | use engine::demux::{Codec, Demuxer}; |
| 52 | -use engine::hw::{CAP_AV1, CAP_H264, CAP_HEVC, CAP_VP9, VhCaps, VhFrame, VhMeta}; | 53 | +use engine::hw::{CAP_AV1, CAP_H264, CAP_HEVC, CAP_VP9, VhCaps, VhDma, VhFrame, VhMeta}; |
| 53 | 54 | ||
| 54 | type PooledFrame = PooledVideoFrame<GenericDmaVideoFrame>; | 55 | type PooledFrame = PooledVideoFrame<GenericDmaVideoFrame>; |
| 55 | type Dec<C> = StatelessDecoder<C, VaapiBackend<PooledFrame>>; | 56 | type Dec<C> = StatelessDecoder<C, VaapiBackend<PooledFrame>>; |
| @@ -118,6 +119,13 @@ const STALL_LIMIT: u32 = 10_000; | |||
| 118 | /// hears it. | 119 | /// hears it. |
| 119 | const LEADING_LIMIT: u32 = 64; | 120 | const LEADING_LIMIT: u32 = 64; |
| 120 | 121 | ||
| 122 | +/// How many pictures handed out as DRM-PRIME buffers stay un-decoded-over, and | ||
| 123 | +/// therefore how many extra buffers the pool reserves the moment a caller asks | ||
| 124 | +/// for one. The export's decode channel is two pictures deep and it encodes the | ||
| 125 | +/// one it is holding, so at most four are ever outstanding; the rest is margin, | ||
| 126 | +/// at ~3 MB of video memory each. | ||
| 127 | +const DMA_HOLD: usize = 6; | ||
| 128 | + | ||
| 121 | struct Session { | 129 | struct Session { |
| 122 | decoder: Decoder, | 130 | decoder: Decoder, |
| 123 | /// NV12 (or, for a 10-bit stream, P010) descriptor for `vaGetImage`, | 131 | /// NV12 (or, for a 10-bit stream, P010) descriptor for `vaGetImage`, |
| @@ -146,6 +154,25 @@ struct Session { | |||
| 146 | out: Vec<u8>, | 154 | out: Vec<u8>, |
| 147 | luma: usize, | 155 | luma: usize, |
| 148 | chroma: usize, | 156 | chroma: usize, |
| 157 | + /// What the caller's encoder can read straight off the GPU, asked once per | ||
| 158 | + /// [`vh_next_frame_dma`] call and `None` for every read-back caller. | ||
| 159 | + want: Option<VhDma>, | ||
| 160 | + /// The descriptor the last such call produced, its file descriptor already | ||
| 161 | + /// belonging to the caller. `None` says that picture was read back instead. | ||
| 162 | + dma: Option<VhDma>, | ||
| 163 | + /// Pictures handed out as DRM-PRIME buffers, newest last: the pool takes a | ||
| 164 | + /// buffer back the moment its handle drops, and the decoder would write the | ||
| 165 | + /// next picture straight into the one an encoder is still reading. Bounded | ||
| 166 | + /// by [`Session::hold`], which is what the pool reserved for it. | ||
| 167 | + held: VecDeque<Handle>, | ||
| 168 | + /// Extra pool buffers reserved for [`Session::held`]: [`DMA_HOLD`] once a | ||
| 169 | + /// caller has asked for a buffer *before* the pool was sized, and 0 | ||
| 170 | + /// otherwise -- a session whose pool is already sized may not hold anything | ||
| 171 | + /// back, because those buffers are the decoder's own. | ||
| 172 | + hold: usize, | ||
| 173 | + /// Whether the pool has been sized, which happens once, at the first | ||
| 174 | + /// `FormatChanged`. | ||
| 175 | + sized: bool, | ||
| 149 | } | 176 | } |
| 150 | 177 | ||
| 151 | /// Mesa's GBM cannot allocate an NV12 buffer object at all (measured on | 178 | /// Mesa's GBM cannot allocate an NV12 buffer object at all (measured on |
| @@ -288,6 +315,11 @@ impl Session { | |||
| 288 | out: Vec::new(), | 315 | out: Vec::new(), |
| 289 | luma: 0, | 316 | luma: 0, |
| 290 | chroma: 0, | 317 | chroma: 0, |
| 318 | + want: None, | ||
| 319 | + dma: None, | ||
| 320 | + held: VecDeque::new(), | ||
| 321 | + hold: 0, | ||
| 322 | + sized: false, | ||
| 291 | }) | 323 | }) |
| 292 | } | 324 | } |
| 293 | 325 | ||
| @@ -318,13 +350,18 @@ impl Session { | |||
| 318 | match self.decoder.get().next_event() { | 350 | match self.decoder.get().next_event() { |
| 319 | Some(DecoderEvent::FrameReady(handle)) => self.ready.push_back(handle), | 351 | Some(DecoderEvent::FrameReady(handle)) => self.ready.push_back(handle), |
| 320 | Some(DecoderEvent::FormatChanged) => { | 352 | Some(DecoderEvent::FormatChanged) => { |
| 321 | - let info = self | 353 | + let mut info = self |
| 322 | .decoder | 354 | .decoder |
| 323 | .get() | 355 | .get() |
| 324 | .stream_info() | 356 | .stream_info() |
| 325 | .ok_or("format changed without stream info")? | 357 | .ok_or("format changed without stream info")? |
| 326 | .clone(); | 358 | .clone(); |
| 359 | + // The buffers a caller may hold on to are *extra*: the | ||
| 360 | + // count the decoder asks for is what it needs to keep | ||
| 361 | + // decoding, and lending one of those out is a stall. | ||
| 362 | + info.min_num_frames += self.hold; | ||
| 327 | self.pool.resize(&info); | 363 | self.pool.resize(&info); |
| 364 | + self.sized = true; | ||
| 328 | } | 365 | } |
| 329 | None => break, | 366 | None => break, |
| 330 | } | 367 | } |
| @@ -336,7 +373,7 @@ impl Session { | |||
| 336 | self.skip -= 1; | 373 | self.skip -= 1; |
| 337 | continue; | 374 | continue; |
| 338 | } | 375 | } |
| 339 | - self.emit(handle); | 376 | + self.deliver(handle); |
| 340 | // Past the random access point's leading pictures: a decode | 377 | // Past the random access point's leading pictures: a decode |
| 341 | // error from here on is a real one again. | 378 | // error from here on is a real one again. |
| 342 | self.leading = LEADING_LIMIT; | 379 | self.leading = LEADING_LIMIT; |
| @@ -405,6 +442,84 @@ impl Session { | |||
| 405 | } | 442 | } |
| 406 | } | 443 | } |
| 407 | 444 | ||
| 445 | + /// Hands one decoded picture to the caller: as the buffer it was decoded | ||
| 446 | + /// into where that is what the caller asked for and the encoder on the | ||
| 447 | + /// other side can read it, and as read-back I420 everywhere else. | ||
| 448 | + fn deliver(&mut self, handle: Handle) { | ||
| 449 | + self.dma = None; | ||
| 450 | + if self.hold > 0 && let Some(dma) = self.export_dma(&handle) { | ||
| 451 | + self.meta.width = dma.width; | ||
| 452 | + self.meta.height = dma.height; | ||
| 453 | + self.dma = Some(dma); | ||
| 454 | + // Kept out of the pool until the caller is [`DMA_HOLD`] pictures | ||
| 455 | + // past it, by which time nothing is reading it any more. | ||
| 456 | + self.held.push_back(handle); | ||
| 457 | + while self.held.len() > self.hold { | ||
| 458 | + self.held.pop_front(); | ||
| 459 | + } | ||
| 460 | + return; | ||
| 461 | + } | ||
| 462 | + self.emit(handle); | ||
| 463 | + } | ||
| 464 | + | ||
| 465 | + /// This picture's surface as a DRM-PRIME buffer, if it *is* the shape the | ||
| 466 | + /// caller's encoder takes -- one composed two-plane layer in at most two | ||
| 467 | + /// objects, the fourcc and both sizes it asked for. `None` for every other | ||
| 468 | + /// answer, and the caller then gets the pixels it always got rather than a | ||
| 469 | + /// failure. | ||
| 470 | + fn export_dma(&self, handle: &Handle) -> Option<VhDma> { | ||
| 471 | + let want = self.want?; | ||
| 472 | + let res = handle.display_resolution(); | ||
| 473 | + if (res.width, res.height) != (want.width, want.height) { | ||
| 474 | + return None; | ||
| 475 | + } | ||
| 476 | + // Cheap no-op in blocking mode, but the encoder must never read a | ||
| 477 | + // surface the decoder has not finished writing. | ||
| 478 | + let _ = DecodedHandle::sync(handle); | ||
| 479 | + let borrowed = handle.borrow(); | ||
| 480 | + // The *display* surface for the same reason [`Session::emit`] reads it: | ||
| 481 | + // an AV1 picture with film grain is displayed from a second surface. | ||
| 482 | + let mut desc = borrowed.display_surface().export_prime().ok()?; | ||
| 483 | + let layer = desc.layers.first()?; | ||
| 484 | + if desc.layers.len() != 1 | ||
| 485 | + || layer.num_planes != 2 | ||
| 486 | + || desc.fourcc != want.fourcc | ||
| 487 | + || desc.width != want.coded_width | ||
| 488 | + || desc.height != want.coded_height | ||
| 489 | + { | ||
| 490 | + return None; | ||
| 491 | + } | ||
| 492 | + // Whatever the driver says the two planes live in, said back to it | ||
| 493 | + // unchanged on the import: radeonsi answers with an object per plane, | ||
| 494 | + // other drivers with one for both, and neither is ours to reinterpret. | ||
| 495 | + let (offset, stride) = ( | ||
| 496 | + [layer.offset[0], layer.offset[1]], | ||
| 497 | + [layer.pitch[0], layer.pitch[1]], | ||
| 498 | + ); | ||
| 499 | + let planes = [layer.object_index[0] as usize, layer.object_index[1] as usize]; | ||
| 500 | + if planes[0] != 0 || planes[1] > 1 || desc.objects.len() != planes[1] + 1 { | ||
| 501 | + return None; | ||
| 502 | + } | ||
| 503 | + let modifier = desc.objects[0].drm_format_modifier; | ||
| 504 | + // Handed over with the descriptor: the caller closes them. | ||
| 505 | + let second = (planes[1] == 1) | ||
| 506 | + .then(|| desc.objects.pop().map(|object| object.fd.into_raw_fd())) | ||
| 507 | + .flatten() | ||
| 508 | + .unwrap_or(-1); | ||
| 509 | + let first = desc.objects.remove(0).fd.into_raw_fd(); | ||
| 510 | + Some(VhDma { | ||
| 511 | + fd: [first, second], | ||
| 512 | + fourcc: desc.fourcc, | ||
| 513 | + modifier, | ||
| 514 | + coded_width: desc.width, | ||
| 515 | + coded_height: desc.height, | ||
| 516 | + width: res.width, | ||
| 517 | + height: res.height, | ||
| 518 | + offset, | ||
| 519 | + stride, | ||
| 520 | + }) | ||
| 521 | + } | ||
| 522 | + | ||
| 408 | /// Copies a decoded NV12 surface into `self.out` as packed I420. | 523 | /// Copies a decoded NV12 surface into `self.out` as packed I420. |
| 409 | fn emit(&mut self, handle: Handle) { | 524 | fn emit(&mut self, handle: Handle) { |
| 410 | let res = handle.display_resolution(); | 525 | let res = handle.display_resolution(); |
| @@ -599,6 +714,74 @@ pub unsafe extern "C" fn vh_next_frame(session: *mut c_void, out: *mut VhFrame) | |||
| 599 | .unwrap_or(-1) | 714 | .unwrap_or(-1) |
| 600 | } | 715 | } |
| 601 | 716 | ||
| 717 | +/// As [`vh_next_frame`], but hands the picture over *on the GPU* where it can | ||
| 718 | +/// be: `dma` is filled and its `fd` belongs to the caller (who closes it) when | ||
| 719 | +/// the decoded surface is exactly what an encoder of `coded_width` x | ||
| 720 | +/// `coded_height` carrying a `width` x `height` picture reads, and `out` is | ||
| 721 | +/// filled with read-back I420 exactly as [`vh_next_frame`] fills it otherwise. | ||
| 722 | +/// `dma.fd` below zero is what says which happened. | ||
| 723 | +/// | ||
| 724 | +/// The buffer stays out of the decoder's pool for [`DMA_HOLD`] further | ||
| 725 | +/// pictures and no longer: encode it before asking for that many more. Only a | ||
| 726 | +/// session that has never read a frame back may hand buffers over at all -- | ||
| 727 | +/// those extra pool buffers are reserved at the first picture, and a decoder | ||
| 728 | +/// robbed of its own would stall. | ||
| 729 | +/// | ||
| 730 | +/// # Safety | ||
| 731 | +/// `session` must come from [`vh_open_at`]; `out` and `dma` must be writable. | ||
| 732 | +#[unsafe(no_mangle)] | ||
| 733 | +pub unsafe extern "C" fn vh_next_frame_dma( | ||
| 734 | + session: *mut c_void, | ||
| 735 | + out: *mut VhFrame, | ||
| 736 | + dma: *mut VhDma, | ||
| 737 | + coded_width: u32, | ||
| 738 | + coded_height: u32, | ||
| 739 | + width: u32, | ||
| 740 | + height: u32, | ||
| 741 | +) -> i32 { | ||
| 742 | + catch_unwind(AssertUnwindSafe(|| { | ||
| 743 | + if session.is_null() || out.is_null() || dma.is_null() { | ||
| 744 | + return -1; | ||
| 745 | + } | ||
| 746 | + // SAFETY: caller-guaranteed live session and writable destinations. | ||
| 747 | + let session = unsafe { &mut *(session as *mut Session) }; | ||
| 748 | + // SAFETY: as above. | ||
| 749 | + unsafe { *dma = VhDma::default() }; | ||
| 750 | + // A pool sized without the reserve has nothing to lend: this session | ||
| 751 | + // has been read back from, so it stays that way. | ||
| 752 | + if !session.sized || session.hold > 0 { | ||
| 753 | + session.hold = DMA_HOLD; | ||
| 754 | + session.want = Some(VhDma { | ||
| 755 | + fourcc: VA_FOURCC_NV12, | ||
| 756 | + coded_width, | ||
| 757 | + coded_height, | ||
| 758 | + width, | ||
| 759 | + height, | ||
| 760 | + ..VhDma::default() | ||
| 761 | + }); | ||
| 762 | + } | ||
| 763 | + let pumped = session.pump(); | ||
| 764 | + session.want = None; | ||
| 765 | + match pumped { | ||
| 766 | + Ok(true) => { | ||
| 767 | + match session.dma.take() { | ||
| 768 | + // SAFETY: `dma` is non-null and writable per the contract. | ||
| 769 | + Some(desc) => unsafe { *dma = desc }, | ||
| 770 | + // SAFETY: as above, for `out`. | ||
| 771 | + None => session.fill(unsafe { &mut *out }), | ||
| 772 | + } | ||
| 773 | + 1 | ||
| 774 | + } | ||
| 775 | + Ok(false) => 0, | ||
| 776 | + Err(e) => { | ||
| 777 | + eprintln!("engine_hw: {e}"); | ||
| 778 | + -2 | ||
| 779 | + } | ||
| 780 | + } | ||
| 781 | + })) | ||
| 782 | + .unwrap_or(-1) | ||
| 783 | +} | ||
| 784 | + | ||
| 602 | /// Releases a session. Safe to call with null. | 785 | /// Releases a session. Safe to call with null. |
| 603 | /// | 786 | /// |
| 604 | /// # Safety | 787 | /// # Safety |
| @@ -1063,6 +1246,70 @@ impl EncSession { | |||
| 1063 | self.collect() | 1246 | self.collect() |
| 1064 | } | 1247 | } |
| 1065 | 1248 | ||
| 1249 | + /// Encodes a picture the decoder left on the GPU: the buffer is imported as | ||
| 1250 | + /// a surface of this session's own shape and read there, so nothing of it | ||
| 1251 | + /// ever passes through the CPU -- no `vaGetImage` on the way out of the | ||
| 1252 | + /// decoder and no interleave on the way in here. | ||
| 1253 | + /// | ||
| 1254 | + /// The geometry is checked rather than trusted: a buffer of another shape | ||
| 1255 | + /// would be coded as garbage, and the caller asked | ||
| 1256 | + /// [`vh_enc_dma_geometry`] what this seat takes before the decoder ever | ||
| 1257 | + /// handed one over. | ||
| 1258 | + fn encode_dma(&mut self, dma: &VhDma, force_keyframe: bool) -> Result<(), String> { | ||
| 1259 | + if dma.fd[0] < 0 | ||
| 1260 | + || dma.fourcc != VA_FOURCC_NV12 | ||
| 1261 | + || (dma.coded_width, dma.coded_height) != (self.coded.width, self.coded.height) | ||
| 1262 | + || (dma.width as usize, dma.height as usize) != (self.width, self.height) | ||
| 1263 | + { | ||
| 1264 | + return Err(format!( | ||
| 1265 | + "imported buffer is {}x{} in {} coded {}x{}, not {}x{} coded {}x{}", | ||
| 1266 | + dma.width, | ||
| 1267 | + dma.height, | ||
| 1268 | + dma.fourcc, | ||
| 1269 | + dma.coded_width, | ||
| 1270 | + dma.coded_height, | ||
| 1271 | + self.width, | ||
| 1272 | + self.height, | ||
| 1273 | + self.coded.width, | ||
| 1274 | + self.coded.height | ||
| 1275 | + )); | ||
| 1276 | + } | ||
| 1277 | + // One object or two, exactly as the decoder's driver described them: | ||
| 1278 | + // the buffers stay the caller's, so each is dup'd for the frame below. | ||
| 1279 | + let mut files = Vec::new(); | ||
| 1280 | + for fd in dma.fd.iter().copied().take_while(|fd| *fd >= 0) { | ||
| 1281 | + // SAFETY: the descriptor's handles are the caller's, open for the | ||
| 1282 | + // length of the call. | ||
| 1283 | + let owned = unsafe { std::os::fd::BorrowedFd::borrow_raw(fd) } | ||
| 1284 | + .try_clone_to_owned() | ||
| 1285 | + .map_err(|e| format!("dup of the imported buffer failed: {e}"))?; | ||
| 1286 | + files.push(std::fs::File::from(owned)); | ||
| 1287 | + } | ||
| 1288 | + let objects = files.len(); | ||
| 1289 | + let layout = FrameLayout { | ||
| 1290 | + format: (Fourcc::from(b"NV12"), dma.modifier), | ||
| 1291 | + size: self.coded, | ||
| 1292 | + planes: (0..2) | ||
| 1293 | + .map(|plane| PlaneLayout { | ||
| 1294 | + buffer_index: plane.min(objects - 1), | ||
| 1295 | + offset: dma.offset[plane] as usize, | ||
| 1296 | + stride: dma.stride[plane] as usize, | ||
| 1297 | + }) | ||
| 1298 | + .collect(), | ||
| 1299 | + }; | ||
| 1300 | + let frame = GenericDmaVideoFrame::new(files, layout.clone())?; | ||
| 1301 | + let meta = FrameMetadata { | ||
| 1302 | + timestamp: self.timestamp, | ||
| 1303 | + layout, | ||
| 1304 | + force_keyframe, | ||
| 1305 | + }; | ||
| 1306 | + self.timestamp += 1; | ||
| 1307 | + self.encoder | ||
| 1308 | + .encode(meta, frame) | ||
| 1309 | + .map_err(|e| e.to_string())?; | ||
| 1310 | + self.collect() | ||
| 1311 | + } | ||
| 1312 | + | ||
| 1066 | /// Moves every access unit the encoder has finished into `ready`. | 1313 | /// Moves every access unit the encoder has finished into `ready`. |
| 1067 | fn collect(&mut self) -> Result<(), String> { | 1314 | fn collect(&mut self) -> Result<(), String> { |
| 1068 | while let Some(coded) = self.encoder.poll().map_err(|e| e.to_string())? { | 1315 | while let Some(coded) = self.encoder.poll().map_err(|e| e.to_string())? { |
| @@ -1212,6 +1459,67 @@ pub unsafe extern "C" fn vh_enc_frame( | |||
| 1212 | .unwrap_or(-1) | 1459 | .unwrap_or(-1) |
| 1213 | } | 1460 | } |
| 1214 | 1461 | ||
| 1462 | +/// What a decoded buffer must look like to reach this encoder without a copy: | ||
| 1463 | +/// the surface size it codes in, written to `coded_width`/`coded_height`. 1 on | ||
| 1464 | +/// an answer, negative on none. NV12 and the size this session was opened for | ||
| 1465 | +/// are the rest of the shape, and the caller already knows both. | ||
| 1466 | +/// | ||
| 1467 | +/// # Safety | ||
| 1468 | +/// `session` must come from [`vh_enc_open`]; both outputs must be writable. | ||
| 1469 | +#[unsafe(no_mangle)] | ||
| 1470 | +pub unsafe extern "C" fn vh_enc_dma_geometry( | ||
| 1471 | + session: *mut c_void, | ||
| 1472 | + coded_width: *mut u32, | ||
| 1473 | + coded_height: *mut u32, | ||
| 1474 | +) -> i32 { | ||
| 1475 | + catch_unwind(AssertUnwindSafe(|| { | ||
| 1476 | + if session.is_null() || coded_width.is_null() || coded_height.is_null() { | ||
| 1477 | + return -1; | ||
| 1478 | + } | ||
| 1479 | + // SAFETY: caller-guaranteed live session and writable destinations. | ||
| 1480 | + unsafe { | ||
| 1481 | + let session = &*(session as *const EncSession); | ||
| 1482 | + *coded_width = session.coded.width; | ||
| 1483 | + *coded_height = session.coded.height; | ||
| 1484 | + } | ||
| 1485 | + 1 | ||
| 1486 | + })) | ||
| 1487 | + .unwrap_or(-1) | ||
| 1488 | +} | ||
| 1489 | + | ||
| 1490 | +/// Encodes one picture the decoder left on the GPU, described by `dma` -- whose | ||
| 1491 | +/// file descriptor stays the *caller's*, borrowed for the length of the call. | ||
| 1492 | +/// Same answer and same lifetime rule as [`vh_enc_frame`]; a buffer of a shape | ||
| 1493 | +/// this session cannot read is an error and not a silent re-shape. | ||
| 1494 | +/// | ||
| 1495 | +/// # Safety | ||
| 1496 | +/// `session` must come from [`vh_enc_open`], `dma` must be readable and its | ||
| 1497 | +/// descriptor open, and `out`/`out_len` must be writable. | ||
| 1498 | +#[unsafe(no_mangle)] | ||
| 1499 | +pub unsafe extern "C" fn vh_enc_frame_dma( | ||
| 1500 | + session: *mut c_void, | ||
| 1501 | + dma: *const VhDma, | ||
| 1502 | + force_key: i32, | ||
| 1503 | + out: *mut *const u8, | ||
| 1504 | + out_len: *mut usize, | ||
| 1505 | +) -> i32 { | ||
| 1506 | + catch_unwind(AssertUnwindSafe(|| { | ||
| 1507 | + if session.is_null() || dma.is_null() || out.is_null() || out_len.is_null() { | ||
| 1508 | + return -1; | ||
| 1509 | + } | ||
| 1510 | + // SAFETY: caller-guaranteed live session and readable descriptor. | ||
| 1511 | + let (session, dma) = unsafe { (&mut *(session as *mut EncSession), &*dma) }; | ||
| 1512 | + match session.encode_dma(dma, force_key != 0) { | ||
| 1513 | + Ok(()) => session.take(out, out_len), | ||
| 1514 | + Err(e) => { | ||
| 1515 | + eprintln!("engine_hw: {e}"); | ||
| 1516 | + -2 | ||
| 1517 | + } | ||
| 1518 | + } | ||
| 1519 | + })) | ||
| 1520 | + .unwrap_or(-1) | ||
| 1521 | +} | ||
| 1522 | + | ||
| 1215 | /// Flushes the encoder: 1 while `out`/`out_len` describe another access unit, | 1523 | /// Flushes the encoder: 1 while `out`/`out_len` describe another access unit, |
| 1216 | /// 0 once every picture fed has been handed back, negative on error. Same | 1524 | /// 0 once every picture fed has been handed back, negative on error. Same |
| 1217 | /// lifetime rule as [`vh_enc_frame`]. | 1525 | /// lifetime rule as [`vh_enc_frame`]. |
crates/engine/src/export.rsmodified+218 -87
| @@ -74,7 +74,7 @@ use oxideav_core::Muxer as _; | |||
| 74 | use crate::audio::{AudioMeta, AudioSession}; | 74 | use crate::audio::{AudioMeta, AudioSession}; |
| 75 | use crate::colorspace::{ColorDescription, Matrix, Transfer}; | 75 | use crate::colorspace::{ColorDescription, Matrix, Transfer}; |
| 76 | use crate::demux::{Codec, Demuxer, MkvDemuxer, VideoMeta}; | 76 | use crate::demux::{Codec, Demuxer, MkvDemuxer, VideoMeta}; |
| 77 | -use crate::hw::{HwEncoder, HwSession}; | 77 | +use crate::hw::{DmaFrame, DmaWant, HwEncoder, HwPicture, HwSession}; |
| 78 | use crate::mux::{ | 78 | use crate::mux::{ |
| 79 | AudioParams, Av1Params, CopyParams, HevcParams, MkvMuxer, Mp4Muxer, SubParams, VideoParams, | 79 | AudioParams, Av1Params, CopyParams, HevcParams, MkvMuxer, Mp4Muxer, SubParams, VideoParams, |
| 80 | }; | 80 | }; |
| @@ -1806,16 +1806,24 @@ fn run( | |||
| 1806 | .get(source) | 1806 | .get(source) |
| 1807 | .ok_or_else(|| format!("clip names source {source} of {}", sources.len()))?; | 1807 | .ok_or_else(|| format!("clip names source {source} of {}", sources.len()))?; |
| 1808 | let (rate, color, _peak) = rates[source]; | 1808 | let (rate, color, _peak) = rates[source]; |
| 1809 | + let mapper = tone[source].as_ref(); | ||
| 1810 | + // Nothing on the way from this span's decoder to the encoder | ||
| 1811 | + // touches a sample: no tone map, no matrix remap, no grade -- | ||
| 1812 | + // which is what lets the *decoded buffer itself* be encoded, | ||
| 1813 | + // never read back and never written out again. The canvas is | ||
| 1814 | + // the fourth thing that would touch it, and the decoder answers | ||
| 1815 | + // that one: a picture of another size than this file's is one | ||
| 1816 | + // the plugin hands back as pixels ([`HwSession::next_frame_dma`]). | ||
| 1817 | + let untouched = mapper.is_none() | ||
| 1818 | + && remap_into(Some(color), false, out_color.matrix).is_none() | ||
| 1819 | + && project | ||
| 1820 | + .composite_color_at(span.start) | ||
| 1821 | + .is_none_or(|params| params.is_identity()); | ||
| 1822 | + let want = untouched.then(|| encoder.dma_want(meta)).flatten(); | ||
| 1809 | // Opened at the file's own frame, which is the only place the | 1823 | // Opened at the file's own frame, which is the only place the |
| 1810 | // file's numbering is used -- the span's are the timeline's. | 1824 | // file's numbering is used -- the span's are the timeline's. |
| 1811 | - let pictures = ClipDecoder::open(&entry.path, rate.source_at(in_frame))?; | 1825 | + let pictures = ClipDecoder::open(&entry.path, rate.source_at(in_frame), want)?; |
| 1812 | - ( | 1826 | + (Some(pictures), rate, in_frame, Some(color), mapper) |
| 1813 | - Some(pictures), | ||
| 1814 | - rate, | ||
| 1815 | - in_frame, | ||
| 1816 | - Some(color), | ||
| 1817 | - tone[source].as_ref(), | ||
| 1818 | - ) | ||
| 1819 | } | 1827 | } |
| 1820 | // A gap's black is 16/128/128, which is black in every matrix here | 1828 | // A gap's black is 16/128/128, which is black in every matrix here |
| 1821 | // and on every curve: nothing to remap and nothing to tone-map, | 1829 | // and on every curve: nothing to remap and nothing to tone-map, |
| @@ -1895,50 +1903,46 @@ fn run( | |||
| 1895 | } | 1903 | } |
| 1896 | } | 1904 | } |
| 1897 | } | 1905 | } |
| 1898 | - None => Some(black.picture()), | 1906 | + None => { |
| 1907 | + let (y, u, v, width, height) = black.picture(); | ||
| 1908 | + Some(Frame::Pixels(y, u, v, width, height)) | ||
| 1909 | + } | ||
| 1899 | }; | 1910 | }; |
| 1900 | - let Some((y, u, v, width, height)) = picture else { | 1911 | + let Some(frame) = picture else { |
| 1901 | break; // source ran out early; the clip list outlives the file | 1912 | break; // source ran out early; the clip list outlives the file |
| 1902 | }; | 1913 | }; |
| 1903 | - // The planes are borrowed from the decoder (and `Black::picture` | 1914 | + // A picture still on the GPU has nothing waiting for it here: the |
| 1904 | - // hands the same slice as both u and v), so a grade cannot be | 1915 | + // span was opened that way only where none of what follows would |
| 1905 | - // applied in place: it goes onto a copy, which the encoder then | 1916 | + // have touched a sample of it, so it is placed by nobody and goes |
| 1906 | - // reads instead. | 1917 | + // into the encoder as the buffer the decoder wrote. |
| 1907 | - let params = grade.filter(|p| !p.is_identity()); | 1918 | + let placed = match frame { |
| 1908 | - let (y, u, v) = match (params, remap, mapper) { | 1919 | + Frame::Dma(_) => None, |
| 1909 | - (None, None, None) => (y, u, v), | 1920 | + Frame::Pixels(y, u, v, width, height) => Some(place_picture( |
| 1910 | - (params, remap, mapper) => { | 1921 | + y, |
| 1911 | - let (gy, gu, gv) = &mut graded; | 1922 | + u, |
| 1912 | - gy.clear(); | 1923 | + v, |
| 1913 | - gy.extend_from_slice(y); | 1924 | + width, |
| 1914 | - gu.clear(); | 1925 | + height, |
| 1915 | - gu.extend_from_slice(u); | 1926 | + grade, |
| 1916 | - gv.clear(); | 1927 | + remap, |
| 1917 | - gv.extend_from_slice(v); | 1928 | + mapper, |
| 1918 | - // Tone-map first, so the grade is applied to the SDR picture | 1929 | + &mut graded, |
| 1919 | - // the canvas showed and not to HDR codes; then remap the | 1930 | + &mut canvas, |
| 1920 | - // graded result. The order playback renders in, and the | 1931 | + )), |
| 1921 | - // only order in which preview and export agree. | ||
| 1922 | - if let Some(mapper) = mapper { | ||
| 1923 | - mapper.map(gy, gu, gv, width as usize, height as usize); | ||
| 1924 | - } | ||
| 1925 | - if let Some(params) = params { | ||
| 1926 | - crate::color::apply_yuv(¶ms, gy, gu, gv); | ||
| 1927 | - } | ||
| 1928 | - if let Some((from, to)) = remap { | ||
| 1929 | - crate::colorspace::remap(from, to, gy, gu, gv, width as usize); | ||
| 1930 | - } | ||
| 1931 | - (&gy[..], &gu[..], &gv[..]) | ||
| 1932 | - } | ||
| 1933 | }; | 1932 | }; |
| 1934 | - // Grade first, place second: the grade is the clip's own pixels | ||
| 1935 | - // and the bars around them are not the clip (see `scale::Composer`). | ||
| 1936 | - let (y, u, v, width, height) = canvas.place(y, u, v, width, height); | ||
| 1937 | // Once per timeline frame this source frame covers: one at real time | 1933 | // Once per timeline frame this source frame covers: one at real time |
| 1938 | // and faster, more when the clip is slowed -- the picture is already | 1934 | // and faster, more when the clip is slowed -- the picture is already |
| 1939 | // graded and placed, so a held frame costs an encode and no decode. | 1935 | // graded and placed, so a held frame costs an encode and no decode. |
| 1940 | for _ in 0..repeats { | 1936 | for _ in 0..repeats { |
| 1941 | - if let Some((au, key)) = encoder.encode(y, u, v, width, height)? { | 1937 | + let coded = match &frame { |
| 1938 | + Frame::Dma(dma) => encoder.encode_dma(dma)?, | ||
| 1939 | + Frame::Pixels(..) => { | ||
| 1940 | + let (y, u, v, width, height) = | ||
| 1941 | + placed.expect("a picture with pixels was placed"); | ||
| 1942 | + encoder.encode(y, u, v, width, height)? | ||
| 1943 | + } | ||
| 1944 | + }; | ||
| 1945 | + if let Some((au, key)) = coded { | ||
| 1942 | write_video( | 1946 | write_video( |
| 1943 | &mut muxer, | 1947 | &mut muxer, |
| 1944 | out, | 1948 | out, |
| @@ -1999,6 +2003,60 @@ fn run( | |||
| 1999 | Ok(()) | 2003 | Ok(()) |
| 2000 | } | 2004 | } |
| 2001 | 2005 | ||
| 2006 | +/// One decoded picture graded, tone-mapped, remapped and placed on the canvas | ||
| 2007 | +/// -- everything between a source's own samples and the ones an encoder is fed, | ||
| 2008 | +/// which is exactly the work a zero-copy span has none of. | ||
| 2009 | +/// | ||
| 2010 | +/// `graded` and `canvas` are the span's scratch: the planes come back borrowed | ||
| 2011 | +/// from one of them, or from the picture itself where not a byte was touched. | ||
| 2012 | +#[expect(clippy::too_many_arguments, reason = "one span's whole picture path")] | ||
| 2013 | +fn place_picture<'a>( | ||
| 2014 | + y: &'a [u8], | ||
| 2015 | + u: &'a [u8], | ||
| 2016 | + v: &'a [u8], | ||
| 2017 | + width: u32, | ||
| 2018 | + height: u32, | ||
| 2019 | + grade: Option<crate::color::ColorParams>, | ||
| 2020 | + remap: Option<(Matrix, Matrix)>, | ||
| 2021 | + mapper: Option<&ToneMapper>, | ||
| 2022 | + graded: &'a mut (Vec<u8>, Vec<u8>, Vec<u8>), | ||
| 2023 | + canvas: &'a mut Composer, | ||
| 2024 | +) -> (&'a [u8], &'a [u8], &'a [u8], u32, u32) { | ||
| 2025 | + // The planes are borrowed from the decoder (and `Black::picture` hands the | ||
| 2026 | + // same slice as both u and v), so a grade cannot be applied in place: it | ||
| 2027 | + // goes onto a copy, which the encoder then reads instead. | ||
| 2028 | + let params = grade.filter(|p| !p.is_identity()); | ||
| 2029 | + let (y, u, v) = match (params, remap, mapper) { | ||
| 2030 | + (None, None, None) => (y, u, v), | ||
| 2031 | + (params, remap, mapper) => { | ||
| 2032 | + let (gy, gu, gv) = graded; | ||
| 2033 | + gy.clear(); | ||
| 2034 | + gy.extend_from_slice(y); | ||
| 2035 | + gu.clear(); | ||
| 2036 | + gu.extend_from_slice(u); | ||
| 2037 | + gv.clear(); | ||
| 2038 | + gv.extend_from_slice(v); | ||
| 2039 | + // Tone-map first, so the grade is applied to the SDR picture the | ||
| 2040 | + // canvas showed and not to HDR codes; then remap the graded result. | ||
| 2041 | + // The order playback renders in, and the only order in which | ||
| 2042 | + // preview and export agree. | ||
| 2043 | + if let Some(mapper) = mapper { | ||
| 2044 | + mapper.map(gy, gu, gv, width as usize, height as usize); | ||
| 2045 | + } | ||
| 2046 | + if let Some(params) = params { | ||
| 2047 | + crate::color::apply_yuv(¶ms, gy, gu, gv); | ||
| 2048 | + } | ||
| 2049 | + if let Some((from, to)) = remap { | ||
| 2050 | + crate::colorspace::remap(from, to, gy, gu, gv, width as usize); | ||
| 2051 | + } | ||
| 2052 | + (&gy[..], &gu[..], &gv[..]) | ||
| 2053 | + } | ||
| 2054 | + }; | ||
| 2055 | + // Grade first, place second: the grade is the clip's own pixels and the | ||
| 2056 | + // bars around them are not the clip (see `scale::Composer`). | ||
| 2057 | + canvas.place(y, u, v, width, height) | ||
| 2058 | +} | ||
| 2059 | + | ||
| 2002 | /// Which matrix pair a span's samples are rewritten by on the way into a file | 2060 | /// Which matrix pair a span's samples are rewritten by on the way into a file |
| 2003 | /// whose own matrix is `out` -- `None` when they are already coded against it, | 2061 | /// whose own matrix is `out` -- `None` when they are already coded against it, |
| 2004 | /// and for a gap, whose 16/128/128 black is black in every matrix here. | 2062 | /// and for a gap, whose 16/128/128 black is black in every matrix here. |
| @@ -2961,6 +3019,36 @@ impl Enc { | |||
| 2961 | } | 3019 | } |
| 2962 | } | 3020 | } |
| 2963 | 3021 | ||
| 3022 | + /// What a decoded buffer must look like to reach this seat without ever | ||
| 3023 | + /// being read back -- `None` for every seat that reads bytes, which is both | ||
| 3024 | + /// software encoders and the intra HEVC one. | ||
| 3025 | + /// | ||
| 3026 | + /// The AV1 hardware seat is left out on purpose: it is opt-in behind | ||
| 3027 | + /// `VE_HW_AV1` because the vendored encoder reset this project's GPU | ||
| 3028 | + /// ([`Enc::open_av1`]), and a path that cannot be measured is not one to | ||
| 3029 | + /// widen. | ||
| 3030 | + fn dma_want(&self, meta: &VideoMeta) -> Option<crate::hw::DmaWant> { | ||
| 3031 | + match self { | ||
| 3032 | + Self::Hw(hw) | Self::HevcHw(hw) => hw.dma_want(meta.width, meta.height), | ||
| 3033 | + _ => None, | ||
| 3034 | + } | ||
| 3035 | + } | ||
| 3036 | + | ||
| 3037 | + /// One picture the decoder left on the GPU in, at most one access unit out. | ||
| 3038 | + /// Same answer as [`Enc::encode`], including which units a decoder may be | ||
| 3039 | + /// started from, because it is the same encoder -- only the picture took | ||
| 3040 | + /// another way in. | ||
| 3041 | + fn encode_dma(&mut self, dma: &DmaFrame) -> crate::Result<Option<(&[u8], bool)>> { | ||
| 3042 | + match self { | ||
| 3043 | + Self::Hw(hw) => Ok(hw.encode_dma(dma, false)?.map(|au| (au, false))), | ||
| 3044 | + // Every picture an IDR here, exactly as in [`Enc::encode`]. | ||
| 3045 | + Self::HevcHw(hw) => Ok(hw.encode_dma(dma, true)?.map(|au| (au, true))), | ||
| 3046 | + // Unreachable through [`Enc::dma_want`], which is the only thing | ||
| 3047 | + // that puts a span's decoder on this path. | ||
| 3048 | + _ => Err("this encoder takes pictures as bytes, not as buffers".into()), | ||
| 3049 | + } | ||
| 3050 | + } | ||
| 3051 | + | ||
| 2964 | /// End of stream; call until it returns `None`. | 3052 | /// End of stream; call until it returns `None`. |
| 2965 | fn drain(&mut self) -> crate::Result<Option<(&[u8], bool)>> { | 3053 | fn drain(&mut self) -> crate::Result<Option<(&[u8], bool)>> { |
| 2966 | match self { | 3054 | match self { |
| @@ -3237,17 +3325,46 @@ impl Drop for DecodeThread { | |||
| 3237 | } | 3325 | } |
| 3238 | } | 3326 | } |
| 3239 | 3327 | ||
| 3240 | -/// One picture, owned, on its way from a decode thread to the encoder. | 3328 | +/// One picture on its way from a decode thread to the encoder: its bytes, or |
| 3241 | -struct Yuv { | 3329 | +/// the GPU buffer they are still in. |
| 3242 | - y: Vec<u8>, | 3330 | +enum Yuv { |
| 3243 | - u: Vec<u8>, | 3331 | + Pixels { |
| 3244 | - v: Vec<u8>, | 3332 | + y: Vec<u8>, |
| 3245 | - width: u32, | 3333 | + u: Vec<u8>, |
| 3246 | - height: u32, | 3334 | + v: Vec<u8>, |
| 3335 | + width: u32, | ||
| 3336 | + height: u32, | ||
| 3337 | + }, | ||
| 3338 | + /// Never read back and never copied: a DRM-PRIME handle the encoder imports | ||
| 3339 | + /// on the other side of the channel. Sending it is sending an integer, and | ||
| 3340 | + /// what keeps the buffer from being decoded over is the channel's own depth | ||
| 3341 | + /// (see [`crate::hw::HwSession::next_frame_dma`]). | ||
| 3342 | + Dma(DmaFrame), | ||
| 3343 | +} | ||
| 3344 | + | ||
| 3345 | +impl Yuv { | ||
| 3346 | + /// The decoder's own buffer copied out, which is what it costs to hand a | ||
| 3347 | + /// picture to another thread when the pixels have to travel. | ||
| 3348 | + fn pixels(y: &[u8], u: &[u8], v: &[u8], width: u32, height: u32) -> Self { | ||
| 3349 | + Self::Pixels { | ||
| 3350 | + y: y.to_vec(), | ||
| 3351 | + u: u.to_vec(), | ||
| 3352 | + v: v.to_vec(), | ||
| 3353 | + width, | ||
| 3354 | + height, | ||
| 3355 | + } | ||
| 3356 | + } | ||
| 3357 | +} | ||
| 3358 | + | ||
| 3359 | +/// One picture as the export loop sees it: planes to grade and place, or a | ||
| 3360 | +/// buffer that goes straight into the encoder. | ||
| 3361 | +enum Frame<'a> { | ||
| 3362 | + Pixels(&'a [u8], &'a [u8], &'a [u8], u32, u32), | ||
| 3363 | + Dma(&'a DmaFrame), | ||
| 3247 | } | 3364 | } |
| 3248 | 3365 | ||
| 3249 | impl ClipDecoder { | 3366 | impl ClipDecoder { |
| 3250 | - fn open(path: &Path, start_frame: u32) -> crate::Result<Self> { | 3367 | + fn open(path: &Path, start_frame: u32, want: Option<DmaWant>) -> crate::Result<Self> { |
| 3251 | // Before either decoder: an image is not a stream, so `start_frame` | 3368 | // Before either decoder: an image is not a stream, so `start_frame` |
| 3252 | // means nothing to it -- every frame of a still span is the same | 3369 | // means nothing to it -- every frame of a still span is the same |
| 3253 | // picture, which is what playback shows for it too. | 3370 | // picture, which is what playback shows for it too. |
| @@ -3258,7 +3375,7 @@ impl ClipDecoder { | |||
| 3258 | let (tx, frames) = sync_channel(2); | 3375 | let (tx, frames) = sync_channel(2); |
| 3259 | let handle = thread::Builder::new() | 3376 | let handle = thread::Builder::new() |
| 3260 | .name("export-decode".into()) | 3377 | .name("export-decode".into()) |
| 3261 | - .spawn(move || decode_stream(&path, start_frame, &tx))?; | 3378 | + .spawn(move || decode_stream(&path, start_frame, want, &tx))?; |
| 3262 | Ok(Self::Streamed(Streamed { | 3379 | Ok(Self::Streamed(Streamed { |
| 3263 | frames, | 3380 | frames, |
| 3264 | _thread: DecodeThread(Some(handle)), | 3381 | _thread: DecodeThread(Some(handle)), |
| @@ -3267,22 +3384,26 @@ impl ClipDecoder { | |||
| 3267 | })) | 3384 | })) |
| 3268 | } | 3385 | } |
| 3269 | 3386 | ||
| 3270 | - /// The next picture as tightly packed I420, borrowed until the call after. | 3387 | + /// The next picture, borrowed until the call after -- as tightly packed |
| 3271 | - fn next(&mut self) -> crate::Result<Option<(&[u8], &[u8], &[u8], u32, u32)>> { | 3388 | + /// I420, or as the GPU buffer the decoder wrote it into. |
| 3389 | + fn next(&mut self) -> crate::Result<Option<Frame<'_>>> { | ||
| 3272 | match self { | 3390 | match self { |
| 3273 | - Self::Still(still) => Ok(Some(still.picture())), | 3391 | + Self::Still(still) => { |
| 3392 | + let (y, u, v, width, height) = still.picture(); | ||
| 3393 | + Ok(Some(Frame::Pixels(y, u, v, width, height))) | ||
| 3394 | + } | ||
| 3274 | Self::Streamed(stream) if stream.ended => Ok(None), | 3395 | Self::Streamed(stream) if stream.ended => Ok(None), |
| 3275 | Self::Streamed(stream) => match stream.frames.recv() { | 3396 | Self::Streamed(stream) => match stream.frames.recv() { |
| 3276 | - Ok(Ok(Some(frame))) => { | 3397 | + Ok(Ok(Some(frame))) => Ok(Some(match stream.current.insert(frame) { |
| 3277 | - let frame = stream.current.insert(frame); | 3398 | + Yuv::Pixels { |
| 3278 | - Ok(Some(( | 3399 | + y, |
| 3279 | - &frame.y, | 3400 | + u, |
| 3280 | - &frame.u, | 3401 | + v, |
| 3281 | - &frame.v, | 3402 | + width, |
| 3282 | - frame.width, | 3403 | + height, |
| 3283 | - frame.height, | 3404 | + } => Frame::Pixels(y, u, v, *width, *height), |
| 3284 | - ))) | 3405 | + Yuv::Dma(dma) => Frame::Dma(dma), |
| 3285 | - } | 3406 | + })), |
| 3286 | // The decoder said end of stream in as many words -- a source | 3407 | // The decoder said end of stream in as many words -- a source |
| 3287 | // shorter than the clip that names it, which the span loop ends | 3408 | // shorter than the clip that names it, which the span loop ends |
| 3288 | // gracefully on. | 3409 | // gracefully on. |
| @@ -3315,7 +3436,12 @@ impl ClipDecoder { | |||
| 3315 | /// error, or the `Ok(None)` that *is* end of stream. Closing the channel is not | 3436 | /// error, or the `Ok(None)` that *is* end of stream. Closing the channel is not |
| 3316 | /// one of them -- a silent close is a panicked thread, and the receiver treats | 3437 | /// one of them -- a silent close is a panicked thread, and the receiver treats |
| 3317 | /// it as the failure it is rather than as a source that ran out. | 3438 | /// it as the failure it is rather than as a source that ran out. |
| 3318 | -fn decode_stream(path: &Path, start_frame: u32, tx: &SyncSender<crate::Result<Option<Yuv>>>) { | 3439 | +fn decode_stream( |
| 3440 | + path: &Path, | ||
| 3441 | + start_frame: u32, | ||
| 3442 | + want: Option<DmaWant>, | ||
| 3443 | + tx: &SyncSender<crate::Result<Option<Yuv>>>, | ||
| 3444 | +) { | ||
| 3319 | let opened = match forced("VE_SW") { | 3445 | let opened = match forced("VE_SW") { |
| 3320 | false => HwSession::open_at(path, start_frame).map(Pictures::Hw), | 3446 | false => HwSession::open_at(path, start_frame).map(Pictures::Hw), |
| 3321 | true => None, | 3447 | true => None, |
| @@ -3331,17 +3457,8 @@ fn decode_stream(path: &Path, start_frame: u32, tx: &SyncSender<crate::Result<Op | |||
| 3331 | }, | 3457 | }, |
| 3332 | }; | 3458 | }; |
| 3333 | loop { | 3459 | loop { |
| 3334 | - // Copied out of the decoder's own buffer, which it reuses for the next | 3460 | + let frame = match decoder.next(want) { |
| 3335 | - // picture: one 3 MB memcpy per frame against the decode and the encode | 3461 | + Ok(Some(frame)) => frame, |
| 3336 | - // it lets overlap. | ||
| 3337 | - let frame = match decoder.next() { | ||
| 3338 | - Ok(Some((y, u, v, width, height))) => Yuv { | ||
| 3339 | - y: y.to_vec(), | ||
| 3340 | - u: u.to_vec(), | ||
| 3341 | - v: v.to_vec(), | ||
| 3342 | - width, | ||
| 3343 | - height, | ||
| 3344 | - }, | ||
| 3345 | Ok(None) => { | 3462 | Ok(None) => { |
| 3346 | let _ = tx.send(Ok(None)); | 3463 | let _ = tx.send(Ok(None)); |
| 3347 | return; | 3464 | return; |
| @@ -3366,15 +3483,29 @@ enum Pictures { | |||
| 3366 | } | 3483 | } |
| 3367 | 3484 | ||
| 3368 | impl Pictures { | 3485 | impl Pictures { |
| 3369 | - fn next(&mut self) -> crate::Result<Option<(&[u8], &[u8], &[u8], u32, u32)>> { | 3486 | + /// The next picture, owned, ready to cross the channel. `want` is what the |
| 3370 | - match self { | 3487 | + /// export's encoder can read straight off the GPU: where the hardware |
| 3371 | - Self::Hw(hw) => hw.next_frame(), | 3488 | + /// decoder can hand such a buffer over there is no copy here at all, and |
| 3372 | - Self::Sw(sw) => { | 3489 | + /// everything else is the 3 MB memcpy out of the decoder's own buffer that |
| 3490 | + /// buys the decode and the encode their overlap. | ||
| 3491 | + fn next(&mut self, want: Option<DmaWant>) -> crate::Result<Option<Yuv>> { | ||
| 3492 | + match (self, want) { | ||
| 3493 | + (Self::Hw(hw), Some(want)) => Ok(match hw.next_frame_dma(want)? { | ||
| 3494 | + Some(HwPicture::Dma(dma)) => Some(Yuv::Dma(dma)), | ||
| 3495 | + Some(HwPicture::Pixels(y, u, v, width, height)) => { | ||
| 3496 | + Some(Yuv::pixels(y, u, v, width, height)) | ||
| 3497 | + } | ||
| 3498 | + None => None, | ||
| 3499 | + }), | ||
| 3500 | + (Self::Hw(hw), None) => Ok(hw | ||
| 3501 | + .next_frame()? | ||
| 3502 | + .map(|(y, u, v, width, height)| Yuv::pixels(y, u, v, width, height))), | ||
| 3503 | + (Self::Sw(sw), _) => { | ||
| 3373 | if !sw.advance()? { | 3504 | if !sw.advance()? { |
| 3374 | return Ok(None); | 3505 | return Ok(None); |
| 3375 | } | 3506 | } |
| 3376 | let frame = sw.frame.as_ref().expect("advance stored a picture"); | 3507 | let frame = sw.frame.as_ref().expect("advance stored a picture"); |
| 3377 | - Ok(Some(( | 3508 | + Ok(Some(Yuv::pixels( |
| 3378 | &frame.y, | 3509 | &frame.y, |
| 3379 | &frame.u, | 3510 | &frame.u, |
| 3380 | &frame.v, | 3511 | &frame.v, |
| @@ -3475,9 +3606,9 @@ mod tests { | |||
| 3475 | panic!("decoder died"); | 3606 | panic!("decoder died"); |
| 3476 | }); | 3607 | }); |
| 3477 | let mut died = streamed(handle, frames); | 3608 | let mut died = streamed(handle, frames); |
| 3478 | - let e = died | 3609 | + let Err(e) = died.next() else { |
| 3479 | - .next() | 3610 | + panic!("a silent death must fail the export, not end the clip") |
| 3480 | - .expect_err("a silent death must fail the export, not end the clip"); | 3611 | + }; |
| 3481 | assert!( | 3612 | assert!( |
| 3482 | e.to_string().contains("without a picture or a reason"), | 3613 | e.to_string().contains("without a picture or a reason"), |
| 3483 | "{e}" | 3614 | "{e}" |
crates/engine/src/hw.rsmodified+200 -2
| @@ -16,6 +16,7 @@ | |||
| 16 | //! honest [`crate::demux::Codec::needs_plugin`] refusal covers both. | 16 | //! honest [`crate::demux::Codec::needs_plugin`] refusal covers both. |
| 17 | 17 | ||
| 18 | use std::ffi::{CString, c_char, c_void}; | 18 | use std::ffi::{CString, c_char, c_void}; |
| 19 | +use std::os::fd::FromRawFd; | ||
| 19 | use std::path::{Path, PathBuf}; | 20 | use std::path::{Path, PathBuf}; |
| 20 | use std::sync::OnceLock; | 21 | use std::sync::OnceLock; |
| 21 | 22 | ||
| @@ -62,6 +63,87 @@ impl Default for VhFrame { | |||
| 62 | } | 63 | } |
| 63 | } | 64 | } |
| 64 | 65 | ||
| 66 | +/// One decoded picture *left on the GPU*: a DRM-PRIME buffer the encoder | ||
| 67 | +/// imports instead of the caller reading the pixels back and writing them out | ||
| 68 | +/// again. All integers, so it crosses a channel to the encoding thread the way | ||
| 69 | +/// a picture's bytes used to. | ||
| 70 | +/// | ||
| 71 | +/// The `fd` belongs to whoever holds this: the plugin hands ownership over with | ||
| 72 | +/// the descriptor and [`DmaFrame`] closes it. What it does *not* own is the | ||
| 73 | +/// buffer's contents -- the decode session keeps the picture from being decoded | ||
| 74 | +/// over for a few frames only (see `vh_next_frame_dma`), which is why nothing | ||
| 75 | +/// but the export's two-deep decode channel may sit between the two calls. | ||
| 76 | +#[repr(C)] | ||
| 77 | +#[derive(Clone, Copy)] | ||
| 78 | +pub struct VhDma { | ||
| 79 | + /// One DRM-PRIME handle per plane, luma then chroma -- which is how the | ||
| 80 | + /// driver hands its own surfaces out (radeonsi exports an NV12 surface as | ||
| 81 | + /// *two* objects into one allocation, measured 2026-08-13), and describing | ||
| 82 | + /// it any other way is guessing at what the second one means. `fd[0]` below | ||
| 83 | + /// zero says this picture is not on the GPU at all; `fd[1]` below zero says | ||
| 84 | + /// both planes live in the first object. | ||
| 85 | + pub fd: [i32; 2], | ||
| 86 | + /// `NV12` and nothing else, today. | ||
| 87 | + pub fourcc: u32, | ||
| 88 | + /// DRM format modifier of the buffer, passed through to the import. | ||
| 89 | + pub modifier: u64, | ||
| 90 | + /// The surface's own size, which is the picture's rounded up to whatever | ||
| 91 | + /// the codec codes in -- what an encoder has to agree with, sample for | ||
| 92 | + /// sample, before it can read this buffer at all. | ||
| 93 | + pub coded_width: u32, | ||
| 94 | + pub coded_height: u32, | ||
| 95 | + /// The picture inside it. | ||
| 96 | + pub width: u32, | ||
| 97 | + pub height: u32, | ||
| 98 | + /// Luma then chroma, each inside its own object above. | ||
| 99 | + pub offset: [u32; 2], | ||
| 100 | + pub stride: [u32; 2], | ||
| 101 | +} | ||
| 102 | + | ||
| 103 | +impl Default for VhDma { | ||
| 104 | + fn default() -> Self { | ||
| 105 | + Self { | ||
| 106 | + fd: [-1, -1], | ||
| 107 | + fourcc: 0, | ||
| 108 | + modifier: 0, | ||
| 109 | + coded_width: 0, | ||
| 110 | + coded_height: 0, | ||
| 111 | + width: 0, | ||
| 112 | + height: 0, | ||
| 113 | + offset: [0; 2], | ||
| 114 | + stride: [0; 2], | ||
| 115 | + } | ||
| 116 | + } | ||
| 117 | +} | ||
| 118 | + | ||
| 119 | +/// A [`VhDma`] with its file descriptor owned: dropping it closes the handle, | ||
| 120 | +/// which is the only thing this side of the ABI has to get right. | ||
| 121 | +pub struct DmaFrame(VhDma); | ||
| 122 | + | ||
| 123 | +impl DmaFrame { | ||
| 124 | + pub fn width(&self) -> u32 { | ||
| 125 | + self.0.width | ||
| 126 | + } | ||
| 127 | + | ||
| 128 | + pub fn height(&self) -> u32 { | ||
| 129 | + self.0.height | ||
| 130 | + } | ||
| 131 | +} | ||
| 132 | + | ||
| 133 | +impl Drop for DmaFrame { | ||
| 134 | + fn drop(&mut self) { | ||
| 135 | + for fd in self.0.fd { | ||
| 136 | + if fd >= 0 { | ||
| 137 | + // SAFETY: the plugin transferred these descriptors to us with | ||
| 138 | + // the frame and nothing else owns them; `DmaFrame` is not | ||
| 139 | + // `Clone`, and the two are distinct handles even where they | ||
| 140 | + // name one allocation. | ||
| 141 | + drop(unsafe { std::os::fd::OwnedFd::from_raw_fd(fd) }); | ||
| 142 | + } | ||
| 143 | + } | ||
| 144 | + } | ||
| 145 | +} | ||
| 146 | + | ||
| 65 | /// What *this machine* takes, as far as the plugin implements it: one bit per | 147 | /// What *this machine* takes, as far as the plugin implements it: one bit per |
| 66 | /// codec ([`CAP_H264`] and its three neighbours) in each mask, so a caller reads | 148 | /// codec ([`CAP_H264`] and its three neighbours) in each mask, so a caller reads |
| 67 | /// "H.264 decodes and encodes here, HEVC only decodes" off three `u32`s. | 149 | /// "H.264 decodes and encodes here, HEVC only decodes" off three `u32`s. |
| @@ -90,6 +172,12 @@ struct Plugin { | |||
| 90 | open_at: unsafe extern "C" fn(*const c_char, u32) -> *mut c_void, | 172 | open_at: unsafe extern "C" fn(*const c_char, u32) -> *mut c_void, |
| 91 | meta: unsafe extern "C" fn(*mut c_void, *mut VhMeta) -> i32, | 173 | meta: unsafe extern "C" fn(*mut c_void, *mut VhMeta) -> i32, |
| 92 | next_frame: unsafe extern "C" fn(*mut c_void, *mut VhFrame) -> i32, | 174 | next_frame: unsafe extern "C" fn(*mut c_void, *mut VhFrame) -> i32, |
| 175 | + /// The zero-copy door, and optional for the same reason [`Plugin::caps`] is: | ||
| 176 | + /// a plugin built before it decodes exactly as it did, through the read-back | ||
| 177 | + /// above. | ||
| 178 | + next_frame_dma: Option< | ||
| 179 | + unsafe extern "C" fn(*mut c_void, *mut VhFrame, *mut VhDma, u32, u32, u32, u32) -> i32, | ||
| 180 | + >, | ||
| 93 | close: unsafe extern "C" fn(*mut c_void), | 181 | close: unsafe extern "C" fn(*mut c_void), |
| 94 | /// The capability query, and the one symbol of this table that may be | 182 | /// The capability query, and the one symbol of this table that may be |
| 95 | /// missing: a plugin built before it exports the four above and not this, | 183 | /// missing: a plugin built before it exports the four above and not this, |
| @@ -129,6 +217,7 @@ fn load() -> Option<Plugin> { | |||
| 129 | open_at: *lib.get(b"vh_open_at\0").ok()?, | 217 | open_at: *lib.get(b"vh_open_at\0").ok()?, |
| 130 | meta: *lib.get(b"vh_meta\0").ok()?, | 218 | meta: *lib.get(b"vh_meta\0").ok()?, |
| 131 | next_frame: *lib.get(b"vh_next_frame\0").ok()?, | 219 | next_frame: *lib.get(b"vh_next_frame\0").ok()?, |
| 220 | + next_frame_dma: lib.get(b"vh_next_frame_dma\0").ok().map(|s| *s), | ||
| 132 | close: *lib.get(b"vh_close\0").ok()?, | 221 | close: *lib.get(b"vh_close\0").ok()?, |
| 133 | caps: lib.get(b"vh_caps\0").ok().map(|s| *s), | 222 | caps: lib.get(b"vh_caps\0").ok().map(|s| *s), |
| 134 | _lib: lib, | 223 | _lib: lib, |
| @@ -214,6 +303,55 @@ impl HwSession { | |||
| 214 | 1 => {} | 303 | 1 => {} |
| 215 | code => return Err(format!("hardware decode failed (code {code})").into()), | 304 | code => return Err(format!("hardware decode failed (code {code})").into()), |
| 216 | } | 305 | } |
| 306 | + self.pixels(&frame).map(Some) | ||
| 307 | + } | ||
| 308 | + | ||
| 309 | + /// The next picture *without reading it back* where the caller's encoder can | ||
| 310 | + /// take the buffer the decoder wrote into -- which is what `want` describes, | ||
| 311 | + /// down to the coded size, because an encoder reads a surface of its own | ||
| 312 | + /// shape or none at all. | ||
| 313 | + /// | ||
| 314 | + /// Anything the plugin cannot hand over that way comes back as pixels | ||
| 315 | + /// instead ([`HwPicture::Pixels`]), so a mismatch costs the read-back it | ||
| 316 | + /// always cost and never a frame. A plugin too old to know the door exists | ||
| 317 | + /// is the same answer. | ||
| 318 | + /// | ||
| 319 | + /// The buffer behind a [`DmaFrame`] is the decoder's, held out of its pool | ||
| 320 | + /// for a few pictures only: encode it before asking this for a few more. | ||
| 321 | + pub fn next_frame_dma(&mut self, want: DmaWant) -> crate::Result<Option<HwPicture<'_>>> { | ||
| 322 | + let Some(next_dma) = self.plugin.next_frame_dma else { | ||
| 323 | + return Ok(self.next_frame()?.map(|(y, u, v, w, h)| HwPicture::Pixels(y, u, v, w, h))); | ||
| 324 | + }; | ||
| 325 | + let mut frame = VhFrame::default(); | ||
| 326 | + let mut dma = VhDma::default(); | ||
| 327 | + // SAFETY: as `next_frame`, plus a writable descriptor whose `fd` the | ||
| 328 | + // plugin either hands us ownership of or leaves at -1. | ||
| 329 | + let code = unsafe { | ||
| 330 | + next_dma( | ||
| 331 | + self.handle, | ||
| 332 | + &mut frame, | ||
| 333 | + &mut dma, | ||
| 334 | + want.coded_width, | ||
| 335 | + want.coded_height, | ||
| 336 | + want.width, | ||
| 337 | + want.height, | ||
| 338 | + ) | ||
| 339 | + }; | ||
| 340 | + match code { | ||
| 341 | + 0 => return Ok(None), | ||
| 342 | + 1 => {} | ||
| 343 | + code => return Err(format!("hardware decode failed (code {code})").into()), | ||
| 344 | + } | ||
| 345 | + if dma.fd[0] >= 0 { | ||
| 346 | + return Ok(Some(HwPicture::Dma(DmaFrame(dma)))); | ||
| 347 | + } | ||
| 348 | + let (y, u, v, w, h) = self.pixels(&frame)?; | ||
| 349 | + Ok(Some(HwPicture::Pixels(y, u, v, w, h))) | ||
| 350 | + } | ||
| 351 | + | ||
| 352 | + /// The plugin's plane pointers as slices, checked against the strides it | ||
| 353 | + /// declares -- the one shape this side takes. | ||
| 354 | + fn pixels(&self, frame: &VhFrame) -> crate::Result<(&[u8], &[u8], &[u8], u32, u32)> { | ||
| 217 | let (w, h) = (frame.width as usize, frame.height as usize); | 355 | let (w, h) = (frame.width as usize, frame.height as usize); |
| 218 | let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); | 356 | let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); |
| 219 | if frame.y.is_null() | 357 | if frame.y.is_null() |
| @@ -228,17 +366,34 @@ impl HwSession { | |||
| 228 | // SAFETY: plane pointers are non-null and the strides just checked above | 366 | // SAFETY: plane pointers are non-null and the strides just checked above |
| 229 | // pin each plane's length; the borrow ends before the next call. | 367 | // pin each plane's length; the borrow ends before the next call. |
| 230 | unsafe { | 368 | unsafe { |
| 231 | - Ok(Some(( | 369 | + Ok(( |
| 232 | std::slice::from_raw_parts(frame.y, w * h), | 370 | std::slice::from_raw_parts(frame.y, w * h), |
| 233 | std::slice::from_raw_parts(frame.u, cw * ch), | 371 | std::slice::from_raw_parts(frame.u, cw * ch), |
| 234 | std::slice::from_raw_parts(frame.v, cw * ch), | 372 | std::slice::from_raw_parts(frame.v, cw * ch), |
| 235 | frame.width, | 373 | frame.width, |
| 236 | frame.height, | 374 | frame.height, |
| 237 | - ))) | 375 | + )) |
| 238 | } | 376 | } |
| 239 | } | 377 | } |
| 240 | } | 378 | } |
| 241 | 379 | ||
| 380 | +/// What an encoder needs a decoded buffer to look like before it can read it | ||
| 381 | +/// without a copy: the surface's coded size and the picture inside it. | ||
| 382 | +#[derive(Clone, Copy)] | ||
| 383 | +pub struct DmaWant { | ||
| 384 | + pub coded_width: u32, | ||
| 385 | + pub coded_height: u32, | ||
| 386 | + pub width: u32, | ||
| 387 | + pub height: u32, | ||
| 388 | +} | ||
| 389 | + | ||
| 390 | +/// One picture out of [`HwSession::next_frame_dma`]: still on the GPU, or read | ||
| 391 | +/// back like every other frame. | ||
| 392 | +pub enum HwPicture<'a> { | ||
| 393 | + Pixels(&'a [u8], &'a [u8], &'a [u8], u32, u32), | ||
| 394 | + Dma(DmaFrame), | ||
| 395 | +} | ||
| 396 | + | ||
| 242 | impl Drop for HwSession { | 397 | impl Drop for HwSession { |
| 243 | fn drop(&mut self) { | 398 | fn drop(&mut self) { |
| 244 | // SAFETY: `handle` came from `vh_open_at` and is closed exactly once. | 399 | // SAFETY: `handle` came from `vh_open_at` and is closed exactly once. |
| @@ -264,6 +419,12 @@ struct EncPlugin { | |||
| 264 | open_hevc: Option<extern "C" fn(u32, u32, u32, u32, u64) -> *mut c_void>, | 419 | open_hevc: Option<extern "C" fn(u32, u32, u32, u32, u64) -> *mut c_void>, |
| 265 | frame: | 420 | frame: |
| 266 | unsafe extern "C" fn(*mut c_void, *const VhFrame, i32, *mut *const u8, *mut usize) -> i32, | 421 | unsafe extern "C" fn(*mut c_void, *const VhFrame, i32, *mut *const u8, *mut usize) -> i32, |
| 422 | + /// The zero-copy pair, both optional together: an older plugin exports | ||
| 423 | + /// neither and every picture reaches it as bytes, which is what it always | ||
| 424 | + /// did. | ||
| 425 | + dma_geometry: Option<unsafe extern "C" fn(*mut c_void, *mut u32, *mut u32) -> i32>, | ||
| 426 | + frame_dma: | ||
| 427 | + Option<unsafe extern "C" fn(*mut c_void, *const VhDma, i32, *mut *const u8, *mut usize) -> i32>, | ||
| 267 | drain: unsafe extern "C" fn(*mut c_void, *mut *const u8, *mut usize) -> i32, | 428 | drain: unsafe extern "C" fn(*mut c_void, *mut *const u8, *mut usize) -> i32, |
| 268 | close: unsafe extern "C" fn(*mut c_void), | 429 | close: unsafe extern "C" fn(*mut c_void), |
| 269 | // Never dropped (lives in a static), so the fn pointers above stay valid. | 430 | // Never dropped (lives in a static), so the fn pointers above stay valid. |
| @@ -290,6 +451,8 @@ fn load_enc() -> Option<EncPlugin> { | |||
| 290 | open_av1: lib.get(b"vh_enc_av1_open\0").ok().map(|s| *s), | 451 | open_av1: lib.get(b"vh_enc_av1_open\0").ok().map(|s| *s), |
| 291 | open_hevc: lib.get(b"vh_enc_hevc_open\0").ok().map(|s| *s), | 452 | open_hevc: lib.get(b"vh_enc_hevc_open\0").ok().map(|s| *s), |
| 292 | frame: *lib.get(b"vh_enc_frame\0").ok()?, | 453 | frame: *lib.get(b"vh_enc_frame\0").ok()?, |
| 454 | + dma_geometry: lib.get(b"vh_enc_dma_geometry\0").ok().map(|s| *s), | ||
| 455 | + frame_dma: lib.get(b"vh_enc_frame_dma\0").ok().map(|s| *s), | ||
| 293 | drain: *lib.get(b"vh_enc_drain\0").ok()?, | 456 | drain: *lib.get(b"vh_enc_drain\0").ok()?, |
| 294 | close: *lib.get(b"vh_enc_close\0").ok()?, | 457 | close: *lib.get(b"vh_enc_close\0").ok()?, |
| 295 | _lib: lib, | 458 | _lib: lib, |
| @@ -423,6 +586,41 @@ impl HwEncoder { | |||
| 423 | }) | 586 | }) |
| 424 | } | 587 | } |
| 425 | 588 | ||
| 589 | + /// What a decoded buffer must look like to reach this encoder without a | ||
| 590 | + /// copy -- the surface size it codes in, plus the picture it was opened for | ||
| 591 | + /// -- or `None` where the plugin has no zero-copy door at all. | ||
| 592 | + pub fn dma_want(&self, width: u32, height: u32) -> Option<DmaWant> { | ||
| 593 | + let geometry = self.plugin.dma_geometry?; | ||
| 594 | + self.plugin.frame_dma?; | ||
| 595 | + let (mut coded_width, mut coded_height) = (0u32, 0u32); | ||
| 596 | + // SAFETY: `handle` is live and both destinations are writable. | ||
| 597 | + if unsafe { geometry(self.handle, &mut coded_width, &mut coded_height) } != 1 { | ||
| 598 | + return None; | ||
| 599 | + } | ||
| 600 | + Some(DmaWant { | ||
| 601 | + coded_width, | ||
| 602 | + coded_height, | ||
| 603 | + width, | ||
| 604 | + height, | ||
| 605 | + }) | ||
| 606 | + } | ||
| 607 | + | ||
| 608 | + /// Feeds one picture the decoder left on the GPU. Same answer and same | ||
| 609 | + /// lifetime rule as [`HwEncoder::encode`]; an error here is a real one, the | ||
| 610 | + /// caller having asked [`HwEncoder::dma_want`] what this seat takes before | ||
| 611 | + /// the decoder handed the buffer over. | ||
| 612 | + pub fn encode_dma(&mut self, dma: &DmaFrame, force_key: bool) -> crate::Result<Option<&[u8]>> { | ||
| 613 | + let Some(frame_dma) = self.plugin.frame_dma else { | ||
| 614 | + return Err("hardware encoder has no zero-copy path".into()); | ||
| 615 | + }; | ||
| 616 | + let desc = dma.0; | ||
| 617 | + // SAFETY: `handle` is live and `desc` outlives the call; the buffer it | ||
| 618 | + // names is the decode session's, held for the caller by contract. | ||
| 619 | + self.take(|_, handle, out, out_len| unsafe { | ||
| 620 | + frame_dma(handle, &desc, force_key as i32, out, out_len) | ||
| 621 | + }) | ||
| 622 | + } | ||
| 623 | + | ||
| 426 | /// Flushes the encoder; call until it returns `Ok(None)`. Same lifetime rule | 624 | /// Flushes the encoder; call until it returns `Ok(None)`. Same lifetime rule |
| 427 | /// as [`HwEncoder::encode`]. | 625 | /// as [`HwEncoder::encode`]. |
| 428 | pub fn drain(&mut self) -> crate::Result<Option<&[u8]>> { | 626 | pub fn drain(&mut self) -> crate::Result<Option<&[u8]>> { |
crates/engine/tests/hw_encode.rsmodified+77 -1
| @@ -14,7 +14,7 @@ | |||
| 14 | 14 | ||
| 15 | use std::time::{Duration, Instant}; | 15 | use std::time::{Duration, Instant}; |
| 16 | 16 | ||
| 17 | -use engine::hw::{HwEncoder, HwSession}; | 17 | +use engine::hw::{HwEncoder, HwPicture, HwSession}; |
| 18 | 18 | ||
| 19 | const FPS: u32 = 30; | 19 | const FPS: u32 = 30; |
| 20 | const BITRATE: u64 = 4_000_000; | 20 | const BITRATE: u64 = 4_000_000; |
| @@ -140,6 +140,82 @@ fn round_trips_unaligned_dimensions() { | |||
| 140 | ); | 140 | ); |
| 141 | } | 141 | } |
| 142 | 142 | ||
| 143 | +/// The zero-copy path: a picture the hardware decoder wrote goes into the | ||
| 144 | +/// hardware encoder as the buffer it was decoded into, never read back and never | ||
| 145 | +/// written out again -- which is what makes an export of an untouched clip cost | ||
| 146 | +/// no `vaGetImage`, no colour conversion and no upload per frame. | ||
| 147 | +/// | ||
| 148 | +/// Two things are checked and the second is the one that matters. That the | ||
| 149 | +/// buffers are handed over *at all* (a driver whose export the plugin refuses | ||
| 150 | +/// falls back to pixels, silently and correctly, which would make a speed claim | ||
| 151 | +/// a lie). And that what came out is what went in: the encoded stream is decoded | ||
| 152 | +/// in software and compared against the same file decoded through the read-back | ||
| 153 | +/// path, so a wrong plane offset, a swapped object or an unsynchronised surface | ||
| 154 | +/// -- the ways an imported buffer goes wrong -- fails here instead of shipping | ||
| 155 | +/// as a garbled export. | ||
| 156 | +#[test] | ||
| 157 | +#[ignore = "needs libengine_hw.so and a VA-API driver with H.264 decode and encode"] | ||
| 158 | +fn a_decoded_buffer_is_encoded_without_ever_being_read_back() { | ||
| 159 | + const FRAMES: usize = 24; | ||
| 160 | + let asset = | ||
| 161 | + std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_baseline.mp4"); | ||
| 162 | + let (width, height) = (1280u32, 720u32); | ||
| 163 | + let Some(mut encoder) = HwEncoder::open(width, height, FPS, 1, BITRATE) else { | ||
| 164 | + println!("no hardware encoder here -- skipping"); | ||
| 165 | + return; | ||
| 166 | + }; | ||
| 167 | + let Some(want) = encoder.dma_want(width, height) else { | ||
| 168 | + panic!("a hardware encoder that takes no imported buffer at all"); | ||
| 169 | + }; | ||
| 170 | + let mut session = HwSession::open(&asset).expect("hardware decode of the fixture"); | ||
| 171 | + | ||
| 172 | + let mut stream = Vec::new(); | ||
| 173 | + let mut buffers = 0; | ||
| 174 | + for index in 0..FRAMES { | ||
| 175 | + match session.next_frame_dma(want).expect("hardware decode") { | ||
| 176 | + Some(HwPicture::Dma(dma)) => { | ||
| 177 | + assert_eq!((dma.width(), dma.height()), (width, height), "frame {index}"); | ||
| 178 | + buffers += 1; | ||
| 179 | + if let Some(au) = encoder.encode_dma(&dma, false).expect("encode") { | ||
| 180 | + stream.extend_from_slice(au); | ||
| 181 | + } | ||
| 182 | + } | ||
| 183 | + Some(HwPicture::Pixels(..)) => panic!("frame {index} was read back after all"), | ||
| 184 | + None => panic!("the fixture ran out at frame {index}"), | ||
| 185 | + } | ||
| 186 | + } | ||
| 187 | + while let Some(au) = encoder.drain().expect("drain") { | ||
| 188 | + stream.extend_from_slice(au); | ||
| 189 | + } | ||
| 190 | + assert_eq!(buffers, FRAMES, "every picture came over as a buffer"); | ||
| 191 | + | ||
| 192 | + // The same file down the path this one exists to avoid, which is the only | ||
| 193 | + // honest reference for "the encoder read the right pixels". | ||
| 194 | + let mut reference = HwSession::open(&asset).expect("hardware decode of the fixture"); | ||
| 195 | + let coded = decode(&stream); | ||
| 196 | + assert_eq!(coded.len(), FRAMES, "decoded picture count"); | ||
| 197 | + for (index, frame) in coded.iter().enumerate() { | ||
| 198 | + let (y, u, v, w, h) = reference | ||
| 199 | + .next_frame() | ||
| 200 | + .expect("read-back decode") | ||
| 201 | + .expect("the fixture is longer than this"); | ||
| 202 | + assert_eq!((w, h), (width, height), "frame {index}"); | ||
| 203 | + for (plane, (got, want)) in [(&frame.y, y), (&frame.u, u), (&frame.v, v)] | ||
| 204 | + .iter() | ||
| 205 | + .enumerate() | ||
| 206 | + { | ||
| 207 | + // Lossy CBR against the source picture: the same tolerance the | ||
| 208 | + // synthetic round trip above uses, and nowhere near what a swapped | ||
| 209 | + // plane or a stale surface would cost. | ||
| 210 | + let diff = mean_abs_diff(got, want); | ||
| 211 | + assert!( | ||
| 212 | + diff < 6.0, | ||
| 213 | + "frame {index} plane {plane} drifted by {diff:.2}" | ||
| 214 | + ); | ||
| 215 | + } | ||
| 216 | + } | ||
| 217 | +} | ||
| 218 | + | ||
| 143 | /// Decode and encode resolve through two independent symbol tables, so an | 219 | /// Decode and encode resolve through two independent symbol tables, so an |
| 144 | /// encoder that cannot load must not cost us the decoder (and vice versa). | 220 | /// encoder that cannot load must not cost us the decoder (and vice versa). |
| 145 | /// | 221 | /// |