//! Fragmented MP4 (fMP4 / CMAF). //! //! A widely supported file format that's also a viable wire format. //! Each moq frame carries one moof+mdat fragment, optionally with //! several samples packed inside. [`Wire`] is the wire-level //! container; [`Import`] parses external fMP4 streams and [`Export`] //! produces them. mod edit; mod export; mod import; pub(crate) mod metadata; mod muxer; mod sample; mod text; pub use export::*; pub use import::*; pub use muxer::*; /// The largest text sample [`Import`] holds whole. /// /// A text sample is rewritten only once its last byte arrives, so a larger one is refused before /// any of it is staged. It matches moq-net's 32 MiB frame bound, /// which the rewritten sample must fit. /// Media samples stream into their frames and have no such bound. const MAX_HELD_BYTES: usize = 32 * 1024 * 1024; /// The largest metadata box body parsed on import or from received CMAF. /// /// A larger declaration is refused at its header, before buffering or expanding its body. /// Parsing expands a body up to tenfold (a 4-byte `trun` entry becomes a 40-byte /// [`TrunEntry`](mp4_atom::TrunEntry)), so this keeps a parse within [`MAX_HELD_BYTES`]. /// Counts and retained metadata-tree entries are checked separately, including entries that /// consume no bytes. Media payloads in `mdat` keep their transport-owned bound. const MAX_METADATA_BYTES: usize = MAX_HELD_BYTES / 16; /// The most samples parsed or planned for one CMAF fragment. /// /// Every sample's byte range is resolved before any of the fragment publishes, at about 200 bytes /// a sample, so a fragment at this bound plans within [`MAX_HELD_BYTES`]. A `moof` at /// [`MAX_METADATA_BYTES`] holds this many 16-byte `trun` entries. A shorter fragment is also held /// to one sample per metadata byte past the first 4,096. const MAX_FRAGMENT_SAMPLES: u64 = (MAX_METADATA_BYTES / 16) as u64; /// Samples a fragment may declare beyond one per byte of its metadata. /// /// A `trun` entry is at least 4 bytes, so only a run without per-sample fields, which stores just /// a count, can declare more samples than it has bytes. Its plan is reserved before any payload /// arrives, so this keeps a few-byte `moof` from planning megabytes. A live fragment is a handful /// of samples. pub(crate) const FRAGMENT_SAMPLE_BASE: u64 = 4096; /// The most tracks [`Import`] accepts from one `moov`, refused before any is created. /// /// Each track costs about 16 KiB to parse and set up, and keeps its catalog entry and output /// state for as long as the import runs. Real files declare a handful. const MAX_TRACKS: usize = 256; #[cfg(test)] mod export_test; #[cfg(test)] mod import_test; use std::time::Duration; use bytes::Bytes; use hang::catalog::{AudioCodec, AudioConfig, VideoCodec, VideoConfig}; use mp4_atom::Atom; use moq_net::Timestamp; use crate::container::{Container, Frame}; /// Fragmented MP4 parsing, muxing, and transport errors. #[derive(Debug, Clone, thiserror::Error)] #[non_exhaustive] pub enum Error { /// Container display metadata has no valid catalog aspect ratio. #[error("invalid display aspect: {0}")] InvalidAspect(&'static str), /// A subtitle sample cannot be reconstructed with valid text and timing. #[error("invalid subtitle: {0}")] InvalidSubtitle(&'static str), /// Parsing or encoding an MP4 atom failed. #[error("mp4: {0}")] Mp4(#[source] std::sync::Arc), /// A MoQ transport operation failed. #[error("moq: {0}")] Moq(#[from] moq_net::Error), /// Parsing the FLAC configuration failed. #[error("flac: {0}")] Flac(#[from] crate::codec::flac::Error), /// Parsing or encoding the Opus configuration failed. #[error("opus: {0}")] Opus(#[from] crate::codec::opus::Error), /// A group was opened without a keyframe. #[error("missing keyframe: a group must open on a keyframe")] MissingKeyframe(#[from] crate::container::MissingKeyframe), /// An explicit video endpoint precedes its last frame. #[error("{0}")] InvalidEnd(#[from] crate::container::InvalidEnd), /// A frame's timestamp sits below the live edge earlier groups reached. #[error("{0}")] TimestampRewind(#[from] crate::container::TimestampRewind), /// A timestamp calculation overflowed. #[error("timestamp overflow")] TimestampOverflow(#[from] moq_net::TimeOverflow), /// The fragment has no traf box. #[error("no traf in moof")] NoTraf, /// The track fragment has no tfdt box. #[error("no tfdt in traf")] NoTfdt, /// The presentation timestamp calculation overflowed. #[error("PTS overflow")] PtsOverflow, /// The fragment has no moof box. #[error("missing moof")] NoMoof, /// The fragment has no mdat box. #[error("missing mdat")] NoMdat, /// The initialization segment has no moov box. #[error("missing moov")] NoMoov, /// The moov box has no tracks. #[error("no tracks in moov")] NoTracks, /// The moov box has multiple tracks where only one is supported. #[error("multiple tracks in moov, use Trak instead")] MultipleTracks, /// The named codec cannot supply a synthesized CMAF initialization segment. #[error("can't synthesize CMAF init for {0}")] UnsupportedSynthesis(String), /// The track handler declares unsupported subtitle media. #[error("subtitle tracks are not supported")] UnsupportedSubtitle, /// The track handler has an unrecognized four-character code. #[error("unknown track handler: {0:?}")] UnknownTrackHandler([u8; 4]), /// The sample description has no codec entry. #[error("missing codec")] MissingCodec, /// The sample description has multiple codec entries. #[error("multiple codecs")] MultipleCodecs, /// The sample entry has an unrecognized codec, named by its four-character code. #[error("unknown codec: {0}")] UnknownCodec(String), /// A `colr` box code point past H.273's 255. #[error("invalid colr code point: {0}")] InvalidColr(u16), /// A Spherical Video V2 `sv3d` or `st3d` box the catalog cannot describe, or a malformed one. #[error("unsupported spherical video: {0}")] UnsupportedSpatial(&'static str), /// The sample entry declares a codec moq-mux does not carry, named by its four-character code. #[error("unsupported codec: {0}")] UnsupportedCodec(String), /// The sample entry declares unsupported MPEG-2 media. #[error("unsupported codec: MPEG2")] UnsupportedMpeg2, /// An AAC sample entry needs DecoderSpecificInfo to identify its codec profile. #[error("AAC sample entry missing DecoderSpecificInfo")] MissingDecoderSpecific, /// A second moof box arrived before the preceding fragment was complete. #[error("duplicate moof")] DuplicateMoof, /// A second moov would re-declare the track set the first one already declared. #[error("duplicate moov")] DuplicateMoov, /// The track fragment has no trun box. #[error("missing trun")] MissingTrun, /// The track fragment has no decode-time box. #[error("missing tfdt")] MissingTfdt, /// The named video codec lacks the configuration needed to synthesize a CMAF init. #[error("video codec {0} needs a description (codec config record) to synthesize a CMAF init")] MissingVideoDescription(String), /// A synthesized video track has no usable encoded dimensions. #[error("missing video dimensions for codec: {0}")] MissingVideoDimensions(String), /// The fragment data offset cannot address its sample data. #[error("invalid data offset")] InvalidDataOffset, /// Streaming import requires each track's sample bytes in decode order. #[error("backwards per-track data offset is unsupported for streaming import")] BackwardsDataOffset, /// A metadata body over 2 MiB is refused before parsing. #[error("{kind} declares {size} bytes, more than the {MAX_METADATA_BYTES} a metadata parser accepts")] MetadataTooLarge { /// The box type's four-character code. kind: String, /// The body size its header declares. size: usize, }, /// A text sample is rewritten whole, so one larger than moq-net's 32 MiB frame bound /// is refused before any of its bytes /// are staged. #[error("text sample of {0} bytes is more than the {MAX_HELD_BYTES} an importer holds")] TextSampleTooLarge(usize), /// A fragment declaring more than 131,072 samples, or more than one sample per byte /// of its metadata past a small base, is refused before parsing. A `trun` without per-sample /// fields declares its count in four bytes, so the byte bound alone does not limit it. #[error("moof declares {0} samples, more than a fragment of its size accepts")] TooManySamples(u64), /// A `moov` declaring more than 256 tracks is refused before any is created. #[error("moov declares {0} tracks, more than the {MAX_TRACKS} an importer accepts")] TooManyTracks(usize), /// Absolute file offsets cannot be resolved in a standalone fragment. #[error("absolute base_data_offset is unsupported; use moof-relative offsets")] UnsupportedBaseDataOffset, /// Every media sample must contain at least one byte. #[error("empty media sample")] EmptySample, /// The frame timestamp carries a fragment's earliest presentation time exactly only when the /// track counts in the same ticks as the media. #[error("track timescale {track:?} doesn't match the CMAF mdhd timescale {mdhd:?}")] TimescaleMismatch { /// The timescale declared by the MoQ track, if any. track: Option, /// The media timescale declared by the mdhd box. mdhd: moq_net::Timescale, }, /// The fragment references an undeclared track ID. #[error("unknown track {0}")] UnknownTrack(u32), /// The first sample in the group is not a keyframe. #[error("no keyframe at start of group")] NoKeyframe, /// The sample byte range extends outside the mdat payload. #[error("track sample range {start}..{end} is out of bounds of mdat (len {len})")] SampleRangeOutOfBounds { /// The first sample byte offset in the mdat payload. start: usize, /// The exclusive end offset in the mdat payload. end: usize, /// The mdat payload length in bytes. len: usize, }, /// Fragment encoding was requested with no frames. #[error("encode_fragment called with no frames")] NoFrames, /// The named audio codec lacks the configuration needed to synthesize a CMAF init. #[error("audio codec {0} needs a description (AudioSpecificConfig) to synthesize a CMAF init")] MissingAudioDescription(String), /// An Opus catalog entry whose OpusHead contradicts its channel count. #[error("Opus head has {head} channels but the catalog declares {catalog}")] OpusChannelCount { /// The channel count declared by the catalog. catalog: u32, /// The channel count declared by the OpusHead. head: u32, }, /// A non-final sample has no duration, so its decode timeline cannot be recovered. #[error("multi-sample fragment has a non-final sample with no duration; DTS is unrecoverable")] MissingSampleDuration, /// `mdhd.timescale` is a 32-bit field, so a larger scale would reach the init segment /// truncated while the fragments kept the full value, putting them on different timelines. #[error("timescale {0} does not fit the 32-bit mdhd field")] TimescaleTooLarge(u64), /// A `Cmaf` rendition's init passes through from the catalog at its own scale, so /// [`Muxer::with_timescale`] can't move it without desynchronising it from the fragments. #[error("a CMAF rendition's timescale comes from its init segment and can't be overridden")] TimescaleOverride, /// A sample duration is a 32-bit `trun` field. A larger value would wrap in the media /// while the fragment metadata kept the full duration, putting them on different timelines. #[error("sample duration {0} does not fit the 32-bit trun field")] SampleDurationTooLarge(u64), /// A positive sample duration must occupy at least one tick in the output timescale. #[error("sample duration is shorter than one tick at timescale {0}")] SampleDurationTooSmall(u64), /// Repeatedly flooring fractional sample ticks would make the decode timeline drift. #[error("sample duration is not exactly representable at timescale {0}")] SampleDurationInexact(u64), /// Presentation timestamps do not reveal decode duration for reordered video. #[error("duration-less video needs stated durations or presentation-ordered inference")] MissingVideoDuration, /// Each fragment restates its decode time, so a stale one lands two different samples on /// the same timestamp. ffmpeg writes one when `frag_every_frame` interleaves audio and /// video; `-frag_duration` cuts just as finely and stamps the fragments correctly. #[error( "track {track}: fragment decode time {decode_time:?} does not advance past {previous:?}; \ ffmpeg repeats a tfdt when frag_every_frame interleaves audio and video, use -frag_duration instead" )] NonMonotonicDecodeTime { /// The track containing the rejected fragment. track: u32, /// The rejected fragment's decode time in the track's timescale. decode_time: moq_net::Timestamp, /// The preceding fragment's decode time in the track's timescale. previous: moq_net::Timestamp, }, /// The init segment fixes the track set, so a rendition that joins later can't be written, /// unless it continues a declared track of its medium that failed. #[error("rendition {0} joined after the init segment; restart the export to include it")] TrackAdded(String), /// A rendition's sample entry no longer matches the one the init segment declared. #[error("rendition {0} changed its codec configuration after it was declared")] TrackChanged(String), /// A rendition restarted at or before media already written for it, such as a /// resubscription replaying cached groups. #[error("rendition {track} went back in time: a fragment starts at {start:?}, after {written:?} was written")] TrackRewound { /// The rendition name. track: String, /// The rejected fragment's presentation time. start: std::time::Duration, /// The latest presentation time already written for the rendition. written: std::time::Duration, }, /// The init segment waited too long, or the broadcast ended, before these renditions /// delivered the codec configuration their track needs. #[error("renditions {0:?} never delivered their codec configuration")] TrackUndescribed(Vec), /// A track's edit list does more than delay the track and start its media at one time. #[error("unsupported edit list: {0}")] UnsupportedEditList(&'static str), /// A fragment written to a regular MP4 can't be indexed in its final `moov`. #[error("track {track} can't be indexed: {reason}")] Unindexable { /// The fragment's track id. track: u32, /// What the sample tables can't express. reason: &'static str, }, /// A regular MP4's chapter list holds 255 chapters. #[error("{0} chapters, more than the 255 a chapter list holds")] TooManyChapters(usize), /// A regular MP4's chapter list holds titles of 255 bytes. #[error("a chapter title of {0} bytes, more than the 255 a chapter list holds")] ChapterTitleTooLong(usize), /// A file to repair is not a recording that an MP4 export left unfinished. #[error("not an unfinished mp4 recording: {0}")] Unrepairable(&'static str), } impl Error { /// An mp4 atom error, kept opaque so an mp4-atom bump is no moq-mux break. pub(crate) fn mp4(err: mp4_atom::Error) -> Self { Error::Mp4(std::sync::Arc::new(err)) } /// A sample entry this crate does not carry, named by the four-character code it encodes with. pub(crate) fn unsupported_codec(codec: &mp4_atom::Codec) -> Self { use mp4_atom::Encode; let mut buf = Vec::new(); let name = match codec.encode(&mut buf) { Ok(()) if buf.len() >= 8 => String::from_utf8_lossy(&buf[4..8]).into_owned(), _ => "?".to_string(), }; Error::UnsupportedCodec(name) } } /// A result using this module's error type. pub type Result = std::result::Result; /// The media carried by a CMAF track. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum Kind { Audio, Video, } impl Kind { fn from_handler(handler: mp4_atom::FourCC) -> Result { match handler.as_ref() { b"soun" => Ok(Self::Audio), b"vide" => Ok(Self::Video), b"sbtl" => Err(Error::UnsupportedSubtitle), _ => Err(Error::UnknownTrackHandler(handler.into())), } } /// The publisher priority for this kind of media. fn priority(self) -> i8 { match self { Self::Video => hang::catalog::PRIORITY.video, Self::Audio => hang::catalog::PRIORITY.audio, } } } /// CMAF container: encodes/decodes a single track's moof+mdat fragments. /// /// Build from a CMAF init segment with [`Wire::from_init`], which refuses a track that is /// neither audio nor video. /// /// The parsed track is heap-allocated so that embedding `Wire` /// in other enums (e.g. [`catalog::hang::Container`](crate::catalog::hang::Container)) /// doesn't bloat unrelated variants. pub struct Wire { trak: Box, defaults: sample::Defaults, kind: Kind, } impl Wire { /// Wrap an already-parsed track, with no `trex` for its samples to fall back to. #[cfg(test)] pub(crate) fn new(trak: mp4_atom::Trak) -> Result { Ok(Self { kind: Kind::from_handler(trak.mdia.hdlr.handler)?, trak: Box::new(trak), defaults: sample::Defaults::default(), }) } /// Parse a CMAF init segment (ftyp+moov), extracting the single track and its `trex` defaults. pub fn from_init(init_data: &[u8]) -> Result { metadata::check(init_data)?; use mp4_atom::DecodeMaybe; let mut cursor = std::io::Cursor::new(init_data); while let Some(atom) = mp4_atom::Any::decode_maybe(&mut cursor).map_err(crate::container::fmp4::Error::mp4)? { if let mp4_atom::Any::Moov(mut moov) = atom { let trak = match moov.trak.len() { 1 => moov.trak.remove(0), 0 => return Err(Error::NoTracks), _ => return Err(Error::MultipleTracks), }; let defaults = sample::Defaults::from_moov(&moov, trak.tkhd.track_id); return Ok(Self { kind: Kind::from_handler(trak.mdia.hdlr.handler)?, trak: Box::new(trak), defaults, }); } } Err(Error::NoMoov) } /// Borrow the MP4 track atom describing this wire container. #[cfg(test)] pub(crate) fn trak(&self) -> &mp4_atom::Trak { &self.trak } /// The media timescale, which a CMAF track must count in. pub(crate) fn timescale(&self) -> Result { Ok(moq_net::Timescale::new(self.trak.mdia.mdhd.timescale as u64)?) } /// What decoding this track's fragments needs. fn track(&self) -> Result { Ok(Track { timescale: self.timescale()?, kind: self.kind, defaults: self.defaults, }) } } impl Container for Wire { fn kind(&self) -> crate::container::Kind { match self.kind { Kind::Audio => crate::container::Kind::Audio, Kind::Video => crate::container::Kind::Video, } } type Error = Error; fn write(&self, group: &mut moq_net::group::Producer, frames: &[Frame]) -> std::result::Result<(), Self::Error> { let timescale = self.timescale()?; if group.timescale() != Some(timescale) { return Err(Error::TimescaleMismatch { track: group.timescale(), mdhd: timescale, }); } let track_id = self.trak.tkhd.track_id; encode( group, frames, FragmentInfo { timescale, track_id, sequence_number: group.frame_count() as u32, kind: self.kind, }, ) } fn decode(&self, frame: moq_net::frame::Frame) -> std::result::Result, Self::Error> { // CMAF carries no data track, so an object with no bytes is no marker and fails to decode. // A scale-less track's unscaled key is no broadcast time, so its samples keep their `tfdt`. let timestamp = frame.timestamp.scale().map(|_| frame.timestamp); decode(frame.payload, timestamp, self.track()?) } } /// What decoding a track's fragments needs from its init segment. #[derive(Debug, Clone, Copy)] pub(crate) struct Track { /// The `mdhd` timescale the samples count in. pub timescale: moq_net::Timescale, /// Whether the samples are audio or video. pub kind: Kind, /// The `trex` values a sample falls back to. pub defaults: sample::Defaults, } #[cfg(test)] impl Track { /// A track whose fragments carry every sample value, as `encode` writes them. pub fn new(timescale: moq_net::Timescale, kind: Kind) -> Self { Self { timescale, kind, defaults: Default::default(), } } } /// Decode one moof+mdat fragment into its samples. /// /// Each sample's size, duration, and flags resolve through [`sample::Defaults`], and a video /// sample is a keyframe when [`sample::Sample::is_sync`]. /// /// `Kind::Audio` says the track's samples are all independently decodable. Packagers flag every /// audio sample a sync sample, which as a [`Frame::keyframe`] would open a group per sample, /// so an audio sample decodes with the bit clear and the consumer marks the group start. /// /// `timestamp` is the moq-lite frame timestamp, which is the broadcast timeline: the fragment's /// earliest sample presents at it. `tfdt` and the `trun` offsets only place the samples relative /// to each other, since a publisher may move a passthrough track to another timeline without /// rewriting the payload. A scale-less track's frame (`None`) has no broadcast time, so its samples /// present at the time `tfdt` gives them. pub(crate) fn decode(data: Bytes, timestamp: Option, track: Track) -> Result> { metadata::check(&data)?; use mp4_atom::DecodeMaybe; let Track { timescale, kind, defaults, } = track; // A slice cursor like the other fMP4 decodes: mp4-atom's `Any` decoder is large and compiles // once per reader type. let mut cursor = std::io::Cursor::new(data.as_ref()); let mut moof = None; let mut mdat = None; loop { let start = cursor.position() as usize; let Some(atom) = mp4_atom::Any::decode_maybe(&mut cursor).map_err(crate::container::fmp4::Error::mp4)? else { break; }; match atom { mp4_atom::Any::Moof(m) => moof = Some((start, m)), mp4_atom::Any::Mdat(m) => mdat = Some((cursor.position() as usize - m.data.len(), m.data)), _ => {} } } let (moof_start, moof) = moof.ok_or(Error::NoMoof)?; let (mdat_start, mdat_data) = mdat.ok_or(Error::NoMdat)?; let traf = moof.traf.first().ok_or(Error::NoTraf)?; let data_start = mdat_start.checked_sub(moof_start).ok_or(Error::InvalidDataOffset)?; let tfdt = traf.tfdt.as_ref().ok_or(Error::NoTfdt)?; let base_dts = tfdt.base_media_decode_time; let mut resolver = sample::Resolver::new(data_start, mdat_data.len()); // Rounded the way `encode` stamps it, so a timestamp the track carried at another scale // lands back on the tick it was written at. let anchor = timestamp.map(|t| timestamp_ticks(t, timescale)).transpose()?; let mut frames = Vec::new(); let mut ptss = Vec::new(); let mut dts = i128::from(base_dts); for resolved in resolver.resolve(traf, defaults)? { let sample::Resolved { sample, cts, range } = resolved?; ptss.push(dts + i128::from(cts)); let payload = Bytes::copy_from_slice(&mdat_data[range]); let keyframe = kind == Kind::Video && sample.is_sync(); let duration = sample .duration .map(|d| Timestamp::new(d as u64, timescale)) .transpose()?; frames.push(Frame { // Placeholder until the earliest PTS is known. timestamp: Timestamp::ZERO, payload, keyframe, duration, }); dts += i128::from(sample.duration.unwrap_or(0)); } let (anchor, earliest) = match anchor { Some(anchor) => (anchor, ptss.iter().copied().min().unwrap_or_default()), None => (0, 0), }; for (frame, pts) in frames.iter_mut().zip(ptss) { let ticks = u64::try_from(pts - earliest) .ok() .and_then(|offset| anchor.checked_add(offset)) .ok_or(Error::PtsOverflow)?; // Preserve the fmp4 track's native scale through the pipeline. frame.timestamp = Timestamp::new(ticks, timescale)?; } Ok(frames) } fn encode(group: &mut moq_net::group::Producer, frames: &[Frame], info: FragmentInfo) -> Result<()> { // The fragment may carry several samples; the net frame's timestamp is the // fragment's earliest presentation time, which `decode` anchors its samples to. // It is rounded to the track's ticks the same way the samples are, so the two agree. let Some(earliest) = frames .iter() .map(|f| f.timestamp) .reduce(|earliest, timestamp| if timestamp < earliest { timestamp } else { earliest }) else { return Ok(()); }; let timestamp = Timestamp::new(timestamp_ticks(earliest, info.timescale)?, info.timescale)?; let bytes = encode_fragment(info, frames)?; group.write_frame(timestamp, bytes)?; Ok(()) } /// Which track a fragment belongs to, and where it sits in that track. /// /// Bundled rather than passed positionally because `track_id` and `sequence_number` are both /// `u32`, so a swapped pair would still compile. #[derive(Debug, Clone, Copy)] pub(crate) struct FragmentInfo { /// The `tfhd` track id, which must match the one the init segment declares. pub track_id: u32, /// The track's media timescale, which every timestamp is re-expressed at. pub timescale: moq_net::Timescale, /// The `mfhd` sequence number, informative only. pub sequence_number: u32, /// Audio tracks carry only sync samples: the [`Frame::keyframe`] /// bit only marks the group start there, so it must not decide the sample flags. pub kind: Kind, } /// Encode a single-traf moof+mdat fragment anchored at its own first frame. /// /// The fragment stands alone: its `tfdt` is `frames[0]`'s presentation time, so it decodes /// without reference to whatever came before it. /// /// Returns an empty `Bytes` when `frames` is empty. pub(crate) fn encode_fragment(info: FragmentInfo, frames: &[Frame]) -> Result { let Some(first) = frames.first() else { return Ok(Bytes::new()); }; Ok(encode_at(info, base_ticks(first, info.timescale)?, frames)?.0) } /// A frame's presentation time as a tick count at the track's timescale. /// /// When the importer preserved the source scale (the common passthrough case) this is a no-op; /// otherwise it's a single rescale rather than the legacy `micros * scale / 1_000_000` /// round-trip. fn base_ticks(frame: &Frame, timescale: moq_net::Timescale) -> Result { timestamp_ticks(frame.timestamp, timescale) } /// Round an absolute timestamp to its nearest tick at the output scale. Refuses an /// [unscaled](Timestamp::unscaled) one, which has no time. fn timestamp_ticks(timestamp: Timestamp, timescale: moq_net::Timescale) -> Result { let source_scale = u128::from(timestamp.scale().ok_or(moq_net::TimeOverflow)?.as_u64()); let scaled = u128::from(timestamp.value()) * u128::from(timescale.as_u64()); let ticks = (scaled + source_scale / 2) / source_scale; u64::try_from(ticks).map_err(|_| Error::PtsOverflow) } /// Encode a single-traf moof+mdat fragment whose decode timeline starts at `base_dts` ticks. /// /// Performs the two-pass encoding required by ISO/IEC 14496-12: encode once /// to learn the moof size, then again with `trun.data_offset` pointing past /// the moof and mdat header. /// /// `base_dts` is already at the track's timescale, so it is the same unit the `trun` sample /// durations are written in. That's what lets [`Export`] carry a timeline across /// calls without a rounding step between them. /// /// Frames arrive in decode order carrying presentation timestamps. DTS is authored by /// accumulating sample durations from `base_dts`, and each sample stores `PTS - DTS` as its /// signed composition offset, so a reordered frame keeps its presentation time even when the /// fragment holds a single sample. /// /// Returns the fragment with the decode time it ends at, which is where the next fragment on /// the same timeline continues, or an empty `Bytes` and `base_dts` when `frames` is empty. pub(super) fn encode_at(info: FragmentInfo, base_dts: u64, frames: &[Frame]) -> Result<(Bytes, u64)> { let FragmentInfo { track_id, timescale, sequence_number, kind, } = info; use mp4_atom::Encode; if frames.is_empty() { return Ok((Bytes::new(), base_dts)); } let mut dts = base_dts; let entries: Vec<_> = frames .iter() .map(|f| { let flags = if kind == Kind::Audio || f.keyframe { 0x0200_0000 } else { 0x0001_0000 }; // Write the sample-duration back at the track's scale when we know it, so // fMP4 -> fMP4 round-trips it. Frames without one stay byte-identical. let duration = f.duration.map(|d| trun_duration(d, timescale)).transpose()?; let pts = i128::from(timestamp_ticks(f.timestamp, timescale)?); let cts = pts - i128::from(dts); let cts = i32::try_from(cts).map_err(|_| Error::PtsOverflow)?; // Frame timestamps are PTS while sample order is decode order. Author DTS // by accumulating durations and store PTS-DTS as the signed CTS. if let Some(duration) = duration { dts = dts.checked_add(u64::from(duration)).ok_or(Error::PtsOverflow)?; } Ok(mp4_atom::TrunEntry { duration, size: Some(f.payload.len() as u32), flags: Some(flags), cts: (cts != 0).then_some(cts.into()), }) }) .collect::>()?; let mdat_data: Vec = frames.iter().flat_map(|f| f.payload.iter().copied()).collect(); let build_moof = |data_offset| mp4_atom::Moof { mfhd: mp4_atom::Mfhd { sequence_number }, traf: vec![mp4_atom::Traf { tfhd: mp4_atom::Tfhd { track_id, ..Default::default() }, tfdt: Some(mp4_atom::Tfdt { base_media_decode_time: base_dts, }), trun: vec![mp4_atom::Trun { data_offset: Some(data_offset), samples: entries.clone().into(), }], ..Default::default() }], }; // First pass to learn the moof size. let mut buf = Vec::new(); build_moof(0) .encode(&mut buf) .map_err(crate::container::fmp4::Error::mp4)?; let moof_size = buf.len(); // Second pass with data_offset = moof_size + 8 (mdat header). buf.clear(); build_moof((moof_size + 8) as i32) .encode(&mut buf) .map_err(crate::container::fmp4::Error::mp4)?; let mdat = mp4_atom::Mdat { data: mdat_data }; mdat.encode(&mut buf).map_err(crate::container::fmp4::Error::mp4)?; Ok((Bytes::from(buf), dts)) } /// Convert a duration to the exact value stored in a 32-bit `trun` sample-duration field. fn trun_duration(duration: Timestamp, timescale: moq_net::Timescale) -> Result { let source_timescale = duration.scale().ok_or(moq_net::TimeOverflow)?.as_u64(); let output_timescale = timescale.as_u64(); let scaled = u128::from(duration.value()) * u128::from(output_timescale); let ticks = scaled / u128::from(source_timescale); if !duration.is_zero() && ticks == 0 { return Err(Error::SampleDurationTooSmall(timescale.as_u64())); } if scaled % u128::from(source_timescale) != 0 { return Err(Error::SampleDurationInexact(output_timescale)); } u32::try_from(ticks).map_err(|_| Error::SampleDurationTooLarge(u64::try_from(ticks).unwrap_or(u64::MAX))) } /// Synthesize a CMAF `Trak` for a video rendition that has no init segment. /// /// Used by the fMP4 exporter when its source is a `Container::Legacy` or `Loc` /// track. H.264/H.265 need a configuration record (`description`). When the /// catalog codec string determined that record, it lists no parameter sets and /// the sample entry is avc3 or hev1; the sets stay in the samples. A record built /// from the bitstream still carries them. VP8 carries no out-of-band config, so /// `description` is `None` for it. /// The colour an ISOBMFF `colr` box signals. `nclx` carries H.273 code points and a range, /// QuickTime's `nclc` the code points alone, and an ICC profile none at all. A code point past 255 /// has no H.273 meaning, so it is refused. pub(crate) fn colr_color(colr: &mp4_atom::Colr) -> Result> { let (primaries, transfer, matrix, full_range) = match *colr { mp4_atom::Colr::Nclx { colour_primaries, transfer_characteristics, matrix_coefficients, full_range_flag, } => ( colour_primaries, transfer_characteristics, matrix_coefficients, Some(full_range_flag), ), mp4_atom::Colr::Nclc { colour_primaries, transfer_characteristics, matrix_coefficients, } => (colour_primaries, transfer_characteristics, matrix_coefficients, None), _ => return Ok(None), }; let code = |value: u16| u8::try_from(value).map_err(|_| Error::InvalidColr(value)); Ok(crate::codec::color::cicp( code(primaries)?, code(transfer)?, code(matrix)?, full_range, )) } /// The projection and stereo packing Spherical Video V2's `sv3d` and `st3d` boxes signal, each /// `None` for flat or mono video. Apple's `vexu` and `hfov` are not read. /// /// The catalog has no cubemap, mesh, pose, or eye order beyond left-right and top-bottom, and an /// absent field claims flat, mono video, so those are refused rather than dropped. So is a box the /// sample entry repeats or could not decode, since it may say any of them. pub(crate) fn spatial( spatial: Option<&mp4_atom::Spatial>, ) -> Result<(Option, Option)> { use mp4_atom::{Atom, Cbmp, Equi, Mshp, Prhd, Proj, ProjKind, St3d, Sv3d}; let Some(spatial) = spatial else { return Ok((None, None)); }; let unsupported = |reason| Err(Error::UnsupportedSpatial(reason)); let kept = |unknown: &[mp4_atom::Any], kinds: &[mp4_atom::FourCC]| unknown.iter().any(|atom| kinds.contains(&atom.kind())); if kept(&spatial.unknown, &[St3d::KIND, Sv3d::KIND]) { return unsupported("repeated or malformed st3d or sv3d"); } let stereo = match spatial.st3d.map(|st3d| st3d.stereo_mode) { None | Some(St3d::MONO) => None, Some(St3d::LEFT_RIGHT) => Some(hang::catalog::Stereo::LeftRight), Some(St3d::TOP_BOTTOM) => Some(hang::catalog::Stereo::TopBottom), Some(_) => return unsupported("stereo mode"), }; let Some(sv3d) = &spatial.sv3d else { return Ok((None, stereo)); }; if kept(&sv3d.unknown, &[Proj::KIND]) { return unsupported("repeated or malformed proj"); } let proj = sv3d .proj .as_ref() .ok_or(Error::UnsupportedSpatial("sv3d without proj"))?; if kept(&proj.unknown, &[Prhd::KIND, Equi::KIND, Cbmp::KIND, Mshp::KIND]) { return unsupported("repeated or malformed projection"); } if let Some(prhd) = proj.prhd && (prhd.pose_yaw_degrees, prhd.pose_pitch_degrees, prhd.pose_roll_degrees) != (0, 0, 0) { return unsupported("nonzero pose"); } let projection = match &proj.kind { Some(ProjKind::Equi(equi)) => crate::codec::spatial::equirectangular( equi.projection_bounds_top, equi.projection_bounds_bottom, equi.projection_bounds_left, equi.projection_bounds_right, ) .map_err(Error::UnsupportedSpatial)?, Some(ProjKind::Cbmp(_)) => return unsupported("cubemap projection"), Some(ProjKind::Mshp(_)) => return unsupported("mesh projection"), _ => return unsupported("unknown projection"), }; Ok((Some(projection), stereo)) } /// The `nclx` box for a catalog colour, or `None` when it has no code point or range to carry. /// An absent code point is written as unspecified (2) and an absent range as limited. fn color_colr(color: Option<&hang::catalog::Color>) -> Option { let color = color?; if color.primaries.is_none() && color.transfer.is_none() && color.matrix.is_none() && color.range.is_none() { return None; } Some(mp4_atom::Colr::Nclx { colour_primaries: color.primaries.unwrap_or(2).into(), transfer_characteristics: color.transfer.unwrap_or(2).into(), matrix_coefficients: color.matrix.unwrap_or(2).into(), full_range_flag: color.range == Some(hang::catalog::ColorRange::Full), }) } /// Write the catalog colour into a `vpcC`, so it never contradicts the `colr` box written beside /// it. A VP9 codec string may carry a container's placeholder BT.709, so once the catalog knows any /// colour, the fields it leaves out are written unspecified (2) rather than kept. fn vpcc_color(mut vpcc: mp4_atom::VpcC, color: Option<&hang::catalog::Color>) -> mp4_atom::VpcC { let Some(color) = color else { return vpcc; }; vpcc.color_primaries = color.primaries.unwrap_or(2); vpcc.transfer_characteristics = color.transfer.unwrap_or(2); vpcc.matrix_coefficients = color.matrix.unwrap_or(2); vpcc.video_full_range_flag = color.range == Some(hang::catalog::ColorRange::Full); vpcc } pub(crate) fn synthesize_video_trak( track_id: u32, timescale: u64, config: &VideoConfig, description: Option<&[u8]>, ) -> Result { if !matches!( config.codec, VideoCodec::H264(_) | VideoCodec::H265(_) | VideoCodec::AV1(_) | VideoCodec::VP8 | VideoCodec::VP9(_) ) { return Err(Error::UnsupportedSynthesis(format!("video codec {:?}", config.codec))); } let width = u16::try_from( config .coded_width .ok_or_else(|| Error::MissingVideoDimensions(config.codec.to_string()))?, ) .map_err(|_| Error::MissingVideoDimensions(config.codec.to_string()))?; let height = u16::try_from( config .coded_height .ok_or_else(|| Error::MissingVideoDimensions(config.codec.to_string()))?, ) .map_err(|_| Error::MissingVideoDimensions(config.codec.to_string()))?; if width == 0 || height == 0 { return Err(Error::MissingVideoDimensions(config.codec.to_string())); } let visual = mp4_atom::Visual { data_reference_index: 1, width, height, ..Default::default() }; // Codecs that carry an out-of-band config record require `description`. let require_description = || description.ok_or_else(|| Error::MissingVideoDescription(config.codec.to_string())); let colr = color_colr(config.color.as_ref()).into_iter().collect(); let sample_entry = match &config.codec { VideoCodec::H264(h264) => { let mut cursor = std::io::Cursor::new(require_description()?); let avcc = mp4_atom::Avcc::decode_body(&mut cursor).map_err(Error::mp4)?; // avc3 when the samples may still carry parameter sets: a catalog record // passes the samples through as they are, and empty lists are the in-band // entry. A record built from the first keyframe strips them from the // samples, so it stays avc1. let catalog_record = config.description.as_ref().is_some_and(|d| !d.is_empty()); let empty = avcc.sequence_parameter_sets.is_empty() && avcc.picture_parameter_sets.is_empty(); if h264.inline && (catalog_record || empty) { mp4_atom::Codec::from(mp4_atom::Avc3 { visual, avcc, colr, ..Default::default() }) } else { mp4_atom::Codec::from(mp4_atom::Avc1 { visual, avcc, colr, ..Default::default() }) } } VideoCodec::H265(h265) => { let mut cursor = std::io::Cursor::new(require_description()?); let hvcc = mp4_atom::Hvcc::decode_body(&mut cursor).map_err(Error::mp4)?; // `in_band` (catalog) ↔ hev1 sample entry; otherwise hvc1. if h265.in_band { mp4_atom::Codec::from(mp4_atom::Hev1 { visual, hvcc, colr, ..Default::default() }) } else { mp4_atom::Codec::from(mp4_atom::Hvc1 { visual, hvcc, colr, ..Default::default() }) } } VideoCodec::AV1(av1) => mp4_atom::Codec::from(mp4_atom::Av01 { visual, av1c: crate::codec::av1::av1c_from_av1(av1), colr, ..Default::default() }), VideoCodec::VP8 => mp4_atom::Codec::from(mp4_atom::Vp08 { visual, vpcc: vpcc_color(crate::codec::vp8::vpcc(), config.color.as_ref()), colr, ..Default::default() }), VideoCodec::VP9(vp9) => mp4_atom::Codec::from(mp4_atom::Vp09 { visual, vpcc: vpcc_color(crate::codec::vp9::vpcc(vp9), config.color.as_ref()), colr, ..Default::default() }), other => unreachable!("unsupported codecs rejected before geometry synthesis: {other:?}"), }; Ok(build_video_trak( track_id, mdhd_timescale(timescale)?, sample_entry, width, height, )) } /// The OpusHead mapping for a `dOps` channel mapping table, checked by [`crate::codec::opus::Mapping::new`]. /// /// Family 3 is refused: its OpusHead carries a demixing matrix (RFC 8486 §3.2) where /// `dOps` has a table, so neither side can describe the other. pub(crate) fn opus_mapping(mapping: &mp4_atom::OpusChannelMapping) -> Result { if mapping.family == 3 { return Err(crate::codec::opus::Error::UnsupportedMappingFamily(3).into()); } Ok(crate::codec::opus::Mapping::new(crate::codec::opus::mapping::Config { family: mapping.family, streams: mapping.stream_count, coupled: mapping.coupled_count, table: &mapping.channel_mapping, })?) } /// The `dOps` channel mapping table for an OpusHead mapping, refusing family 3 as /// [`opus_mapping`] does. fn dops_mapping(mapping: &crate::codec::opus::Mapping) -> Result { if mapping.family() == 3 { return Err(crate::codec::opus::Error::UnsupportedMappingFamily(3).into()); } Ok(mp4_atom::OpusChannelMapping { family: mapping.family(), stream_count: mapping.streams(), coupled_count: mapping.coupled(), channel_mapping: mapping.table().to_vec(), }) } /// Synthesize a CMAF `Trak` for an audio rendition that has no init segment. pub(crate) fn synthesize_audio_trak(track_id: u32, timescale: u64, config: &AudioConfig) -> Result { use mp4_atom::Decode; let audio = mp4_atom::Audio { data_reference_index: 1, channel_count: config.channel_count as u16, sample_size: 16, sample_rate: mp4_atom::FixedPoint::from(config.sample_rate as u16), }; let sample_entry = match &config.codec { AudioCodec::Opus => { let head = match &config.description { Some(description) => { let head = crate::codec::opus::Config::parse(&mut description.as_ref())?; if head.channel_count != config.channel_count { return Err(Error::OpusChannelCount { catalog: config.channel_count, head: head.channel_count, }); } head } None => crate::codec::opus::Config::new(config.sample_rate, config.channel_count), }; mp4_atom::Codec::from(mp4_atom::Opus { audio, dops: mp4_atom::Dops { output_channel_count: config.channel_count as u8, pre_skip: head.pre_skip, input_sample_rate: head.sample_rate, output_gain: head.output_gain, channel_mapping: head.mapping.as_ref().map(dops_mapping).transpose()?, }, btrt: None, }) } AudioCodec::AAC(_) => { // The catalog `description` is the AudioSpecificConfig (set by the TS // importer via aac::Config::encode, or carried over from a CMAF source). // mp4_atom models the esds DecoderSpecific as the parsed // AudioSpecificConfig, so decode the blob back into that shape. let description = config .description .as_ref() .ok_or_else(|| Error::MissingAudioDescription(config.codec.to_string()))?; let mut cursor = std::io::Cursor::new(description.as_ref()); let dec_specific = mp4_atom::esds::DecoderSpecific::decode(&mut cursor).map_err(crate::container::fmp4::Error::mp4)?; // Safari and AVFoundation reject an AAC track whose DecoderConfigDescriptor is all // zeros: they endOfStream("decode") on the *init* append, which leaves the // ManagedMediaSource ended and every later audio and video append failing. The // catalog bitrate is optional and real publishers omit it, so fall back to the // AAC-LC values ffmpeg and the iTunes encoders write. A zero or wider-than-u32 // bitrate takes the fallback as well, since writing it back would rebuild the // all-zero descriptor this exists to avoid. let bitrate = config.bitrate.and_then(|b| u32::try_from(b).ok()).filter(|b| *b > 0); let (max_bitrate, avg_bitrate) = match bitrate { Some(bitrate) => (bitrate, bitrate), None => (256_000, 128_000), }; mp4_atom::Codec::from(mp4_atom::Mp4a { audio, esds: mp4_atom::Esds { es_desc: mp4_atom::esds::EsDescriptor { // ISO/IEC 14496-14 §5.6: ES_ID is 0 in an MP4 file (the track id carries identity). es_id: 0, dec_config: mp4_atom::esds::DecoderConfig { object_type_indication: 0x40, // MPEG-4 AAC stream_type: 0x05, // audio up_stream: 0, // 24 KiB, the decoder buffer those same encoders declare. buffer_size_db: mp4_atom::u24::from([0x00, 0x60, 0x00]), max_bitrate, avg_bitrate, dec_specific: Some(dec_specific), }, ..Default::default() }, }, btrt: None, taic: None, }) } AudioCodec::Flac => { // The catalog `description` is the FLAC header (`fLaC` marker + STREAMINFO). // Parse it back into the STREAMINFO fields the `dfLa` box stores. let description = config .description .as_ref() .ok_or_else(|| Error::MissingAudioDescription(config.codec.to_string()))?; let info = crate::codec::flac::Config::parse(&mut description.as_ref())?; let stream_info = mp4_atom::FlacMetadataBlock::StreamInfo { minimum_block_size: info.min_block_size, maximum_block_size: info.max_block_size, // Frame sizes are 24-bit; clamp defensively so the conversion can't fail. minimum_frame_size: info.min_frame_size.min(0xFF_FFFF).try_into().expect("fits in u24"), maximum_frame_size: info.max_frame_size.min(0xFF_FFFF).try_into().expect("fits in u24"), sample_rate: info.sample_rate, num_channels_minus_one: info.channel_count.saturating_sub(1) as u8, bits_per_sample_minus_one: info.bits_per_sample.saturating_sub(1) as u8, number_of_interchannel_samples: info.total_samples, md5_checksum: info.md5.to_vec(), }; mp4_atom::Codec::from(mp4_atom::Flac { audio, dfla: mp4_atom::Dfla { blocks: vec![stream_info], }, }) } other => return Err(Error::UnsupportedSynthesis(format!("audio codec {:?}", other))), }; Ok(build_audio_trak(track_id, mdhd_timescale(timescale)?, sample_entry)) } /// All-ones: the ISO/IEC 14496-12 spelling of "duration not known up front", which is always /// the case for the live fragmented streams synthesized here. Zero reads as an empty file to a /// strict parser, and VLC refuses to play one. const UNKNOWN_DURATION: u64 = u64::MAX; fn build_video_trak( track_id: u32, timescale: u32, sample_entry: mp4_atom::Codec, width: u16, height: u16, ) -> mp4_atom::Trak { mp4_atom::Trak { tkhd: mp4_atom::Tkhd { track_id, enabled: true, // track_in_movie. A player is entitled to skip a track the presentation doesn't // claim, and the flags field is 0x000001 rather than 0x000003 without it. in_movie: true, duration: UNKNOWN_DURATION, width: mp4_atom::FixedPoint::from(width), height: mp4_atom::FixedPoint::from(height), ..Default::default() }, mdia: build_mdia(timescale, b"vide", true, sample_entry), ..Default::default() } } fn build_audio_trak(track_id: u32, timescale: u32, sample_entry: mp4_atom::Codec) -> mp4_atom::Trak { mp4_atom::Trak { tkhd: mp4_atom::Tkhd { track_id, enabled: true, in_movie: true, duration: UNKNOWN_DURATION, // Full volume (8.8 fixed point). The default is 0, which is a muted track, and // only an audio track carries a meaningful value. volume: mp4_atom::FixedPoint::from(1), ..Default::default() }, mdia: build_mdia(timescale, b"soun", false, sample_entry), ..Default::default() } } /// Assemble a fragmented init segment (ftyp + moov) around already-built traks. /// /// `ftyp` is the one a passed-through CMAF init carried, if any; otherwise a plain `isom` one /// is synthesized. The `mvhd` is ours either way, so it declares the unknown duration and the /// movie timescale of the assembled init rather than of whatever source a trak came from. /// [`extract_init`] normalizes a passed-through trak to match. pub(crate) fn encode_init( ftyp: Option, mut traks: Vec, trexs: Vec, ) -> Result { use mp4_atom::Encode; let ftyp = ftyp.unwrap_or(mp4_atom::Ftyp { major_brand: b"isom".into(), minor_version: 0x200, compatible_brands: vec![b"isom".into(), b"iso6".into(), b"mp41".into()], }); // Hang places every decoded Opus sample one pre-skip before its packet timestamp. // dOps alone describes decoder priming; ISO BMFF needs an edit to express that // presentation shift. Rebuild it after the output track timescales are settled. for trak in &mut traks { let skip = priming(trak); if skip != 0 { trak.edts = Some(mp4_atom::Edts { elst: Some(mp4_atom::Elst { entries: vec![mp4_atom::ElstEntry { // A live edit's duration is implicit in the fragments that follow. segment_duration: 0, media_time: Some(skip), media_rate: mp4_atom::FixedPoint::from(1), }], }), }); } } let timescale = traks.first().map(|t| t.mdia.mdhd.timescale).unwrap_or(1000); let next_track_id = traks.iter().map(|t| t.tkhd.track_id).max().unwrap_or(0) + 1; let moov = mp4_atom::Moov { mvhd: mp4_atom::Mvhd { timescale, duration: UNKNOWN_DURATION, // Normal playback rate and full volume (16.16 and 8.8 fixed point). Both default // to 0, which declares a stopped, muted presentation. rate: mp4_atom::FixedPoint::from(1), volume: mp4_atom::FixedPoint::from(1), // The next id a track could take, so it must be past every one already present. next_track_id, ..Default::default() }, trak: traks, mvex: (!trexs.is_empty()).then(|| mp4_atom::Mvex { trex: trexs, ..Default::default() }), ..Default::default() }; let mut buf = Vec::new(); ftyp.encode(&mut buf).map_err(crate::container::fmp4::Error::mp4)?; moov.encode(&mut buf).map_err(crate::container::fmp4::Error::mp4)?; Ok(Bytes::from(buf)) } /// An Opus track's pre-skip in its media timescale, or zero for any other track. pub(crate) fn priming(trak: &mp4_atom::Trak) -> u64 { match trak.mdia.minf.stbl.stsd.codecs.as_slice() { [mp4_atom::Codec::Opus(opus)] => u64::from(opus.dops.pre_skip) * u64::from(trak.mdia.mdhd.timescale) / 48_000, _ => 0, } } /// Narrow a media timescale to the 32-bit `mdhd` field, rejecting what would truncate. /// /// `moq_net::Timescale` permits the whole QUIC varint range, so a caller-supplied scale can be /// wider than the field. Truncating would put the init segment and the fragments on different /// timelines, silently, so refuse instead. fn mdhd_timescale(timescale: u64) -> Result { u32::try_from(timescale).map_err(|_| Error::TimescaleTooLarge(timescale)) } fn build_mdia(timescale: u32, handler: &[u8; 4], is_video: bool, sample_entry: mp4_atom::Codec) -> mp4_atom::Mdia { mp4_atom::Mdia { mdhd: mp4_atom::Mdhd { timescale, ..Default::default() }, hdlr: mp4_atom::Hdlr { handler: mp4_atom::FourCC::new(handler), name: String::new(), }, minf: mp4_atom::Minf { vmhd: is_video.then(mp4_atom::Vmhd::default), smhd: (!is_video).then(mp4_atom::Smhd::default), dinf: mp4_atom::Dinf { dref: mp4_atom::Dref { entries: vec![mp4_atom::DrefEntry::Url(mp4_atom::Url::default())], }, }, stbl: mp4_atom::Stbl { stsd: mp4_atom::Stsd { codecs: vec![sample_entry], }, ..Default::default() }, ..Default::default() }, } } /// Default video timescale when the catalog doesn't supply one. /// /// Used by the fMP4 exporter when synthesizing an init segment for a Legacy or LOC source. /// Prefer `framerate * 1000`, then the common NTSC denominator, an exact scale for the /// nanosecond-rounded cadence, and finally the highest safe approximate scale. /// /// A framerate that scales to less than one tick takes the fallback too: zero and negative land /// on 0 through `as u64`, which is not a timescale anything accepts, and a non-finite one is /// filtered out before the cast, since infinity would saturate to `u64::MAX`, past the varint /// range a `Timescale` holds. pub(crate) fn default_video_timescale(config: &VideoConfig) -> u64 { usable_video_framerate(config) .and_then(select_video_timescale) .unwrap_or(90_000) } /// The fallback duration of an audio frame that states none: ~1024 samples, which SBR doubles /// along with the output rate the catalog names. pub(crate) fn audio_default_frame(config: &AudioConfig) -> Duration { let samples = match &config.codec { AudioCodec::AAC(aac) if matches!(aac.profile, 5 | 29) => 2048.0, _ => 1024.0, }; Duration::from_secs_f64(samples / config.sample_rate.max(1) as f64) } /// A finite catalog framerate with a synthesized scale and duration that fit their MP4 fields. pub(crate) fn usable_video_framerate(config: &VideoConfig) -> Option { config .framerate .filter(|fps| fps.is_finite() && *fps > 0.0 && (*fps * 1000.0) as u64 > 0) .filter(|fps| select_video_timescale(*fps).is_some()) } /// Choose a scale that represents the rounded cadence without overflowing `trun` duration. fn select_video_timescale(framerate: f64) -> Option { let preferred = (framerate * 1000.0) as u64; let frame = Duration::from_secs_f64(1.0 / framerate); for timescale in [preferred, (framerate * 1001.0).round() as u64] { if duration_fits_trun(frame, timescale) { return Some(timescale); } } const NANOS_PER_SECOND: u128 = 1_000_000_000; let exact = NANOS_PER_SECOND / gcd(frame.as_nanos(), NANOS_PER_SECOND); let exact = u64::try_from(exact).ok()?; if duration_fits_trun(frame, exact) { return Some(exact); } if let Some(timescale) = rational_timescale(frame) { return Some(timescale); } let max_scale = u128::from(u32::MAX) .checked_mul(NANOS_PER_SECOND)? .checked_div(frame.as_nanos())? .min(u128::from(u32::MAX)); let max_scale = u64::try_from(max_scale).ok()?; duration_fits_trun(frame, max_scale).then_some(max_scale) } /// Find a small rational scale whose rounded cadence stays within one nanosecond. fn rational_timescale(duration: Duration) -> Option { const NANOS_PER_SECOND: u128 = 1_000_000_000; let mut numerator = duration.as_nanos(); let mut denominator = NANOS_PER_SECOND; let (mut previous_ticks, mut ticks) = (0_u128, 1_u128); let (mut previous_scale, mut scale) = (1_u128, 0_u128); while denominator != 0 { let coefficient = numerator / denominator; let next_ticks = coefficient.checked_mul(ticks)?.checked_add(previous_ticks)?; let next_scale = coefficient.checked_mul(scale)?.checked_add(previous_scale)?; if next_ticks > u128::from(u32::MAX) || next_scale > u128::from(u32::MAX) { break; } let candidate = u64::try_from(next_scale).ok()?; if duration_fits_trun(duration, candidate) { return Some(candidate); } (previous_ticks, ticks) = (ticks, next_ticks); (previous_scale, scale) = (scale, next_scale); (numerator, denominator) = (denominator, numerator % denominator); } None } /// Whether the scale represents the rounded cadence and keeps its sample duration 32-bit. fn duration_fits_trun(duration: Duration, timescale: u64) -> bool { timescale > 0 && rounded_duration_ticks(duration, timescale).is_some_and(|ticks| u32::try_from(ticks).is_ok()) } /// Convert a rounded duration to ticks when it is within one nanosecond of an exact tick. fn rounded_duration_ticks(duration: Duration, timescale: u64) -> Option { const NANOS_PER_SECOND: u128 = 1_000_000_000; let scaled = duration.as_nanos().checked_mul(u128::from(timescale))?; let rounded = scaled.checked_add(NANOS_PER_SECOND / 2)? / NANOS_PER_SECOND; let exact = rounded.checked_mul(NANOS_PER_SECOND)?; if scaled.abs_diff(exact) > u128::from(timescale) { return None; } u64::try_from(rounded).ok() } /// Greatest common divisor for reducing exact timestamp ratios. fn gcd(mut a: u128, mut b: u128) -> u128 { while b != 0 { (a, b) = (b, a % b); } a } /// The decode timeline a fragment actually carries: its `tfdt` and each sample's composition /// offset. This is what a player reads, as opposed to the PTS [`decode`] reconstructs from it. #[cfg(test)] pub(crate) fn timeline(fragment: &Bytes) -> (u64, Vec) { let traf = first_traf(fragment); let cts = traf.trun[0].samples.iter().map(|e| e.cts.unwrap_or_default()).collect(); (traf.tfdt.as_ref().unwrap().base_media_decode_time, cts) } /// How long each sample in a fragment claims to last, as written into its `trun`. #[cfg(test)] pub(crate) fn sample_durations(fragment: &Bytes) -> Vec> { first_traf(fragment).trun[0] .samples .iter() .map(|e| e.duration) .collect() } /// One case of `test_data/sample-defaults.json`, which `js/hang` decodes too. #[cfg(test)] #[serde_with::serde_as] #[derive(serde::Deserialize)] pub(crate) struct Fixture { pub name: String, #[serde_as(as = "serde_with::base64::Base64")] pub init: Vec, #[serde_as(as = "serde_with::base64::Base64")] pub fragment: Vec, pub samples: Vec, } /// A sample a [`Fixture`] decodes to, timed in microseconds. #[cfg(test)] #[derive(serde::Deserialize, Debug, PartialEq)] pub(crate) struct FixtureSample { pub timestamp: u64, pub duration: u64, pub keyframe: bool, pub data: Vec, } #[cfg(test)] impl From<&Frame> for FixtureSample { fn from(frame: &Frame) -> Self { Self { timestamp: frame.timestamp.as_micros().unwrap() as u64, duration: frame.duration.map_or(0, |d| d.as_micros().unwrap() as u64), keyframe: frame.keyframe, data: frame.payload.to_vec(), } } } #[cfg(test)] pub(crate) fn fixtures() -> Vec { #[derive(serde::Deserialize)] struct File { cases: Vec, } let file: File = serde_json::from_str(include_str!("test_data/sample-defaults.json")).unwrap(); file.cases } #[cfg(test)] fn first_traf(fragment: &Bytes) -> mp4_atom::Traf { use mp4_atom::DecodeMaybe; let mut cursor = std::io::Cursor::new(fragment.as_ref()); while let Some(atom) = mp4_atom::Any::decode_maybe(&mut cursor).unwrap() { if let mp4_atom::Any::Moof(moof) = atom { return moof.traf.into_iter().next().expect("a traf"); } } panic!("no moof"); } #[cfg(test)] mod tests { #[test] fn received_metadata_is_bounded() { let mut bounded = true; for (name, data) in super::metadata::tests::attacks(b"moov") { bounded &= super::metadata::tests::measure(name, || super::Wire::from_init(&data).is_err()); } let config = AudioConfig::new(AudioCodec::Opus, 48_000, 2); let wire = Wire::new(synthesize_audio_trak(1, 48_000, &config).unwrap()).unwrap(); for (name, data) in super::metadata::tests::attacks(b"moof") { bounded &= super::metadata::tests::measure(name, || { wire.decode(moq_net::frame::Frame::new(Timestamp::unscaled(0), data.clone())) .is_err() }); } assert!(bounded); } use super::*; fn ts(micros: u64) -> Timestamp { Timestamp::from_micros(micros).unwrap() } fn info(track_id: u32, timescale: moq_net::Timescale, sequence_number: u32) -> FragmentInfo { FragmentInfo { track_id, timescale, sequence_number, kind: Kind::Video, } } // An AAC-LC / 44.1 kHz / stereo AudioSpecificConfig, the catalog `description` shape. fn aac_config(bitrate: Option) -> AudioConfig { let mut config = AudioConfig::new(AudioCodec::AAC(hang::catalog::AAC { profile: 2 }), 44_100, 2); config.description = Some(Bytes::from_static(&[0x12, 0x10])); config.bitrate = bitrate; config } #[test] fn he_aac_default_frame_spans_the_core_frame() { // 1024 core samples at 24 kHz, named as 2048 at the 48 kHz output. for profile in [5, 29] { let config = AudioConfig::new(AudioCodec::AAC(hang::catalog::AAC { profile }), 48_000, 2); assert_eq!(audio_default_frame(&config), Duration::from_secs_f64(1024.0 / 24_000.0)); } let lc = AudioConfig::new(AudioCodec::AAC(hang::catalog::AAC { profile: 2 }), 48_000, 2); assert_eq!(audio_default_frame(&lc), Duration::from_secs_f64(1024.0 / 48_000.0)); } /// The moov an encoded init segment carries, so a test asserts on what a player parses /// rather than on the struct that went in. fn moov(init: &Bytes) -> mp4_atom::Moov { use mp4_atom::DecodeMaybe; let mut cursor = std::io::Cursor::new(init.as_ref()); while let Some(atom) = mp4_atom::Any::decode_maybe(&mut cursor).unwrap() { if let mp4_atom::Any::Moov(moov) = atom { return moov; } } panic!("no moov"); } fn dec_config(trak: &mp4_atom::Trak) -> mp4_atom::esds::DecoderConfig { match &trak.mdia.minf.stbl.stsd.codecs[0] { mp4_atom::Codec::Mp4a(mp4a) => mp4a.esds.es_desc.dec_config.clone(), other => panic!("expected mp4a, got {other:?}"), } } // Safari and AVFoundation reject an all-zero DecoderConfigDescriptor on the *init* append, // which ends the ManagedMediaSource and fails every append after it. The catalog bitrate is // optional and real publishers omit it, so a synthesized esds must not lean on it. #[test] fn synthesized_aac_init_has_non_zero_bitrates() { let inferred = dec_config(&synthesize_audio_trak(1, 44_100, &aac_config(None)).unwrap()); assert_ne!(u32::from(inferred.buffer_size_db), 0); assert_ne!(inferred.max_bitrate, 0); assert_ne!(inferred.avg_bitrate, 0); let stated = dec_config(&synthesize_audio_trak(1, 44_100, &aac_config(Some(96_000))).unwrap()); assert_eq!(stated.max_bitrate, 96_000, "the catalog's bitrate wins"); assert_eq!(stated.avg_bitrate, 96_000); // A stated bitrate the field can't carry rebuilds the same all-zero descriptor, so it // takes the fallback rather than the catalog. for unusable in [Some(0), Some(u64::from(u32::MAX) + 1)] { let config = dec_config(&synthesize_audio_trak(1, 44_100, &aac_config(unusable)).unwrap()); assert_eq!(config.max_bitrate, inferred.max_bitrate, "{unusable:?}"); assert_eq!(config.avg_bitrate, inferred.avg_bitrate, "{unusable:?}"); } } // `framerate * 1000` is 0 for a zero, negative or non-finite catalog framerate, and 0 is not // a timescale: Timescale::new rejects it, so Muxer::video would fail to build at all. #[test] fn default_video_timescale_ignores_an_unusable_framerate() { let mut config = VideoConfig::new(hang::catalog::VideoCodec::VP8); for unusable in [0.0, -30.0, f64::NAN, f64::INFINITY, 0.0005] { config.framerate = Some(unusable); assert_eq!(default_video_timescale(&config), 90_000, "{unusable}"); } config.framerate = Some(30.0); assert_eq!(default_video_timescale(&config), 30_000); config.framerate = Some(30_000.0 / 1001.0); assert_eq!(default_video_timescale(&config), 30_000); } #[test] fn default_video_timescale_keeps_low_cadence_within_trun() { let mut config = VideoConfig::new(hang::catalog::VideoCodec::VP8); for framerate in [0.2001, 0.0011] { config.framerate = Some(framerate); let timescale = default_video_timescale(&config); let duration = Duration::from_secs_f64(1.0 / framerate); let ticks = rounded_duration_ticks(duration, timescale).unwrap(); assert!(timescale <= u64::from(u32::MAX)); assert!(ticks <= u64::from(u32::MAX)); } assert_eq!(default_video_timescale(&config), 11); } // A live fragmented stream's duration isn't known up front. Zero reads as an empty file to a // strict parser: VLC refuses to play one. #[test] fn synthesized_init_declares_unknown_duration() { let trak = synthesize_audio_trak(1, 44_100, &aac_config(None)).unwrap(); assert_eq!(trak.tkhd.duration, u64::MAX); let init = encode_init(None, vec![trak], Vec::new()).unwrap(); let moov = moov(&init); assert_eq!(moov.mvhd.duration, u64::MAX); assert_eq!(moov.trak[0].tkhd.duration, u64::MAX); } /// Opus media time counts priming; Hang time places the first kept sample at the /// first frame timestamp. Both init sources must express the same inverse mapping. #[test] fn opus_init_maps_hang_timestamps_to_media() { for timescale in [48_000, 1_000_000] { for pre_skip in [0, 312, u16::MAX] { let mut config = AudioConfig::new(AudioCodec::Opus, 48_000, 2); config.description = Some( crate::codec::opus::Config::new(48_000, 2) .with_pre_skip(pre_skip) .encode() .unwrap(), ); for source_edit in [false, true] { let mut trak = synthesize_audio_trak(1, timescale, &config).unwrap(); if source_edit { trak.edts = Some(mp4_atom::Edts { elst: Some(mp4_atom::Elst { entries: vec![mp4_atom::ElstEntry { media_time: Some(96000), ..Default::default() }], }), }); let mut init = Vec::new(); mp4_atom::Encode::encode( &mp4_atom::Moov { trak: vec![trak], ..Default::default() }, &mut init, ) .unwrap(); let mut traks = Vec::new(); extract_init(&Bytes::from(init), 1, &mut None, &mut traks, &mut Vec::new()).unwrap(); trak = traks.pop().unwrap(); } let init = encode_init(None, vec![trak], Vec::new()).unwrap(); let moov = moov(&init); let trak = &moov.trak[0]; let skip = u64::from(pre_skip) * timescale / 48_000; if skip == 0 { assert!(trak.edts.is_none()); } else { let entries = &trak.edts.as_ref().unwrap().elst.as_ref().unwrap().entries; assert_eq!(entries.len(), 1); assert_eq!(entries[0].media_time, Some(skip)); assert_eq!(entries[0].segment_duration, 0, "the live duration is implicit"); assert_eq!(entries[0].media_rate, mp4_atom::FixedPoint::from(1)); } let edit = edit::Edit::new(trak, moov.mvhd.timescale).unwrap(); for pts in [0, skip, timescale * 10] { assert_eq!(edit.present(pts).unwrap(), Some(pts), "the importer inverts the edit"); } } } } } // The header defaults are all the "off" value: a track the presentation doesn't claim, a // stopped playback rate, a muted volume, and a next id that collides with the track already // there. A strict player is entitled to act on any of them. #[test] fn synthesized_init_headers_describe_a_playable_presentation() { let audio = synthesize_audio_trak(1, 44_100, &aac_config(None)).unwrap(); let init = encode_init(None, vec![audio], Vec::new()).unwrap(); let moov = moov(&init); assert_eq!(moov.mvhd.rate.integer(), 1, "normal playback rate"); assert_eq!(moov.mvhd.volume.integer(), 1, "full volume"); assert_eq!(moov.mvhd.next_track_id, 2, "past the only track id"); let tkhd = &moov.trak[0].tkhd; assert!(tkhd.enabled && tkhd.in_movie, "flags 0x000003"); assert_eq!(tkhd.volume.integer(), 1, "an audio track carries the volume"); } // A video track's volume stays 0: the field only means something for audio. #[test] fn synthesized_video_init_sets_the_track_flags() { let mut config = VideoConfig::new(hang::catalog::VideoCodec::VP8); config.coded_width = Some(320); config.coded_height = Some(240); config.framerate = Some(30.0); let video = synthesize_video_trak(1, 30_000, &config, None).unwrap(); let init = encode_init(None, vec![video], Vec::new()).unwrap(); let moov = moov(&init); let tkhd = &moov.trak[0].tkhd; assert!(tkhd.enabled && tkhd.in_movie, "flags 0x000003"); assert_eq!(tkhd.volume.integer(), 0); } #[test] fn synthesized_video_init_rejects_missing_dimensions() { let config = VideoConfig::new(hang::catalog::VideoCodec::VP8); let error = synthesize_video_trak(1, 30_000, &config, None).unwrap_err(); assert!(matches!(error, Error::MissingVideoDimensions(_))); } #[test] fn decode_reads_trun_sample_duration() { use mp4_atom::Encode; // Microsecond timescale so each tick maps 1:1 to the Timestamp's µs. // Without a data_offset, decode() reads the run from the start of the mdat, so a // hand-built moof+mdat with explicit per-sample durations is enough. let timescale = moq_net::Timescale::MICRO; let moof = mp4_atom::Moof { mfhd: mp4_atom::Mfhd { sequence_number: 0 }, traf: vec![mp4_atom::Traf { tfhd: mp4_atom::Tfhd { track_id: 1, ..Default::default() }, tfdt: Some(mp4_atom::Tfdt { base_media_decode_time: 0, }), trun: vec![mp4_atom::Trun { data_offset: None, samples: vec![ mp4_atom::TrunEntry { size: Some(2), duration: Some(33_333), ..Default::default() }, mp4_atom::TrunEntry { size: Some(2), duration: Some(33_333), ..Default::default() }, ] .into(), }], ..Default::default() }], }; let mut buf = Vec::new(); moof.encode(&mut buf).unwrap(); mp4_atom::Mdat { data: vec![0xDE, 0xAD, 0xBE, 0xEF], } .encode(&mut buf) .unwrap(); let frames = decode(Bytes::from(buf), None, Track::new(timescale, Kind::Video)).unwrap(); assert_eq!(frames.len(), 2); assert_eq!(frames[0].timestamp, ts(0)); assert_eq!(frames[0].duration, Some(ts(33_333))); assert_eq!(frames[1].timestamp, ts(33_333)); assert_eq!(frames[1].duration, Some(ts(33_333))); } #[test] fn duration_round_trips_through_encode() { // A frame with a known duration must survive encode -> decode. let timescale = moq_net::Timescale::MICRO; let input = vec![Frame { timestamp: ts(0), payload: Bytes::from_static(&[0xDE, 0xAD]), keyframe: true, duration: Some(ts(33_333)), }]; let fragment = encode_fragment(info(1, timescale, 0), &input).unwrap(); let frames = decode(fragment, None, Track::new(timescale, Kind::Video)).unwrap(); assert_eq!(frames.len(), 1); assert_eq!(frames[0].duration, Some(ts(33_333))); } // A trun sample duration is 32 bits. Narrowing silently would make the media claim a // shorter duration than the metadata returned to the fragmenting consumer. #[test] fn encode_fragment_rejects_a_duration_too_large_for_trun() { let timescale = moq_net::Timescale::new(u64::from(u32::MAX)).unwrap(); let over = u64::from(u32::MAX) + 1; let frame = Frame { timestamp: Timestamp::from_scale(0, timescale.as_u64()).unwrap(), payload: Bytes::from_static(&[0xDE, 0xAD]), keyframe: true, duration: Some(Timestamp::from_scale(over, timescale.as_u64()).unwrap()), }; let err = encode_fragment(info(1, timescale, 0), std::slice::from_ref(&frame)).unwrap_err(); assert!(matches!(err, Error::SampleDurationTooLarge(ticks) if ticks == over)); let largest = Frame { duration: Some(Timestamp::from_scale(u64::from(u32::MAX), timescale.as_u64()).unwrap()), ..frame }; let fragment = encode_fragment(info(1, timescale, 0), &[largest]).unwrap(); assert_eq!(sample_durations(&fragment), vec![Some(u32::MAX)]); } // A positive duration that becomes zero ticks would leave tfdt stationary while the // fragment metadata still advances, so a coarse override has to fail explicitly. #[test] fn encode_fragment_rejects_a_duration_shorter_than_one_tick() { let timescale = moq_net::Timescale::SECOND; let frame = Frame { timestamp: Timestamp::from_secs(0).unwrap(), payload: Bytes::from_static(&[0xDE, 0xAD]), keyframe: true, duration: Some(Timestamp::from_millis(33).unwrap()), }; let err = encode_fragment(info(1, timescale, 0), std::slice::from_ref(&frame)).unwrap_err(); assert!(matches!(err, Error::SampleDurationTooSmall(1))); let one_tick = Frame { duration: Some(Timestamp::from_secs(1).unwrap()), ..frame }; let fragment = encode_fragment(info(1, timescale, 0), &[one_tick]).unwrap(); assert_eq!(sample_durations(&fragment), vec![Some(1)]); } // Flooring every 1/24-second sample at a 1 kHz output scale would lose 16 ticks per // second. The caller must choose a scale that represents the duration exactly. #[test] fn encode_fragment_rejects_an_inexact_sample_duration() { let input_scale = moq_net::Timescale::new(24).unwrap(); let output_scale = moq_net::Timescale::MILLI; let frame = Frame { timestamp: Timestamp::new(0, input_scale).unwrap(), payload: Bytes::from_static(&[0xDE, 0xAD]), keyframe: true, duration: Some(Timestamp::new(1, input_scale).unwrap()), }; let err = encode_fragment(info(1, output_scale, 0), std::slice::from_ref(&frame)).unwrap_err(); assert!(matches!(err, Error::SampleDurationInexact(1_000))); let exact_scale = moq_net::Timescale::new(24_000).unwrap(); let fragment = encode_fragment(info(1, exact_scale, 0), &[frame]).unwrap(); assert_eq!(sample_durations(&fragment), vec![Some(1_000)]); } // tfdt is 64 bits. A timestamp rescaled past that range must fail rather than wrap the // fragment back onto an unrelated point in the presentation. #[test] fn encode_fragment_rejects_a_pts_too_large_for_tfdt() { let timescale = moq_net::Timescale::new(u64::from(u32::MAX)).unwrap(); let frame = Frame { timestamp: Timestamp::from_secs(1 << 40).unwrap(), payload: Bytes::from_static(&[0xDE, 0xAD]), keyframe: true, duration: None, }; let err = encode_fragment(info(1, timescale, 0), &[frame]).unwrap_err(); assert!(matches!(err, Error::PtsOverflow)); } #[test] fn reordered_pts_round_trips_with_cts() { let timescale = moq_net::Timescale::new(1_000_000).unwrap(); let input = vec![ Frame { timestamp: ts(0), payload: Bytes::from_static(&[0x00]), keyframe: true, duration: Some(ts(33_000)), }, Frame { timestamp: ts(99_000), payload: Bytes::from_static(&[0x01]), keyframe: false, duration: Some(ts(33_000)), }, Frame { timestamp: ts(33_000), payload: Bytes::from_static(&[0x02]), keyframe: false, duration: Some(ts(33_000)), }, ]; let fragment = encode_fragment(info(1, timescale, 0), &input).unwrap(); let frames = decode(fragment, None, Track::new(timescale, Kind::Video)).unwrap(); assert_eq!(frames.len(), input.len()); for (actual, expected) in frames.iter().zip(&input) { assert_eq!(actual.timestamp, expected.timestamp); assert_eq!(actual.duration, expected.duration); assert_eq!(actual.payload, expected.payload); } } /// Packagers flag every audio sample a sync sample. Decoded as keyframes, those would /// each open a group, so audio decodes with the bit clear: the group start is the /// consumer's to mark. #[test] fn audio_samples_decode_without_the_keyframe_bit() { let timescale = moq_net::Timescale::new(48_000).unwrap(); let input: Vec = (0..3) .map(|i| Frame { timestamp: Timestamp::new(i * 960, timescale).unwrap(), payload: Bytes::from_static(&[0x00]), keyframe: i == 0, duration: Some(Timestamp::new(960, timescale).unwrap()), }) .collect(); let fragment = encode_fragment( FragmentInfo { kind: Kind::Audio, ..info(1, timescale, 0) }, &input, ) .unwrap(); // On the wire every sample is a sync sample, whatever the keyframe bit said. let flags: Vec = first_traf(&fragment).trun[0] .samples .iter() .map(|entry| entry.flags.unwrap()) .collect(); assert_eq!(flags, vec![0x0200_0000; 3]); let audio = decode(fragment.clone(), None, Track::new(timescale, Kind::Audio)).unwrap(); assert!( audio.iter().all(|frame| !frame.keyframe), "audio never decodes a keyframe" ); let video = decode(fragment, None, Track::new(timescale, Kind::Video)).unwrap(); assert!( video.iter().all(|frame| frame.keyframe), "the sync flag is a video keyframe" ); } /// A fragment that leaves sample values to `tfhd` or the init segment's `trex` decodes the way /// `js/hang` decodes the same fixtures. #[test] fn decodes_the_sample_defaults_fixtures() { for fixture in fixtures() { let wire = Wire::from_init(&fixture.init).unwrap(); let frames = decode(Bytes::from(fixture.fragment), None, wire.track().unwrap()) .unwrap_or_else(|err| panic!("{}: {err}", fixture.name)); let samples: Vec = frames.iter().map(FixtureSample::from).collect(); assert_eq!(samples, fixture.samples, "{}", fixture.name); } } #[test] fn unsupported_track_handler_is_rejected() { assert!(matches!( Kind::from_handler((*b"text").into()), Err(Error::UnknownTrackHandler(_)) )); } /// The wire container tells audio from video by the handler its init declares. #[test] fn wire_knows_an_audio_track_by_its_handler() { let audio = Wire::new(synthesize_audio_trak(1, 44_100, &aac_config(None)).unwrap()).unwrap(); assert_eq!(audio.kind, Kind::Audio); let mut config = VideoConfig::new(hang::catalog::VideoCodec::VP8); config.coded_width = Some(320); config.coded_height = Some(240); let video = Wire::new(synthesize_video_trak(1, 90_000, &config, None).unwrap()).unwrap(); assert_eq!(video.kind, Kind::Video); } /// A track that is neither audio nor video is refused when the container is built, so /// nothing reads it as a data track. #[test] fn wire_refuses_a_track_that_is_neither_audio_nor_video() { let mut trak = synthesize_audio_trak(1, 44_100, &aac_config(None)).unwrap(); trak.mdia.hdlr.handler = (*b"sbtl").into(); assert!(matches!(Wire::new(trak), Err(Error::UnsupportedSubtitle))); } fn sample(micros: u64) -> Frame { Frame { timestamp: ts(micros), payload: Bytes::from_static(&[0xAB]), keyframe: false, duration: Some(ts(33_000)), } } fn micros(frames: &[Frame]) -> Vec { frames.iter().map(|f| f.timestamp.as_micros().unwrap()).collect() } /// The frame timestamp is the broadcast timeline: a passthrough fragment whose `tfdt` still /// carries its source PTS decodes at the frame timestamp, keeping its B-frame order. #[test] fn decode_times_samples_from_the_frame_timestamp() { let timescale = moq_net::Timescale::MICRO; let source = 3_600_000_000; let input = [sample(source), sample(source + 66_000), sample(source + 33_000)]; let fragment = encode_fragment(info(1, timescale, 0), &input).unwrap(); let frames = decode(fragment, Some(ts(10_000_000)), Track::new(timescale, Kind::Video)).unwrap(); assert_eq!(micros(&frames), [10_000_000, 10_066_000, 10_033_000]); } /// A fragment can open on a sample that presents after a later one (open-GOP leading /// pictures, or a cut mid-GOP). The earliest presentation time is the anchor, on both sides. #[tokio::test] async fn the_frame_timestamp_is_the_earliest_presentation_time() { let mut config = VideoConfig::new(hang::catalog::VideoCodec::VP8); config.coded_width = Some(320); config.coded_height = Some(240); let timescale = moq_net::Timescale::MICRO; let wire = Wire::new(synthesize_video_trak(1, 1_000_000, &config, None).unwrap()).unwrap(); let broadcast = moq_net::broadcast::Info::new().produce(); let info = moq_net::track::Info::default().with_timescale(timescale); let track = broadcast.create_track("video", info).unwrap(); let mut group = track.append_group(Timestamp::from_micros(0).unwrap()).unwrap(); let input = [sample(100_000), sample(33_000), sample(66_000)]; wire.write(&mut group, &input).unwrap(); let frame = group.consume().read_frame().await.unwrap().unwrap(); assert_eq!(frame.timestamp.as_micros().unwrap(), 33_000); let frames = decode( frame.payload.clone(), Some(frame.timestamp), Track::new(timescale, Kind::Video), ) .unwrap(); assert_eq!(micros(&frames), [100_000, 33_000, 66_000]); let shifted = decode(frame.payload, Some(ts(5_000_000)), Track::new(timescale, Kind::Video)).unwrap(); assert_eq!(micros(&shifted), [5_067_000, 5_000_000, 5_033_000]); } /// A scale-less track's frames carry no broadcast time, so their samples present at `tfdt`. #[test] fn an_untimed_fragment_decodes_at_its_tfdt() { let mut config = VideoConfig::new(hang::catalog::VideoCodec::VP8); config.coded_width = Some(320); config.coded_height = Some(240); let timescale = moq_net::Timescale::MICRO; let wire = Wire::new(synthesize_video_trak(1, 1_000_000, &config, None).unwrap()).unwrap(); let source = 3_600_000_000; let input = [sample(source), sample(source + 66_000), sample(source + 33_000)]; let fragment = encode_fragment(info(1, timescale, 0), &input).unwrap(); let frames = wire .decode(moq_net::frame::Frame::new(Timestamp::unscaled(0), fragment)) .unwrap(); let source = u128::from(source); assert_eq!(micros(&frames), [source, source + 66_000, source + 33_000]); } /// A track at another scale than the media couldn't carry the earliest presentation time /// exactly, so writing a fragment to it fails. #[test] fn write_refuses_a_track_at_another_timescale() { let mut config = VideoConfig::new(hang::catalog::VideoCodec::VP8); config.coded_width = Some(320); config.coded_height = Some(240); let wire = Wire::new(synthesize_video_trak(1, 90_000, &config, None).unwrap()).unwrap(); let broadcast = moq_net::broadcast::Info::new().produce(); let info = moq_net::track::Info::default().with_timescale(moq_net::Timescale::MILLI); let track = broadcast.create_track("video", info).unwrap(); let mut group = track.append_group(Timestamp::from_millis(0).unwrap()).unwrap(); let err = wire.write(&mut group, &[sample(0)]).unwrap_err(); assert!(matches!(err, Error::TimescaleMismatch { .. }), "got {err:?}"); } /// A run whose samples extend beyond the payload is refused. #[test] fn decode_refuses_a_run_past_the_payload() { use mp4_atom::{DecodeMaybe, Encode}; let timescale = moq_net::Timescale::MICRO; let fragment = encode_fragment(info(1, timescale, 0), &[sample(0), sample(33_000)]).unwrap(); let mut cursor = std::io::Cursor::new(fragment.as_ref()); let Some(mp4_atom::Any::Moof(mut moof)) = mp4_atom::Any::decode_maybe(&mut cursor).unwrap() else { panic!("a moof first"); }; let mdat = &fragment[cursor.position() as usize..]; let offset = moof.traf[0].trun[0].data_offset.as_mut().unwrap(); *offset += 1; let mut skewed = Vec::new(); moof.encode(&mut skewed).unwrap(); skewed.extend_from_slice(mdat); let err = decode(Bytes::from(skewed), None, Track::new(timescale, Kind::Video)).unwrap_err(); assert!(matches!(err, Error::SampleRangeOutOfBounds { .. }), "got {err:?}"); } /// A frame timestamp the track carries at another scale anchors to the nearest tick, the way /// `encode` stamps it. #[test] fn decode_rounds_the_frame_timestamp_to_the_nearest_tick() { let timescale = moq_net::Timescale::new(90_000).unwrap(); let fragment = encode_fragment(info(1, timescale, 0), &[sample(0)]).unwrap(); // Tick 100 is 1111.1 µs, which a microsecond track truncates to 1111. let frames = decode(fragment, Some(ts(1_111)), Track::new(timescale, Kind::Video)).unwrap(); assert_eq!(frames[0].timestamp, Timestamp::new(100, timescale).unwrap()); } #[test] fn decode_without_duration_reports_none() { // encode_fragment writes no sample-duration for a duration-less frame, // so decode must report None (and output stays byte-identical to before). let timescale = moq_net::Timescale::new(90_000).unwrap(); let frames = vec![Frame { timestamp: ts(0), payload: Bytes::from_static(&[0xDE, 0xAD]), keyframe: true, duration: None, }]; let fragment = encode_fragment(info(1, timescale, 0), &frames).unwrap(); let frames = decode(fragment, None, Track::new(timescale, Kind::Video)).unwrap(); assert_eq!(frames.len(), 1); assert_eq!(frames[0].duration, None); } #[test] fn decode_zero_duration_reports_none() { use mp4_atom::Encode; let timescale = moq_net::Timescale::new(24_000).unwrap(); let moof = mp4_atom::Moof { mfhd: mp4_atom::Mfhd { sequence_number: 0 }, traf: vec![mp4_atom::Traf { tfhd: mp4_atom::Tfhd { track_id: 1, default_sample_duration: Some(0), default_sample_size: Some(2), ..Default::default() }, tfdt: Some(mp4_atom::Tfdt { base_media_decode_time: 2_000, }), trun: vec![mp4_atom::Trun { data_offset: None, samples: vec![mp4_atom::TrunEntry { size: None, duration: None, ..Default::default() }] .into(), }], ..Default::default() }], }; let mut buf = Vec::new(); moof.encode(&mut buf).unwrap(); mp4_atom::Mdat { data: vec![0xDE, 0xAD] }.encode(&mut buf).unwrap(); let frames = decode(Bytes::from(buf), None, Track::new(timescale, Kind::Video)).unwrap(); assert_eq!(frames.len(), 1); assert_eq!(frames[0].timestamp.as_micros().unwrap(), 83_333); assert_eq!(frames[0].duration, None); } }