oxideav-mp4 0.0.10

Pure-Rust MP4 / ISO base media file container for oxideav
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
//! Muxer configuration for the MP4 / ISOBMFF writer.
//!
//! The default [`Mp4MuxerOptions`] matches what `muxer::open` has always done:
//! major brand `mp42`, no faststart, no fragmentation. Three convenience
//! presets are provided via [`BrandPreset`] for the common `mp4`, `mov`, and
//! `ismv` registry entries; a `Custom` variant lets callers supply any
//! major + compatible brand list directly.
//!
//! Setting [`Mp4MuxerOptions::fragmented`] to `Some(...)` switches the muxer
//! into fragmented-MP4 mode (DASH / HLS / Smooth-Streaming / CMAF output).

/// Brand preset controlling the `ftyp` box written at the start of the file.
///
/// The four-byte codes follow ISO/IEC 14496-12 and the de-facto QuickTime /
/// Smooth Streaming conventions:
///
/// * [`Mp4`](BrandPreset::Mp4): `mp42` / `isom mp42 mp41 iso2`
/// * [`Mov`](BrandPreset::Mov): `qt  ` / `qt  `
/// * [`Ismv`](BrandPreset::Ismv): `iso4` / `iso4 piff iso6 isml`
/// * [`Custom`](BrandPreset::Custom): caller-supplied major + compatible list
#[derive(Clone, Debug)]
pub enum BrandPreset {
    /// Standard MP4 — `major=mp42`, compatible=`isom mp42 mp41 iso2`.
    Mp4,
    /// Apple QuickTime — `major=qt  `, compatible=`qt  `.
    Mov,
    /// Microsoft Smooth Streaming / ISMV — `major=iso4`, compatible=`iso4 piff iso6 isml`.
    Ismv,
    /// Custom brand with an explicit major + compatible list.
    Custom {
        major: [u8; 4],
        compatible: Vec<[u8; 4]>,
    },
}

impl BrandPreset {
    /// Return the major brand for this preset.
    pub fn major_brand(&self) -> [u8; 4] {
        match self {
            BrandPreset::Mp4 => *b"mp42",
            BrandPreset::Mov => *b"qt  ",
            BrandPreset::Ismv => *b"iso4",
            BrandPreset::Custom { major, .. } => *major,
        }
    }

    /// Return the list of compatible brands for this preset.
    pub fn compatible_brands(&self) -> Vec<[u8; 4]> {
        match self {
            BrandPreset::Mp4 => vec![*b"isom", *b"mp42", *b"mp41", *b"iso2"],
            BrandPreset::Mov => vec![*b"qt  "],
            BrandPreset::Ismv => vec![*b"iso4", *b"piff", *b"iso6", *b"isml"],
            BrandPreset::Custom { compatible, .. } => compatible.clone(),
        }
    }
}

/// Cadence policy controlling when the fragmented muxer emits a `moof+mdat`
/// pair (one segment / fragment per flush).
///
/// In a true CMAF / DASH `init+seg*` workflow each `moof+mdat` becomes one
/// addressable HTTP range; the cadence picks how big each one is.
#[derive(Clone, Copy, Debug)]
pub enum FragmentCadence {
    /// Flush whenever the running fragment duration of the *first* track
    /// (typically video) reaches `seconds`. Falls back to per-track total
    /// when there is no first track. Compressed audio samples are tiny
    /// (~20 ms each) so picking 2..6 s yields reasonable fragment sizes.
    EverySeconds(f64),
    /// Flush at every keyframe of the *first* track (typically video). The
    /// run before the first keyframe is held until one arrives. Audio-only
    /// inputs (every audio sample is a keyframe) effectively get one
    /// fragment per audio sample with this — pair with seconds/N for
    /// audio-only output.
    EveryKeyframe,
    /// Flush every `n` packets of the first track. Useful for testing
    /// (predictable cadence without timing dependence).
    EveryNPackets(u32),
}

