| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | use std::collections::VecDeque; |
| 20 | use std::ffi::OsString; |
| 21 | use std::os::fd::OwnedFd; |
| 22 | use std::path::Path; |
| 23 | use std::process::Child; |
| 24 | use std::sync::OnceLock; |
| 25 | use std::sync::mpsc::{self, Receiver, Sender, SyncSender, TryRecvError}; |
| 26 | use std::thread::JoinHandle; |
| 27 | |
| 28 | use crate::colorspace::ColorDescription; |
| 29 | use crate::hwproc::{ |
| 30 | DMA_BODY, HW_LOST, K_DMA, K_PIXELS, K_PIXELS16, Lost, Open, R_AU, R_ERR, R_NONE, Remote, Seat, SeatRate, Shm, |
| 31 | T_NEXT, T_NEXT_DMA, T_NEXT_DMA16, T_NEXT_WIDE, T_SEEK, pack16, recv_reply, send_msg, spawn_child, |
| 32 | }; |
| 33 | |
| 34 | #[cfg(test)] |
| 35 | thread_local! { |
| 36 | |
| 37 | |
| 38 | |
| 39 | pub(crate) static OPEN_ATTEMPTS: std::cell::Cell<u32> = const { std::cell::Cell::new(0) }; |
| 40 | } |
| 41 | |
| 42 | |
| 43 | |
| 44 | type Planes<'a> = (&'a [u8], &'a [u8], &'a [u8], u32, u32); |
| 45 | |
| 46 | |
| 47 | |
| 48 | |
| 49 | |
| 50 | |
| 51 | |
| 52 | |
| 53 | |
| 54 | #[derive(Default, Clone, Copy, Debug, PartialEq)] |
| 55 | pub struct VhMeta { |
| 56 | pub width: u32, |
| 57 | pub height: u32, |
| 58 | pub frame_rate: f64, |
| 59 | pub frame_count: u32, |
| 60 | pub coded_width: u32, |
| 61 | pub coded_height: u32, |
| 62 | pub pixel_aspect_h: u32, |
| 63 | pub pixel_aspect_v: u32, |
| 64 | } |
| 65 | |
| 66 | |
| 67 | |
| 68 | pub const META_WIRE: usize = 36; |
| 69 | |
| 70 | |
| 71 | pub fn meta_to_wire(meta: &VhMeta) -> [u8; META_WIRE] { |
| 72 | let mut out = [0u8; META_WIRE]; |
| 73 | out[0..4].copy_from_slice(&meta.width.to_le_bytes()); |
| 74 | out[4..8].copy_from_slice(&meta.height.to_le_bytes()); |
| 75 | out[8..16].copy_from_slice(&meta.frame_rate.to_bits().to_le_bytes()); |
| 76 | out[16..20].copy_from_slice(&meta.frame_count.to_le_bytes()); |
| 77 | out[20..24].copy_from_slice(&meta.coded_width.to_le_bytes()); |
| 78 | out[24..28].copy_from_slice(&meta.coded_height.to_le_bytes()); |
| 79 | out[28..32].copy_from_slice(&meta.pixel_aspect_h.to_le_bytes()); |
| 80 | out[32..36].copy_from_slice(&meta.pixel_aspect_v.to_le_bytes()); |
| 81 | out |
| 82 | } |
| 83 | |
| 84 | |
| 85 | pub fn meta_from_wire(bytes: &[u8]) -> Option<VhMeta> { |
| 86 | if bytes.len() != META_WIRE { |
| 87 | return None; |
| 88 | } |
| 89 | let u32_at = |at: usize| Some(u32::from_le_bytes(bytes.get(at..at + 4)?.try_into().ok()?)); |
| 90 | Some(VhMeta { |
| 91 | width: u32_at(0)?, |
| 92 | height: u32_at(4)?, |
| 93 | frame_rate: f64::from_bits(u64::from_le_bytes(bytes.get(8..16)?.try_into().ok()?)), |
| 94 | frame_count: u32_at(16)?, |
| 95 | coded_width: u32_at(20)?, |
| 96 | coded_height: u32_at(24)?, |
| 97 | pixel_aspect_h: u32_at(28)?, |
| 98 | pixel_aspect_v: u32_at(32)?, |
| 99 | }) |
| 100 | } |
| 101 | |
| 102 | |
| 103 | |
| 104 | #[derive(Default, Clone, Copy, Debug, PartialEq, Eq)] |
| 105 | pub struct VhCaps { |
| 106 | pub decode: u32, |
| 107 | pub encode: u32, |
| 108 | |
| 109 | pub decode_10bit: u32, |
| 110 | } |
| 111 | |
| 112 | pub const CAP_H264: u32 = 1 << 0; |
| 113 | pub const CAP_HEVC: u32 = 1 << 1; |
| 114 | pub const CAP_VP9: u32 = 1 << 2; |
| 115 | pub const CAP_AV1: u32 = 1 << 3; |
| 116 | |
| 117 | |
| 118 | |
| 119 | |
| 120 | |
| 121 | pub const CAP_VP8: u32 = 1 << 4; |
| 122 | |
| 123 | |
| 124 | |
| 125 | |
| 126 | #[derive(Default, Clone, Copy, Debug, PartialEq, Eq)] |
| 127 | pub struct VhDma { |
| 128 | |
| 129 | pub fourcc: u32, |
| 130 | |
| 131 | pub modifier: u64, |
| 132 | |
| 133 | pub coded_width: u32, |
| 134 | pub coded_height: u32, |
| 135 | |
| 136 | pub width: u32, |
| 137 | pub height: u32, |
| 138 | |
| 139 | pub offset: [u32; 2], |
| 140 | pub stride: [u32; 2], |
| 141 | } |
| 142 | |
| 143 | |
| 144 | |
| 145 | |
| 146 | |
| 147 | #[derive(Debug)] |
| 148 | pub struct DmaFrame { |
| 149 | pub desc: VhDma, |
| 150 | |
| 151 | pub fds: Vec<OwnedFd>, |
| 152 | } |
| 153 | |
| 154 | impl DmaFrame { |
| 155 | pub fn width(&self) -> u32 { |
| 156 | self.desc.width |
| 157 | } |
| 158 | |
| 159 | pub fn height(&self) -> u32 { |
| 160 | self.desc.height |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | |
| 165 | fn i420_bytes(width: u32, height: u32) -> usize { |
| 166 | let (w, h) = (width as usize, height as usize); |
| 167 | w * h + 2 * (w.div_ceil(2) * h.div_ceil(2)) |
| 168 | } |
| 169 | |
| 170 | |
| 171 | fn le_u32(bytes: &[u8], at: usize) -> Option<u32> { |
| 172 | Some(u32::from_le_bytes(bytes.get(at..at + 4)?.try_into().ok()?)) |
| 173 | } |
| 174 | |
| 175 | |
| 176 | |
| 177 | |
| 178 | |
| 179 | |
| 180 | |
| 181 | |
| 182 | |
| 183 | pub fn caps() -> Option<VhCaps> { |
| 184 | static CAPS: OnceLock<Option<VhCaps>> = OnceLock::new(); |
| 185 | *CAPS.get_or_init(query_caps) |
| 186 | } |
| 187 | |
| 188 | fn query_caps() -> Option<VhCaps> { |
| 189 | let (mut child, mut sock) = spawn_child(&[OsString::from("caps")])?; |
| 190 | let mut body = Vec::new(); |
| 191 | let answer = match recv_reply(&mut sock, &mut body) { |
| 192 | Ok((R_AU, _)) => Some(VhCaps { |
| 193 | decode: le_u32(&body, 0)?, |
| 194 | encode: le_u32(&body, 4)?, |
| 195 | decode_10bit: le_u32(&body, 8)?, |
| 196 | }), |
| 197 | _ => None, |
| 198 | }; |
| 199 | reap(&mut child); |
| 200 | answer |
| 201 | } |
| 202 | |
| 203 | |
| 204 | |
| 205 | fn reap(child: &mut Child) { |
| 206 | let _ = child.kill(); |
| 207 | let _ = child.wait(); |
| 208 | } |
| 209 | |
| 210 | |
| 211 | |
| 212 | static FAIL_AFTER: std::sync::atomic::AtomicI64 = std::sync::atomic::AtomicI64::new(-1); |
| 213 | |
| 214 | |
| 215 | |
| 216 | |
| 217 | |
| 218 | #[doc(hidden)] |
| 219 | pub fn inject_failure_after(pictures: Option<u64>) { |
| 220 | let value = pictures.map_or(-1, |n| i64::try_from(n).unwrap_or(i64::MAX)); |
| 221 | FAIL_AFTER.store(value, std::sync::atomic::Ordering::SeqCst); |
| 222 | } |
| 223 | |
| 224 | fn injected_failure() -> Option<u64> { |
| 225 | match FAIL_AFTER.load(std::sync::atomic::Ordering::SeqCst) { |
| 226 | n if n >= 0 => Some(n as u64), |
| 227 | _ => crate::envcfg::var("EC_HW_FAIL_AT")?.parse().ok(), |
| 228 | } |
| 229 | } |
| 230 | |
| 231 | |
| 232 | enum Fetched { |
| 233 | |
| 234 | Pixels, |
| 235 | |
| 236 | Dma(DmaFrame), |
| 237 | } |
| 238 | |
| 239 | |
| 240 | |
| 241 | pub struct HwSession { |
| 242 | child: Child, |
| 243 | sock: std::os::unix::net::UnixStream, |
| 244 | |
| 245 | |
| 246 | shm: Shm, |
| 247 | meta: VhMeta, |
| 248 | |
| 249 | body: Vec<u8>, |
| 250 | |
| 251 | pixels: Vec<u8>, |
| 252 | |
| 253 | pixels_wide: bool, |
| 254 | |
| 255 | |
| 256 | lost: Option<String>, |
| 257 | |
| 258 | |
| 259 | fail_after: Option<u64>, |
| 260 | delivered: u64, |
| 261 | } |
| 262 | |
| 263 | impl HwSession { |
| 264 | |
| 265 | |
| 266 | pub fn open(path: &Path) -> Option<Self> { |
| 267 | Self::open_at(path, 0) |
| 268 | } |
| 269 | |
| 270 | |
| 271 | |
| 272 | |
| 273 | pub fn open_at(path: &Path, start_frame: u32) -> Option<Self> { |
| 274 | #[cfg(test)] |
| 275 | OPEN_ATTEMPTS.with(|n| n.set(n.get() + 1)); |
| 276 | |
| 277 | let target_sample = start_frame.saturating_add(1); |
| 278 | let args = [ |
| 279 | OsString::from("decode"), |
| 280 | path.as_os_str().to_owned(), |
| 281 | OsString::from(target_sample.to_string()), |
| 282 | ]; |
| 283 | let (mut child, mut sock) = spawn_child(&args)?; |
| 284 | let mut body = Vec::new(); |
| 285 | let opened = match recv_reply(&mut sock, &mut body) { |
| 286 | Ok((R_AU, mut fds)) if fds.len() == 1 => { |
| 287 | meta_from_wire(&body).map(|meta| (meta, fds.remove(0))) |
| 288 | } |
| 289 | |
| 290 | _ => None, |
| 291 | }; |
| 292 | let Some((meta, fd)) = opened else { |
| 293 | reap(&mut child); |
| 294 | return None; |
| 295 | }; |
| 296 | Some(Self { |
| 297 | child, |
| 298 | sock, |
| 299 | shm: Shm::from_fd(fd, i420_bytes(meta.width, meta.height)), |
| 300 | meta, |
| 301 | body, |
| 302 | pixels: Vec::new(), |
| 303 | pixels_wide: false, |
| 304 | lost: None, |
| 305 | fail_after: injected_failure(), |
| 306 | delivered: 0, |
| 307 | }) |
| 308 | } |
| 309 | |
| 310 | |
| 311 | |
| 312 | |
| 313 | |
| 314 | |
| 315 | pub fn seek(&mut self, start_frame: u32) -> bool { |
| 316 | |
| 317 | let target_sample = start_frame.saturating_add(1); |
| 318 | let moved = matches!(self.call(T_SEEK, &target_sample.to_le_bytes()), Ok((R_AU, _))); |
| 319 | if moved { |
| 320 | self.delivered = 0; |
| 321 | } |
| 322 | moved |
| 323 | } |
| 324 | |
| 325 | |
| 326 | fn inject(&mut self) -> crate::Result<()> { |
| 327 | if let Some(limit) = self.fail_after { |
| 328 | if self.delivered >= limit { |
| 329 | return Err(format!("injected hardware error after {limit} pictures").into()); |
| 330 | } |
| 331 | self.delivered += 1; |
| 332 | } |
| 333 | Ok(()) |
| 334 | } |
| 335 | |
| 336 | pub fn meta(&self) -> Option<VhMeta> { |
| 337 | Some(self.meta) |
| 338 | } |
| 339 | |
| 340 | |
| 341 | |
| 342 | pub fn next_frame(&mut self) -> crate::Result<Option<Planes<'_>>> { |
| 343 | self.inject()?; |
| 344 | match self.fetch(T_NEXT, &[])? { |
| 345 | None => Ok(None), |
| 346 | Some(Fetched::Pixels) => Ok(Some(self.planes())), |
| 347 | Some(Fetched::Dma(_)) => Err("the decoder handed over a GPU buffer nobody asked for".into()), |
| 348 | } |
| 349 | } |
| 350 | |
| 351 | |
| 352 | |
| 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 | |
| 366 | |
| 367 | |
| 368 | |
| 369 | |
| 370 | |
| 371 | |
| 372 | |
| 373 | |
| 374 | pub fn next_frame_dma(&mut self, want: DmaWant) -> crate::Result<Option<HwPicture<'_>>> { |
| 375 | self.inject()?; |
| 376 | let mut body = Vec::with_capacity(16); |
| 377 | for value in [want.coded_width, want.coded_height, want.width, want.height] { |
| 378 | body.extend_from_slice(&value.to_le_bytes()); |
| 379 | } |
| 380 | match self.fetch(if want.ten_bit { T_NEXT_DMA16 } else { T_NEXT_DMA }, &body)? { |
| 381 | None => Ok(None), |
| 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 | } |
| 387 | Some(Fetched::Pixels) => { |
| 388 | let (y, u, v, width, height) = self.planes(); |
| 389 | Ok(Some(HwPicture::Pixels(y, u, v, width, height))) |
| 390 | } |
| 391 | } |
| 392 | } |
| 393 | |
| 394 | |
| 395 | |
| 396 | fn fetch(&mut self, request: u8, body: &[u8]) -> crate::Result<Option<Fetched>> { |
| 397 | let (tag, mut fds) = self.call(request, body)?; |
| 398 | if tag == R_NONE { |
| 399 | return Ok(None); |
| 400 | } |
| 401 | let reply = self.body.clone(); |
| 402 | match reply.first().copied() { |
| 403 | Some(kind @ (K_PIXELS | K_PIXELS16)) if tag == R_AU => { |
| 404 | let bad = || -> crate::Error { "the decoder sent a short picture header".into() }; |
| 405 | let width = le_u32(&reply, 1).ok_or_else(bad)?; |
| 406 | let height = le_u32(&reply, 5).ok_or_else(bad)?; |
| 407 | self.pixels_wide = kind == K_PIXELS16; |
| 408 | let needed = i420_bytes(width, height) * if self.pixels_wide { 2 } else { 1 }; |
| 409 | if let Some(fd) = fds.pop() { |
| 410 | |
| 411 | self.shm = Shm::from_fd(fd, needed); |
| 412 | } |
| 413 | if needed > self.shm.capacity() { |
| 414 | return Err(format!("a {width}x{height} picture does not fit the staging buffer").into()); |
| 415 | } |
| 416 | self.shm |
| 417 | .read_into(&mut self.pixels, needed) |
| 418 | .map_err(|e| format!("cannot read the staging buffer: {e}"))?; |
| 419 | self.meta.width = width; |
| 420 | self.meta.height = height; |
| 421 | Ok(Some(Fetched::Pixels)) |
| 422 | } |
| 423 | Some(K_DMA) if tag == R_AU => { |
| 424 | let desc = dma_from_wire(&reply).ok_or("the decoder sent a short GPU buffer header")?; |
| 425 | let count = usize::from(*reply.get(DMA_BODY).ok_or("the decoder sent a short GPU buffer header")?); |
| 426 | if fds.len() != count || !(1..=2).contains(&count) { |
| 427 | return Err(format!("the decoder's GPU buffer came without its descriptors ({} of {count})", fds.len()).into()); |
| 428 | } |
| 429 | self.meta.width = desc.width; |
| 430 | self.meta.height = desc.height; |
| 431 | Ok(Some(Fetched::Dma(DmaFrame { desc, fds }))) |
| 432 | } |
| 433 | _ => Err(format!("unexpected reply {tag} from the decoder").into()), |
| 434 | } |
| 435 | } |
| 436 | |
| 437 | |
| 438 | fn planes(&self) -> Planes<'_> { |
| 439 | let (w, h) = (self.meta.width as usize, self.meta.height as usize); |
| 440 | let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); |
| 441 | let (y, rest) = self.pixels.split_at(w * h); |
| 442 | let (u, rest) = rest.split_at(cw * ch); |
| 443 | (y, u, &rest[..cw * ch], self.meta.width, self.meta.height) |
| 444 | } |
| 445 | |
| 446 | |
| 447 | |
| 448 | fn call(&mut self, tag: u8, body: &[u8]) -> crate::Result<(u8, Vec<OwnedFd>)> { |
| 449 | if let Some(gone) = &self.lost { |
| 450 | return Err(Lost(gone.clone()).into()); |
| 451 | } |
| 452 | let mut msg = Vec::with_capacity(1 + body.len()); |
| 453 | msg.push(tag); |
| 454 | msg.extend_from_slice(body); |
| 455 | if let Err(e) = send_msg(&self.sock, &msg, &[]) { |
| 456 | return Err(self.bury(&e.to_string())); |
| 457 | } |
| 458 | match recv_reply(&mut self.sock, &mut self.body) { |
| 459 | Ok((R_ERR, _)) => Err(String::from_utf8_lossy(&self.body).into_owned().into()), |
| 460 | Ok(answer) => Ok(answer), |
| 461 | Err(e) => Err(self.bury(&e.to_string())), |
| 462 | } |
| 463 | } |
| 464 | |
| 465 | fn bury(&mut self, why: &str) -> crate::Error { |
| 466 | reap(&mut self.child); |
| 467 | let message = format!("{HW_LOST} stopped answering ({why}) and was killed; the driver took it down and not the editor"); |
| 468 | self.lost = Some(message.clone()); |
| 469 | Lost(message).into() |
| 470 | } |
| 471 | } |
| 472 | |
| 473 | |
| 474 | fn dma_from_wire(body: &[u8]) -> Option<VhDma> { |
| 475 | let at = 1; |
| 476 | Some(VhDma { |
| 477 | fourcc: le_u32(body, at)?, |
| 478 | modifier: u64::from_le_bytes(body.get(at + 4..at + 12)?.try_into().ok()?), |
| 479 | coded_width: le_u32(body, at + 12)?, |
| 480 | coded_height: le_u32(body, at + 16)?, |
| 481 | width: le_u32(body, at + 20)?, |
| 482 | height: le_u32(body, at + 24)?, |
| 483 | offset: [le_u32(body, at + 28)?, le_u32(body, at + 32)?], |
| 484 | stride: [le_u32(body, at + 36)?, le_u32(body, at + 40)?], |
| 485 | }) |
| 486 | } |
| 487 | |
| 488 | impl Drop for HwSession { |
| 489 | fn drop(&mut self) { |
| 490 | reap(&mut self.child); |
| 491 | } |
| 492 | } |
| 493 | |
| 494 | |
| 495 | |
| 496 | #[derive(Clone, Copy, PartialEq, Eq)] |
| 497 | pub struct DmaWant { |
| 498 | pub coded_width: u32, |
| 499 | pub coded_height: u32, |
| 500 | pub width: u32, |
| 501 | pub height: u32, |
| 502 | pub ten_bit: bool, |
| 503 | } |
| 504 | |
| 505 | |
| 506 | |
| 507 | pub enum HwFrame<'a> { |
| 508 | Narrow(Planes<'a>), |
| 509 | Wide(&'a [u8], u32, u32), |
| 510 | } |
| 511 | |
| 512 | |
| 513 | |
| 514 | pub enum HwPicture<'a> { |
| 515 | Pixels(&'a [u8], &'a [u8], &'a [u8], u32, u32), |
| 516 | Wide(&'a [u8], u32, u32), |
| 517 | Dma(DmaFrame), |
| 518 | } |
| 519 | |
| 520 | |
| 521 | |
| 522 | |
| 523 | |
| 524 | |
| 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 | |
| 535 | |
| 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 | |
| 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 | } |
| 615 | |
| 616 | impl HwEncoder { |
| 617 | |
| 618 | |
| 619 | |
| 620 | |
| 621 | |
| 622 | pub fn open(width: u32, height: u32, fps_num: u32, fps_den: u32, rate: SeatRate, gop: Option<u32>) -> Option<Self> { |
| 623 | Self::seated( |
| 624 | Seat::H264, |
| 625 | width, |
| 626 | height, |
| 627 | fps_num, |
| 628 | fps_den, |
| 629 | rate, |
| 630 | ColorDescription::default(), |
| 631 | gop, |
| 632 | false, |
| 633 | ) |
| 634 | } |
| 635 | |
| 636 | |
| 637 | |
| 638 | |
| 639 | |
| 640 | |
| 641 | pub fn open_intra(width: u32, height: u32, fps_num: u32, fps_den: u32, rate: SeatRate) -> Option<Self> { |
| 642 | Self::seated( |
| 643 | Seat::Intra, |
| 644 | width, |
| 645 | height, |
| 646 | fps_num, |
| 647 | fps_den, |
| 648 | rate, |
| 649 | ColorDescription::default(), |
| 650 | None, |
| 651 | false, |
| 652 | ) |
| 653 | } |
| 654 | |
| 655 | |
| 656 | |
| 657 | |
| 658 | pub fn open_av1(width: u32, height: u32, fps_num: u32, fps_den: u32, rate: SeatRate, gop: Option<u32>) -> Option<Self> { |
| 659 | Self::seated( |
| 660 | Seat::Av1, |
| 661 | width, |
| 662 | height, |
| 663 | fps_num, |
| 664 | fps_den, |
| 665 | rate, |
| 666 | ColorDescription::default(), |
| 667 | gop, |
| 668 | false, |
| 669 | ) |
| 670 | } |
| 671 | |
| 672 | |
| 673 | |
| 674 | |
| 675 | #[allow(clippy::too_many_arguments)] |
| 676 | pub fn open_hevc( |
| 677 | width: u32, |
| 678 | height: u32, |
| 679 | fps_num: u32, |
| 680 | fps_den: u32, |
| 681 | rate: SeatRate, |
| 682 | colour: ColorDescription, |
| 683 | gop: Option<u32>, |
| 684 | ten_bit: bool, |
| 685 | ) -> Option<Self> { |
| 686 | Self::seated(Seat::Hevc, width, height, fps_num, fps_den, rate, colour, gop, ten_bit) |
| 687 | } |
| 688 | |
| 689 | |
| 690 | |
| 691 | pub fn open_hevc_intra( |
| 692 | width: u32, |
| 693 | height: u32, |
| 694 | fps_num: u32, |
| 695 | fps_den: u32, |
| 696 | rate: SeatRate, |
| 697 | colour: ColorDescription, |
| 698 | ten_bit: bool, |
| 699 | ) -> Option<Self> { |
| 700 | Self::seated(Seat::HevcIntra, width, height, fps_num, fps_den, rate, colour, None, ten_bit) |
| 701 | } |
| 702 | |
| 703 | #[allow(clippy::too_many_arguments)] |
| 704 | fn seated( |
| 705 | seat: Seat, |
| 706 | width: u32, |
| 707 | height: u32, |
| 708 | fps_num: u32, |
| 709 | fps_den: u32, |
| 710 | rate: SeatRate, |
| 711 | colour: ColorDescription, |
| 712 | gop: Option<u32>, |
| 713 | ten_bit: bool, |
| 714 | ) -> Option<Self> { |
| 715 | let open = Open { |
| 716 | seat, |
| 717 | width, |
| 718 | height, |
| 719 | fps_num, |
| 720 | fps_den, |
| 721 | rate, |
| 722 | colour, |
| 723 | gop, |
| 724 | ten_bit, |
| 725 | }; |
| 726 | |
| 727 | |
| 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 | }) |
| 736 | } |
| 737 | |
| 738 | |
| 739 | |
| 740 | |
| 741 | pub fn encode( |
| 742 | &mut self, |
| 743 | y: &[u8], |
| 744 | u: &[u8], |
| 745 | v: &[u8], |
| 746 | width: u32, |
| 747 | height: u32, |
| 748 | force_key: bool, |
| 749 | ) -> crate::Result<Option<&[u8]>> { |
| 750 | |
| 751 | |
| 752 | |
| 753 | let (w, h) = (width as usize, height as usize); |
| 754 | let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); |
| 755 | if y.len() < w * h || u.len() < cw * ch || v.len() < cw * ch { |
| 756 | return Err("encode input is not a packed I420 frame".into()); |
| 757 | } |
| 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 | |
| 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()) |
| 800 | } |
| 801 | |
| 802 | |
| 803 | |
| 804 | pub fn dma_want(&mut self, width: u32, height: u32) -> Option<DmaWant> { |
| 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()?; |
| 813 | Some(DmaWant { |
| 814 | coded_width, |
| 815 | coded_height, |
| 816 | width, |
| 817 | height, |
| 818 | ten_bit: false, |
| 819 | }) |
| 820 | } |
| 821 | |
| 822 | |
| 823 | |
| 824 | pub fn encode_dma(&mut self, dma: &DmaFrame, force_key: bool) -> crate::Result<Option<&[u8]>> { |
| 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()) |
| 830 | } |
| 831 | |
| 832 | |
| 833 | pub fn drain(&mut self) -> crate::Result<Option<&[u8]>> { |
| 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 | |
| 887 | |
| 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) |
| 930 | } |
| 931 | } |
| 932 | |
| 933 | #[cfg(test)] |
| 934 | mod tests { |
| 935 | use super::*; |
| 936 | |
| 937 | |
| 938 | #[test] |
| 939 | fn meta_round_trips_through_the_wire() { |
| 940 | let meta = VhMeta { |
| 941 | width: 1920, |
| 942 | height: 1080, |
| 943 | frame_rate: 30000.0 / 1001.0, |
| 944 | frame_count: 4321, |
| 945 | coded_width: 1920, |
| 946 | coded_height: 1088, |
| 947 | pixel_aspect_h: 4, |
| 948 | pixel_aspect_v: 3, |
| 949 | }; |
| 950 | assert_eq!(meta_from_wire(&meta_to_wire(&meta)), Some(meta)); |
| 951 | assert_eq!(meta_from_wire(&[0u8; 35]), None); |
| 952 | } |
| 953 | |
| 954 | #[test] |
| 955 | fn i420_size_rounds_chroma_up() { |
| 956 | assert_eq!(i420_bytes(3, 3), 9 + 2 * 4); |
| 957 | assert_eq!(i420_bytes(1920, 1080), 1920 * 1080 * 3 / 2); |
| 958 | } |
| 959 | } |