Skip to main content

moq_ext_sources/source/
media_file.rs

1//! A media file, published as it is or decoded like a camera.
2//!
3//! [`MediaFile::open`] reads the sample index of an MP4 file once. From it,
4//! [`encoded_video`](MediaFile::encoded_video) and
5//! [`encoded_audio`](MediaFile::encoded_audio) hand the file's H.264 and AAC
6//! to a broadcast without decoding, and [`video`](MediaFile::video) and
7//! [`audio`](MediaFile::audio) decode them into raw sources for the normal
8//! encoders. Every stream of one file paces against one clock, so audio and
9//! video stay in sync and loop together.
10
11use 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
35/// The frame rate of a video track whose samples have no durations.
36const FALLBACK_FPS: u32 = 30;
37
38/// The shortest pass over a file, one frame at [`FALLBACK_FPS`].
39///
40/// A file of one sample, or of samples without durations, would otherwise
41/// loop a million times a second.
42const MIN_PASS: Duration = Duration::from_micros(1_000_000 / FALLBACK_FPS as u64);
43
44/// How far playback can fall behind the wall clock before the timeline moves forward.
45///
46/// A stalled disk makes playback late. Without the move, the file would play
47/// fast until it caught up. After the move, the content resumes where it
48/// stopped.
49const MAX_BEHIND: Duration = Duration::from_secs(1);
50
51/// The deepest picture reordering the decode path allows for, the size of the largest H.264 picture buffer.
52const MAX_HELD: usize = 16;
53
54/// An MP4 file, ready to publish as it is or to decode.
55///
56/// Opening reads the boxes that describe the file and none of its media.
57/// Cheap to clone: clones share the file and its clock.
58#[derive(Debug, Clone)]
59pub struct MediaFile {
60    shared: Arc<Shared>,
61    end: FileEnd,
62}
63
64/// What every stream of a [`MediaFile`] shares.
65#[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    /// The length of one pass over the file.
73    pass: Duration,
74    clock: Clock,
75}
76
77/// What a [`MediaFile`] holds, as [`MediaFile::info`] reports it.
78#[derive(Debug, Clone, PartialEq, Eq)]
79#[non_exhaustive]
80pub struct MediaInfo {
81    /// The first video track, if any.
82    pub video: Option<VideoInfo>,
83    /// The first audio track, if any.
84    pub audio: Option<AudioInfo>,
85    /// How long one pass over the file plays.
86    pub duration: Duration,
87}
88
89/// The video track of a [`MediaFile`].
90#[derive(Debug, Clone, PartialEq, Eq)]
91#[non_exhaustive]
92pub struct VideoInfo {
93    /// The codec's name, such as `H.264` or `H.265`.
94    pub codec: &'static str,
95    /// The picture size, from the SPS for H.264 and otherwise from the sample entry.
96    pub size: video::Size,
97    /// The average frame rate over the whole track.
98    pub rate: video::FrameRate,
99    /// The longest time between two keyframes, which a new passthrough viewer may wait.
100    pub gop: Duration,
101}
102
103/// The audio track of a [`MediaFile`].
104#[derive(Debug, Clone, PartialEq, Eq)]
105#[non_exhaustive]
106pub struct AudioInfo {
107    /// The codec's name, such as `AAC` or `Opus`.
108    pub codec: &'static str,
109    /// Samples per second per channel.
110    pub sample_rate: u32,
111    /// The number of channels.
112    pub channels: u32,
113}
114
115/// How [`MediaFile::video`] decodes the video.
116///
117/// The default lets moq-video pick the decoder.
118#[derive(Debug, Clone, Default, PartialEq, Eq)]
119#[non_exhaustive]
120pub struct VideoFileConfig {
121    /// The decoder backend to open.
122    pub decoder: video::decode::Backend,
123}
124
125impl VideoFileConfig {
126    /// Returns this config with `decoder` as the decoder backend to open.
127    #[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    /// Opens the MP4 file at `path`, plain or fragmented, and reads its sample index.
136    ///
137    /// The file plays once, and [`with_end`](Self::with_end) makes it loop.
138    /// The index stays in memory, about 40 bytes per sample, which is 22 MB
139    /// for two hours of 30 fps video with 48 kHz AAC.
140    ///
141    /// # Errors
142    ///
143    /// Fails with [`Error::Device`] if the file cannot be read, is not an MP4
144    /// file, is corrupt, or holds neither audio nor video.
145    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    /// Returns this file with `end` as what its streams do at the end of the file.
157    ///
158    /// With [`FileEnd::Restart`], every stream starts over after the longest
159    /// track ends, and timestamps keep rising across the passes.
160    #[must_use]
161    pub fn with_end(mut self, end: FileEnd) -> Self {
162        self.end = end;
163        self
164    }
165
166    /// Returns whether `other` is a clone of this open file with the same end.
167    ///
168    /// Clones share the file and its clock. Two opens of one path do not.
169    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    /// Returns the file's tracks, codecs and length.
174    #[must_use]
175    pub fn info(&self) -> &MediaInfo {
176        &self.shared.info
177    }
178
179    /// Returns the path the file was opened from.
180    #[must_use]
181    pub fn path(&self) -> &Path {
182        &self.shared.path
183    }
184
185    /// Returns the file's H.264 video as it is, paced to the wall clock.
186    ///
187    /// For `LocalBroadcast::set_encoded_video`. Each access unit is due when
188    /// its decode time comes. Passthrough costs no CPU and keeps the original
189    /// quality, but it publishes one rendition at the file's size and
190    /// bitrate. Keyframes come only where the file has them, and nothing can
191    /// ask for another. A stream that starts while the file already plays
192    /// starts at the next keyframe. A read error ends the stream with that
193    /// error.
194    ///
195    /// # Errors
196    ///
197    /// Fails with [`Error::InvalidConfig`] if the file has no video, or video
198    /// in another codec than H.264.
199    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    /// Returns the file's AAC audio as it is, paced to the wall clock.
207    ///
208    /// For `LocalBroadcast::set_encoded_audio`, with the trade-offs of
209    /// [`encoded_video`](Self::encoded_video).
210    ///
211    /// # Errors
212    ///
213    /// Fails with [`Error::InvalidConfig`] if the file has no audio, or audio
214    /// in another codec than AAC.
215    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    /// Decodes the file's H.264 video in real time into a raw source, like a camera.
223    ///
224    /// Each picture comes when its presentation time is due, at the file's
225    /// size and in the decoder's own memory, so a hardware decoder's pictures
226    /// reach a hardware encoder without a copy. The renditions of the
227    /// broadcast scale them. The rate is the track's average. The decoder
228    /// opens before this returns, and decodes whether or not a broadcast
229    /// wants the source.
230    ///
231    /// Cancellation safe: dropping the future stops the decode thread.
232    ///
233    /// # Errors
234    ///
235    /// Fails with [`Error::InvalidConfig`] for a file without H.264 video,
236    /// and with [`Error::Decoder`] if no decoder of the
237    /// [`VideoFileConfig::decoder`] backend opens. A read or decode error
238    /// later fails the source, as [`VideoSource::failure`] reports.
239    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        // The decoder may be bound to the thread that opens it, so it opens on
249        // the decode thread, which reports the result back.
250        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    /// Decodes the file's AAC audio in real time into a raw source, like a microphone.
277    ///
278    /// The samples keep the file's rate and layout and come when they are due.
279    ///
280    /// # Errors
281    ///
282    /// Fails with [`Error::InvalidConfig`] if the file has no AAC audio, and
283    /// with [`Error::Decoder`] if the decoder does not open.
284    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    /// Returns the avcC record of the video track, or the AudioSpecificConfig of the audio track.
300    ///
301    /// Fails if the track is missing or in another codec than H.264 or AAC.
302    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    /// Returns the samples of the video or audio track, each when its decode time is due.
322    ///
323    /// The stream ends after a read error, which it yields.
324    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    /// Reads the sample of `next`, and returns it once it is due.
339    async fn when_due(&self, next: Scheduled) -> Result<EncodedFrame, Error> {
340        let shared = self.shared.clone();
341        // The read comes before the wait, so its time falls inside it.
342        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    /// Decodes the video track and hands each picture to `push` when it is due.
358    ///
359    /// Returns when the file ends, or when `push` returns `false` or `closed`
360    /// returns `true` because the source is gone.
361    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        // A workaround for moq-video's VideoToolbox backend, which returns
369        // pictures in decode order: up to `depth` pictures wait here, by
370        // presentation time, and the earliest goes once more wait. It can go
371        // once that backend reorders on its own.
372        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        // Takes the pictures the decoder readied, and hands over those whose
380        // turn it is once each is due.
381        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                // The pictures a reordering decoder still holds belong to the last pass.
404                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    /// Decodes the audio track into `sender`, each packet when it is due.
426    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                // Each pass starts with the encoder delay again.
435                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            // A corrupt packet is not fatal. The file keeps playing without it.
446            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    /// Opens `path` and reads its sample index.
477    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    /// Reads the data of `sample`, which the index checked to lie within the file.
521    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
536/// Reports whether the file at `path` starts with a box an MP4 or QuickTime file starts with.
537pub(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
554/// Returns the info of a video track.
555///
556/// The rate is the track's average, so a long first frame of a screen
557/// recording does not set it.
558fn 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    // The longest run from one keyframe to the next, or to the end.
569    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
590/// Returns a media time as a timestamp, or an error past the timestamp range.
591fn 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
598/// Returns how many pictures of `samples`, in decode order, can come before an earlier one.
599///
600/// That is the most samples that follow one sample in decode order and
601/// present before it, up to [`MAX_HELD`].
602fn 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
617/// Returns the presentation time of `frame` in microseconds.
618fn micros(frame: &video::Frame) -> u64 {
619    frame
620        .timestamp
621        .as_micros()
622        .map_or(0, |micros| micros as u64)
623}
624
625/// The wall clock every stream of a file plays against.
626///
627/// It starts with the first sample any stream asks for, so a file opened
628/// early does not rush its first seconds out. A stream that starts later
629/// joins at the clock's position.
630#[derive(Debug, Default)]
631struct Clock {
632    /// When media time zero is due.
633    epoch: OnceLock<Instant>,
634    /// How far the timeline moved forward after playback fell behind, in microseconds.
635    skipped: AtomicU64,
636}
637
638impl Clock {
639    /// Returns when media time `at` is due, starting the clock if it has not started.
640    fn instant(&self, at: Duration) -> Instant {
641        *self.epoch.get_or_init(Instant::now) + at
642    }
643
644    /// Returns how far the timeline moved forward, which every media time adds.
645    fn skipped(&self) -> Duration {
646        Duration::from_micros(self.skipped.load(Ordering::Relaxed))
647    }
648
649    /// Returns how far the timeline moved forward, and when media time `at` is due on it.
650    fn due(&self, at: Duration) -> (Duration, Instant) {
651        let skipped = self.skipped();
652        (skipped, self.instant(skipped + at))
653    }
654
655    /// Sleeps this thread until media time `at` is due, and returns `at` on the moved timeline.
656    ///
657    /// Returns `None` once `closed` reports the source gone.
658    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    /// Returns the media time that plays now, or `None` before the clock starts.
668    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    /// Moves the timeline forward if a sample due at `due` comes more than [`MAX_BEHIND`] late.
678    ///
679    /// `skipped` is what [`due`](Self::due) returned with `due`. When every stream falls behind in one stall, only the
680    /// first one moves the timeline, so the stall counts once. The move holds
681    /// for every stream of the file, so they stay in sync.
682    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/// One sample with its times on the file's timeline.
703#[derive(Debug, Clone, Copy)]
704struct Scheduled {
705    sample: Sample,
706    /// Whether the sample starts a pass over the file after an earlier one.
707    restarted: bool,
708    /// When the sample decodes.
709    decode_at: Duration,
710    /// When the sample presents.
711    timestamp: Duration,
712}
713
714/// The samples of one track in decode order, pass after pass for a looping file.
715///
716/// Every track of a file starts a pass at the same time, after the longest
717/// track ended, so a shorter track pauses and the tracks stay in sync. The
718/// first sample is the first keyframe at or after the clock's position, so a
719/// stream that joins a playing file plays in sync with the others.
720#[derive(Debug)]
721struct Schedule {
722    file: MediaFile,
723    video: bool,
724    /// The next sample, or `None` before the first.
725    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    /// Returns the path of a test clip in `test_data`.
790    ///
791    /// - `clip.mp4`: 64x48 H.264 Baseline at 10 fps and 16 kHz mono AAC, one
792    ///   second each, made with `ffmpeg -f lavfi -i
793    ///   testsrc2=size=64x48:rate=10:duration=1 -f lavfi -i
794    ///   sine=frequency=440:sample_rate=16000:duration=1 -c:v libx264 -profile:v
795    ///   baseline -crf 40 -g 10 -pix_fmt yuv420p -c:a aac -b:a 16k -ac 1
796    ///   -movflags +faststart clip.mp4`. The audio's edit list trims the
797    ///   encoder's priming packet.
798    /// - `fragmented.mp4`: the same streams, copied with `-movflags
799    ///   cmaf+frag_keyframe+empty_moov+default_base_moof`.
800    /// - `bframes.mp4`: the same video in High profile with two B-frames
801    ///   (`-profile:v high -bf 2`) and no audio. Its edit list starts the
802    ///   presentation two frames into the decode timeline.
803    fn clip(name: &str) -> PathBuf {
804        PathBuf::from(env!("CARGO_MANIFEST_DIR"))
805            .join("src/source/test_data")
806            .join(name)
807    }
808
809    /// Opens the test clip `name`.
810    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    /// A fragmented copy of a file indexes to the same samples, spaced the same.
831    ///
832    /// ffmpeg drops the audio's edit list when it fragments, so the fragmented
833    /// audio keeps the priming packet that the plain file trims. The tracks
834    /// are compared from their ends.
835    #[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    /// A looping file starts each pass one file length after the last, on every track.
864    #[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            // The edit list trims the audio's priming, so both tracks start at zero.
872            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    /// Passthrough hands each access unit over when its decode time is due.
887    #[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        // The first two samples decode before the presentation starts.
906        assert_eq!(arrivals, [0, 0, 0, 100, 200, 300, 400, 500, 600, 700]);
907    }
908
909    /// A stream that starts while the file plays joins at the clock's position, and the others go on.
910    #[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        // A pass ends with the longer audio, so the video pauses a little at each loop.
945        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    /// A stall that every stream sees moves the timeline once.
952    #[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    /// A backend that returns decode order needs as many pictures held as the stream reorders.
965    #[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    /// A looping B-frame file decodes to pictures with rising timestamps.
992    ///
993    /// The software decoder keeps the test independent of the platform's
994    /// backend.
995    #[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    /// `AudioSource::file` takes an MP4 file and decodes its AAC at the file's rate and layout.
1021    #[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}