/// Fragmented-MP4 muxer options.
///
/// When [`Mp4MuxerOptions::fragmented`] is `Some(FragmentedOptions { .. })`,
/// the muxer writes the file as
///
/// ```text
/// ftyp
/// moov                    (mvex+trex; no media samples in moov)
/// sidx?                   (one per fragment, references the next moof+mdat)
/// styp? + moof + mdat     (per fragment, repeated)
/// sidx? + styp? + moof + mdat
/// ...
/// mfra?                   (at end: per-track tfra + mfro size trailer)
/// ```
///
/// matching ISO/IEC 14496-12 §8.8 (Movie Fragments) + §8.16 (sidx) + §8.8.10
/// (mfra) + DASH-IF Interop guidelines for `styp` brands.
#[derive(Clone, Debug)]
pub struct FragmentedOptions {
    /// When to flush a fragment; see [`FragmentCadence`].
    pub cadence: FragmentCadence,
    /// Emit a `styp` SegmentTypeBox before each `moof+mdat` pair (CMAF
    /// segment marker). When `None`, no `styp` is written and the file is
    /// a plain fragmented ISOBMFF (still valid for any DASH parser, but
    /// not a CMAF-conformant addressable segment).
    ///
    /// DASH-IF Interop §6.2 recommends `styp(major=msdh, compat=msdh msix)`
    /// for an indexed media segment, or `cmfs` / `cmff` for CMAF brand
    /// signalling. The default `Some(BrandPreset::Custom { major: msdh,
    /// compatible: [msdh, msix] })` is the broadly-interop choice.
    pub styp: Option<BrandPreset>,
    /// Emit `sidx` (SegmentIndexBox §8.16.3) before each `moof+mdat` and
    /// an `mfra` (MovieFragmentRandomAccessBox §8.8.10) trailer with
    /// per-track `tfra` random-access tables + the size-of-mfra `mfro`
    /// at end of file. Required for the DASH on-demand profile (single
    /// file with embedded byte-range index) and for fast random-access
    /// without scanning every moof. Default `true`.
    ///
    /// The emitted `sidx` is a single-entry index covering the immediately-
    /// following moof+mdat (the simplest legal form per §8.16.3); a
    /// multi-segment top-level sidx can be layered on by an outer
    /// segmenter if needed.
    pub emit_random_access_indexes: bool,
    /// Per-level assignment entries for a `leva` (LevelAssignmentBox,
    /// ISO/IEC 14496-12 §8.8.13) emitted inside the init `mvex`.
    ///
    /// When non-empty, the muxer writes one `leva` after the `trex` boxes
    /// in `mvex`, advertising how the file's content is partitioned into
    /// **levels** for partial-subsegment fetch. Each entry is a
    /// [`demux::LevaEntry`](crate::demux::LevaEntry) (`track_id` +
    /// `padding_flag` + `assignment_type` + the type-specific tail). The
    /// level *order* in this slice is the level *number* a sibling `ssix`
    /// SubsegmentIndexBox refers to (§8.16.4.2).
    ///
    /// The §8.8.13.3 conformance constraints (`level_count ≥ 2`, the
    /// "zero or more of type 2/3 then zero or more of exactly one type"
    /// ordering rule) are the caller's responsibility; the muxer
    /// serialises whatever is supplied verbatim. Empty by default — most
    /// fragmented files don't declare levels.
    pub levels: Vec<crate::demux::LevaEntry>,
    /// Emit an `ssix` (SubsegmentIndexBox, ISO/IEC 14496-12 §8.16.4)
    /// immediately after each per-fragment `sidx`, partitioning the
    /// fragment's single referenced subsegment into two level byte ranges
    /// for partial-subsegment fetch (§8.16.4.1).
    ///
    /// Requires `emit_random_access_indexes == true` (the `ssix` documents
    /// the preceding `sidx`); when `emit_random_access_indexes` is `false`,
    /// this flag has no effect. Each emitted `ssix` carries
    /// `subsegment_count == 1` (matching the one-reference `sidx`) with two
    /// ranges that together cover the whole subsegment (`styp? + prft? +
    /// moof + mdat`):
    ///
    /// 1. `level = ssix_levels.0` → the leading metadata bytes
    ///    (`styp? + prft? + moof`),
    /// 2. `level = ssix_levels.1` → the trailing media bytes (`mdat`).
    ///
    /// The two level numbers should match level numbers assigned by the
    /// [`levels`](Self::levels) `leva`; the §8.16.4 "ranges partition the
    /// subsegment / ≥ 2 ranges" constraint is satisfied by construction.
    /// Default `false` (no `ssix`); when enabled the default
    /// `ssix_levels` is `(1, 2)`.
    pub emit_ssix: bool,
    /// The two `ssix` level numbers `(metadata_level, media_level)` used
    /// when [`emit_ssix`](Self::emit_ssix) is set: the first labels the
    /// leading `styp? + prft? + moof` range, the second the trailing
    /// `mdat` range. Defaults to `(1, 2)`. Ignored when `emit_ssix` is
    /// `false`.
    pub ssix_levels: (u8, u8),
    /// Per-track `trep` (TrackExtensionPropertiesBox, ISO/IEC 14496-12
    /// §8.8.15) records emitted inside the init `mvex`.
    ///
    /// When non-empty, the muxer writes one `trep` per record after the
    /// `trex` boxes (and after any `leva`), in slice order. Each record
    /// is a [`demux::TrepRecord`](crate::demux::TrepRecord) carrying its
    /// `track_id` and child boxes; the one base-spec-defined child,
    /// `assp` (AlternativeStartupSequencePropertiesBox, §8.8.16), is
    /// serialised from its typed [`AsspRecord`](crate::demux::AsspRecord)
    /// when present on a [`TrepChild`](crate::demux::TrepChild). The
    /// records read back through the demuxer's `mvex` walk (`trep_<n>`
    /// metadata + `Mp4Demuxer::treps()`).
    ///
    /// §8.8.15.1 fixes quantity at zero or one `trep` per track; the
    /// muxer serialises whatever is supplied verbatim (the per-track
    /// uniqueness is the caller's responsibility). Empty by default —
    /// most fragmented files don't declare track extension properties.
    pub treps: Vec<crate::demux::TrepRecord>,
    /// Write a `mehd` (MovieExtendsHeaderBox, ISO/IEC 14496-12 §8.8.2)
    /// as the first child of the init-segment `mvex`, sealing the
    /// file's overall presentation duration at `write_trailer`.
    ///
    /// §8.8.2.3 defines `fragment_duration` as "the duration of the
    /// longest track, including movie fragments" in the movie
    /// timescale — a value only known once the last fragment is laid
    /// down. The muxer therefore reserves a version-1 (64-bit) `mehd`
    /// with `fragment_duration = 0` at `write_header` and patches the
    /// eight duration bytes in place at `write_trailer` (the output is
    /// `WriteSeek`, so the seek-back is always available). A sealed
    /// file then demuxes with an authoritative `duration_micros` even
    /// though its `mvhd.duration` is 0 (no moov-resident samples); the
    /// demuxer surfaces the raw value as the `mehd_fragment_duration`
    /// metadata key. If `write_trailer` is never reached (a truncated
    /// live capture), the placeholder 0 is exactly the "value unknown"
    /// posture readers already handle — §8.8.2.1 says the overall
    /// duration must then be computed by examining each fragment.
    ///
    /// Default `false`: no `mehd` is written and the init segment is
    /// byte-identical to before (the right choice for live/low-latency
    /// output where the init segment ships before the stream ends).
    pub write_mehd: bool,
}

