1use std::{
12 collections::BTreeMap,
13 io::{Read, Seek, SeekFrom},
14 path::{Path, PathBuf},
15 sync::{
16 Arc, Mutex, OnceLock,
17 atomic::{AtomicU64, Ordering},
18 },
19 time::Duration,
20};
21
22use bytes::Bytes;
23use tokio::time::Instant;
24use tracing::{debug, warn};
25
26use self::mp4::{Codec, Sample, Track};
27use super::{
28 AudioFormat, AudioSource, FileEnd, FrameSender, VideoFormat, VideoSource, file::file_error,
29 sleep_until,
30};
31use crate::{EncodedAudio, EncodedFrame, EncodedVideo, Error, audio, video};
32
33mod mp4;
34
35const FALLBACK_FPS: u32 = 30;
37
38const MIN_PASS: Duration = Duration::from_micros(1_000_000 / FALLBACK_FPS as u64);
43
44const MAX_BEHIND: Duration = Duration::from_secs(1);
50
51const MAX_HELD: usize = 16;
53
54#[derive(Debug, Clone)]
59pub struct MediaFile {
60 shared: Arc<Shared>,
61 end: FileEnd,
62}
63
64#[derive(Debug)]
66struct Shared {
67 path: PathBuf,
68 file: Mutex<std::fs::File>,
69 video: Option<Track>,
70 audio: Option<Track>,
71 info: MediaInfo,
72 pass: Duration,
74 clock: Clock,
75}
76
77#[derive(Debug, Clone, PartialEq, Eq)]
79#[non_exhaustive]
80pub struct MediaInfo {
81 pub video: Option<VideoInfo>,
83 pub audio: Option<AudioInfo>,
85 pub duration: Duration,
87}
88
89#[derive(Debug, Clone, PartialEq, Eq)]
91#[non_exhaustive]
92pub struct VideoInfo {
93 pub codec: &'static str,
95 pub size: video::Size,
97 pub rate: video::FrameRate,
99 pub gop: Duration,
101}
102
103#[derive(Debug, Clone, PartialEq, Eq)]
105#[non_exhaustive]
106pub struct AudioInfo {
107 pub codec: &'static str,
109 pub sample_rate: u32,
111 pub channels: u32,
113}
114
115#[derive(Debug, Clone, Default, PartialEq, Eq)]
119#[non_exhaustive]
120pub struct VideoFileConfig {
121 pub decoder: video::decode::Backend,
123}
124
125impl VideoFileConfig {
126 #[must_use]
128 pub fn with_decoder(mut self, decoder: video::decode::Backend) -> Self {
129 self.decoder = decoder;
130 self
131 }
132}
133
134impl MediaFile {
135 pub async fn open(path: impl AsRef<Path>) -> Result<Self, Error> {
146 let path = path.as_ref().to_path_buf();
147 let shared = tokio::task::spawn_blocking(move || Shared::open(path))
148 .await
149 .map_err(|err| Error::device_msg(format!("the file reader failed: {err}")))??;
150 Ok(Self {
151 shared: Arc::new(shared),
152 end: FileEnd::Stop,
153 })
154 }
155
156 #[must_use]
161 pub fn with_end(mut self, end: FileEnd) -> Self {
162 self.end = end;
163 self
164 }
165
166 pub(crate) fn is_clone_of(&self, other: &Self) -> bool {
170 Arc::ptr_eq(&self.shared, &other.shared) && self.end == other.end
171 }
172
173 #[must_use]
175 pub fn info(&self) -> &MediaInfo {
176 &self.shared.info
177 }
178
179 #[must_use]
181 pub fn path(&self) -> &Path {
182 &self.shared.path
183 }
184
185 pub fn encoded_video(&self) -> Result<EncodedVideo, Error> {
200 Ok(EncodedVideo::Avc1 {
201 config: self.codec_record(true)?,
202 frames: Box::pin(self.paced(true)),
203 })
204 }
205
206 pub fn encoded_audio(&self) -> Result<EncodedAudio, Error> {
216 Ok(EncodedAudio::Aac {
217 config: self.codec_record(false)?,
218 frames: Box::pin(self.paced(false)),
219 })
220 }
221
222 pub async fn video(&self, config: VideoFileConfig) -> Result<VideoSource, Error> {
240 let catalog =
241 moq_mux::codec::h264::config(&self.codec_record(true)?).map_err(Error::decoder)?;
242 let info = self.shared.info.video.as_ref().expect("the file has video");
243 let format = VideoFormat {
244 size: info.size,
245 rate: info.rate,
246 };
247 let file = self.clone();
248 let (opened, ready) = tokio::sync::oneshot::channel();
251 let source = VideoSource::spawn("video-file", format, move |sender| {
252 let mut decoder_config = video::decode::Config::new();
253 decoder_config.backend = config.decoder;
254 let decoder = match video::decode::Decoder::new(&catalog, &decoder_config) {
255 Ok(decoder) => {
256 let _ = opened.send(Ok(()));
257 decoder
258 }
259 Err(err) => {
260 let _ = opened.send(Err(Error::decoder(err)));
261 return Ok(());
262 }
263 };
264 file.decode_video(
265 decoder,
266 |frame| sender.push(frame).is_ok(),
267 || sender.is_closed(),
268 )
269 })?;
270 ready
271 .await
272 .map_err(|_| Error::device_msg("the file decoder stopped before it opened"))??;
273 Ok(source)
274 }
275
276 pub fn audio(&self) -> Result<AudioSource, Error> {
285 let catalog =
286 moq_mux::codec::aac::config(&self.codec_record(false)?).map_err(Error::decoder)?;
287 let decoder = moq_audio::decode::Decoder::new(&catalog, &Default::default())
288 .map_err(Error::decoder)?;
289 let format = AudioFormat {
290 sample_rate: decoder.sample_rate(),
291 layout: decoder.layout(),
292 };
293 let file = self.clone();
294 AudioSource::spawn("audio-file", format, move |sender| {
295 file.decode_audio(decoder, &sender)
296 })
297 }
298
299 fn codec_record(&self, video: bool) -> Result<Bytes, Error> {
303 let (track, kind, supported) = if video {
304 (&self.shared.video, "video", "H.264")
305 } else {
306 (&self.shared.audio, "audio", "AAC")
307 };
308 let path = self.path().display();
309 let track = track
310 .as_ref()
311 .ok_or_else(|| Error::invalid(format!("{path} has no {kind} track")))?;
312 match (&track.codec, video) {
313 (Codec::H264(record), true) | (Codec::Aac(record), false) => Ok(record.clone()),
314 (codec, _) => Err(Error::invalid(format!(
315 "{path}: its {kind} is in {}, and only {supported} is supported",
316 codec.name()
317 ))),
318 }
319 }
320
321 fn paced(
325 &self,
326 video: bool,
327 ) -> impl n0_future::Stream<Item = Result<EncodedFrame, Error>> + use<> {
328 let schedule = Schedule::new(self.clone(), video);
329 n0_future::stream::unfold(Some(schedule), |schedule| async move {
330 let mut schedule = schedule?;
331 let next = schedule.next()?;
332 let frame = schedule.file.when_due(next).await;
333 let more = frame.is_ok().then_some(schedule);
334 Some((frame, more))
335 })
336 }
337
338 async fn when_due(&self, next: Scheduled) -> Result<EncodedFrame, Error> {
340 let shared = self.shared.clone();
341 let data = tokio::task::spawn_blocking(move || shared.read(&next.sample))
343 .await
344 .map_err(|err| Error::device_msg(format!("the file reader failed: {err}")))??;
345 let clock = &self.shared.clock;
346 let (skipped, due) = clock.due(next.decode_at);
347 tokio::time::sleep_until(due).await;
348 clock.catch_up(skipped, due);
349 let timestamp = skipped + next.timestamp;
350 Ok(EncodedFrame::new(
351 data,
352 to_timestamp(timestamp)?,
353 clock.instant(timestamp).into_std(),
354 ))
355 }
356
357 fn decode_video(
362 &self,
363 mut decoder: video::decode::Decoder,
364 mut push: impl FnMut(video::Frame) -> bool,
365 closed: impl Fn() -> bool,
366 ) -> Result<(), Error> {
367 let clock = &self.shared.clock;
368 let depth = reorder_depth(
373 self.shared
374 .video
375 .as_ref()
376 .map_or(&[], |track| &track.samples),
377 );
378 let mut held = BTreeMap::new();
379 let mut drain = |decoder: &mut video::decode::Decoder,
382 held: &mut BTreeMap<u64, video::Frame>,
383 flushing: bool|
384 -> Result<bool, Error> {
385 while let Some(frame) = decoder.receive().map_err(Error::decoder)? {
386 held.insert(micros(&frame), frame);
387 }
388 let keep = if flushing { 0 } else { depth };
389 while held.len() > keep {
390 let (at, mut frame) = held.pop_first().expect("a held picture");
391 let Some(at) = clock.wait(Duration::from_micros(at), &closed) else {
392 return Ok(false);
393 };
394 frame.timestamp = to_timestamp(at)?;
395 if !push(frame) {
396 return Ok(false);
397 }
398 }
399 Ok(true)
400 };
401 for next in Schedule::new(self.clone(), true) {
402 if next.restarted {
403 decoder.flush().map_err(Error::decoder)?;
405 if !drain(&mut decoder, &mut held, true)? {
406 return Ok(());
407 }
408 debug!(path = %self.path().display(), "video file looping");
409 }
410 let data = self.shared.read(&next.sample)?;
411 let timestamp = to_timestamp(next.timestamp)?;
412 decoder
413 .decode(&data, timestamp, next.sample.keyframe)
414 .map_err(Error::decoder)?;
415 if !drain(&mut decoder, &mut held, false)? {
416 return Ok(());
417 }
418 }
419 decoder.flush().map_err(Error::decoder)?;
420 drain(&mut decoder, &mut held, true)?;
421 debug!(path = %self.path().display(), "video file ended");
422 Ok(())
423 }
424
425 fn decode_audio(
427 &self,
428 mut decoder: moq_audio::decode::Decoder,
429 sender: &FrameSender<audio::Frame>,
430 ) -> Result<(), Error> {
431 let mut corrupt = 0u64;
432 for next in Schedule::new(self.clone(), false) {
433 if next.restarted {
434 decoder.reset().map_err(Error::decoder)?;
436 }
437 let data = self.shared.read(&next.sample)?;
438 let Some(timestamp) = self
439 .shared
440 .clock
441 .wait(next.timestamp, || sender.is_closed())
442 else {
443 return Ok(());
444 };
445 if let Err(err) = decoder.decode(&data) {
447 corrupt += 1;
448 if corrupt == 1 {
449 warn!(path = %self.path().display(), error = %err, "skipping a corrupt audio packet, later ones log at debug");
450 } else {
451 debug!(corrupt, error = %err, "skipping a corrupt audio packet");
452 }
453 continue;
454 }
455 while let Some(decoded) = decoder.receive().map_err(Error::decoder)? {
456 let data = Bytes::from_iter(
457 decoded
458 .samples
459 .iter()
460 .flat_map(|sample| sample.to_le_bytes()),
461 );
462 if sender
463 .push(audio::Frame::new(to_timestamp(timestamp)?, data))
464 .is_err()
465 {
466 return Ok(());
467 }
468 }
469 }
470 debug!(path = %self.path().display(), "audio file ended");
471 Ok(())
472 }
473}
474
475impl Shared {
476 fn open(path: PathBuf) -> Result<Self, Error> {
478 let mut file = std::fs::File::open(&path).map_err(|err| file_error(&path, err))?;
479 let tracks = mp4::index(&mut file).map_err(|err| file_error(&path, err))?;
480 let mut video = None;
481 let mut audio = None;
482 for track in tracks {
483 let slot = if track.video { &mut video } else { &mut audio };
484 if slot.is_none() && !track.samples.is_empty() {
485 *slot = Some(track);
486 }
487 }
488 if video.is_none() && audio.is_none() {
489 return Err(file_error(&path, "the file has no audio or video samples"));
490 }
491 let end = video
492 .iter()
493 .chain(&audio)
494 .flat_map(|track| &track.samples)
495 .map(|sample| sample.pts.saturating_add(i64::from(sample.duration)))
496 .max()
497 .unwrap_or(0);
498 let pass = Duration::from_micros(u64::try_from(end).unwrap_or(0)).max(MIN_PASS);
499 let info = MediaInfo {
500 video: video.as_ref().map(video_info),
501 audio: audio.as_ref().map(|track| AudioInfo {
502 codec: track.codec.name(),
503 sample_rate: track.sample_rate,
504 channels: track.channels,
505 }),
506 duration: pass,
507 };
508 debug!(path = %path.display(), ?video, ?audio, ?pass, "file opened");
509 Ok(Self {
510 path,
511 file: Mutex::new(file),
512 video,
513 audio,
514 info,
515 pass,
516 clock: Clock::default(),
517 })
518 }
519
520 fn read(&self, sample: &Sample) -> Result<Bytes, Error> {
522 let mut data = vec![0; sample.size as usize];
523 let mut file = self.file.lock().expect("poisoned");
524 file.seek(SeekFrom::Start(sample.offset))
525 .and_then(|_| file.read_exact(&mut data))
526 .map_err(|err| {
527 file_error(
528 &self.path,
529 format!("sample at byte {}: {err}", sample.offset),
530 )
531 })?;
532 Ok(data.into())
533 }
534}
535
536pub(super) async fn is_mp4(path: &Path) -> bool {
538 let path = path.to_path_buf();
539 tokio::task::spawn_blocking(move || {
540 let mut head = [0; 8];
541 std::fs::File::open(path)
542 .and_then(|mut file| file.read_exact(&mut head))
543 .is_ok_and(|()| {
544 matches!(
545 &head[4..],
546 b"ftyp" | b"moov" | b"mdat" | b"free" | b"wide" | b"skip"
547 )
548 })
549 })
550 .await
551 .unwrap_or(false)
552}
553
554fn video_info(track: &Track) -> VideoInfo {
559 let span: i64 = track
560 .samples
561 .iter()
562 .map(|sample| i64::from(sample.duration))
563 .sum();
564 let rate = (span > 0)
565 .then(|| video::FrameRate::from_f64(track.samples.len() as f64 * 1e6 / span as f64).ok())
566 .flatten()
567 .unwrap_or_else(|| video::FrameRate::new(FALLBACK_FPS, 1).expect("a valid rate"));
568 let end = track
570 .samples
571 .last()
572 .map_or(0, |last| last.dts + i64::from(last.duration));
573 let mut gop = 0i64;
574 let mut last = None;
575 for sample in track.samples.iter().filter(|sample| sample.keyframe) {
576 if let Some(last) = last {
577 gop = gop.max(sample.dts - last);
578 }
579 last = Some(sample.dts);
580 }
581 gop = gop.max(end - last.unwrap_or(0));
582 VideoInfo {
583 codec: track.codec.name(),
584 size: video::Size::new(track.width, track.height),
585 rate,
586 gop: Duration::from_micros(gop.max(0) as u64),
587 }
588}
589
590fn to_timestamp(at: Duration) -> Result<moq_net::Timestamp, Error> {
592 u64::try_from(at.as_micros())
593 .ok()
594 .and_then(|micros| moq_net::Timestamp::from_micros(micros).ok())
595 .ok_or_else(|| Error::device_msg(format!("a file time of {at:?} is out of range")))
596}
597
598fn reorder_depth(samples: &[Sample]) -> usize {
603 samples
604 .iter()
605 .enumerate()
606 .map(|(index, sample)| {
607 samples[index + 1..]
608 .iter()
609 .take(MAX_HELD)
610 .filter(|later| later.pts < sample.pts)
611 .count()
612 })
613 .max()
614 .unwrap_or(0)
615}
616
617fn micros(frame: &video::Frame) -> u64 {
619 frame
620 .timestamp
621 .as_micros()
622 .map_or(0, |micros| micros as u64)
623}
624
625#[derive(Debug, Default)]
631struct Clock {
632 epoch: OnceLock<Instant>,
634 skipped: AtomicU64,
636}
637
638impl Clock {
639 fn instant(&self, at: Duration) -> Instant {
641 *self.epoch.get_or_init(Instant::now) + at
642 }
643
644 fn skipped(&self) -> Duration {
646 Duration::from_micros(self.skipped.load(Ordering::Relaxed))
647 }
648
649 fn due(&self, at: Duration) -> (Duration, Instant) {
651 let skipped = self.skipped();
652 (skipped, self.instant(skipped + at))
653 }
654
655 fn wait(&self, at: Duration, closed: impl Fn() -> bool) -> Option<Duration> {
659 let (skipped, due) = self.due(at);
660 if !sleep_until(due.into_std(), closed) {
661 return None;
662 }
663 self.catch_up(skipped, due);
664 Some(skipped + at)
665 }
666
667 fn position(&self) -> Option<Duration> {
669 let epoch = self.epoch.get()?;
670 Some(
671 Instant::now()
672 .saturating_duration_since(*epoch)
673 .saturating_sub(self.skipped()),
674 )
675 }
676
677 fn catch_up(&self, skipped: Duration, due: Instant) {
683 let behind = Instant::now().saturating_duration_since(due);
684 if behind <= MAX_BEHIND {
685 return;
686 }
687 let read = skipped.as_micros() as u64;
688 let moved = read + behind.as_micros() as u64;
689 if self
690 .skipped
691 .compare_exchange(read, moved, Ordering::Relaxed, Ordering::Relaxed)
692 .is_ok()
693 {
694 warn!(
695 ?behind,
696 "file playback fell behind, so its timeline moves forward"
697 );
698 }
699 }
700}
701
702#[derive(Debug, Clone, Copy)]
704struct Scheduled {
705 sample: Sample,
706 restarted: bool,
708 decode_at: Duration,
710 timestamp: Duration,
712}
713
714#[derive(Debug)]
721struct Schedule {
722 file: MediaFile,
723 video: bool,
724 index: Option<usize>,
726 pass: u64,
727}
728
729impl Schedule {
730 fn new(file: MediaFile, video: bool) -> Self {
731 Self {
732 file,
733 video,
734 index: None,
735 pass: 0,
736 }
737 }
738}
739
740impl Iterator for Schedule {
741 type Item = Scheduled;
742
743 fn next(&mut self) -> Option<Scheduled> {
744 let shared = &self.file.shared;
745 let track = if self.video {
746 shared.video.as_ref()?
747 } else {
748 shared.audio.as_ref()?
749 };
750 let pass = shared.pass.as_micros() as u64;
751 let first = self.index.is_none();
752 let mut index = self.index.unwrap_or_else(|| {
753 let position = shared.clock.position().unwrap_or_default().as_micros() as u64;
754 self.pass = position / pass;
755 let offset = (position % pass) as i64;
756 track
757 .samples
758 .iter()
759 .position(|sample| sample.keyframe && sample.pts >= offset)
760 .unwrap_or(track.samples.len())
761 });
762 let wrapped = index == track.samples.len();
763 if wrapped {
764 self.pass += 1;
765 index = 0;
766 }
767 if self.pass > 0 && self.file.end == FileEnd::Stop {
768 return None;
769 }
770 let sample = track.samples[index];
771 self.index = Some(index + 1);
772 let start = self.pass.saturating_mul(pass);
773 let at = |time: i64| Duration::from_micros(start.saturating_add_signed(time));
774 Some(Scheduled {
775 sample,
776 restarted: wrapped && !first,
777 decode_at: at(sample.dts),
778 timestamp: at(sample.pts),
779 })
780 }
781}
782
783#[cfg(test)]
784mod tests {
785 use n0_future::StreamExt;
786
787 use super::*;
788
789 fn clip(name: &str) -> PathBuf {
804 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
805 .join("src/source/test_data")
806 .join(name)
807 }
808
809 async fn open(name: &str) -> MediaFile {
811 MediaFile::open(clip(name)).await.expect("the clip opens")
812 }
813
814 #[tokio::test]
815 async fn a_plain_mp4_reports_its_tracks() {
816 let file = open("clip.mp4").await;
817 let info = file.info();
818 let video = info.video.as_ref().expect("a video track");
819 assert_eq!(video.codec, "H.264");
820 assert_eq!(video.size, video::Size::new(64, 48));
821 assert_eq!(video.rate, video::FrameRate::new(10, 1).unwrap());
822 assert_eq!(video.gop, Duration::from_secs(1));
823 let audio = info.audio.as_ref().expect("an audio track");
824 assert_eq!(
825 (audio.codec, audio.sample_rate, audio.channels),
826 ("AAC", 16_000, 1)
827 );
828 }
829
830 #[tokio::test]
836 async fn a_fragmented_mp4_matches_the_plain_one() {
837 let plain = open("clip.mp4").await;
838 let fragmented = open("fragmented.mp4").await;
839 assert_eq!(plain.info().video, fragmented.info().video);
840 assert_eq!(plain.info().audio, fragmented.info().audio);
841 for video in [true, false] {
842 let plain_samples: Vec<_> = Schedule::new(plain.clone(), video).collect();
843 let fragmented_samples: Vec<_> = Schedule::new(fragmented.clone(), video).collect();
844 let primed = usize::from(!video);
845 assert_eq!(plain_samples.len() + primed, fragmented_samples.len());
846 let end = |samples: &[Scheduled]| samples.last().unwrap().timestamp;
847 let (plain_end, fragmented_end) = (end(&plain_samples), end(&fragmented_samples));
848 for (a, b) in plain_samples
849 .iter()
850 .rev()
851 .zip(fragmented_samples.iter().rev())
852 {
853 assert_eq!(plain_end - a.timestamp, fragmented_end - b.timestamp);
854 assert_eq!(a.sample.keyframe, b.sample.keyframe);
855 assert_eq!(
856 plain.shared.read(&a.sample).unwrap(),
857 fragmented.shared.read(&b.sample).unwrap()
858 );
859 }
860 }
861 }
862
863 #[tokio::test]
865 async fn a_looping_file_continues_its_timeline() {
866 let file = open("clip.mp4").await.with_end(FileEnd::Restart);
867 let length = file.info().duration;
868 for video in [true, false] {
869 let count = Schedule::new(file.clone().with_end(FileEnd::Stop), video).count();
870 let two_passes: Vec<_> = Schedule::new(file.clone(), video).take(2 * count).collect();
871 assert_eq!(two_passes[0].timestamp, Duration::ZERO);
873 let restarts: Vec<_> = two_passes.iter().map(|next| next.restarted).collect();
874 assert_eq!(
875 restarts.iter().position(|&restarted| restarted),
876 Some(count)
877 );
878 assert_eq!(restarts.iter().filter(|&&restarted| restarted).count(), 1);
879 for (first, second) in two_passes[..count].iter().zip(&two_passes[count..]) {
880 assert_eq!(second.timestamp, first.timestamp + length);
881 assert_eq!(second.decode_at, first.decode_at + length);
882 }
883 }
884 }
885
886 #[tokio::test(start_paused = true)]
888 async fn passthrough_paces_to_the_decode_times() {
889 let file = open("bframes.mp4").await;
890 let EncodedVideo::Avc1 { config, mut frames } = file.encoded_video().expect("H.264") else {
891 panic!("not avc1");
892 };
893 assert_eq!(config[0], 1, "an avcC record starts with version 1");
894 let start = Instant::now();
895 let mut arrivals = Vec::new();
896 while let Some(frame) = frames.next().await {
897 let frame = frame.expect("the clip reads");
898 arrivals.push((Instant::now() - start).as_millis() as u64);
899 assert_eq!(
900 frame.at,
901 (start + Duration::from_micros(frame.timestamp.as_micros().unwrap() as u64))
902 .into_std()
903 );
904 }
905 assert_eq!(arrivals, [0, 0, 0, 100, 200, 300, 400, 500, 600, 700]);
907 }
908
909 #[tokio::test(start_paused = true)]
911 async fn a_late_stream_joins_without_stalling_the_others() {
912 let file = open("clip.mp4").await.with_end(FileEnd::Restart);
913 let EncodedVideo::Avc1 { mut frames, .. } = file.encoded_video().expect("H.264") else {
914 panic!("not avc1");
915 };
916 let start = Instant::now();
917 let video = tokio::spawn(async move {
918 let mut arrivals = Vec::new();
919 while arrivals.len() < 50 {
920 frames
921 .next()
922 .await
923 .expect("a loop")
924 .expect("the clip reads");
925 arrivals.push(Instant::now() - start);
926 }
927 arrivals
928 });
929 tokio::time::sleep(Duration::from_secs(3)).await;
930 let EncodedAudio::Aac { mut frames, .. } = file.encoded_audio().expect("AAC");
931 let first = frames
932 .next()
933 .await
934 .expect("a frame")
935 .expect("the clip reads");
936 let now = Instant::now() - start;
937 let presents = Duration::from_micros(first.timestamp.as_micros().unwrap() as u64);
938 assert!(
939 presents + Duration::from_millis(70) >= now
940 && presents <= now + Duration::from_millis(70),
941 "the audio joins at {presents:?}, at {now:?}"
942 );
943 let arrivals = video.await.unwrap();
944 let pause = file.info().duration - Duration::from_millis(900);
946 let longest = arrivals.windows(2).map(|pair| pair[1] - pair[0]).max();
947 assert_eq!(longest, Some(pause), "{arrivals:?}");
948 assert_eq!(file.shared.clock.skipped(), Duration::ZERO);
949 }
950
951 #[tokio::test(start_paused = true)]
953 async fn a_shared_stall_counts_once() {
954 let clock = Clock::default();
955 let (skipped, due) = clock.due(Duration::ZERO);
956 tokio::time::advance(Duration::from_secs(3)).await;
957 for _stream in 0..2 {
958 clock.catch_up(skipped, due);
959 }
960 assert_eq!(clock.skipped(), Duration::from_secs(3));
961 assert_eq!(clock.position(), Some(Duration::ZERO));
962 }
963
964 #[tokio::test]
966 async fn the_reorder_depth_follows_the_b_frames() {
967 let file = open("bframes.mp4").await;
968 assert_eq!(
969 reorder_depth(&file.shared.video.as_ref().unwrap().samples),
970 2
971 );
972 let plain = open("clip.mp4").await;
973 assert_eq!(
974 reorder_depth(&plain.shared.video.as_ref().unwrap().samples),
975 0
976 );
977 }
978
979 #[tokio::test]
980 async fn passthrough_refuses_another_codec() {
981 let file = open("bframes.mp4").await;
982 assert!(matches!(
983 file.encoded_audio(),
984 Err(Error::InvalidConfig { .. })
985 ));
986 let not_mp4 =
987 MediaFile::open(PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("Cargo.toml")).await;
988 assert!(matches!(not_mp4, Err(Error::Device { .. })));
989 }
990
991 #[test]
996 fn a_looping_b_frame_file_decodes_in_presentation_order() {
997 let runtime = tokio::runtime::Runtime::new().unwrap();
998 let file = runtime
999 .block_on(MediaFile::open(clip("bframes.mp4")))
1000 .expect("the clip opens")
1001 .with_end(FileEnd::Restart);
1002 let catalog = moq_mux::codec::h264::config(&file.codec_record(true).unwrap()).unwrap();
1003 let mut config = video::decode::Config::new();
1004 config.backend = video::decode::Backend::Software;
1005 let decoder = video::decode::Decoder::new(&catalog, &config).unwrap();
1006 let mut frames = Vec::new();
1007 file.decode_video(
1008 decoder,
1009 |frame| {
1010 frames.push(frame);
1011 frames.len() < 12
1012 },
1013 || false,
1014 )
1015 .expect("the clip plays");
1016 let millis: Vec<u64> = frames.iter().map(|frame| micros(frame) / 1000).collect();
1017 assert_eq!(millis, (0..12).map(|n| n * 100).collect::<Vec<_>>());
1018 }
1019
1020 #[tokio::test]
1022 async fn an_mp4_audio_file_decodes() {
1023 let source = AudioSource::file(clip("clip.mp4"), FileEnd::Stop)
1024 .await
1025 .expect("the audio opens");
1026 let format = source.format().expect("PCM");
1027 assert_eq!(format.sample_rate, 16_000);
1028 assert_eq!(format.layout, audio::Layout::Mono);
1029 }
1030}