yumush
Clone
https://git.tahinli.com/Tahinli/yumush.git
0 watching·0 forks·Rust·AGPL-3.0·7.5 MiB·debc8fb·Tahinli·2 days ago·352 commits
| 1 | use std::collections::HashMap; |
| 2 | use std::sync::atomic::{AtomicU8, AtomicU32, AtomicU64, Ordering}; |
| 3 | use std::sync::mpsc::{Receiver, Sender, SyncSender, sync_channel}; |
| 4 | use std::sync::{Arc, OnceLock}; |
| 5 | use std::thread; |
| 6 | |
| 7 | use common::share::{Codec, Layer}; |
| 8 | |
| 9 | use super::frame::{Encoded, Frame}; |
| 10 | use crate::media::decode::Engine; |
| 11 | |
| 12 | const SOFTWARE: Codec = Codec::H264; |
| 13 | const DEFAULT_MAX_HEIGHT: u32 = 2160; |
| 14 | const KEYFRAME_SECONDS: u32 = 3600; |
| 15 | const SLACK_MS: u32 = 4; |
| 16 | |
| 17 | pub struct Capabilities { |
| 18 | pub encode: Vec<Codec>, |
| 19 | pub decode: Vec<Codec>, |
| 20 | pub max_height: u32, |
| 21 | } |
| 22 | |
| 23 | struct Probe { |
| 24 | capabilities: Capabilities, |
| 25 | hardware: Vec<Codec>, |
| 26 | vulkan: Vec<Codec>, |
| 27 | } |
| 28 | |
| 29 | fn probe() -> &'static Probe { |
| 30 | static PROBE: OnceLock<Probe> = OnceLock::new(); |
| 31 | PROBE.get_or_init(|| { |
| 32 | let (hardware, vulkan) = hardware::probe(); |
| 33 | let codecs: Vec<Codec> = hardware.iter().map(|(codec, _)| *codec).collect(); |
| 34 | let max_height = hardware |
| 35 | .iter() |
| 36 | .map(|(_, height)| *height) |
| 37 | .max() |
| 38 | .unwrap_or(DEFAULT_MAX_HEIGHT); |
| 39 | let encode = Codec::ALL |
| 40 | .into_iter() |
| 41 | .filter(|codec| *codec == SOFTWARE || codecs.contains(codec)) |
| 42 | .collect(); |
| 43 | Probe { |
| 44 | capabilities: Capabilities { |
| 45 | encode, |
| 46 | decode: Codec::ALL.to_vec(), |
| 47 | max_height, |
| 48 | }, |
| 49 | hardware: codecs, |
| 50 | vulkan, |
| 51 | } |
| 52 | }) |
| 53 | } |
| 54 | |
| 55 | pub fn capabilities() -> &'static Capabilities { |
| 56 | &probe().capabilities |
| 57 | } |
| 58 | |
| 59 | #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] |
| 60 | enum Request { |
| 61 | Nothing, |
| 62 | Recover, |
| 63 | Keyframe, |
| 64 | } |
| 65 | |
| 66 | impl Request { |
| 67 | fn from_u8(value: u8) -> Self { |
| 68 | match value { |
| 69 | 1 => Self::Recover, |
| 70 | 2 => Self::Keyframe, |
| 71 | _ => Self::Nothing, |
| 72 | } |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | #[derive(Default)] |
| 77 | struct Control { |
| 78 | request: AtomicU8, |
| 79 | acked: AtomicU64, |
| 80 | } |
| 81 | |
| 82 | impl Control { |
| 83 | fn ask(&self, request: Request) { |
| 84 | self.request.fetch_max(request as u8, Ordering::Relaxed); |
| 85 | } |
| 86 | |
| 87 | fn take(&self) -> Request { |
| 88 | Request::from_u8(self.request.swap(Request::Nothing as u8, Ordering::Relaxed)) |
| 89 | } |
| 90 | |
| 91 | fn pending(&self) -> bool { |
| 92 | self.request.load(Ordering::Relaxed) != Request::Nothing as u8 |
| 93 | } |
| 94 | |
| 95 | fn ack(&self, timestamp_ms: u32) { |
| 96 | self.acked |
| 97 | .store(u64::from(timestamp_ms) + 1, Ordering::Relaxed); |
| 98 | } |
| 99 | |
| 100 | fn acked(&self) -> Option<u32> { |
| 101 | let value = self.acked.load(Ordering::Relaxed); |
| 102 | (value > 0).then(|| (value - 1) as u32) |
| 103 | } |
| 104 | } |
| 105 | |
| 106 | struct Settings { |
| 107 | codec: Codec, |
| 108 | width: u32, |
| 109 | height: u32, |
| 110 | fps: u32, |
| 111 | bitrate: u32, |
| 112 | gop: u32, |
| 113 | } |
| 114 | |
| 115 | enum Backend { |
| 116 | Hardware(Box<hardware::Encoder>), |
| 117 | H264(Box<ec_h264::Encoder>), |
| 118 | } |
| 119 | |
| 120 | impl Backend { |
| 121 | fn open(settings: &Settings) -> Option<Self> { |
| 122 | let hardware = if probe().hardware.contains(&settings.codec) { |
| 123 | hardware::open(settings) |
| 124 | } else { |
| 125 | None |
| 126 | }; |
| 127 | hardware |
| 128 | .map(|encoder| Self::Hardware(Box::new(encoder))) |
| 129 | .or_else(|| { |
| 130 | tracing::warn!(codec = ?settings.codec, "share encode falls back to software"); |
| 131 | Self::software(settings) |
| 132 | }) |
| 133 | } |
| 134 | |
| 135 | fn software(settings: &Settings) -> Option<Self> { |
| 136 | let (width, height) = (settings.width, settings.height); |
| 137 | match settings.codec { |
| 138 | Codec::H264 => { |
| 139 | let mut config = ec_h264::EncoderConfig::new(width, height); |
| 140 | config.framerate = settings.fps as f32; |
| 141 | config.bitrate = settings.bitrate; |
| 142 | config.gop_size = settings.gop; |
| 143 | config.threads = 4; |
| 144 | report(ec_h264::Encoder::new(config)).map(|encoder| Self::H264(Box::new(encoder))) |
| 145 | } |
| 146 | Codec::H265 | Codec::Av1 | Codec::Vp8 | Codec::Vp9 => None, |
| 147 | } |
| 148 | } |
| 149 | |
| 150 | fn tune(&mut self, bitrate: u32, fps: u32) { |
| 151 | if let Self::Hardware(encoder) = self { |
| 152 | encoder.tune(bitrate, fps); |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | fn ack(&mut self, timestamp_ms: u32) { |
| 157 | if let Self::Hardware(encoder) = self { |
| 158 | encoder.ack(timestamp_ms); |
| 159 | } |
| 160 | } |
| 161 | |
| 162 | fn engine(&self) -> Engine { |
| 163 | match self { |
| 164 | Self::Hardware(_) => Engine::Hardware, |
| 165 | Self::H264(_) => Engine::Software, |
| 166 | } |
| 167 | } |
| 168 | |
| 169 | fn encode( |
| 170 | &mut self, |
| 171 | frame: &Frame, |
| 172 | settings: &Settings, |
| 173 | request: Request, |
| 174 | ) -> Option<(Vec<u8>, bool, bool)> { |
| 175 | match self { |
| 176 | Self::Hardware(encoder) => encoder.encode(frame, settings, request), |
| 177 | Self::H264(_) if frame.gpu.is_some() => { |
| 178 | super::frame::gpu_failed(); |
| 179 | None |
| 180 | } |
| 181 | Self::H264(encoder) => { |
| 182 | let planes = frame.to_i420(settings.width, settings.height)?; |
| 183 | let picture = ec_h264::PictureView::i420( |
| 184 | planes.width, |
| 185 | planes.height, |
| 186 | &planes.y, |
| 187 | &planes.u, |
| 188 | &planes.v, |
| 189 | ); |
| 190 | report(encoder.encode_with(&picture, request != Request::Nothing)) |
| 191 | .map(|picture| (picture.au, picture.key_frame, false)) |
| 192 | } |
| 193 | } |
| 194 | } |
| 195 | } |
| 196 | |
| 197 | fn report<T, E: std::fmt::Debug>(result: Result<T, E>) -> Option<T> { |
| 198 | result |
| 199 | .inspect_err(|error| tracing::warn!(?error, "share encoder failed")) |
| 200 | .ok() |
| 201 | } |
| 202 | |
| 203 | mod hardware { |
| 204 | const VULKAN_ATTEMPTS: u32 = 5; |
| 205 | const VULKAN_RETRY: std::time::Duration = std::time::Duration::from_millis(100); |
| 206 | const RATE_BUFFER_MS: u32 = 66; |
| 207 | const BT709_LIMITED: ec_hw::types::Colour = ec_hw::types::Colour { |
| 208 | primaries: 1, |
| 209 | transfer: 1, |
| 210 | matrix: 1, |
| 211 | full_range: false, |
| 212 | }; |
| 213 | |
| 214 | use common::share::Codec; |
| 215 | |
| 216 | use super::{Request, Settings, report}; |
| 217 | use crate::share::frame::Frame; |
| 218 | |
| 219 | pub struct Encoder(ec_hw::HwEncoder); |
| 220 | |
| 221 | impl Encoder { |
| 222 | pub fn tune(&mut self, bitrate: u32, fps: u32) { |
| 223 | report(self.0.tune(ec_hw::Tunings { |
| 224 | bitrate, |
| 225 | framerate: (fps, 1), |
| 226 | })); |
| 227 | } |
| 228 | |
| 229 | pub fn ack(&mut self, timestamp_ms: u32) { |
| 230 | self.0.ack(i64::from(timestamp_ms)); |
| 231 | } |
| 232 | |
| 233 | pub fn encode( |
| 234 | &mut self, |
| 235 | frame: &Frame, |
| 236 | settings: &Settings, |
| 237 | request: Request, |
| 238 | ) -> Option<(Vec<u8>, bool, bool)> { |
| 239 | if request == Request::Recover { |
| 240 | self.0.recover(); |
| 241 | } |
| 242 | let meta = ec_hw::FrameMetadata { |
| 243 | timestamp: i64::from(frame.timestamp_ms), |
| 244 | force_keyframe: request == Request::Keyframe, |
| 245 | }; |
| 246 | #[cfg(target_os = "linux")] |
| 247 | if let Some(dmabuf) = &frame.gpu { |
| 248 | use std::os::fd::AsFd; |
| 249 | let Some(fd) = report(ec_hw::dup_fd(dmabuf.fd)) else { |
| 250 | crate::share::frame::gpu_failed(); |
| 251 | return None; |
| 252 | }; |
| 253 | let source = ec_hw::DmaBufFrame { |
| 254 | fd: fd.as_fd(), |
| 255 | width: frame.width, |
| 256 | height: frame.height, |
| 257 | stride: dmabuf.stride, |
| 258 | offset: dmabuf.offset, |
| 259 | modifier: dmabuf.modifier, |
| 260 | order: if dmabuf.bgra { |
| 261 | ec_hw::RgbOrder::Bgra |
| 262 | } else { |
| 263 | ec_hw::RgbOrder::Rgba |
| 264 | }, |
| 265 | }; |
| 266 | let coded = self.0.encode_dmabuf(&source, meta); |
| 267 | if coded.is_err() { |
| 268 | crate::share::frame::gpu_failed(); |
| 269 | } |
| 270 | return report(coded).map(|coded| (coded.data, coded.is_keyframe, coded.recovery)); |
| 271 | } |
| 272 | #[cfg(target_os = "windows")] |
| 273 | if let Some(gpu) = &frame.gpu { |
| 274 | use std::os::windows::io::AsHandle; |
| 275 | let source = ec_hw::D3d11Frame { |
| 276 | handle: gpu.handle.as_handle(), |
| 277 | id: gpu.id, |
| 278 | width: frame.width, |
| 279 | height: frame.height, |
| 280 | order: if gpu.bgra { |
| 281 | ec_hw::RgbOrder::Bgra |
| 282 | } else { |
| 283 | ec_hw::RgbOrder::Rgba |
| 284 | }, |
| 285 | }; |
| 286 | let coded = self.0.encode_d3d11(&source, meta); |
| 287 | if coded.is_err() { |
| 288 | crate::share::frame::gpu_failed(); |
| 289 | } |
| 290 | return report(coded).map(|coded| (coded.data, coded.is_keyframe, coded.recovery)); |
| 291 | } |
| 292 | let coded = if frame.width.is_multiple_of(2) |
| 293 | && frame.height.is_multiple_of(2) |
| 294 | && frame.stride.is_multiple_of(4) |
| 295 | { |
| 296 | let rgb = ec_hw::RgbFrame { |
| 297 | data: &frame.bgra, |
| 298 | width: frame.width, |
| 299 | height: frame.height, |
| 300 | stride: frame.stride, |
| 301 | order: ec_hw::RgbOrder::Bgra, |
| 302 | }; |
| 303 | self.0.encode_rgb(&rgb, meta) |
| 304 | } else { |
| 305 | let planes = frame.to_i420(settings.width, settings.height)?; |
| 306 | let picture = ec_hw::I420 { |
| 307 | y: planes.y, |
| 308 | u: planes.u, |
| 309 | v: planes.v, |
| 310 | width: planes.width, |
| 311 | height: planes.height, |
| 312 | }; |
| 313 | self.0.encode(&picture, meta) |
| 314 | }; |
| 315 | report(coded).map(|coded| (coded.data, coded.is_keyframe, coded.recovery)) |
| 316 | } |
| 317 | } |
| 318 | |
| 319 | fn codec(codec: ec_hw::Codec) -> Option<Codec> { |
| 320 | match codec { |
| 321 | ec_hw::Codec::H264 => Some(Codec::H264), |
| 322 | ec_hw::Codec::H265 => Some(Codec::H265), |
| 323 | ec_hw::Codec::Av1 => Some(Codec::Av1), |
| 324 | ec_hw::Codec::Vp9 => None, |
| 325 | } |
| 326 | } |
| 327 | |
| 328 | pub fn probe() -> (Vec<(Codec, u32)>, Vec<Codec>) { |
| 329 | let mut found: Vec<(Codec, u32)> = Vec::new(); |
| 330 | let mut vulkan = Vec::new(); |
| 331 | for capability in ec_hw::capabilities() { |
| 332 | if capability.direction != ec_hw::Direction::Encode { |
| 333 | continue; |
| 334 | } |
| 335 | let Some(codec) = codec(capability.codec) else { |
| 336 | continue; |
| 337 | }; |
| 338 | if capability.backend == ec_hw::Backend::Vk && !vulkan.contains(&codec) { |
| 339 | vulkan.push(codec); |
| 340 | } |
| 341 | match found.iter_mut().find(|(known, _)| *known == codec) { |
| 342 | Some((_, height)) => *height = (*height).max(capability.max_height), |
| 343 | None => found.push((codec, capability.max_height)), |
| 344 | } |
| 345 | } |
| 346 | (found, vulkan) |
| 347 | } |
| 348 | |
| 349 | fn open_vulkan(config: ec_hw::EncoderConfig, wanted: Codec) -> Option<ec_hw::HwEncoder> { |
| 350 | if !super::probe().vulkan.contains(&wanted) { |
| 351 | return None; |
| 352 | } |
| 353 | for attempt in 1..=VULKAN_ATTEMPTS { |
| 354 | match ec_hw::HwEncoder::open(config, Some(ec_hw::Backend::Vk)) { |
| 355 | Ok(encoder) => return Some(encoder), |
| 356 | Err(error) => tracing::warn!(attempt, %error, "share Vulkan encoder open failed"), |
| 357 | } |
| 358 | std::thread::sleep(VULKAN_RETRY); |
| 359 | } |
| 360 | None |
| 361 | } |
| 362 | |
| 363 | pub fn open(settings: &Settings) -> Option<Encoder> { |
| 364 | let codec = match settings.codec { |
| 365 | Codec::H264 => ec_hw::EncCodec::H264, |
| 366 | Codec::H265 => ec_hw::EncCodec::H265, |
| 367 | Codec::Av1 => ec_hw::EncCodec::Av1, |
| 368 | Codec::Vp8 | Codec::Vp9 => return None, |
| 369 | }; |
| 370 | let mut config = ec_hw::EncoderConfig::new(codec, settings.width, settings.height); |
| 371 | config.framerate = (settings.fps, 1); |
| 372 | config.bitrate = settings.bitrate; |
| 373 | config.gop_size = settings.gop; |
| 374 | config.rate_control = ec_hw::RateControlMode::VariableBitrate; |
| 375 | config.buffer_ms = Some(RATE_BUFFER_MS); |
| 376 | config.colour = Some(BT709_LIMITED); |
| 377 | let encoder = open_vulkan(config, settings.codec) |
| 378 | .or_else(|| report(ec_hw::HwEncoder::open(config, None)))?; |
| 379 | tracing::info!(backend = ?encoder.backend(), ?codec, "share hardware encoder opened"); |
| 380 | Some(Encoder(encoder)) |
| 381 | } |
| 382 | } |
| 383 | |
| 384 | fn run( |
| 385 | layer: Layer, |
| 386 | settings: Settings, |
| 387 | input: Receiver<Arc<Frame>>, |
| 388 | control: Arc<Control>, |
| 389 | scale: Arc<AtomicU32>, |
| 390 | output: Sender<Encoded>, |
| 391 | ) { |
| 392 | let mut acked = None; |
| 393 | let Some(mut backend) = Backend::open(&settings) else { |
| 394 | return; |
| 395 | }; |
| 396 | let mut applied = 1.0; |
| 397 | let interval = 1000 / settings.fps; |
| 398 | let mut due = 0u32; |
| 399 | for frame in input { |
| 400 | crate::usage::tick(crate::usage::Group::Encode); |
| 401 | if frame.timestamp_ms + SLACK_MS < due { |
| 402 | continue; |
| 403 | } |
| 404 | due = due.max(frame.timestamp_ms.saturating_sub(SLACK_MS)) + interval; |
| 405 | let wanted = f32::from_bits(scale.load(Ordering::Relaxed)); |
| 406 | if wanted != applied { |
| 407 | applied = wanted; |
| 408 | backend.tune((settings.bitrate as f32 * wanted) as u32, settings.fps); |
| 409 | } |
| 410 | let ack = control.acked(); |
| 411 | if ack != acked { |
| 412 | acked = ack; |
| 413 | if let Some(timestamp_ms) = ack { |
| 414 | backend.ack(timestamp_ms); |
| 415 | } |
| 416 | } |
| 417 | let Some((data, keyframe, recovery)) = backend.encode(&frame, &settings, control.take()) |
| 418 | else { |
| 419 | continue; |
| 420 | }; |
| 421 | let encoded = Encoded { |
| 422 | layer, |
| 423 | engine: backend.engine(), |
| 424 | data, |
| 425 | keyframe, |
| 426 | recovery, |
| 427 | timestamp_ms: frame.timestamp_ms, |
| 428 | }; |
| 429 | if output.send(encoded).is_err() { |
| 430 | break; |
| 431 | } |
| 432 | } |
| 433 | } |
| 434 | |
| 435 | struct Lane { |
| 436 | input: SyncSender<Arc<Frame>>, |
| 437 | control: Arc<Control>, |
| 438 | } |
| 439 | |
| 440 | pub struct Encoders { |
| 441 | source_width: u32, |
| 442 | source_height: u32, |
| 443 | output: Sender<Encoded>, |
| 444 | lanes: HashMap<Layer, Lane>, |
| 445 | scale: Arc<AtomicU32>, |
| 446 | } |
| 447 | |
| 448 | impl Encoders { |
| 449 | pub fn new(source_width: u32, source_height: u32, output: Sender<Encoded>) -> Self { |
| 450 | Self { |
| 451 | source_width, |
| 452 | source_height, |
| 453 | output, |
| 454 | lanes: HashMap::new(), |
| 455 | scale: Arc::new(AtomicU32::new(1f32.to_bits())), |
| 456 | } |
| 457 | } |
| 458 | |
| 459 | pub fn set_layers(&mut self, layers: &[Layer]) { |
| 460 | self.lanes.retain(|layer, _| layers.contains(layer)); |
| 461 | for &layer in layers { |
| 462 | if !self.lanes.contains_key(&layer) { |
| 463 | let lane = self.spawn(layer); |
| 464 | self.lanes.insert(layer, lane); |
| 465 | } |
| 466 | } |
| 467 | } |
| 468 | |
| 469 | pub fn keyframe(&self, layer: Layer, recover: bool) { |
| 470 | if let Some(lane) = self.lanes.get(&layer) { |
| 471 | lane.control.ask(if recover { |
| 472 | Request::Recover |
| 473 | } else { |
| 474 | Request::Keyframe |
| 475 | }); |
| 476 | } |
| 477 | } |
| 478 | |
| 479 | pub fn ack(&self, layer: Layer, timestamp_ms: u32) { |
| 480 | if let Some(lane) = self.lanes.get(&layer) { |
| 481 | lane.control.ack(timestamp_ms); |
| 482 | } |
| 483 | } |
| 484 | |
| 485 | pub fn keyframe_pending(&self) -> bool { |
| 486 | self.lanes.values().any(|lane| lane.control.pending()) |
| 487 | } |
| 488 | |
| 489 | pub fn layer_bitrate(&self, layer: Layer) -> u32 { |
| 490 | layer.bitrate(self.source_width, self.source_height) |
| 491 | } |
| 492 | |
| 493 | pub fn set_scale(&self, scale: f32) { |
| 494 | self.scale.store(scale.to_bits(), Ordering::Relaxed); |
| 495 | } |
| 496 | |
| 497 | pub fn push(&self, frame: Arc<Frame>) { |
| 498 | for lane in self.lanes.values() { |
| 499 | let _ = lane.input.try_send(Arc::clone(&frame)); |
| 500 | } |
| 501 | } |
| 502 | |
| 503 | fn spawn(&self, layer: Layer) -> Lane { |
| 504 | let (width, height) = layer |
| 505 | .quality |
| 506 | .resolution |
| 507 | .size(self.source_width, self.source_height); |
| 508 | let fps = layer.quality.fps.value(); |
| 509 | let settings = Settings { |
| 510 | codec: layer.codec, |
| 511 | width, |
| 512 | height, |
| 513 | fps, |
| 514 | bitrate: layer.bitrate(self.source_width, self.source_height), |
| 515 | gop: fps * KEYFRAME_SECONDS, |
| 516 | }; |
| 517 | let (input, receiver) = sync_channel(1); |
| 518 | let control = Arc::new(Control::default()); |
| 519 | let thread_control = Arc::clone(&control); |
| 520 | let output = self.output.clone(); |
| 521 | let scale = Arc::clone(&self.scale); |
| 522 | let spawned = thread::Builder::new() |
| 523 | .name("share-encode".into()) |
| 524 | .spawn(move || run(layer, settings, receiver, thread_control, scale, output)); |
| 525 | if let Err(error) = spawned { |
| 526 | tracing::warn!(?error, "share encode thread failed to start"); |
| 527 | } |
| 528 | Lane { input, control } |
| 529 | } |
| 530 | } |