impl Default for FragmentedOptions {
    fn default() -> Self {
        Self {
            cadence: FragmentCadence::EverySeconds(2.0),
            styp: Some(BrandPreset::Custom {
                major: *b"msdh",
                compatible: vec![*b"msdh", *b"msix"],
            }),
            emit_random_access_indexes: true,
            levels: Vec::new(),
            emit_ssix: false,
            ssix_levels: (1, 2),
            treps: Vec::new(),
            write_mehd: false,
        }
    }
}

/// Per-track sample-group emission request.
///
/// Each entry attaches an `sbgp` (SampleToGroupBox), `csgp`
/// (CompactSampleToGroupBox) and / or `sgpd` (SampleGroupDescriptionBox)
/// box into one track's `stbl`. The halves share `grouping_type`; the
/// writer simply serialises whatever the caller supplies — content
/// interpretation belongs to a layer that knows the grouping-type
/// semantics (per ISO/IEC 14496-12 §8.9).
///
/// Multiple `TrackSampleGroups` entries may target the same
/// `stream_index`; they accumulate in encounter order. The muxer
/// emits all `sgpd` boxes first, then all `sbgp` boxes, then all
/// `csgp` boxes, after the chunk-offset table inside each track's
/// `stbl`. `sbgp` and `csgp` are *alternative* encodings of the same
/// per-sample → group mapping (§8.9.5: "at most one `csgp` *or* `sbgp`
/// with a given `grouping_type` may exist per track"); a caller picks
/// one form per `grouping_type` and never both.
#[derive(Clone, Debug, Default)]
pub struct TrackSampleGroups {
    /// Index into the muxer's `streams` slice (the stream slot that
    /// owns these groups).
    pub stream_index: usize,
    /// `sbgp` boxes to emit for this track. Order is preserved.
    pub sbgp: Vec<crate::sample_groups::SampleToGroup>,
    /// `sgpd` boxes to emit for this track. Order is preserved.
    pub sgpd: Vec<crate::sample_groups::SampleGroupDescription>,
    /// `csgp` (CompactSampleToGroupBox, §8.9.5) boxes to emit for this
    /// track — the compact, bit-packed alternative to `sbgp` for tracks
    /// whose per-sample group membership is periodic. Order is preserved
    /// and they follow any `sbgp`. Use `csgp` *or* `sbgp` for a given
    /// `grouping_type`, never both.
    pub csgp: Vec<crate::sample_groups::CompactSampleToGroup>,
}

