yumush
Clone
https://git.tahinli.com/Tahinli/yumush.git
0 watching·0 forks·Rust·AGPL-3.0·7.6 MiB·fc2d7c9·Tahinli·33 minutes ago·408 commits
| 1 | use std::{ |
| 2 | collections::VecDeque, |
| 3 | path::PathBuf, |
| 4 | sync::{ |
| 5 | Arc, Mutex, MutexGuard, PoisonError, |
| 6 | atomic::{AtomicBool, Ordering}, |
| 7 | }, |
| 8 | time::{Duration, Instant}, |
| 9 | }; |
| 10 | |
| 11 | use common::{constant::VOICE_SAMPLE_RATE, share::Codec}; |
| 12 | use ec_core::frame::{Frame as CodecFrame, PixelFormat, VideoFrame}; |
| 13 | use ec_core::packet::Packet; |
| 14 | use ec_core::registry::{CodecId, CodecParameters, Decoder as CodecDecoder, SeekMode}; |
| 15 | use ec_core::timebase::{TimeBase, Timestamp}; |
| 16 | use ec_h264::H264Decoder; |
| 17 | use ec_probe::{Reader, decoder::AudioDecoder}; |
| 18 | use rtrb::Producer; |
| 19 | use tracing::warn; |
| 20 | |
| 21 | use super::{ |
| 22 | Frame, Tracks, convert, |
| 23 | resample::{self, Resampler, Stereo}, |
| 24 | }; |
| 25 | use crate::voice::{PLAYBACK_CHANNELS, Playback}; |
| 26 | |
| 27 | pub const RING_FRAMES: usize = VOICE_SAMPLE_RATE as usize / 4; |
| 28 | pub const RING_SAMPLES: usize = RING_FRAMES * PLAYBACK_CHANNELS; |
| 29 | const QUEUE_LIMIT: usize = 8; |
| 30 | const BACKLOG_LIMIT: usize = 600; |
| 31 | const LATE: f64 = 0.1; |
| 32 | const TICK: Duration = Duration::from_millis(4); |
| 33 | const MAX_PAD: usize = VOICE_SAMPLE_RATE as usize * 5; |
| 34 | |
| 35 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 36 | pub enum State { |
| 37 | Playing, |
| 38 | Paused, |
| 39 | Finished, |
| 40 | } |
| 41 | |
| 42 | #[derive(Debug)] |
| 43 | pub struct Clock { |
| 44 | pub state: State, |
| 45 | pub base: f64, |
| 46 | pub written: u64, |
| 47 | pub started: Option<Instant>, |
| 48 | pub audio: bool, |
| 49 | } |
| 50 | |
| 51 | impl Clock { |
| 52 | pub fn new(audio: bool) -> Clock { |
| 53 | Clock { |
| 54 | state: State::Paused, |
| 55 | base: 0.0, |
| 56 | written: 0, |
| 57 | started: None, |
| 58 | audio, |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | pub fn position(&self, queued: usize) -> f64 { |
| 63 | let played = if self.audio { |
| 64 | self.written.saturating_sub(queued as u64) as f64 / f64::from(VOICE_SAMPLE_RATE) |
| 65 | } else { |
| 66 | self.started |
| 67 | .map_or(0.0, |started| started.elapsed().as_secs_f64()) |
| 68 | }; |
| 69 | self.base + played |
| 70 | } |
| 71 | |
| 72 | pub fn set(&mut self, state: State) { |
| 73 | if !self.audio { |
| 74 | self.base = self.position(0); |
| 75 | } |
| 76 | self.state = state; |
| 77 | self.started = self.wall_start(); |
| 78 | } |
| 79 | |
| 80 | pub fn rebase(&mut self, to: f64) { |
| 81 | self.base = to; |
| 82 | self.written = 0; |
| 83 | self.started = self.wall_start(); |
| 84 | } |
| 85 | |
| 86 | fn wall_start(&self) -> Option<Instant> { |
| 87 | (self.state == State::Playing && !self.audio).then(Instant::now) |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | #[derive(Debug, Default)] |
| 92 | pub struct Video { |
| 93 | pub queue: VecDeque<(f64, Frame)>, |
| 94 | pub current: Option<Frame>, |
| 95 | pub generation: u64, |
| 96 | } |
| 97 | |
| 98 | #[derive(Debug)] |
| 99 | pub struct Shared { |
| 100 | pub stop: AtomicBool, |
| 101 | pub seek: Mutex<Option<f64>>, |
| 102 | pub clock: Mutex<Clock>, |
| 103 | pub video: Mutex<Video>, |
| 104 | pub stash: Mutex<VecDeque<Stereo>>, |
| 105 | } |
| 106 | |
| 107 | impl Shared { |
| 108 | pub fn new(audio: bool) -> Shared { |
| 109 | Shared { |
| 110 | stop: AtomicBool::new(false), |
| 111 | seek: Mutex::new(None), |
| 112 | clock: Mutex::new(Clock::new(audio)), |
| 113 | video: Mutex::new(Video::default()), |
| 114 | stash: Mutex::new(VecDeque::new()), |
| 115 | } |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | pub fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> { |
| 120 | mutex.lock().unwrap_or_else(PoisonError::into_inner) |
| 121 | } |
| 122 | |
| 123 | fn wait() { |
| 124 | std::thread::sleep(TICK); |
| 125 | } |
| 126 | |
| 127 | pub struct Planes { |
| 128 | pub y: Vec<u8>, |
| 129 | pub y_stride: usize, |
| 130 | pub u: Vec<u8>, |
| 131 | pub v: Vec<u8>, |
| 132 | pub uv_stride: usize, |
| 133 | pub width: u32, |
| 134 | pub height: u32, |
| 135 | } |
| 136 | |
| 137 | pub enum Picture { |
| 138 | Planes(Planes), |
| 139 | Bgra { |
| 140 | data: Vec<u8>, |
| 141 | width: u32, |
| 142 | height: u32, |
| 143 | }, |
| 144 | } |
| 145 | |
| 146 | impl Picture { |
| 147 | pub fn size(&self) -> (u32, u32) { |
| 148 | match self { |
| 149 | Picture::Planes(planes) => (planes.width, planes.height), |
| 150 | Picture::Bgra { width, height, .. } => (*width, *height), |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | pub fn into_frame(self, max_width: u32) -> Option<Frame> { |
| 155 | let (width, height, bgra) = match self { |
| 156 | Picture::Planes(planes) => convert::yuv_to_bgra( |
| 157 | &planes.y, |
| 158 | planes.y_stride, |
| 159 | &planes.u, |
| 160 | &planes.v, |
| 161 | planes.uv_stride, |
| 162 | planes.width, |
| 163 | planes.height, |
| 164 | max_width, |
| 165 | )?, |
| 166 | Picture::Bgra { |
| 167 | data, |
| 168 | width, |
| 169 | height, |
| 170 | } => (width, height, data), |
| 171 | }; |
| 172 | Some(Frame { |
| 173 | width, |
| 174 | height, |
| 175 | bgra: Arc::new(bgra), |
| 176 | generation: 0, |
| 177 | }) |
| 178 | } |
| 179 | } |
| 180 | |
| 181 | pub use common::stats::Engine; |
| 182 | |
| 183 | pub enum VideoDecoder { |
| 184 | H264(Box<H264Decoder>), |
| 185 | Vp8(Box<ec_vp8::decode::Decoder>), |
| 186 | H265(Box<ec_h265::Decoder>), |
| 187 | Vp9(Box<ec_vp9::decode::Decoder>), |
| 188 | Av1(Box<ec_av1::stream::StreamDecoder>), |
| 189 | Hardware(Box<ec_hw::HwDecoder>, Codec), |
| 190 | } |
| 191 | |
| 192 | impl VideoDecoder { |
| 193 | pub fn new(params: &CodecParameters) -> Option<VideoDecoder> { |
| 194 | match params.codec { |
| 195 | CodecId::H264 => { |
| 196 | let decoder = H264Decoder::new(params.clone()).ok()?; |
| 197 | let i420 = decoder |
| 198 | .codec_parameters() |
| 199 | .video() |
| 200 | .is_some_and(|video| video.format == Some(PixelFormat::I420)); |
| 201 | i420.then_some(VideoDecoder::H264(Box::new(decoder))) |
| 202 | } |
| 203 | CodecId::Vp8 => Some(VideoDecoder::Vp8(Box::new(ec_vp8::decode::Decoder::new()))), |
| 204 | _ => None, |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | pub fn for_codec(codec: Codec) -> Option<VideoDecoder> { |
| 209 | hardware(codec).or_else(|| software(codec)) |
| 210 | } |
| 211 | |
| 212 | pub fn engine(&self) -> Engine { |
| 213 | match self { |
| 214 | VideoDecoder::Hardware(..) => Engine::Hardware, |
| 215 | _ => Engine::Software, |
| 216 | } |
| 217 | } |
| 218 | |
| 219 | pub fn decode(&mut self, data: &[u8], timestamp_ms: u32) -> Vec<Picture> { |
| 220 | crate::usage::tick(crate::usage::Group::Decode); |
| 221 | let mut packet = Packet::new(0, TimeBase::MILLIS, data); |
| 222 | packet.pts = Some(i64::from(timestamp_ms)); |
| 223 | self.send(&packet) |
| 224 | .into_iter() |
| 225 | .map(|(_, picture)| picture) |
| 226 | .collect() |
| 227 | } |
| 228 | |
| 229 | pub fn send(&mut self, packet: &Packet) -> Vec<(f64, Picture)> { |
| 230 | let seconds = packet.pts.map_or(0.0, |ticks| { |
| 231 | Timestamp::new(ticks, packet.time_base).as_secs_f64() |
| 232 | }); |
| 233 | match self { |
| 234 | VideoDecoder::H264(decoder) => { |
| 235 | if let Err(error) = decoder.send_packet(packet) { |
| 236 | warn!("video packet skipped: {error}"); |
| 237 | return Vec::new(); |
| 238 | } |
| 239 | drain_h264(decoder) |
| 240 | } |
| 241 | VideoDecoder::Vp8(decoder) => { |
| 242 | let Some(pts) = packet |
| 243 | .pts |
| 244 | .map(|ticks| Timestamp::new(ticks, packet.time_base).as_secs_f64()) |
| 245 | else { |
| 246 | return Vec::new(); |
| 247 | }; |
| 248 | skipped(decoder.decode(&packet.data)) |
| 249 | .map_or_else(Vec::new, |picture| vec![(pts, vp8_picture(picture))]) |
| 250 | } |
| 251 | VideoDecoder::H265(decoder) => { |
| 252 | if let Err(error) = decoder.decode_annex_b(&packet.data) { |
| 253 | warn!("video packet skipped: {error}"); |
| 254 | return Vec::new(); |
| 255 | } |
| 256 | decoder.end_picture(); |
| 257 | drain_h265(decoder, seconds) |
| 258 | } |
| 259 | VideoDecoder::Vp9(decoder) => skipped(decoder.decode(&packet.data)) |
| 260 | .map_or_else(Vec::new, |picture| vec![(seconds, vp9_picture(picture))]), |
| 261 | VideoDecoder::Av1(decoder) => match decoder.decode_temporal_unit(&packet.data) { |
| 262 | Ok(pictures) => pictures |
| 263 | .into_iter() |
| 264 | .map(|picture| (seconds, av1_picture(picture))) |
| 265 | .collect(), |
| 266 | Err(error) => { |
| 267 | warn!("video packet skipped: {error}"); |
| 268 | **decoder = av1_decoder(); |
| 269 | Vec::new() |
| 270 | } |
| 271 | }, |
| 272 | VideoDecoder::Hardware(decoder, codec) => { |
| 273 | if let Err(error) = decoder.decode(&packet.data, packet.pts.unwrap_or(0)) { |
| 274 | warn!( |
| 275 | ?codec, |
| 276 | "hardware decode failed, switching to software: {error}" |
| 277 | ); |
| 278 | let Some(software) = software(*codec) else { |
| 279 | return Vec::new(); |
| 280 | }; |
| 281 | *self = software; |
| 282 | return self.send(packet); |
| 283 | } |
| 284 | hardware_pictures(decoder) |
| 285 | } |
| 286 | } |
| 287 | } |
| 288 | |
| 289 | pub fn flush(&mut self) -> Vec<(f64, Picture)> { |
| 290 | match self { |
| 291 | VideoDecoder::H264(decoder) => { |
| 292 | let _ = CodecDecoder::flush(decoder.as_mut()); |
| 293 | drain_h264(decoder) |
| 294 | } |
| 295 | VideoDecoder::H265(decoder) => { |
| 296 | let _ = decoder.flush(); |
| 297 | drain_h265(decoder, 0.0) |
| 298 | } |
| 299 | VideoDecoder::Vp8(_) | VideoDecoder::Vp9(_) | VideoDecoder::Av1(_) => Vec::new(), |
| 300 | VideoDecoder::Hardware(decoder, _) => { |
| 301 | let _ = decoder.flush(); |
| 302 | hardware_pictures(decoder) |
| 303 | } |
| 304 | } |
| 305 | } |
| 306 | |
| 307 | pub fn fit(&mut self, max_width: u32) { |
| 308 | if let VideoDecoder::Hardware(decoder, _) = self |
| 309 | && let Err(error) = decoder.set_rgb_output(rgb_output(max_width)) |
| 310 | { |
| 311 | warn!("decoder output size: {error}"); |
| 312 | } |
| 313 | } |
| 314 | |
| 315 | pub fn reset(&mut self) { |
| 316 | match self { |
| 317 | VideoDecoder::H264(decoder) => CodecDecoder::reset(decoder.as_mut()), |
| 318 | VideoDecoder::Vp8(decoder) => **decoder = ec_vp8::decode::Decoder::new(), |
| 319 | VideoDecoder::H265(decoder) => **decoder = ec_h265::Decoder::new(), |
| 320 | VideoDecoder::Vp9(decoder) => **decoder = ec_vp9::decode::Decoder::new(), |
| 321 | VideoDecoder::Av1(decoder) => **decoder = av1_decoder(), |
| 322 | VideoDecoder::Hardware(decoder, codec) => { |
| 323 | if let Some(fresh) = open_hardware(*codec) { |
| 324 | **decoder = fresh; |
| 325 | } |
| 326 | } |
| 327 | } |
| 328 | } |
| 329 | } |
| 330 | |
| 331 | fn hardware_codec(codec: Codec) -> Option<ec_hw::Codec> { |
| 332 | match codec { |
| 333 | Codec::H264 => Some(ec_hw::Codec::H264), |
| 334 | Codec::H265 => Some(ec_hw::Codec::H265), |
| 335 | Codec::Vp9 => Some(ec_hw::Codec::Vp9), |
| 336 | Codec::Av1 => Some(ec_hw::Codec::Av1), |
| 337 | Codec::Vp8 => None, |
| 338 | } |
| 339 | } |
| 340 | |
| 341 | fn rgb_output(max_width: u32) -> ec_hw::RgbOutput { |
| 342 | ec_hw::RgbOutput { |
| 343 | order: ec_hw::RgbOrder::Bgra, |
| 344 | max_width: Some(max_width), |
| 345 | max_height: None, |
| 346 | } |
| 347 | } |
| 348 | |
| 349 | fn open_hardware(codec: Codec) -> Option<ec_hw::HwDecoder> { |
| 350 | ec_hw::HwDecoder::open_rgb(hardware_codec(codec)?, rgb_output(convert::SHARE_WIDTH)).ok() |
| 351 | } |
| 352 | |
| 353 | fn hardware(codec: Codec) -> Option<VideoDecoder> { |
| 354 | let decoder = open_hardware(codec)?; |
| 355 | tracing::info!(backend = ?decoder.backend(), ?codec, "hardware decoder opened"); |
| 356 | Some(VideoDecoder::Hardware(Box::new(decoder), codec)) |
| 357 | } |
| 358 | |
| 359 | pub(crate) fn software(codec: Codec) -> Option<VideoDecoder> { |
| 360 | match codec { |
| 361 | Codec::H264 => H264Decoder::new(CodecParameters::new(CodecId::H264)) |
| 362 | .ok() |
| 363 | .map(|decoder| VideoDecoder::H264(Box::new(decoder))), |
| 364 | Codec::Vp8 => Some(VideoDecoder::Vp8(Box::new(ec_vp8::decode::Decoder::new()))), |
| 365 | Codec::H265 => Some(VideoDecoder::H265(Box::new(ec_h265::Decoder::new()))), |
| 366 | Codec::Vp9 => Some(VideoDecoder::Vp9(Box::new(ec_vp9::decode::Decoder::new()))), |
| 367 | Codec::Av1 => Some(VideoDecoder::Av1(Box::new(av1_decoder()))), |
| 368 | } |
| 369 | } |
| 370 | |
| 371 | fn av1_decoder() -> ec_av1::stream::StreamDecoder { |
| 372 | let threads = std::thread::available_parallelism().map_or(1, |count| count.get().min(4)); |
| 373 | ec_av1::stream::StreamDecoder::new(threads) |
| 374 | } |
| 375 | |
| 376 | fn av1_picture(picture: ec_av1::encode::Picture) -> Picture { |
| 377 | Picture::Planes(Planes { |
| 378 | y: plane(&picture.y, 0), |
| 379 | y_stride: picture.width, |
| 380 | u: plane(&picture.u, 0), |
| 381 | v: plane(&picture.v, 0), |
| 382 | uv_stride: picture.width.div_ceil(2), |
| 383 | width: picture.width as u32, |
| 384 | height: picture.height as u32, |
| 385 | }) |
| 386 | } |
| 387 | |
| 388 | fn plane(samples: &[u16], shift: u32) -> Vec<u8> { |
| 389 | samples |
| 390 | .iter() |
| 391 | .map(|sample| (sample >> shift) as u8) |
| 392 | .collect() |
| 393 | } |
| 394 | |
| 395 | fn drain_h265(decoder: &mut ec_h265::Decoder, pts: f64) -> Vec<(f64, Picture)> { |
| 396 | std::iter::from_fn(|| decoder.next_frame()) |
| 397 | .map(|frame| (pts, h265_picture(&frame.cropped()))) |
| 398 | .collect() |
| 399 | } |
| 400 | |
| 401 | fn h265_picture(picture: &ec_h265::decode::DecodedPicture) -> Picture { |
| 402 | let shift = picture.bit_depth.saturating_sub(8); |
| 403 | let (uv_width, _) = picture.chroma_dims(); |
| 404 | Picture::Planes(Planes { |
| 405 | y: plane(&picture.y, shift), |
| 406 | y_stride: picture.width, |
| 407 | u: plane(&picture.cb, shift), |
| 408 | v: plane(&picture.cr, shift), |
| 409 | uv_stride: uv_width, |
| 410 | width: picture.width as u32, |
| 411 | height: picture.height as u32, |
| 412 | }) |
| 413 | } |
| 414 | |
| 415 | fn skipped<T: Default, E: std::fmt::Display>(result: Result<T, E>) -> T { |
| 416 | result.unwrap_or_else(|error| { |
| 417 | warn!("video packet skipped: {error}"); |
| 418 | T::default() |
| 419 | }) |
| 420 | } |
| 421 | |
| 422 | fn vp8_picture(picture: ec_vp8::decode::Picture) -> Picture { |
| 423 | Picture::Planes(Planes { |
| 424 | y: picture.y, |
| 425 | y_stride: picture.stride, |
| 426 | u: picture.u, |
| 427 | v: picture.v, |
| 428 | uv_stride: picture.uv_stride, |
| 429 | width: u32::from(picture.width), |
| 430 | height: u32::from(picture.height), |
| 431 | }) |
| 432 | } |
| 433 | |
| 434 | fn vp9_picture(picture: ec_vp9::decode::Picture) -> Picture { |
| 435 | let shift = u32::from(picture.bit_depth.saturating_sub(8)); |
| 436 | Picture::Planes(Planes { |
| 437 | y: plane(&picture.y, shift), |
| 438 | y_stride: picture.stride, |
| 439 | u: plane(&picture.u, shift), |
| 440 | v: plane(&picture.v, shift), |
| 441 | uv_stride: picture.uv_stride, |
| 442 | width: u32::from(picture.width), |
| 443 | height: u32::from(picture.height), |
| 444 | }) |
| 445 | } |
| 446 | |
| 447 | fn hardware_pictures(decoder: &mut ec_hw::HwDecoder) -> Vec<(f64, Picture)> { |
| 448 | std::iter::from_fn(|| decoder.next_rgb().transpose()) |
| 449 | .filter_map(Result::ok) |
| 450 | .map(|(timestamp, picture)| { |
| 451 | let pts = Timestamp::new(timestamp, TimeBase::MILLIS).as_secs_f64(); |
| 452 | ( |
| 453 | pts, |
| 454 | Picture::Bgra { |
| 455 | data: picture.data, |
| 456 | width: picture.width, |
| 457 | height: picture.height, |
| 458 | }, |
| 459 | ) |
| 460 | }) |
| 461 | .collect() |
| 462 | } |
| 463 | |
| 464 | enum Queued { |
| 465 | Packet(Packet), |
| 466 | Flush, |
| 467 | } |
| 468 | |
| 469 | pub struct Worker { |
| 470 | shared: Arc<Shared>, |
| 471 | path: PathBuf, |
| 472 | reader: Reader, |
| 473 | playback: Playback, |
| 474 | producer: Option<Producer<f32>>, |
| 475 | video: Option<(u32, VideoDecoder)>, |
| 476 | backlog: VecDeque<Queued>, |
| 477 | audio: Option<(u32, AudioDecoder)>, |
| 478 | pending: VecDeque<Stereo>, |
| 479 | resampler: Resampler, |
| 480 | align: Option<f64>, |
| 481 | skip: usize, |
| 482 | scratch: Vec<f32>, |
| 483 | eof: bool, |
| 484 | } |
| 485 | |
| 486 | impl Worker { |
| 487 | pub fn new( |
| 488 | shared: Arc<Shared>, |
| 489 | path: PathBuf, |
| 490 | reader: Reader, |
| 491 | playback: Playback, |
| 492 | producer: Option<Producer<f32>>, |
| 493 | tracks: Tracks, |
| 494 | ) -> Worker { |
| 495 | Worker { |
| 496 | shared, |
| 497 | path, |
| 498 | reader, |
| 499 | playback, |
| 500 | producer, |
| 501 | video: tracks.video.map(|(index, _, decoder)| (index, decoder)), |
| 502 | backlog: VecDeque::new(), |
| 503 | audio: tracks.audio, |
| 504 | pending: VecDeque::new(), |
| 505 | resampler: Resampler::default(), |
| 506 | align: Some(0.0), |
| 507 | skip: 0, |
| 508 | scratch: Vec::new(), |
| 509 | eof: false, |
| 510 | } |
| 511 | } |
| 512 | |
| 513 | pub fn run(mut self) { |
| 514 | while !self.shared.stop.load(Ordering::Relaxed) { |
| 515 | let seek = lock(&self.shared.seek).take(); |
| 516 | if let Some(to) = seek { |
| 517 | self.seek(to); |
| 518 | continue; |
| 519 | } |
| 520 | let state = lock(&self.shared.clock).state; |
| 521 | match state { |
| 522 | State::Playing => self.play_step(), |
| 523 | State::Paused => { |
| 524 | if self.eof || self.primed() { |
| 525 | wait(); |
| 526 | } else { |
| 527 | self.decode_backlog(); |
| 528 | self.step(); |
| 529 | } |
| 530 | } |
| 531 | State::Finished => wait(), |
| 532 | } |
| 533 | } |
| 534 | } |
| 535 | |
| 536 | fn play_step(&mut self) { |
| 537 | self.feed(); |
| 538 | let decoded = self.decode_backlog(); |
| 539 | if self.eof { |
| 540 | self.finish(); |
| 541 | } |
| 542 | let read = !self.eof && !self.buffered() && self.fill(); |
| 543 | if !decoded && !read { |
| 544 | wait(); |
| 545 | } |
| 546 | } |
| 547 | |
| 548 | fn buffered(&self) -> bool { |
| 549 | self.pending.len() >= RING_FRAMES |
| 550 | } |
| 551 | |
| 552 | fn fill(&mut self) -> bool { |
| 553 | let mut read = false; |
| 554 | while !self.eof |
| 555 | && !self.buffered() |
| 556 | && self.backlog.len() < BACKLOG_LIMIT |
| 557 | && (self.producer.is_some() || self.backlog.is_empty()) |
| 558 | { |
| 559 | self.step(); |
| 560 | read = true; |
| 561 | } |
| 562 | read |
| 563 | } |
| 564 | |
| 565 | fn primed(&self) -> bool { |
| 566 | let base = lock(&self.shared.clock).base; |
| 567 | self.video.is_none() |
| 568 | || lock(&self.shared.video) |
| 569 | .queue |
| 570 | .back() |
| 571 | .is_some_and(|(pts, _)| *pts >= base) |
| 572 | } |
| 573 | |
| 574 | fn ring_empty(&self) -> bool { |
| 575 | self.producer |
| 576 | .as_ref() |
| 577 | .is_none_or(|producer| producer.slots() == RING_SAMPLES) |
| 578 | } |
| 579 | |
| 580 | fn feed(&mut self) { |
| 581 | let Some(producer) = self.producer.as_mut() else { |
| 582 | return; |
| 583 | }; |
| 584 | let mut clock = lock(&self.shared.clock); |
| 585 | if clock.state != State::Playing { |
| 586 | return; |
| 587 | } |
| 588 | let mut stash = lock(&self.shared.stash); |
| 589 | while let Some(frame) = stash.pop_back() { |
| 590 | self.pending.push_front(frame); |
| 591 | } |
| 592 | drop(stash); |
| 593 | while let Some(&[left, right]) = self.pending.front() { |
| 594 | if producer.slots() < PLAYBACK_CHANNELS { |
| 595 | break; |
| 596 | } |
| 597 | let _ = producer.push(left); |
| 598 | let _ = producer.push(right); |
| 599 | self.pending.pop_front(); |
| 600 | clock.written += 1; |
| 601 | } |
| 602 | } |
| 603 | |
| 604 | fn finish(&self) { |
| 605 | let mut clock = lock(&self.shared.clock); |
| 606 | if clock.state == State::Playing |
| 607 | && self.pending.is_empty() |
| 608 | && self.ring_empty() |
| 609 | && self.backlog.is_empty() |
| 610 | && lock(&self.shared.seek).is_none() |
| 611 | && lock(&self.shared.video).queue.is_empty() |
| 612 | { |
| 613 | clock.set(State::Finished); |
| 614 | } |
| 615 | } |
| 616 | |
| 617 | fn step(&mut self) { |
| 618 | if self.backlog.len() >= BACKLOG_LIMIT { |
| 619 | wait(); |
| 620 | return; |
| 621 | } |
| 622 | match self.reader.next_packet() { |
| 623 | Ok(packet) => self.packet(packet), |
| 624 | Err(error) => { |
| 625 | if !error.is_eof() { |
| 626 | warn!("media demux ended: {error}"); |
| 627 | } |
| 628 | self.end_of_input(); |
| 629 | } |
| 630 | } |
| 631 | } |
| 632 | |
| 633 | fn packet(&mut self, packet: Packet) { |
| 634 | if self |
| 635 | .video |
| 636 | .as_ref() |
| 637 | .is_some_and(|(index, _)| *index == packet.stream) |
| 638 | { |
| 639 | self.backlog.push_back(Queued::Packet(packet)); |
| 640 | } else if self |
| 641 | .audio |
| 642 | .as_ref() |
| 643 | .is_some_and(|(index, _)| *index == packet.stream) |
| 644 | { |
| 645 | self.audio_packet(&packet); |
| 646 | } |
| 647 | } |
| 648 | |
| 649 | fn decode_backlog(&mut self) -> bool { |
| 650 | crate::usage::tick(crate::usage::Group::Decode); |
| 651 | let Some((_, video)) = self.video.as_mut() else { |
| 652 | return false; |
| 653 | }; |
| 654 | if lock(&self.shared.video).queue.len() >= QUEUE_LIMIT { |
| 655 | return false; |
| 656 | } |
| 657 | let pictures = match self.backlog.pop_front() { |
| 658 | Some(Queued::Packet(packet)) => video.send(&packet), |
| 659 | Some(Queued::Flush) => video.flush(), |
| 660 | None => return false, |
| 661 | }; |
| 662 | let position = position(&self.shared, &self.playback); |
| 663 | for (pts, picture) in pictures { |
| 664 | if pts + LATE >= position { |
| 665 | show(&self.shared, pts, picture); |
| 666 | } |
| 667 | } |
| 668 | true |
| 669 | } |
| 670 | |
| 671 | fn audio_packet(&mut self, packet: &Packet) { |
| 672 | if self.producer.is_none() { |
| 673 | return; |
| 674 | } |
| 675 | let Some((_, audio)) = self.audio.as_mut() else { |
| 676 | return; |
| 677 | }; |
| 678 | let mut samples = std::mem::take(&mut self.scratch); |
| 679 | if let Err(error) = audio.decode(packet, &mut samples) { |
| 680 | warn!("audio packet skipped: {error}"); |
| 681 | } else { |
| 682 | let (rate, channels) = (audio.sample_rate(), audio.channels()); |
| 683 | let pts = packet |
| 684 | .pts |
| 685 | .map(|ticks| Timestamp::new(ticks, packet.time_base).as_secs_f64()); |
| 686 | self.queue_audio(&samples, channels, rate, pts); |
| 687 | } |
| 688 | self.scratch = samples; |
| 689 | } |
| 690 | |
| 691 | fn queue_audio(&mut self, interleaved: &[f32], channels: usize, rate: u32, pts: Option<f64>) { |
| 692 | if rate == 0 { |
| 693 | return; |
| 694 | } |
| 695 | let frames = resample::stereo(interleaved, channels); |
| 696 | let mut out = self.resampler.process(&frames, rate); |
| 697 | if let Some(target) = self.align.filter(|_| !out.is_empty()) { |
| 698 | self.align = None; |
| 699 | self.align_to(&mut out, target, pts.unwrap_or(target)); |
| 700 | } |
| 701 | let dropped = self.skip.min(out.len()); |
| 702 | out.drain(..dropped); |
| 703 | self.skip -= dropped; |
| 704 | self.pending.extend(out); |
| 705 | } |
| 706 | |
| 707 | fn align_to(&mut self, out: &mut Vec<Stereo>, target: f64, pts: f64) { |
| 708 | let shift = ((target - pts) * f64::from(VOICE_SAMPLE_RATE)).round() as i64; |
| 709 | if shift > 0 { |
| 710 | self.skip = shift as usize; |
| 711 | } else if shift < 0 { |
| 712 | let pad = ((-shift) as usize).min(MAX_PAD); |
| 713 | out.splice(0..0, std::iter::repeat_n([0.0; 2], pad)); |
| 714 | } |
| 715 | } |
| 716 | |
| 717 | fn end_of_input(&mut self) { |
| 718 | self.eof = true; |
| 719 | if self.video.is_some() { |
| 720 | self.backlog.push_back(Queued::Flush); |
| 721 | } |
| 722 | if self.producer.is_some() { |
| 723 | let mut samples = std::mem::take(&mut self.scratch); |
| 724 | let params = self.audio.as_mut().and_then(|(_, audio)| { |
| 725 | audio |
| 726 | .flush(&mut samples) |
| 727 | .ok() |
| 728 | .map(|()| (audio.sample_rate(), audio.channels())) |
| 729 | }); |
| 730 | if let Some((rate, channels)) = params { |
| 731 | self.queue_audio(&samples, channels, rate, None); |
| 732 | } |
| 733 | self.scratch = samples; |
| 734 | } |
| 735 | } |
| 736 | |
| 737 | fn seek(&mut self, to: f64) { |
| 738 | self.pending.clear(); |
| 739 | self.scratch.clear(); |
| 740 | self.resampler = Resampler::default(); |
| 741 | self.align = Some(to); |
| 742 | self.skip = 0; |
| 743 | self.eof = false; |
| 744 | self.backlog.clear(); |
| 745 | if let Some((_, video)) = self.video.as_mut() { |
| 746 | video.reset(); |
| 747 | } |
| 748 | if let Some((_, audio)) = self.audio.as_mut() { |
| 749 | audio.reset(); |
| 750 | } |
| 751 | lock(&self.shared.video).queue.clear(); |
| 752 | { |
| 753 | let mut clock = lock(&self.shared.clock); |
| 754 | let mut playback = lock(&self.playback); |
| 755 | while playback.pop().is_ok() {} |
| 756 | drop(playback); |
| 757 | lock(&self.shared.stash).clear(); |
| 758 | clock.rebase(to); |
| 759 | } |
| 760 | let stream = self |
| 761 | .video |
| 762 | .as_ref() |
| 763 | .map(|(index, _)| *index) |
| 764 | .or(self.audio.as_ref().map(|(index, _)| *index)); |
| 765 | if let Some(stream) = stream { |
| 766 | let at = Timestamp::new((to * 1_000_000.0) as i64, TimeBase::MICROS); |
| 767 | if self.reader.seek(stream, at, SeekMode::SyncBefore).is_err() { |
| 768 | self.restart(); |
| 769 | } |
| 770 | } |
| 771 | } |
| 772 | |
| 773 | fn restart(&mut self) { |
| 774 | match Reader::open(&self.path) { |
| 775 | Ok(reader) => self.reader = reader, |
| 776 | Err(error) => { |
| 777 | warn!("media restart failed: {error}"); |
| 778 | self.eof = true; |
| 779 | } |
| 780 | } |
| 781 | } |
| 782 | } |
| 783 | |
| 784 | pub fn position(shared: &Shared, playback: &Playback) -> f64 { |
| 785 | let clock = lock(&shared.clock); |
| 786 | let queued = if clock.audio { |
| 787 | lock(playback).slots() / PLAYBACK_CHANNELS |
| 788 | } else { |
| 789 | 0 |
| 790 | }; |
| 791 | clock.position(queued).max(0.0) |
| 792 | } |
| 793 | |
| 794 | fn show(shared: &Shared, pts: f64, picture: Picture) { |
| 795 | let Some(frame) = picture.into_frame(convert::ATTACHMENT_WIDTH) else { |
| 796 | return; |
| 797 | }; |
| 798 | lock(&shared.video).queue.push_back((pts, frame)); |
| 799 | } |
| 800 | |
| 801 | fn drain_h264(decoder: &mut H264Decoder) -> Vec<(f64, Picture)> { |
| 802 | std::iter::from_fn(|| decoder.receive_frame().ok()) |
| 803 | .filter_map(|frame| match frame { |
| 804 | CodecFrame::Video(picture) => h264_picture(&picture), |
| 805 | CodecFrame::Audio(_) => None, |
| 806 | }) |
| 807 | .collect() |
| 808 | } |
| 809 | |
| 810 | fn h264_picture(frame: &VideoFrame) -> Option<(f64, Picture)> { |
| 811 | let pts = frame.pts?.as_secs_f64(); |
| 812 | if frame.format != PixelFormat::I420 { |
| 813 | return None; |
| 814 | } |
| 815 | let [y, u, v] = frame.planes.as_slice() else { |
| 816 | return None; |
| 817 | }; |
| 818 | Some(( |
| 819 | pts, |
| 820 | Picture::Planes(Planes { |
| 821 | y: y.data.to_vec(), |
| 822 | y_stride: y.stride, |
| 823 | u: u.data.to_vec(), |
| 824 | v: v.data.to_vec(), |
| 825 | uv_stride: u.stride, |
| 826 | width: frame.width, |
| 827 | height: frame.height, |
| 828 | }), |
| 829 | )) |
| 830 | } |