/// An explicit per-track edit list for the muxer (ISO/IEC 14496-12
/// §8.6.5–6).
///
/// When a [`Mp4MuxerOptions::track_edit_lists`] entry targets a
/// stream, the muxer emits that track's `edts/elst` from the given
/// entries verbatim (serialised through `demux::build_elst_box`, so
/// the §8.6.6.3 round-trip rules apply — `media_rate_integer` must be
/// 0 or 1, the final entry may not be an empty edit, `media_time`
/// may not sit below the `-1` empty-edit sentinel, and the entry list
/// may not be empty; violations fail at `open` time). An explicit
/// list *overrides* the automatic start-delay emission for that track
/// and is written even when [`Mp4MuxerOptions::write_edit_list`] is
/// `false` (the flag governs only the automatic behaviour).
///
/// This is the write-side dual of `Mp4Demuxer::edit_list`: a remuxer
/// carries a source's elst across by feeding the demuxer's slice
/// straight back in. Note the §8.6.6.3 unit split — each entry's
/// `segment_duration` is in the *movie* timescale (this muxer writes
/// movie timescale 1000) while `media_time` is in the track's media
/// timescale.
#[derive(Clone, Debug, Default)]
pub struct TrackEditList {
    /// Index into the muxer's `streams` slice (the stream slot that
    /// owns this edit list).
    pub stream_index: usize,
    /// The `elst` entries, emitted in order.
    pub entries: Vec<crate::demux::EditListEntry>,
}

/// Per-track CENC protection signalling for the muxer (ISO/IEC
/// 14496-12 §8.12 envelope + ISO/IEC 23001-7 §4.1 carriage).
///
/// When a [`Mp4MuxerOptions::track_protection`] entry targets a
/// stream, the muxer wraps that track's sample entry into its
/// protected form: the FourCC becomes `encv` / `enca` / `enct` /
/// `encs` (per the stream's media type) and a `sinf` box —
/// `frma(original_format)` + `schm(scheme_type, scheme_version)` +
/// `schi(tenc)` — is appended to the entry body, exactly the shape
/// this crate's demuxer unwraps back to the original codec id plus
/// `protection_scheme` / `cenc_default_*` options.
///
/// The muxer signals protection only — packet payloads are written
/// as handed in. The caller encrypts each sample first (e.g. via
/// `cenc_cipher::encrypt_sample_in_place` with a
/// `CencSchemeDecision` built from this same `(scheme_type, tenc)`
/// pair) and carries the per-sample IVs / subsample maps through its
/// own `senc` / `saiz` / `saio` channel.
#[derive(Clone, Debug)]
pub struct TrackProtection {
    /// Index into the muxer's `streams` slice (the stream to protect).
    pub stream_index: usize,
    /// §8.12.5 `scheme_type` FourCC — one of the ISO/IEC 23001-7 §10
    /// schemes (`cenc` / `cbc1` / `cens` / `cbcs`) or a private
    /// dialect FourCC (validated structurally only in that case).
    pub scheme_type: [u8; 4],
    /// §8.12.5 32-bit `scheme_version` word. Every ISO/IEC 23001-7
    /// edition to date uses `0x0001_0000` (the [`Default`] here).
    pub scheme_version: u32,
    /// Track-default encryption parameters written into `schi/tenc`
    /// (ISO/IEC 23001-7 §8.2). Must satisfy the same round-trip rules
    /// as `cenc::build_tenc_box` plus scheme coherence (a §10 scheme
    /// pins the `tenc` version; pattern schemes need a non-zero
    /// pattern pair) — violations fail at `open`.
    pub tenc: crate::cenc::TencBox,
}

/// Runtime options controlling how the MP4 muxer shapes its output.
///
/// Call [`Mp4MuxerOptions::default`] for the historical behavior of the
/// plain `"mp4"` registry entry (major=`mp42`, no faststart, no fragmentation).
#[derive(Clone, Debug)]
pub struct Mp4MuxerOptions {
    /// `ftyp` brand preset written at the beginning of the file.
    pub brand: BrandPreset,
    /// If `true`, rewrite the file at `write_trailer` time so `moov` precedes
    /// `mdat` ("faststart" / "web-optimized" layout). Requires a seekable
    /// output (which `WriteSeek` already provides). Mutually exclusive with
    /// `fragmented`.
    pub faststart: bool,
    /// If `Some(...)`, switch the muxer to fragmented-MP4 mode (DASH / HLS /
    /// Smooth-Streaming / CMAF). The first call to `write_header` emits
    /// `ftyp + moov` (with `mvex+trex` defaults, no media samples); each
    /// fragment cadence boundary emits `styp? + moof + mdat`. Mutually
    /// exclusive with `faststart`.
    pub fragmented: Option<FragmentedOptions>,
    /// If `true` (the default), the muxer emits a per-track `edts/elst`
    /// (EditBox/EditListBox, ISO/IEC 14496-12 §8.6.5–6) whenever a track's
    /// first packet has a positive presentation timestamp. The edit list
    /// carries a leading **empty edit** (`media_time = -1`) of that start
    /// delay followed by a normal `media_time = 0` segment for the track's
    /// duration, so a player offsets the track start instead of beginning
    /// at presentation time 0 (the §8.6.5 "An empty edit is used to offset
    /// the start time of a track" idiom).
    ///
    /// Tracks whose first PTS is zero (or absent) get no `edts` — the
    /// implicit one-to-one timeline mapping applies. Set this to `false`
    /// to suppress edit-list emission entirely.
    pub write_edit_list: bool,
    /// Per-track sample-group declarations (`sbgp` + `sgpd`, ISO/IEC
    /// 14496-12 §8.9.2 / §8.9.3). Empty by default — most muxed files
    /// don't need sample groups. When non-empty, each
    /// [`TrackSampleGroups`] entry's `sbgp` / `sgpd` boxes are emitted
    /// into the target track's `stbl` after the chunk-offset table.
    pub track_sample_groups: Vec<TrackSampleGroups>,
    /// Explicit per-track edit lists (`edts`/`elst`, ISO/IEC 14496-12
    /// §8.6.5–6). Empty by default — the automatic start-delay
    /// emission (see [`Self::write_edit_list`]) covers the common
    /// case. A [`TrackEditList`] entry overrides the automatic elst
    /// for its stream and is emitted even when `write_edit_list` is
    /// `false`. Validated at `open` through `demux::build_elst_box`'s
    /// §8.6.6.3 round-trip rules.
    pub track_edit_lists: Vec<TrackEditList>,
    /// Reserve a 64-bit `largesize` header for the `mdat` box so the
    /// media payload may exceed 4 GiB (ISO/IEC 14496-12 §4.2 extended
    /// size form: `size == 1` then an `unsigned int(64) largesize`).
    ///
    /// The plain 32-bit `mdat` header can only describe a box up to
    /// `u32::MAX` bytes; without this flag the muxer errors at
    /// `write_trailer` if the accumulated payload would overflow that.
    /// Because the direct-write path streams `mdat` to the output before
    /// the final size is known, the header form has to be chosen *up
    /// front* — so a producer that expects a >4 GiB `mdat` (long
    /// uncompressed captures, multi-hour high-bitrate masters) sets this
    /// to `true` to reserve the 16-byte largesize header. The 8 extra
    /// bytes are the only cost for files that stay under 4 GiB, so the
    /// default is `false` (compact 32-bit header, byte-identical to the
    /// historical output). `co64` chunk offsets are still chosen
    /// automatically when any chunk offset itself exceeds `u32::MAX`,
    /// independent of this flag.
    pub large_mdat: bool,
    /// Per-track CENC protection signalling (ISO/IEC 14496-12 §8.12 +
    /// ISO/IEC 23001-7). Empty by default. Each [`TrackProtection`]
    /// entry wraps the target stream's sample entry into its `enc*`
    /// protected form with a `sinf`(`frma`+`schm`+`schi`/`tenc`)
    /// envelope. See [`TrackProtection`] for the caller's encryption
    /// responsibilities.
    pub track_protection: Vec<TrackProtection>,
    /// `pssh` (ProtectionSystemSpecificHeaderBox, ISO/IEC 23001-7
    /// §8.1) boxes emitted at `moov` level, after the `trak` boxes —
    /// one per DRM system the content keys are provisioned for.
    /// Empty by default (no box). Serialised through
    /// `cenc::build_pssh_box`, so a record that would not round-trip
    /// (a v0 record carrying KIDs, oversize counts) fails at
    /// `write_trailer` (non-fragmented) / `write_header` (fragmented
    /// init segment) rather than emitting a malformed box.
    pub pssh: Vec<crate::cenc::PsshBox>,
}

impl Default for Mp4MuxerOptions {
    fn default() -> Self {
        Self {
            brand: BrandPreset::Mp4,
            faststart: false,
            fragmented: None,
            write_edit_list: true,
            track_sample_groups: Vec::new(),
            track_edit_lists: Vec::new(),
            large_mdat: false,
            track_protection: Vec::new(),
            pssh: Vec::new(),
        }
    }
}