edith_codecs
Clone
https://git.tahinli.com/Tahinli/edith_codecs.git
0 watching·0 forks·Rust·370.3 MiB·9b67700·Tahinli·3 days ago·4021 commits
| 1 | //! The writer: `ftyp`, then one `mdat` the samples stream into, then the `moov` |
| 2 | //! built from what was written. |
| 3 | |
| 4 | use std::io::{Read, Seek, SeekFrom, Write}; |
| 5 | |
| 6 | use ec_core::{ |
| 7 | CodecId, ContentLight, Error, Muxer, Packet, Result, Rounding, StreamInfo, TimeBase, |
| 8 | }; |
| 9 | |
| 10 | use crate::boxes::{close, full_head, leaf, open}; |
| 11 | use crate::esds::{Esds, object_type}; |
| 12 | |
| 13 | /// The clock the movie header counts in. Only `mvhd`/`tkhd` durations are in it; |
| 14 | /// every sample time is in its own track's timescale. |
| 15 | const MOVIE_TIMESCALE: u32 = 1_000; |
| 16 | |
| 17 | /// How much of the `mdat` is copied at a time when a faststart file is laid out. |
| 18 | const COPY_CHUNK: u64 = 8 << 20; |
| 19 | |
| 20 | /// One written sample, as the sample tables will state it. |
| 21 | struct Sample { |
| 22 | size: u32, |
| 23 | dts: i64, |
| 24 | cts: i64, |
| 25 | duration: u32, |
| 26 | sync: bool, |
| 27 | } |
| 28 | |
| 29 | /// One declared stream and everything written on it. |
| 30 | struct Track { |
| 31 | info: StreamInfo, |
| 32 | /// Ticks a second on this track: `time_base.den()`, so a `1001/24000` base |
| 33 | /// becomes a 24000 clock counting 1001 a frame — exact, never rounded. |
| 34 | timescale: u32, |
| 35 | time_base: TimeBase, |
| 36 | samples: Vec<Sample>, |
| 37 | /// `(file offset, sample count)` per chunk: a run of this track's samples |
| 38 | /// written back to back, which is what an interleaved file is made of. |
| 39 | chunks: Vec<(u64, u32)>, |
| 40 | /// Where the last sample of this track ended, to tell "same chunk" from "a |
| 41 | /// new one". |
| 42 | chunk_end: u64, |
| 43 | title: Option<String>, |
| 44 | /// An audio encoder's priming: samples it emits before the first audible |
| 45 | /// one (an AAC-LC encoder's 1024-sample delay), in this track's |
| 46 | /// timescale. Written the same way as a video track's reorder delay: an |
| 47 | /// `edts/elst` media_time shift, never a trim. |
| 48 | audio_delay: i64, |
| 49 | /// An explicit edit set by [`Mp4Muxer::set_edit`]: `(media_time, duration)` |
| 50 | /// in this track's timescale. When set it replaces the priming shift and |
| 51 | /// the track's presentation length, so the edit plays exactly this span. |
| 52 | edit: Option<(u32, u32)>, |
| 53 | /// Written as a `fiel` box on a video track. [`Some`]`(Progressive)` unless |
| 54 | /// [`Mp4Muxer::set_field_order`] says otherwise; [`None`] writes no box. |
| 55 | field_order: Option<ec_core::Interlace>, |
| 56 | /// Write a QuickTime `chan` channel-layout box in an audio sample entry |
| 57 | /// that would not otherwise carry one ([`Mp4Muxer::set_channel_layout_box`]). |
| 58 | chan: bool, |
| 59 | } |
| 60 | |
| 61 | /// An MP4 writer over anything seekable. |
| 62 | /// |
| 63 | /// **Layout: `mdat` first, `moov` last.** Samples are written the instant they |
| 64 | /// arrive, so muxing costs one pass and no temporary file, and the sample tables |
| 65 | /// — which cannot be written before the sizes they state are known — go at the |
| 66 | /// end. The cost is that a player streaming the file over HTTP has to reach the |
| 67 | /// end before it can start; [`Mp4Muxer::set_faststart`] moves the `moov` in |
| 68 | /// front instead, at the price of copying the `mdat` once more. |
| 69 | /// |
| 70 | /// Interleaving is the caller's: packets are written in the order they are |
| 71 | /// handed over, and the chunk table follows that order exactly. |
| 72 | pub struct Mp4Muxer<W> { |
| 73 | w: W, |
| 74 | tracks: Vec<Track>, |
| 75 | /// Current write offset. |
| 76 | pos: u64, |
| 77 | /// Offset of the `mdat` box header, patched with its real size at |
| 78 | /// [`Mp4Muxer::finish`]. |
| 79 | mdat_at: u64, |
| 80 | started: bool, |
| 81 | finished: bool, |
| 82 | title: Option<String>, |
| 83 | /// The `ftyp` brands a caller chose, as `(major, compatible)`. `None` is the |
| 84 | /// default: `isom` with the video codecs' own brands and `mp41`. |
| 85 | brands: Option<([u8; 4], Vec<[u8; 4]>)>, |
| 86 | /// Chapter marks as `(start in ns, title)`, sorted by start. Written as a |
| 87 | /// Nero `chpl` in `moov/udta` and as a QuickTime text track. |
| 88 | chapters: Vec<(u64, String)>, |
| 89 | /// Lay the `moov` in front of the `mdat`; see [`Mp4Muxer::set_faststart`]. |
| 90 | faststart: bool, |
| 91 | } |
| 92 | |
| 93 | /// The chapter text track as it is laid out in the file: its samples sit in the |
| 94 | /// `mdat`, one per chapter, after the media. |
| 95 | struct ChapterText { |
| 96 | /// The first chapter's start in movie milliseconds. The text track's media |
| 97 | /// time starts at zero, so an edit list shifts it to this point. |
| 98 | first_ms: i64, |
| 99 | /// The end of the film in movie milliseconds, which the last chapter runs to. |
| 100 | end_ms: i64, |
| 101 | /// `(duration in ms, sample size in bytes)` per chapter. |
| 102 | samples: Vec<(u32, u32)>, |
| 103 | /// File offset of the first sample; the samples are contiguous. |
| 104 | offset: u64, |
| 105 | } |
| 106 | |
| 107 | impl<W: Write + Seek> Mp4Muxer<W> { |
| 108 | /// A writer over `w`, which is positioned at its start. |
| 109 | pub fn new(w: W) -> Result<Mp4Muxer<W>> { |
| 110 | Self::build(w, None) |
| 111 | } |
| 112 | |
| 113 | /// A writer whose `ftyp` states `major` and then `compatible`, in that |
| 114 | /// order, instead of the default brands. An audio-only file names its own |
| 115 | /// kind here: `M4A ` for an `.m4a`, `isom` for an `.mp4` of sound. |
| 116 | pub fn with_brands(w: W, major: [u8; 4], compatible: &[[u8; 4]]) -> Result<Mp4Muxer<W>> { |
| 117 | Self::build(w, Some((major, compatible.to_vec()))) |
| 118 | } |
| 119 | |
| 120 | fn build(mut w: W, brands: Option<([u8; 4], Vec<[u8; 4]>)>) -> Result<Mp4Muxer<W>> { |
| 121 | let pos = w.seek(SeekFrom::Start(0))?; |
| 122 | Ok(Mp4Muxer { |
| 123 | w, |
| 124 | tracks: Vec::new(), |
| 125 | pos, |
| 126 | mdat_at: 0, |
| 127 | started: false, |
| 128 | finished: false, |
| 129 | title: None, |
| 130 | brands, |
| 131 | chapters: Vec::new(), |
| 132 | faststart: false, |
| 133 | }) |
| 134 | } |
| 135 | |
| 136 | /// Name the movie: a `moov/udta/name` box. |
| 137 | pub fn set_title(&mut self, title: impl Into<String>) { |
| 138 | self.title = Some(title.into()); |
| 139 | } |
| 140 | |
| 141 | /// Set the chapter marks: `(start in ns, title)` each. They are sorted by |
| 142 | /// start (stably, so equal starts keep the order given) and replace any set |
| 143 | /// before. The file gets both a Nero `chpl` box in `moov/udta` (version 1, |
| 144 | /// 100 ns units, titles cut to 255 bytes) and a QuickTime text track with one |
| 145 | /// sample per chapter, referenced from the first video track (or the first |
| 146 | /// audio track, else the first track). Each chapter runs to the next one's |
| 147 | /// start, and the last to the end of the film. An empty list writes neither. |
| 148 | /// |
| 149 | /// More than 255 chapters: the `chpl` box counts them in one byte, so it is left out |
| 150 | /// and the chapter text track, which has no such limit, carries all of them. |
| 151 | pub fn set_chapters(&mut self, chapters: &[(u64, String)]) -> Result<()> { |
| 152 | let mut sorted = chapters.to_vec(); |
| 153 | sorted.sort_by_key(|(start, _)| *start); |
| 154 | self.chapters = sorted; |
| 155 | Ok(()) |
| 156 | } |
| 157 | |
| 158 | /// Name one track: a `trak/udta/name` box, which is what an mp4 calls a |
| 159 | /// subtitle track in a player's menu. |
| 160 | pub fn set_track_title(&mut self, stream: u32, title: impl Into<String>) -> Result<()> { |
| 161 | let track = self |
| 162 | .tracks |
| 163 | .get_mut(stream as usize) |
| 164 | .ok_or_else(|| Error::corrupt(format!("mp4: no stream {stream} to name")))?; |
| 165 | track.title = Some(title.into()); |
| 166 | Ok(()) |
| 167 | } |
| 168 | |
| 169 | /// Say what a video stream's samples mean after the stream was declared. |
| 170 | /// |
| 171 | /// The `colr` box is part of the sample entry and the sample entry is |
| 172 | /// written at [`Muxer::finish`], so this may be said any time before then — |
| 173 | /// which is what a caller that learns the source's colour space after it has |
| 174 | /// opened the file needs. |
| 175 | pub fn set_color(&mut self, stream: u32, color: ec_core::ColorInfo) -> Result<()> { |
| 176 | let track = self |
| 177 | .tracks |
| 178 | .get_mut(stream as usize) |
| 179 | .ok_or_else(|| Error::corrupt(format!("mp4: no stream {stream} to colour")))?; |
| 180 | match &mut track.info.params.media { |
| 181 | ec_core::MediaParameters::Video(video) => video.color = color, |
| 182 | _ => { |
| 183 | return Err(Error::corrupt(format!( |
| 184 | "mp4: stream {stream} is not a video track" |
| 185 | ))); |
| 186 | } |
| 187 | } |
| 188 | Ok(()) |
| 189 | } |
| 190 | |
| 191 | /// State a video stream's HDR light levels after the stream was declared: |
| 192 | /// the `mdcv` (mastering display colour volume) and `clli` (content light |
| 193 | /// level) boxes of its sample entry, written at [`Muxer::finish`]. `mdcv` |
| 194 | /// is written when `light` has a mastering luminance or primaries (BT.2020 / |
| 195 | /// D65 where only the luminances are given), `clli` when it has MaxCLL or |
| 196 | /// MaxFALL. Units are those of [`ec_core::ContentLight`]: nits, with |
| 197 | /// chromaticities in increments of 0.00002. A track never told writes no |
| 198 | /// such box. |
| 199 | pub fn set_content_light(&mut self, stream: u32, light: ContentLight) -> Result<()> { |
| 200 | let track = self |
| 201 | .tracks |
| 202 | .get_mut(stream as usize) |
| 203 | .ok_or_else(|| Error::corrupt(format!("mp4: no stream {stream} to light")))?; |
| 204 | match &mut track.info.params.media { |
| 205 | ec_core::MediaParameters::Video(video) => video.light = light, |
| 206 | _ => { |
| 207 | return Err(Error::corrupt(format!( |
| 208 | "mp4: stream {stream} is not a video track" |
| 209 | ))); |
| 210 | } |
| 211 | } |
| 212 | Ok(()) |
| 213 | } |
| 214 | |
| 215 | /// Write a QuickTime `chan` channel-layout box in `stream`'s audio sample |
| 216 | /// entry (mono, stereo and 5.1 have one; other layouts write none). The |
| 217 | /// QuickTime PCM entries (`in24`, `in32`, `fl32`) always carry it, as |
| 218 | /// ffmpeg writes them; this adds it to the entries that otherwise do not, |
| 219 | /// such as `sowt`. Without this call those are unchanged. |
| 220 | pub fn set_channel_layout_box(&mut self, stream: u32, on: bool) -> Result<()> { |
| 221 | let track = self |
| 222 | .tracks |
| 223 | .get_mut(stream as usize) |
| 224 | .ok_or_else(|| Error::corrupt(format!("mp4: no stream {stream} to lay out")))?; |
| 225 | track.chan = on; |
| 226 | Ok(()) |
| 227 | } |
| 228 | |
| 229 | /// Say how a video stream's pictures are scanned: written as a `fiel` box |
| 230 | /// at [`Muxer::finish`]. Every video track is `Some(Progressive)` until |
| 231 | /// told otherwise; [`None`] writes no box (field order unknown). |
| 232 | pub fn set_field_order( |
| 233 | &mut self, |
| 234 | stream: u32, |
| 235 | order: Option<ec_core::Interlace>, |
| 236 | ) -> Result<()> { |
| 237 | let track = self |
| 238 | .tracks |
| 239 | .get_mut(stream as usize) |
| 240 | .ok_or_else(|| Error::corrupt(format!("mp4: no stream {stream} to scan")))?; |
| 241 | track.field_order = order; |
| 242 | Ok(()) |
| 243 | } |
| 244 | |
| 245 | /// Declare an audio track's encoder delay: `priming_samples` produced |
| 246 | /// before the first audible one, in the track's own sample rate (which is |
| 247 | /// its timescale, so this is a sample count with no conversion). Written |
| 248 | /// as an `edts/elst` media_time shift at [`Muxer::finish`] — the same |
| 249 | /// mechanism a reordered video track's `elst` uses, and the ISO |
| 250 | /// 14496-14 convention for AAC priming. |
| 251 | pub fn set_audio_delay(&mut self, stream: u32, priming_samples: u32) -> Result<()> { |
| 252 | let track = self |
| 253 | .tracks |
| 254 | .get_mut(stream as usize) |
| 255 | .ok_or_else(|| Error::corrupt(format!("mp4: no stream {stream} to delay")))?; |
| 256 | track.audio_delay = i64::from(priming_samples); |
| 257 | Ok(()) |
| 258 | } |
| 259 | |
| 260 | /// Play `stream` from `media_time` for `duration` ticks, and no further: the |
| 261 | /// audio edit is trimmed to a stated length rather than running to the end |
| 262 | /// of the samples written. Both are in the track's own timescale (for audio, |
| 263 | /// its sample rate), so `media_time` is the priming to skip and `duration` |
| 264 | /// the picture's length, with no conversion by the caller. |
| 265 | /// |
| 266 | /// Written at [`Muxer::finish`] as one `edts/elst` entry with its |
| 267 | /// `segment_duration` in the movie timescale (rounded up, as the movie |
| 268 | /// durations are), and the track's `tkhd` and the movie's `mvhd` durations |
| 269 | /// follow it. It replaces [`Mp4Muxer::set_audio_delay`] for this stream: the |
| 270 | /// `media_time` given is the shift. Without this call the output is unchanged. |
| 271 | pub fn set_edit(&mut self, stream: u32, media_time: u32, duration: u32) -> Result<()> { |
| 272 | let track = self |
| 273 | .tracks |
| 274 | .get_mut(stream as usize) |
| 275 | .ok_or_else(|| Error::corrupt(format!("mp4: no stream {stream} to edit")))?; |
| 276 | track.edit = Some((media_time, duration)); |
| 277 | Ok(()) |
| 278 | } |
| 279 | |
| 280 | /// Lay the file out `ftyp`, `moov`, `mdat` instead of `ftyp`, `mdat`, `moov`, |
| 281 | /// so a player can start before the end. Such a file is finished with |
| 282 | /// [`Mp4Muxer::finish_faststart`], which reads the `mdat` back to move it. |
| 283 | pub fn set_faststart(&mut self, on: bool) { |
| 284 | self.faststart = on; |
| 285 | } |
| 286 | |
| 287 | /// Take the writer back once the file is finished. |
| 288 | pub fn into_inner(self) -> W { |
| 289 | self.w |
| 290 | } |
| 291 | |
| 292 | fn start(&mut self) -> Result<()> { |
| 293 | if self.started { |
| 294 | return Ok(()); |
| 295 | } |
| 296 | self.started = true; |
| 297 | let mut head = Vec::with_capacity(64); |
| 298 | let at = open(&mut head, b"ftyp"); |
| 299 | match &self.brands { |
| 300 | Some((major, compatible)) => { |
| 301 | head.extend_from_slice(major); |
| 302 | head.extend_from_slice(&512u32.to_be_bytes()); |
| 303 | for brand in compatible { |
| 304 | head.extend_from_slice(brand); |
| 305 | } |
| 306 | } |
| 307 | None => { |
| 308 | head.extend_from_slice(b"isom"); |
| 309 | head.extend_from_slice(&512u32.to_be_bytes()); |
| 310 | head.extend_from_slice(b"isom"); |
| 311 | head.extend_from_slice(b"iso2"); |
| 312 | for track in &self.tracks { |
| 313 | if let Some(brand) = video_entry(track.info.params.codec) { |
| 314 | head.extend_from_slice(brand); |
| 315 | } |
| 316 | } |
| 317 | head.extend_from_slice(b"mp41"); |
| 318 | } |
| 319 | } |
| 320 | close(&mut head, at); |
| 321 | self.mdat_at = head.len() as u64; |
| 322 | // The 64-bit form of an `mdat` header, always: a two-hour 4K export goes |
| 323 | // past 4 GB and the placeholder cannot grow later without moving every |
| 324 | // sample in the file. |
| 325 | head.extend_from_slice(&1u32.to_be_bytes()); |
| 326 | head.extend_from_slice(b"mdat"); |
| 327 | head.extend_from_slice(&0u64.to_be_bytes()); |
| 328 | self.w.write_all(&head)?; |
| 329 | self.pos = head.len() as u64; |
| 330 | Ok(()) |
| 331 | } |
| 332 | |
| 333 | /// Sample durations, resolved: a packet that stated one keeps it, and one |
| 334 | /// that did not gets the step to the next sample — which is what the last |
| 335 | /// sample has no next for, so it repeats the step before it. |
| 336 | fn resolve_durations(track: &mut Track) { |
| 337 | for i in 0..track.samples.len() { |
| 338 | if track.samples[i].duration != 0 { |
| 339 | continue; |
| 340 | } |
| 341 | let step = match track.samples.get(i + 1) { |
| 342 | Some(next) => next.dts - track.samples[i].dts, |
| 343 | None => i |
| 344 | .checked_sub(1) |
| 345 | .map_or(0, |prev| i64::from(track.samples[prev].duration)), |
| 346 | }; |
| 347 | track.samples[i].duration = u32::try_from(step.max(0)).unwrap_or(0); |
| 348 | } |
| 349 | } |
| 350 | |
| 351 | /// The film's length in movie milliseconds: the longest track's presentation. |
| 352 | fn movie_duration(&self) -> i64 { |
| 353 | let movie_base = TimeBase::from_rate(MOVIE_TIMESCALE); |
| 354 | self.tracks |
| 355 | .iter() |
| 356 | .map(|t| presentation_movie_ticks(t, movie_base)) |
| 357 | .max() |
| 358 | .unwrap_or(0) |
| 359 | } |
| 360 | |
| 361 | /// The track a chapter text track is referenced from: the first video track, |
| 362 | /// else the first audio track, else the first track of any kind. |
| 363 | fn chapter_reference(&self) -> Option<usize> { |
| 364 | let is = |kind: ec_core::MediaType| { |
| 365 | self.tracks |
| 366 | .iter() |
| 367 | .position(|t| t.info.params.codec.media_type() == kind) |
| 368 | }; |
| 369 | is(ec_core::MediaType::Video) |
| 370 | .or_else(|| is(ec_core::MediaType::Audio)) |
| 371 | .or(match self.tracks.is_empty() { |
| 372 | true => None, |
| 373 | false => Some(0), |
| 374 | }) |
| 375 | } |
| 376 | |
| 377 | /// Lay the chapter samples down in the `mdat`, at the current write position: |
| 378 | /// each is a 16-bit length and the title's UTF-8 bytes, as QuickTime text |
| 379 | /// samples are. Their times come from the starts, rounded to milliseconds. |
| 380 | fn write_chapter_text(&mut self) -> Result<ChapterText> { |
| 381 | let starts: Vec<i64> = self |
| 382 | .chapters |
| 383 | .iter() |
| 384 | .map(|(ns, _)| (ns.saturating_add(500_000) / 1_000_000) as i64) |
| 385 | .collect(); |
| 386 | let first_ms = starts.first().copied().unwrap_or(0); |
| 387 | let end_ms = self |
| 388 | .movie_duration() |
| 389 | .max(starts.last().copied().unwrap_or(0)); |
| 390 | let offset = self.pos; |
| 391 | let mut payload = Vec::new(); |
| 392 | let mut samples = Vec::with_capacity(self.chapters.len()); |
| 393 | for (i, (_, title)) in self.chapters.iter().enumerate() { |
| 394 | let next = starts.get(i + 1).copied().unwrap_or(end_ms); |
| 395 | let mut duration = (next - starts[i]).max(0) as u32; |
| 396 | if i + 1 == starts.len() { |
| 397 | // Readers that end the last chapter at the text track's media duration |
| 398 | // (ffmpeg) do not count the leading empty edit, so the media is padded by |
| 399 | // the first chapter's start; the edit list below still plays only to the end. |
| 400 | duration += first_ms.max(0) as u32; |
| 401 | } |
| 402 | let text = clip(title, usize::from(u16::MAX)); |
| 403 | payload.extend_from_slice(&(text.len() as u16).to_be_bytes()); |
| 404 | payload.extend_from_slice(text.as_bytes()); |
| 405 | samples.push((duration, 2 + text.len() as u32)); |
| 406 | } |
| 407 | self.w.write_all(&payload)?; |
| 408 | self.pos += payload.len() as u64; |
| 409 | Ok(ChapterText { |
| 410 | first_ms, |
| 411 | end_ms, |
| 412 | samples, |
| 413 | offset, |
| 414 | }) |
| 415 | } |
| 416 | |
| 417 | /// Everything `finish` writes before the `moov`: the chapter text, the |
| 418 | /// durations, and the `mdat`'s real size. Returns the chapter text, if any. |
| 419 | fn seal_mdat(&mut self) -> Result<Option<ChapterText>> { |
| 420 | self.start()?; |
| 421 | for track in &mut self.tracks { |
| 422 | Mp4Muxer::<W>::resolve_durations(track); |
| 423 | } |
| 424 | // The chapter text samples are media, so they go in the mdat before its |
| 425 | // size is known. |
| 426 | let chapters = match self.chapters.is_empty() { |
| 427 | true => None, |
| 428 | false => Some(self.write_chapter_text()?), |
| 429 | }; |
| 430 | // The mdat's real size, into the 64-bit field left for it. |
| 431 | let mdat_len = self.pos - self.mdat_at; |
| 432 | self.w.seek(SeekFrom::Start(self.mdat_at + 8))?; |
| 433 | self.w.write_all(&mdat_len.to_be_bytes())?; |
| 434 | self.w.seek(SeekFrom::Start(self.pos))?; |
| 435 | Ok(chapters) |
| 436 | } |
| 437 | |
| 438 | /// The `moov` as bytes, its chunk offsets moved `shift` bytes further into |
| 439 | /// the file: 0 when it follows the `mdat`, its own length when it leads. |
| 440 | fn moov_bytes(&self, chapters: Option<&ChapterText>, shift: u64) -> Result<Vec<u8>> { |
| 441 | let mut moov = Vec::with_capacity(4096); |
| 442 | let at = open(&mut moov, b"moov"); |
| 443 | let duration = self.movie_duration().max(chapters.map_or(0, |c| c.end_ms)); |
| 444 | let chapter_id = chapters.map(|_| self.tracks.len() as u32 + 1); |
| 445 | let reference = self.chapter_reference(); |
| 446 | |
| 447 | let mvhd = open(&mut moov, b"mvhd"); |
| 448 | full_head(&mut moov, 0, 0); |
| 449 | moov.extend_from_slice(&0u32.to_be_bytes()); // creation |
| 450 | moov.extend_from_slice(&0u32.to_be_bytes()); // modification |
| 451 | moov.extend_from_slice(&MOVIE_TIMESCALE.to_be_bytes()); |
| 452 | moov.extend_from_slice(&(duration.max(0) as u32).to_be_bytes()); |
| 453 | moov.extend_from_slice(&0x0001_0000u32.to_be_bytes()); // rate 1.0 |
| 454 | moov.extend_from_slice(&0x0100u16.to_be_bytes()); // volume 1.0 |
| 455 | moov.extend_from_slice(&[0; 2 + 8]); |
| 456 | moov.extend_from_slice(&UNITY_MATRIX); |
| 457 | moov.extend_from_slice(&[0; 24]); // pre_defined |
| 458 | let next_id = chapter_id.unwrap_or(self.tracks.len() as u32) + 1; |
| 459 | moov.extend_from_slice(&next_id.to_be_bytes()); |
| 460 | close(&mut moov, mvhd); |
| 461 | |
| 462 | for i in 0..self.tracks.len() { |
| 463 | let chapter_ref = match reference == Some(i) { |
| 464 | true => chapter_id, |
| 465 | false => None, |
| 466 | }; |
| 467 | self.write_trak(&mut moov, i, duration, chapter_ref, shift)?; |
| 468 | } |
| 469 | if let (Some(text), Some(id)) = (chapters, chapter_id) { |
| 470 | write_chapter_trak(&mut moov, id, text, shift); |
| 471 | } |
| 472 | let chpl = (1..=255).contains(&self.chapters.len()); |
| 473 | if self.title.is_some() || chpl { |
| 474 | let udta = open(&mut moov, b"udta"); |
| 475 | if let Some(title) = &self.title { |
| 476 | leaf(&mut moov, b"name", title.as_bytes()); |
| 477 | } |
| 478 | if chpl { |
| 479 | write_chpl(&mut moov, &self.chapters); |
| 480 | } |
| 481 | close(&mut moov, udta); |
| 482 | } |
| 483 | close(&mut moov, at); |
| 484 | Ok(moov) |
| 485 | } |
| 486 | |
| 487 | fn write_moov(&mut self, chapters: Option<&ChapterText>) -> Result<()> { |
| 488 | let moov = self.moov_bytes(chapters, 0)?; |
| 489 | self.w.write_all(&moov)?; |
| 490 | self.pos += moov.len() as u64; |
| 491 | Ok(()) |
| 492 | } |
| 493 | |
| 494 | /// One `trak`. `chapter_ref` is the id of the chapter text track this track |
| 495 | /// points at with a `tref/chap`, if it is the one the chapters hang off. |
| 496 | fn write_trak( |
| 497 | &self, |
| 498 | out: &mut Vec<u8>, |
| 499 | i: usize, |
| 500 | movie_duration: i64, |
| 501 | chapter_ref: Option<u32>, |
| 502 | shift: u64, |
| 503 | ) -> Result<()> { |
| 504 | let track = &self.tracks[i]; |
| 505 | let codec = track.info.params.codec; |
| 506 | let at = open(out, b"trak"); |
| 507 | |
| 508 | let tkhd = open(out, b"tkhd"); |
| 509 | full_head(out, 0, 0x7); // enabled, in movie, in preview |
| 510 | out.extend_from_slice(&0u32.to_be_bytes()); |
| 511 | out.extend_from_slice(&0u32.to_be_bytes()); |
| 512 | out.extend_from_slice(&(i as u32 + 1).to_be_bytes()); // track_ID |
| 513 | out.extend_from_slice(&0u32.to_be_bytes()); |
| 514 | let tkhd_duration = match track.edit { |
| 515 | Some(_) => presentation_movie_ticks(track, TimeBase::from_rate(MOVIE_TIMESCALE)), |
| 516 | None => movie_duration, |
| 517 | }; |
| 518 | out.extend_from_slice(&(tkhd_duration.max(0) as u32).to_be_bytes()); |
| 519 | out.extend_from_slice(&[0; 8]); |
| 520 | out.extend_from_slice(&0u16.to_be_bytes()); // layer |
| 521 | out.extend_from_slice(&0u16.to_be_bytes()); // alternate group |
| 522 | let volume: u16 = match codec.media_type() { |
| 523 | ec_core::MediaType::Audio => 0x0100, |
| 524 | _ => 0, |
| 525 | }; |
| 526 | out.extend_from_slice(&volume.to_be_bytes()); |
| 527 | out.extend_from_slice(&0u16.to_be_bytes()); |
| 528 | out.extend_from_slice(&UNITY_MATRIX); |
| 529 | let (width, height) = match track.info.params.video() { |
| 530 | Some(v) => (v.width, v.height), |
| 531 | None => (0, 0), |
| 532 | }; |
| 533 | out.extend_from_slice(&(width << 16).to_be_bytes()); |
| 534 | out.extend_from_slice(&(height << 16).to_be_bytes()); |
| 535 | close(out, tkhd); |
| 536 | |
| 537 | if let Some(id) = chapter_ref { |
| 538 | let tref = open(out, b"tref"); |
| 539 | let chap = open(out, b"chap"); |
| 540 | out.extend_from_slice(&id.to_be_bytes()); |
| 541 | close(out, chap); |
| 542 | close(out, tref); |
| 543 | } |
| 544 | |
| 545 | // An `elst`, where the first picture is not the first *decoded* one, or |
| 546 | // an audio track's encoder primed samples ahead of the first audible |
| 547 | // one (`set_audio_delay`): a reordered stream's earliest composition |
| 548 | // time is the reorder delay, and without an edit saying so every |
| 549 | // player starts the track that much late. This is where a demuxer's |
| 550 | // `media_time` comes from, and it is a shift, never a trim. |
| 551 | if let Some((media_time, _)) = track.edit { |
| 552 | let edts = open(out, b"edts"); |
| 553 | let elst = open(out, b"elst"); |
| 554 | full_head(out, 0, 0); |
| 555 | out.extend_from_slice(&1u32.to_be_bytes()); |
| 556 | let movie_base = TimeBase::from_rate(MOVIE_TIMESCALE); |
| 557 | let segment = presentation_movie_ticks(track, movie_base); |
| 558 | out.extend_from_slice(&(segment.max(0) as u32).to_be_bytes()); |
| 559 | out.extend_from_slice(&media_time.to_be_bytes()); |
| 560 | out.extend_from_slice(&0x0001_0000u32.to_be_bytes()); // media rate 1.0 |
| 561 | close(out, elst); |
| 562 | close(out, edts); |
| 563 | } |
| 564 | let priming = presentation_start(track) |
| 565 | .max(track.audio_delay) |
| 566 | .max(opus_pre_skip(track)); |
| 567 | if track.edit.is_none() && priming > 0 { |
| 568 | let edts = open(out, b"edts"); |
| 569 | let elst = open(out, b"elst"); |
| 570 | full_head(out, 0, 0); |
| 571 | out.extend_from_slice(&1u32.to_be_bytes()); |
| 572 | let movie_base = TimeBase::from_rate(MOVIE_TIMESCALE); |
| 573 | let segment = |
| 574 | track |
| 575 | .time_base |
| 576 | .rescale(track_ticks(track) - priming, movie_base, Rounding::Up); |
| 577 | out.extend_from_slice(&(segment.max(0) as u32).to_be_bytes()); |
| 578 | out.extend_from_slice(&(priming as u32).to_be_bytes()); |
| 579 | out.extend_from_slice(&0x0001_0000u32.to_be_bytes()); // media rate 1.0 |
| 580 | close(out, elst); |
| 581 | close(out, edts); |
| 582 | } |
| 583 | |
| 584 | let mdia = open(out, b"mdia"); |
| 585 | let mdhd = open(out, b"mdhd"); |
| 586 | full_head(out, 0, 0); |
| 587 | out.extend_from_slice(&0u32.to_be_bytes()); |
| 588 | out.extend_from_slice(&0u32.to_be_bytes()); |
| 589 | out.extend_from_slice(&track.timescale.to_be_bytes()); |
| 590 | out.extend_from_slice(&(track_ticks(track).max(0) as u32).to_be_bytes()); |
| 591 | out.extend_from_slice(&pack_language(track.info.language.as_deref()).to_be_bytes()); |
| 592 | out.extend_from_slice(&0u16.to_be_bytes()); // pre_defined |
| 593 | close(out, mdhd); |
| 594 | |
| 595 | let (handler, handler_name) = match codec.media_type() { |
| 596 | ec_core::MediaType::Video => (b"vide", "VideoHandler"), |
| 597 | ec_core::MediaType::Audio => (b"soun", "SoundHandler"), |
| 598 | ec_core::MediaType::Subtitle => (b"sbtl", "SubtitleHandler"), |
| 599 | }; |
| 600 | let hdlr = open(out, b"hdlr"); |
| 601 | full_head(out, 0, 0); |
| 602 | out.extend_from_slice(&0u32.to_be_bytes()); // pre_defined |
| 603 | out.extend_from_slice(handler); |
| 604 | out.extend_from_slice(&[0; 12]); // reserved |
| 605 | out.extend_from_slice(handler_name.as_bytes()); |
| 606 | out.push(0); |
| 607 | close(out, hdlr); |
| 608 | |
| 609 | let minf = open(out, b"minf"); |
| 610 | match codec.media_type() { |
| 611 | ec_core::MediaType::Video => { |
| 612 | let vmhd = open(out, b"vmhd"); |
| 613 | full_head(out, 0, 1); |
| 614 | out.extend_from_slice(&[0; 8]); // graphicsmode + opcolor |
| 615 | close(out, vmhd); |
| 616 | } |
| 617 | ec_core::MediaType::Audio => { |
| 618 | let smhd = open(out, b"smhd"); |
| 619 | full_head(out, 0, 0); |
| 620 | out.extend_from_slice(&[0; 4]); // balance + reserved |
| 621 | close(out, smhd); |
| 622 | } |
| 623 | ec_core::MediaType::Subtitle => { |
| 624 | let nmhd = open(out, b"nmhd"); |
| 625 | full_head(out, 0, 0); |
| 626 | close(out, nmhd); |
| 627 | } |
| 628 | } |
| 629 | let dinf = open(out, b"dinf"); |
| 630 | let dref = open(out, b"dref"); |
| 631 | full_head(out, 0, 0); |
| 632 | out.extend_from_slice(&1u32.to_be_bytes()); |
| 633 | let url = open(out, b"url "); |
| 634 | full_head(out, 0, 1); // flag 1: the media is in this very file |
| 635 | close(out, url); |
| 636 | close(out, dref); |
| 637 | close(out, dinf); |
| 638 | |
| 639 | let stbl = open(out, b"stbl"); |
| 640 | let stsd = open(out, b"stsd"); |
| 641 | full_head(out, 0, 0); |
| 642 | out.extend_from_slice(&1u32.to_be_bytes()); |
| 643 | sample_entry(out, &track.info, track.field_order, track.chan)?; |
| 644 | close(out, stsd); |
| 645 | sample_tables(out, track, shift); |
| 646 | close(out, stbl); |
| 647 | close(out, minf); |
| 648 | close(out, mdia); |
| 649 | |
| 650 | if let Some(title) = &track.title { |
| 651 | let udta = open(out, b"udta"); |
| 652 | leaf(out, b"name", title.as_bytes()); |
| 653 | close(out, udta); |
| 654 | } |
| 655 | close(out, at); |
| 656 | Ok(()) |
| 657 | } |
| 658 | } |
| 659 | |
| 660 | impl<W: Write + Seek + Send> Muxer for Mp4Muxer<W> { |
| 661 | /// Declare a stream — **at any point before [`Muxer::finish`]**, which is |
| 662 | /// more than the trait promises. Samples are written where they arrive and |
| 663 | /// the chunk table follows, so a track declared after the picture is |
| 664 | /// already in the `mdat` costs nothing: its `trak` is built at the end with |
| 665 | /// every other. That is what lets an export mix and encode its sound *while* |
| 666 | /// it writes the picture, and add its subtitles once the film's length is |
| 667 | /// known. |
| 668 | fn add_stream(&mut self, info: StreamInfo) -> Result<u32> { |
| 669 | let timescale = u32::try_from(info.time_base.den()).map_err(|_| { |
| 670 | Error::corrupt(format!( |
| 671 | "mp4: a time base of 1/{} does not fit a 32-bit timescale", |
| 672 | info.time_base.den() |
| 673 | )) |
| 674 | })?; |
| 675 | if timescale == 0 { |
| 676 | return Err(Error::corrupt("mp4: a stream with a zero timescale")); |
| 677 | } |
| 678 | let index = self.tracks.len() as u32; |
| 679 | self.tracks.push(Track { |
| 680 | info, |
| 681 | timescale, |
| 682 | time_base: TimeBase::from_rate(timescale), |
| 683 | samples: Vec::new(), |
| 684 | chunks: Vec::new(), |
| 685 | chunk_end: u64::MAX, |
| 686 | title: None, |
| 687 | audio_delay: 0, |
| 688 | edit: None, |
| 689 | field_order: Some(ec_core::Interlace::Progressive), |
| 690 | chan: false, |
| 691 | }); |
| 692 | Ok(index) |
| 693 | } |
| 694 | |
| 695 | fn write_packet(&mut self, packet: &Packet) -> Result<()> { |
| 696 | self.start()?; |
| 697 | let pos = self.pos; |
| 698 | let track = self |
| 699 | .tracks |
| 700 | .get_mut(packet.stream as usize) |
| 701 | .ok_or_else(|| Error::corrupt(format!("mp4: no stream {}", packet.stream)))?; |
| 702 | let to = track.time_base; |
| 703 | let at = |ticks: i64| packet.time_base.rescale(ticks, to, Rounding::Nearest); |
| 704 | let dts = match (packet.dts, packet.pts) { |
| 705 | (Some(dts), _) => at(dts), |
| 706 | (None, Some(pts)) => at(pts), |
| 707 | // A stream that states no time at all is laid end to end, which is |
| 708 | // what a constant-rate audio track is anyway. |
| 709 | (None, None) => track |
| 710 | .samples |
| 711 | .last() |
| 712 | .map_or(0, |s| s.dts + i64::from(s.duration)), |
| 713 | }; |
| 714 | let cts = packet.pts.map_or(dts, at); |
| 715 | let size = u32::try_from(packet.data.len()) |
| 716 | .map_err(|_| Error::corrupt("mp4: a sample over 4 GB"))?; |
| 717 | track.samples.push(Sample { |
| 718 | size, |
| 719 | dts, |
| 720 | cts, |
| 721 | duration: packet.duration.map_or(0, |d| at(d).max(0) as u32), |
| 722 | sync: packet.flags.keyframe, |
| 723 | }); |
| 724 | match track.chunk_end == pos { |
| 725 | true => { |
| 726 | if let Some(chunk) = track.chunks.last_mut() { |
| 727 | chunk.1 += 1; |
| 728 | } |
| 729 | } |
| 730 | false => track.chunks.push((pos, 1)), |
| 731 | } |
| 732 | track.chunk_end = pos + u64::from(size); |
| 733 | self.w.write_all(&packet.data)?; |
| 734 | self.pos = pos + u64::from(size); |
| 735 | Ok(()) |
| 736 | } |
| 737 | |
| 738 | fn finish(&mut self) -> Result<()> { |
| 739 | if self.finished { |
| 740 | return Ok(()); |
| 741 | } |
| 742 | if self.faststart { |
| 743 | return Err(Error::unsupported( |
| 744 | "mp4 faststart", |
| 745 | "finish it with finish_faststart, which reads the mdat back", |
| 746 | )); |
| 747 | } |
| 748 | self.finished = true; |
| 749 | let chapters = self.seal_mdat()?; |
| 750 | self.write_moov(chapters.as_ref())?; |
| 751 | self.w.flush()?; |
| 752 | Ok(()) |
| 753 | } |
| 754 | } |
| 755 | |
| 756 | impl<W: Read + Write + Seek + Send> Mp4Muxer<W> { |
| 757 | /// Finish a faststart file: `ftyp`, `moov`, `mdat`. The `mdat` is copied |
| 758 | /// `moov`-length bytes further on, from the end backwards, then the `moov` |
| 759 | /// goes where the `mdat` was. |
| 760 | pub fn finish_faststart(mut self) -> Result<W> { |
| 761 | if self.finished { |
| 762 | return Ok(self.w); |
| 763 | } |
| 764 | self.finished = true; |
| 765 | let chapters = self.seal_mdat()?; |
| 766 | let moov = self.faststart_moov(chapters.as_ref())?; |
| 767 | let shift = moov.len() as u64; |
| 768 | self.move_mdat(shift)?; |
| 769 | self.w.seek(SeekFrom::Start(self.mdat_at))?; |
| 770 | self.w.write_all(&moov)?; |
| 771 | self.w.flush()?; |
| 772 | Ok(self.w) |
| 773 | } |
| 774 | |
| 775 | /// The `moov` whose offsets are shifted by its own length. The length can |
| 776 | /// change with the shift (a `stco` becoming a `co64`), so this repeats until |
| 777 | /// it is stable; the length only grows, so it does. |
| 778 | fn faststart_moov(&self, chapters: Option<&ChapterText>) -> Result<Vec<u8>> { |
| 779 | let mut moov = self.moov_bytes(chapters, 0)?; |
| 780 | loop { |
| 781 | let shift = moov.len() as u64; |
| 782 | let next = self.moov_bytes(chapters, shift)?; |
| 783 | if next.len() as u64 == shift { |
| 784 | return Ok(next); |
| 785 | } |
| 786 | moov = next; |
| 787 | } |
| 788 | } |
| 789 | |
| 790 | /// Move the `mdat` (from its header to the end of the file) `shift` bytes on. |
| 791 | /// Destination is above source, so chunks are copied from the end down: a |
| 792 | /// chunk's destination only reaches bytes already read or already moved. |
| 793 | fn move_mdat(&mut self, shift: u64) -> Result<()> { |
| 794 | let start = self.mdat_at; |
| 795 | let end = self.pos; |
| 796 | let mut buf = vec![0u8; (end - start).min(COPY_CHUNK) as usize]; |
| 797 | let mut hi = end; |
| 798 | while hi > start { |
| 799 | let lo = hi.saturating_sub(COPY_CHUNK).max(start); |
| 800 | let len = (hi - lo) as usize; |
| 801 | self.w.seek(SeekFrom::Start(lo))?; |
| 802 | self.w.read_exact(&mut buf[..len])?; |
| 803 | self.w.seek(SeekFrom::Start(lo + shift))?; |
| 804 | self.w.write_all(&buf[..len])?; |
| 805 | hi = lo; |
| 806 | } |
| 807 | Ok(()) |
| 808 | } |
| 809 | } |
| 810 | |
| 811 | /// The QuickTime chapter text track: one `text` sample per chapter, in the movie |
| 812 | /// clock (milliseconds), with a `co64` offset so it stays right past 4 GB. It is |
| 813 | /// disabled, as a chapter track is in a QuickTime file, and its `edts` puts the |
| 814 | /// first chapter at its own start when that is not zero. |
| 815 | fn write_chapter_trak(out: &mut Vec<u8>, id: u32, chap: &ChapterText, shift: u64) { |
| 816 | let at = open(out, b"trak"); |
| 817 | |
| 818 | let tkhd = open(out, b"tkhd"); |
| 819 | full_head(out, 0, 0); // not enabled, not in the movie: a reference target |
| 820 | out.extend_from_slice(&[0; 8]); |
| 821 | out.extend_from_slice(&id.to_be_bytes()); |
| 822 | out.extend_from_slice(&0u32.to_be_bytes()); |
| 823 | out.extend_from_slice(&(chap.end_ms.max(0) as u32).to_be_bytes()); |
| 824 | out.extend_from_slice(&[0; 8]); |
| 825 | out.extend_from_slice(&0u16.to_be_bytes()); // layer |
| 826 | out.extend_from_slice(&0u16.to_be_bytes()); // alternate group |
| 827 | out.extend_from_slice(&0u16.to_be_bytes()); // volume |
| 828 | out.extend_from_slice(&0u16.to_be_bytes()); |
| 829 | out.extend_from_slice(&UNITY_MATRIX); |
| 830 | out.extend_from_slice(&[0; 8]); // width, height |
| 831 | close(out, tkhd); |
| 832 | |
| 833 | if chap.first_ms > 0 { |
| 834 | let edts = open(out, b"edts"); |
| 835 | let elst = open(out, b"elst"); |
| 836 | full_head(out, 0, 0); |
| 837 | out.extend_from_slice(&2u32.to_be_bytes()); |
| 838 | // An empty edit: the chapter track is silent until the first chapter. |
| 839 | out.extend_from_slice(&(chap.first_ms as u32).to_be_bytes()); |
| 840 | out.extend_from_slice(&u32::MAX.to_be_bytes()); // media_time -1 |
| 841 | out.extend_from_slice(&0x0001_0000u32.to_be_bytes()); |
| 842 | // The chapters themselves, from media time zero. |
| 843 | let length = (chap.end_ms - chap.first_ms).max(0) as u32; |
| 844 | out.extend_from_slice(&length.to_be_bytes()); |
| 845 | out.extend_from_slice(&0u32.to_be_bytes()); |
| 846 | out.extend_from_slice(&0x0001_0000u32.to_be_bytes()); |
| 847 | close(out, elst); |
| 848 | close(out, edts); |
| 849 | } |
| 850 | |
| 851 | let mdia = open(out, b"mdia"); |
| 852 | let mdhd = open(out, b"mdhd"); |
| 853 | full_head(out, 0, 0); |
| 854 | out.extend_from_slice(&0u32.to_be_bytes()); |
| 855 | out.extend_from_slice(&0u32.to_be_bytes()); |
| 856 | out.extend_from_slice(&MOVIE_TIMESCALE.to_be_bytes()); |
| 857 | let total: u64 = chap.samples.iter().map(|(d, _)| u64::from(*d)).sum(); |
| 858 | out.extend_from_slice(&(total as u32).to_be_bytes()); |
| 859 | out.extend_from_slice(&pack_language(None).to_be_bytes()); |
| 860 | out.extend_from_slice(&0u16.to_be_bytes()); |
| 861 | close(out, mdhd); |
| 862 | |
| 863 | let hdlr = open(out, b"hdlr"); |
| 864 | full_head(out, 0, 0); |
| 865 | out.extend_from_slice(&0u32.to_be_bytes()); |
| 866 | out.extend_from_slice(b"text"); |
| 867 | out.extend_from_slice(&[0; 12]); |
| 868 | out.extend_from_slice(b"ChapterHandler"); |
| 869 | out.push(0); |
| 870 | close(out, hdlr); |
| 871 | |
| 872 | let minf = open(out, b"minf"); |
| 873 | let nmhd = open(out, b"nmhd"); |
| 874 | full_head(out, 0, 0); |
| 875 | close(out, nmhd); |
| 876 | let dinf = open(out, b"dinf"); |
| 877 | let dref = open(out, b"dref"); |
| 878 | full_head(out, 0, 0); |
| 879 | out.extend_from_slice(&1u32.to_be_bytes()); |
| 880 | let url = open(out, b"url "); |
| 881 | full_head(out, 0, 1); |
| 882 | close(out, url); |
| 883 | close(out, dref); |
| 884 | close(out, dinf); |
| 885 | |
| 886 | let stbl = open(out, b"stbl"); |
| 887 | let stsd = open(out, b"stsd"); |
| 888 | full_head(out, 0, 0); |
| 889 | out.extend_from_slice(&1u32.to_be_bytes()); |
| 890 | // A QuickTime `text` sample description with the defaults: left-justified, |
| 891 | // white, no font name. The samples carry only the title. |
| 892 | let text = open(out, b"text"); |
| 893 | out.extend_from_slice(&[0; 6]); |
| 894 | out.extend_from_slice(&1u16.to_be_bytes()); // data_reference_index |
| 895 | out.extend_from_slice(&[0; 4 + 4 + 6 + 8 + 8]); // flags, justification, colours, box |
| 896 | out.extend_from_slice(&[0; 2 + 2 + 1 + 2]); // font id, face, reserved |
| 897 | for _ in 0..3 { |
| 898 | out.extend_from_slice(&0xFFFFu16.to_be_bytes()); // foreground: white |
| 899 | } |
| 900 | out.push(0); // empty font name |
| 901 | close(out, text); |
| 902 | close(out, stsd); |
| 903 | |
| 904 | let stts = open(out, b"stts"); |
| 905 | full_head(out, 0, 0); |
| 906 | out.extend_from_slice(&(chap.samples.len() as u32).to_be_bytes()); |
| 907 | for (duration, _) in &chap.samples { |
| 908 | out.extend_from_slice(&1u32.to_be_bytes()); |
| 909 | out.extend_from_slice(&duration.to_be_bytes()); |
| 910 | } |
| 911 | close(out, stts); |
| 912 | |
| 913 | let stsc = open(out, b"stsc"); |
| 914 | full_head(out, 0, 0); |
| 915 | out.extend_from_slice(&1u32.to_be_bytes()); |
| 916 | out.extend_from_slice(&1u32.to_be_bytes()); // first chunk |
| 917 | out.extend_from_slice(&(chap.samples.len() as u32).to_be_bytes()); |
| 918 | out.extend_from_slice(&1u32.to_be_bytes()); // description index |
| 919 | close(out, stsc); |
| 920 | |
| 921 | let stsz = open(out, b"stsz"); |
| 922 | full_head(out, 0, 0); |
| 923 | out.extend_from_slice(&0u32.to_be_bytes()); // sizes differ, so none is common |
| 924 | out.extend_from_slice(&(chap.samples.len() as u32).to_be_bytes()); |
| 925 | for (_, size) in &chap.samples { |
| 926 | out.extend_from_slice(&size.to_be_bytes()); |
| 927 | } |
| 928 | close(out, stsz); |
| 929 | |
| 930 | let co64 = open(out, b"co64"); |
| 931 | full_head(out, 0, 0); |
| 932 | out.extend_from_slice(&1u32.to_be_bytes()); |
| 933 | out.extend_from_slice(&(chap.offset + shift).to_be_bytes()); |
| 934 | close(out, co64); |
| 935 | close(out, stbl); |
| 936 | close(out, minf); |
| 937 | close(out, mdia); |
| 938 | close(out, at); |
| 939 | } |
| 940 | |
| 941 | /// The Nero `chpl` box in `moov/udta`: version 1 (its 4 extra bytes are |
| 942 | /// reserved), start times in 100 ns units, and titles cut to 255 bytes. Written |
| 943 | /// only for 1 to 255 chapters: the count is one byte. |
| 944 | fn write_chpl(out: &mut Vec<u8>, chapters: &[(u64, String)]) { |
| 945 | let chpl = open(out, b"chpl"); |
| 946 | full_head(out, 1, 0); |
| 947 | out.extend_from_slice(&0u32.to_be_bytes()); |
| 948 | out.push(chapters.len() as u8); |
| 949 | for (start_ns, title) in chapters { |
| 950 | out.extend_from_slice(&(start_ns / 100).to_be_bytes()); |
| 951 | let text = clip(title, usize::from(u8::MAX)); |
| 952 | out.push(text.len() as u8); |
| 953 | out.extend_from_slice(text.as_bytes()); |
| 954 | } |
| 955 | close(out, chpl); |
| 956 | } |
| 957 | |
| 958 | /// `title` cut to at most `max` bytes, on a character boundary. |
| 959 | fn clip(title: &str, max: usize) -> &str { |
| 960 | if title.len() <= max { |
| 961 | return title; |
| 962 | } |
| 963 | let mut end = max; |
| 964 | while !title.is_char_boundary(end) { |
| 965 | end -= 1; |
| 966 | } |
| 967 | &title[..end] |
| 968 | } |
| 969 | |
| 970 | /// A track's presentation length in movie-timescale ticks: the explicit edit's |
| 971 | /// duration when one was set, else the whole track. |
| 972 | fn presentation_movie_ticks(track: &Track, movie_base: TimeBase) -> i64 { |
| 973 | match track.edit { |
| 974 | Some((_, duration)) => { |
| 975 | track |
| 976 | .time_base |
| 977 | .rescale(i64::from(duration), movie_base, Rounding::Up) |
| 978 | } |
| 979 | None => track |
| 980 | .time_base |
| 981 | .rescale(track_ticks(track), movie_base, Rounding::Up), |
| 982 | } |
| 983 | } |
| 984 | |
| 985 | /// Total media ticks of a track: from the first sample's decode time to the latest |
| 986 | /// end of any sample, in presentation or decode time. A span rather than an |
| 987 | /// endpoint, because a track handed over with an edit list already applied starts |
| 988 | /// at a negative decode time and its duration is still the whole of it. The |
| 989 | /// presentation end is not always the last decode end: a reordered stream's last |
| 990 | /// picture is shown a reorder delay after its decode time, and the `elst` that |
| 991 | /// starts the picture at its priming must span to there or the track ends early. |
| 992 | fn track_ticks(track: &Track) -> i64 { |
| 993 | let first = track.samples.first().map_or(0, |s| s.dts); |
| 994 | track |
| 995 | .samples |
| 996 | .iter() |
| 997 | .map(|s| { |
| 998 | let end = i64::from(s.duration); |
| 999 | (s.dts + end).max(s.cts + end) - first |
| 1000 | }) |
| 1001 | .max() |
| 1002 | .unwrap_or(0) |
| 1003 | } |
| 1004 | |
| 1005 | /// Where the first *picture* is on the written timeline: decode times start at |
| 1006 | /// zero in the file (`stts` states durations, not instants), so this is the |
| 1007 | /// smallest composition offset — the reorder delay of a stream with B-frames and |
| 1008 | /// zero for everything else. |
| 1009 | fn presentation_start(track: &Track) -> i64 { |
| 1010 | let first = track.samples.first().map_or(0, |s| s.dts); |
| 1011 | track |
| 1012 | .samples |
| 1013 | .iter() |
| 1014 | .map(|s| s.cts - first) |
| 1015 | .min() |
| 1016 | .unwrap_or(0) |
| 1017 | } |
| 1018 | |
| 1019 | /// An Opus track's pre-skip, in its own 48 kHz clock, from the `OpusHead` it |
| 1020 | /// carries (bytes 10 and 11, little-endian). The Opus-in-ISOBMFF convention states |
| 1021 | /// it as the `elst` `media_time`, so a remux of an Opus file keeps its shift; 0 |
| 1022 | /// for every other track, or where the head is too short to say. |
| 1023 | fn opus_pre_skip(track: &Track) -> i64 { |
| 1024 | if track.info.params.codec != CodecId::Opus { |
| 1025 | return 0; |
| 1026 | } |
| 1027 | let Some(head) = track.info.params.extradata.as_deref() else { |
| 1028 | return 0; |
| 1029 | }; |
| 1030 | // `dOps` carries it big-endian at bytes 2 and 3; an `OpusHead` little-endian at 10. |
| 1031 | match head.starts_with(b"OpusHead") { |
| 1032 | true => match head.get(10..12) { |
| 1033 | Some(&[lo, hi]) => i64::from(u16::from_le_bytes([lo, hi])), |
| 1034 | _ => 0, |
| 1035 | }, |
| 1036 | false => match head.get(2..4) { |
| 1037 | Some(&[hi, lo]) => i64::from(u16::from_be_bytes([hi, lo])), |
| 1038 | _ => 0, |
| 1039 | }, |
| 1040 | } |
| 1041 | } |
| 1042 | |
| 1043 | /// The tables of a QuickTime PCM track the way QuickTime and ffmpeg lay them |
| 1044 | /// out: a *sample* is one frame (`frame_bytes`, one `stts` tick), and a chunk |
| 1045 | /// holds as many samples as the packets written into it had frames. |
| 1046 | fn pcm_tables(out: &mut Vec<u8>, track: &Track, frame_bytes: u32, shift: u64) { |
| 1047 | let frame_bytes = frame_bytes.max(1); |
| 1048 | let total: u64 = track |
| 1049 | .samples |
| 1050 | .iter() |
| 1051 | .map(|s| u64::from(s.size / frame_bytes)) |
| 1052 | .sum(); |
| 1053 | let stts = open(out, b"stts"); |
| 1054 | full_head(out, 0, 0); |
| 1055 | out.extend_from_slice(&u32::from(total > 0).to_be_bytes()); |
| 1056 | if total > 0 { |
| 1057 | out.extend_from_slice(&(total as u32).to_be_bytes()); |
| 1058 | out.extend_from_slice(&1u32.to_be_bytes()); |
| 1059 | } |
| 1060 | close(out, stts); |
| 1061 | |
| 1062 | // Frames per chunk: the chunk's packets are the next `chunk.1` samples. |
| 1063 | let mut per_chunk = Vec::with_capacity(track.chunks.len()); |
| 1064 | let mut at = 0usize; |
| 1065 | for &(_, packets) in &track.chunks { |
| 1066 | let end = (at + packets as usize).min(track.samples.len()); |
| 1067 | per_chunk.push( |
| 1068 | track.samples[at..end] |
| 1069 | .iter() |
| 1070 | .map(|s| s.size / frame_bytes) |
| 1071 | .sum::<u32>(), |
| 1072 | ); |
| 1073 | at = end; |
| 1074 | } |
| 1075 | let stsc = open(out, b"stsc"); |
| 1076 | full_head(out, 0, 0); |
| 1077 | let count_at = out.len(); |
| 1078 | out.extend_from_slice(&0u32.to_be_bytes()); |
| 1079 | let mut runs = 0u32; |
| 1080 | let mut first = 0usize; |
| 1081 | while first < per_chunk.len() { |
| 1082 | let per = per_chunk[first]; |
| 1083 | out.extend_from_slice(&(first as u32 + 1).to_be_bytes()); |
| 1084 | out.extend_from_slice(&per.to_be_bytes()); |
| 1085 | out.extend_from_slice(&1u32.to_be_bytes()); |
| 1086 | runs += 1; |
| 1087 | first += 1; |
| 1088 | while first < per_chunk.len() && per_chunk[first] == per { |
| 1089 | first += 1; |
| 1090 | } |
| 1091 | } |
| 1092 | out[count_at..count_at + 4].copy_from_slice(&runs.to_be_bytes()); |
| 1093 | close(out, stsc); |
| 1094 | |
| 1095 | let stsz = open(out, b"stsz"); |
| 1096 | full_head(out, 0, 0); |
| 1097 | out.extend_from_slice(&frame_bytes.to_be_bytes()); |
| 1098 | out.extend_from_slice(&(total as u32).to_be_bytes()); |
| 1099 | close(out, stsz); |
| 1100 | |
| 1101 | let big = track |
| 1102 | .chunks |
| 1103 | .iter() |
| 1104 | .any(|&(at, _)| at + shift > u64::from(u32::MAX)); |
| 1105 | let kind = if big { b"co64" } else { b"stco" }; |
| 1106 | let chunks = open(out, kind); |
| 1107 | full_head(out, 0, 0); |
| 1108 | out.extend_from_slice(&(track.chunks.len() as u32).to_be_bytes()); |
| 1109 | for &(at, _) in &track.chunks { |
| 1110 | match big { |
| 1111 | true => out.extend_from_slice(&(at + shift).to_be_bytes()), |
| 1112 | false => out.extend_from_slice(&((at + shift) as u32).to_be_bytes()), |
| 1113 | } |
| 1114 | } |
| 1115 | close(out, chunks); |
| 1116 | } |
| 1117 | |
| 1118 | /// The `stts`/`ctts`/`stss`/`stsc`/`stsz` and chunk-offset tables of one track. |
| 1119 | fn sample_tables(out: &mut Vec<u8>, track: &Track, shift: u64) { |
| 1120 | if let (Some((bytes, _)), Some(audio)) = |
| 1121 | (qt_pcm(track.info.params.codec), track.info.params.audio()) |
| 1122 | { |
| 1123 | pcm_tables( |
| 1124 | out, |
| 1125 | track, |
| 1126 | bytes * audio.layout.channel_count() as u32, |
| 1127 | shift, |
| 1128 | ); |
| 1129 | return; |
| 1130 | } |
| 1131 | // stts: runs of equal durations, which for constant-rate video is one entry |
| 1132 | // for the whole film. |
| 1133 | let stts = open(out, b"stts"); |
| 1134 | full_head(out, 0, 0); |
| 1135 | let count_at = out.len(); |
| 1136 | out.extend_from_slice(&0u32.to_be_bytes()); |
| 1137 | let mut runs = 0u32; |
| 1138 | let mut i = 0; |
| 1139 | while i < track.samples.len() { |
| 1140 | let delta = track.samples[i].duration; |
| 1141 | let mut run = 0u32; |
| 1142 | while i < track.samples.len() && track.samples[i].duration == delta { |
| 1143 | run += 1; |
| 1144 | i += 1; |
| 1145 | } |
| 1146 | out.extend_from_slice(&run.to_be_bytes()); |
| 1147 | out.extend_from_slice(&delta.to_be_bytes()); |
| 1148 | runs += 1; |
| 1149 | } |
| 1150 | out[count_at..count_at + 4].copy_from_slice(&runs.to_be_bytes()); |
| 1151 | close(out, stts); |
| 1152 | |
| 1153 | // ctts, only where something is actually reordered. |
| 1154 | let offsets: Vec<i64> = track.samples.iter().map(|s| s.cts - s.dts).collect(); |
| 1155 | if offsets.iter().any(|&o| o != 0) { |
| 1156 | let negative = offsets.iter().any(|&o| o < 0); |
| 1157 | let ctts = open(out, b"ctts"); |
| 1158 | // Version 1 states the offset as signed, which is the only way to say |
| 1159 | // that a picture is shown *before* it is decoded. |
| 1160 | full_head(out, u8::from(negative), 0); |
| 1161 | let count_at = out.len(); |
| 1162 | out.extend_from_slice(&0u32.to_be_bytes()); |
| 1163 | let mut runs = 0u32; |
| 1164 | let mut i = 0; |
| 1165 | while i < offsets.len() { |
| 1166 | let offset = offsets[i]; |
| 1167 | let mut run = 0u32; |
| 1168 | while i < offsets.len() && offsets[i] == offset { |
| 1169 | run += 1; |
| 1170 | i += 1; |
| 1171 | } |
| 1172 | out.extend_from_slice(&run.to_be_bytes()); |
| 1173 | out.extend_from_slice(&(offset as i32).to_be_bytes()); |
| 1174 | runs += 1; |
| 1175 | } |
| 1176 | out[count_at..count_at + 4].copy_from_slice(&runs.to_be_bytes()); |
| 1177 | close(out, ctts); |
| 1178 | } |
| 1179 | |
| 1180 | // stss, only where some samples are not sync ones: no box at all means |
| 1181 | // every sample is a random access point, which is the truth for audio. |
| 1182 | if track.samples.iter().any(|s| !s.sync) { |
| 1183 | let stss = open(out, b"stss"); |
| 1184 | full_head(out, 0, 0); |
| 1185 | let syncs: Vec<u32> = track |
| 1186 | .samples |
| 1187 | .iter() |
| 1188 | .enumerate() |
| 1189 | .filter(|(_, s)| s.sync) |
| 1190 | .map(|(i, _)| i as u32 + 1) |
| 1191 | .collect(); |
| 1192 | out.extend_from_slice(&(syncs.len() as u32).to_be_bytes()); |
| 1193 | for n in syncs { |
| 1194 | out.extend_from_slice(&n.to_be_bytes()); |
| 1195 | } |
| 1196 | close(out, stss); |
| 1197 | } |
| 1198 | |
| 1199 | // stsc: runs of chunks holding the same number of samples. |
| 1200 | let stsc = open(out, b"stsc"); |
| 1201 | full_head(out, 0, 0); |
| 1202 | let count_at = out.len(); |
| 1203 | out.extend_from_slice(&0u32.to_be_bytes()); |
| 1204 | let mut runs = 0u32; |
| 1205 | let mut first = 0usize; |
| 1206 | while first < track.chunks.len() { |
| 1207 | let per = track.chunks[first].1; |
| 1208 | out.extend_from_slice(&(first as u32 + 1).to_be_bytes()); |
| 1209 | out.extend_from_slice(&per.to_be_bytes()); |
| 1210 | out.extend_from_slice(&1u32.to_be_bytes()); // sample_description_index |
| 1211 | runs += 1; |
| 1212 | first += 1; |
| 1213 | while first < track.chunks.len() && track.chunks[first].1 == per { |
| 1214 | first += 1; |
| 1215 | } |
| 1216 | } |
| 1217 | out[count_at..count_at + 4].copy_from_slice(&runs.to_be_bytes()); |
| 1218 | close(out, stsc); |
| 1219 | |
| 1220 | // stsz: one size for all, where they really are all one size. |
| 1221 | let stsz = open(out, b"stsz"); |
| 1222 | full_head(out, 0, 0); |
| 1223 | let uniform = track |
| 1224 | .samples |
| 1225 | .first() |
| 1226 | .map(|f| f.size) |
| 1227 | .filter(|&size| track.samples.iter().all(|s| s.size == size)) |
| 1228 | .unwrap_or(0); |
| 1229 | out.extend_from_slice(&uniform.to_be_bytes()); |
| 1230 | out.extend_from_slice(&(track.samples.len() as u32).to_be_bytes()); |
| 1231 | if uniform == 0 { |
| 1232 | for sample in &track.samples { |
| 1233 | out.extend_from_slice(&sample.size.to_be_bytes()); |
| 1234 | } |
| 1235 | } |
| 1236 | close(out, stsz); |
| 1237 | |
| 1238 | // co64 where the file is big enough to need it, stco where it is not. |
| 1239 | let big = track |
| 1240 | .chunks |
| 1241 | .iter() |
| 1242 | .any(|&(at, _)| at + shift > u64::from(u32::MAX)); |
| 1243 | let kind = if big { b"co64" } else { b"stco" }; |
| 1244 | let chunks = open(out, kind); |
| 1245 | full_head(out, 0, 0); |
| 1246 | out.extend_from_slice(&(track.chunks.len() as u32).to_be_bytes()); |
| 1247 | for &(at, _) in &track.chunks { |
| 1248 | match big { |
| 1249 | true => out.extend_from_slice(&(at + shift).to_be_bytes()), |
| 1250 | false => out.extend_from_slice(&((at + shift) as u32).to_be_bytes()), |
| 1251 | } |
| 1252 | } |
| 1253 | close(out, chunks); |
| 1254 | } |
| 1255 | |
| 1256 | /// The sample entry name and configuration box of a video codec. |
| 1257 | fn video_entry(codec: CodecId) -> Option<&'static [u8; 4]> { |
| 1258 | Some(match codec { |
| 1259 | CodecId::H264 => b"avc1", |
| 1260 | // `hvc1` and not `hev1`: the parameter sets are in the `hvcC`, which is |
| 1261 | // exactly what the `hvc1` name promises a reader. |
| 1262 | CodecId::H265 => b"hvc1", |
| 1263 | CodecId::Av1 => b"av01", |
| 1264 | CodecId::Vp9 => b"vp09", |
| 1265 | CodecId::Vp8 => b"vp08", |
| 1266 | _ => return None, |
| 1267 | }) |
| 1268 | } |
| 1269 | |
| 1270 | fn config_box(codec: CodecId) -> &'static [u8; 4] { |
| 1271 | match codec { |
| 1272 | CodecId::H264 => b"avcC", |
| 1273 | CodecId::H265 => b"hvcC", |
| 1274 | CodecId::Av1 => b"av1C", |
| 1275 | _ => b"vpcC", |
| 1276 | } |
| 1277 | } |
| 1278 | |
| 1279 | /// One `stsd` entry for `info`. |
| 1280 | fn sample_entry( |
| 1281 | out: &mut Vec<u8>, |
| 1282 | info: &StreamInfo, |
| 1283 | field_order: Option<ec_core::Interlace>, |
| 1284 | chan: bool, |
| 1285 | ) -> Result<()> { |
| 1286 | let codec = info.params.codec; |
| 1287 | let extradata = info.params.extradata.as_deref(); |
| 1288 | if codec == CodecId::ProRes { |
| 1289 | // The profile is the sample-entry name; the frame header is self-describing, so there |
| 1290 | // is no configuration box. `extradata` carries the fourcc (apco apcs apcn apch ap4h ap4x). |
| 1291 | let name: [u8; 4] = match extradata |
| 1292 | .and_then(|e| e.get(..4)) |
| 1293 | .map(|e| [e[0], e[1], e[2], e[3]]) |
| 1294 | { |
| 1295 | Some(n) |
| 1296 | if matches!( |
| 1297 | &n, |
| 1298 | b"apco" | b"apcs" | b"apcn" | b"apch" | b"ap4h" | b"ap4x" |
| 1299 | ) => |
| 1300 | { |
| 1301 | n |
| 1302 | } |
| 1303 | _ => { |
| 1304 | return Err(Error::unsupported( |
| 1305 | "mp4: a ProRes track without a profile fourcc", |
| 1306 | "set extradata to apco, apcs, apcn, apch, ap4h or ap4x", |
| 1307 | )); |
| 1308 | } |
| 1309 | }; |
| 1310 | let video = info.params.video().ok_or_else(|| { |
| 1311 | Error::corrupt("mp4: a video codec declared without video parameters") |
| 1312 | })?; |
| 1313 | let at = open(out, &name); |
| 1314 | out.extend_from_slice(&[0; 6]); // reserved |
| 1315 | out.extend_from_slice(&1u16.to_be_bytes()); // data_reference_index |
| 1316 | out.extend_from_slice(&[0; 16]); // pre_defined + reserved |
| 1317 | out.extend_from_slice(&(video.width as u16).to_be_bytes()); |
| 1318 | out.extend_from_slice(&(video.height as u16).to_be_bytes()); |
| 1319 | out.extend_from_slice(&0x0048_0000u32.to_be_bytes()); |
| 1320 | out.extend_from_slice(&0x0048_0000u32.to_be_bytes()); |
| 1321 | out.extend_from_slice(&0u32.to_be_bytes()); |
| 1322 | out.extend_from_slice(&1u16.to_be_bytes()); // frame_count |
| 1323 | out.extend_from_slice(&[0; 32]); // compressorname |
| 1324 | out.extend_from_slice(&0x0018u16.to_be_bytes()); |
| 1325 | out.extend_from_slice(&(-1i16).to_be_bytes()); |
| 1326 | colour_boxes(out, video.color, video.light); |
| 1327 | if let Some(order) = field_order { |
| 1328 | let (count, detail) = match order { |
| 1329 | ec_core::Interlace::Progressive => (1u8, 0u8), |
| 1330 | ec_core::Interlace::TopFieldFirst => (2, 1), |
| 1331 | ec_core::Interlace::BottomFieldFirst => (2, 6), |
| 1332 | }; |
| 1333 | leaf(out, b"fiel", &[count, detail]); |
| 1334 | } |
| 1335 | let sar = video.sample_aspect_ratio; |
| 1336 | let (n, d) = sar.map_or((1, 1), |s| (s.num() as u32, s.den() as u32)); |
| 1337 | let pasp = open(out, b"pasp"); |
| 1338 | out.extend_from_slice(&n.to_be_bytes()); |
| 1339 | out.extend_from_slice(&d.to_be_bytes()); |
| 1340 | close(out, pasp); |
| 1341 | close(out, at); |
| 1342 | return Ok(()); |
| 1343 | } |
| 1344 | if let Some(name) = video_entry(codec) { |
| 1345 | let video = info.params.video().ok_or_else(|| { |
| 1346 | Error::corrupt("mp4: a video codec declared without video parameters") |
| 1347 | })?; |
| 1348 | let config = extradata.ok_or_else(|| { |
| 1349 | Error::unsupported( |
| 1350 | format!("mp4: a {} track with no codec configuration", codec.name()), |
| 1351 | "an ISOBMFF video sample entry has to carry its avcC/hvcC/av1C/vpcC record", |
| 1352 | ) |
| 1353 | })?; |
| 1354 | let at = open(out, name); |
| 1355 | out.extend_from_slice(&[0; 6]); // reserved |
| 1356 | out.extend_from_slice(&1u16.to_be_bytes()); // data_reference_index |
| 1357 | out.extend_from_slice(&[0; 16]); // pre_defined + reserved |
| 1358 | out.extend_from_slice(&(video.width as u16).to_be_bytes()); |
| 1359 | out.extend_from_slice(&(video.height as u16).to_be_bytes()); |
| 1360 | out.extend_from_slice(&0x0048_0000u32.to_be_bytes()); // 72 dpi |
| 1361 | out.extend_from_slice(&0x0048_0000u32.to_be_bytes()); |
| 1362 | out.extend_from_slice(&0u32.to_be_bytes()); // reserved |
| 1363 | out.extend_from_slice(&1u16.to_be_bytes()); // frame_count |
| 1364 | out.extend_from_slice(&[0; 32]); // compressorname |
| 1365 | out.extend_from_slice(&0x0018u16.to_be_bytes()); // depth: colour, no alpha |
| 1366 | out.extend_from_slice(&(-1i16).to_be_bytes()); // pre_defined |
| 1367 | leaf(out, config_box(codec), config); |
| 1368 | colour_boxes(out, video.color, video.light); |
| 1369 | if let Some(sar) = video.sample_aspect_ratio { |
| 1370 | let pasp = open(out, b"pasp"); |
| 1371 | out.extend_from_slice(&(sar.num() as u32).to_be_bytes()); |
| 1372 | out.extend_from_slice(&(sar.den() as u32).to_be_bytes()); |
| 1373 | close(out, pasp); |
| 1374 | } |
| 1375 | // ffmpeg's order: after `colr`/`pasp`. field_count 1 / detail 0 is a |
| 1376 | // progressive picture; 2 fields with detail 1 is top first (stored and |
| 1377 | // displayed), 6 bottom first: what ffmpeg writes for tt/bb (its 9/14, tb/bt, |
| 1378 | // are read back as top/bottom first too, but never written here). |
| 1379 | if let Some(order) = field_order { |
| 1380 | let (count, detail) = match order { |
| 1381 | ec_core::Interlace::Progressive => (1u8, 0u8), |
| 1382 | ec_core::Interlace::TopFieldFirst => (2, 1), |
| 1383 | ec_core::Interlace::BottomFieldFirst => (2, 6), |
| 1384 | }; |
| 1385 | leaf(out, b"fiel", &[count, detail]); |
| 1386 | } |
| 1387 | close(out, at); |
| 1388 | return Ok(()); |
| 1389 | } |
| 1390 | if codec == CodecId::Tx3g { |
| 1391 | let at = open(out, b"tx3g"); |
| 1392 | out.extend_from_slice(&[0; 6]); |
| 1393 | out.extend_from_slice(&1u16.to_be_bytes()); |
| 1394 | match extradata { |
| 1395 | // Round-tripped from another mp4: the style it already stated. |
| 1396 | Some(style) if style.len() >= 30 => out.extend_from_slice(style), |
| 1397 | _ => { |
| 1398 | out.extend_from_slice(&0u32.to_be_bytes()); // displayFlags |
| 1399 | out.push(1); // horizontal justification: centred |
| 1400 | out.push(0xFF); // vertical: bottom |
| 1401 | out.extend_from_slice(&[0, 0, 0, 0]); // background: transparent |
| 1402 | out.extend_from_slice(&[0; 8]); // text box: the whole picture |
| 1403 | out.extend_from_slice(&0u16.to_be_bytes()); // startChar |
| 1404 | out.extend_from_slice(&0u16.to_be_bytes()); // endChar |
| 1405 | out.extend_from_slice(&1u16.to_be_bytes()); // font-ID |
| 1406 | out.push(0); // face-style-flags |
| 1407 | out.push(18); // font-size |
| 1408 | out.extend_from_slice(&[0xFF; 4]); // text colour: opaque white |
| 1409 | let ftab = open(out, b"ftab"); |
| 1410 | out.extend_from_slice(&1u16.to_be_bytes()); |
| 1411 | out.extend_from_slice(&1u16.to_be_bytes()); |
| 1412 | out.push(5); |
| 1413 | out.extend_from_slice(b"Serif"); |
| 1414 | close(out, ftab); |
| 1415 | } |
| 1416 | } |
| 1417 | close(out, at); |
| 1418 | return Ok(()); |
| 1419 | } |
| 1420 | |
| 1421 | let (name, audio) = match info.params.audio() { |
| 1422 | Some(audio) => (audio_entry(codec)?, audio), |
| 1423 | None => { |
| 1424 | return Err(Error::unsupported( |
| 1425 | format!("mp4: a {} track", codec.name()), |
| 1426 | "this writer has a sample entry for video, AAC-family audio and tx3g text only; \ |
| 1427 | Matroska carries the rest", |
| 1428 | )); |
| 1429 | } |
| 1430 | }; |
| 1431 | let at = open(out, name); |
| 1432 | out.extend_from_slice(&[0; 6]); |
| 1433 | out.extend_from_slice(&1u16.to_be_bytes()); // data_reference_index |
| 1434 | // QuickTime sound description version 1 for the PCM wider than 16 bits, |
| 1435 | // which is what ffmpeg writes for them in a .mov. |
| 1436 | let qt = qt_pcm(codec); |
| 1437 | out.extend_from_slice(&[0, u8::from(qt.is_some()), 0, 0, 0, 0, 0, 0]); // version, revision, vendor |
| 1438 | out.extend_from_slice(&(audio.layout.channel_count() as u16).to_be_bytes()); |
| 1439 | let bits = if qt.is_some() { |
| 1440 | 16 |
| 1441 | } else { |
| 1442 | audio.bits_per_sample.unwrap_or(16) |
| 1443 | }; |
| 1444 | out.extend_from_slice(&(bits as u16).to_be_bytes()); |
| 1445 | out.extend_from_slice(&0u16.to_be_bytes()); // pre_defined |
| 1446 | out.extend_from_slice(&0u16.to_be_bytes()); // reserved |
| 1447 | // 16.16, so a rate over 65535 is stated as its low half — which is what |
| 1448 | // every writer does and what the `mdhd` timescale says exactly anyway. |
| 1449 | out.extend_from_slice(&((audio.sample_rate as u16 as u32) << 16).to_be_bytes()); |
| 1450 | if let Some((bytes, little)) = qt { |
| 1451 | let channels = audio.layout.channel_count() as u32; |
| 1452 | out.extend_from_slice(&1u32.to_be_bytes()); // samples per packet |
| 1453 | out.extend_from_slice(&bytes.to_be_bytes()); // bytes per packet |
| 1454 | out.extend_from_slice(&(bytes * channels).to_be_bytes()); // bytes per frame |
| 1455 | out.extend_from_slice(&2u32.to_be_bytes()); // bytes per sample (ffmpeg's constant) |
| 1456 | let wave = open(out, b"wave"); |
| 1457 | leaf(out, b"frma", name); |
| 1458 | leaf(out, b"enda", &u16::from(little).to_be_bytes()); |
| 1459 | out.extend_from_slice(&[0, 0, 0, 8, 0, 0, 0, 0]); // terminator: an 8-byte box of type zero |
| 1460 | close(out, wave); |
| 1461 | } |
| 1462 | match codec { |
| 1463 | CodecId::Aac => { |
| 1464 | let asc = extradata.ok_or_else(|| { |
| 1465 | Error::unsupported( |
| 1466 | "mp4: an AAC track with no AudioSpecificConfig", |
| 1467 | "an esds descriptor is the only place an mp4 states an AAC track's setup", |
| 1468 | ) |
| 1469 | })?; |
| 1470 | let esds = open(out, b"esds"); |
| 1471 | out.extend_from_slice(&Esds::aac(asc).write()); |
| 1472 | close(out, esds); |
| 1473 | } |
| 1474 | CodecId::Mp3 => { |
| 1475 | let mut mp3 = Esds::aac(&[][..]); |
| 1476 | mp3.object_type = object_type::MPEG1_AUDIO; |
| 1477 | mp3.decoder_specific = None; |
| 1478 | let esds = open(out, b"esds"); |
| 1479 | out.extend_from_slice(&mp3.write()); |
| 1480 | close(out, esds); |
| 1481 | } |
| 1482 | CodecId::Ac3 |
| 1483 | | CodecId::EAc3 |
| 1484 | | CodecId::Dts |
| 1485 | | CodecId::Flac |
| 1486 | | CodecId::Opus |
| 1487 | | CodecId::Alac => { |
| 1488 | let config = extradata.ok_or_else(|| { |
| 1489 | Error::unsupported( |
| 1490 | format!("mp4: a {} track with no codec configuration", codec.name()), |
| 1491 | "its sample entry has to carry the codec's own configuration box", |
| 1492 | ) |
| 1493 | })?; |
| 1494 | match codec { |
| 1495 | // ALAC's cookie is carried with its box header, so it is written |
| 1496 | // back exactly as it was read; a bare cookie gets its header here. |
| 1497 | CodecId::Alac if config.len() > 8 && &config[4..8] == b"alac" => { |
| 1498 | out.extend_from_slice(config) |
| 1499 | } |
| 1500 | CodecId::Alac => leaf(out, b"alac", config), |
| 1501 | CodecId::Opus => leaf(out, b"dOps", &dops(config)), |
| 1502 | _ => leaf(out, audio_config_box(codec), config), |
| 1503 | } |
| 1504 | } |
| 1505 | _ => {} |
| 1506 | } |
| 1507 | if chan || qt.is_some() { |
| 1508 | chan_box(out, &audio.layout); |
| 1509 | } |
| 1510 | close(out, at); |
| 1511 | Ok(()) |
| 1512 | } |
| 1513 | |
| 1514 | /// `colr`, and the two HDR boxes where the grade stated them — metadata a remux |
| 1515 | /// must not quietly drop, because nothing downstream can reconstruct it. |
| 1516 | fn colour_boxes(out: &mut Vec<u8>, color: ec_core::ColorInfo, light: ContentLight) { |
| 1517 | if color != ec_core::ColorInfo::default() { |
| 1518 | let colr = open(out, b"colr"); |
| 1519 | out.extend_from_slice(b"nclx"); |
| 1520 | out.extend_from_slice(&u16::from(color.primaries).to_be_bytes()); |
| 1521 | out.extend_from_slice(&u16::from(color.transfer).to_be_bytes()); |
| 1522 | out.extend_from_slice(&u16::from(color.matrix).to_be_bytes()); |
| 1523 | out.push(u8::from(color.full_range) << 7); |
| 1524 | close(out, colr); |
| 1525 | } |
| 1526 | if light.mastering_max.is_some() |
| 1527 | || light.mastering_min.is_some() |
| 1528 | || light.mastering_primaries.is_some() |
| 1529 | { |
| 1530 | let mdcv = open(out, b"mdcv"); |
| 1531 | // Display primaries and white point as stated; BT.2020 is what an HDR |
| 1532 | // grade is mastered on and what a writer states when nothing is. |
| 1533 | let primaries = light |
| 1534 | .mastering_primaries |
| 1535 | .map_or(BT2020_PRIMARIES, |p| p.to_array()); |
| 1536 | for xy in primaries { |
| 1537 | out.extend_from_slice(&xy.to_be_bytes()); |
| 1538 | } |
| 1539 | let nits = |v: Option<f32>| { |
| 1540 | ((f64::from(v.unwrap_or(0.0)) * 10_000.0).round() as u32).to_be_bytes() |
| 1541 | }; |
| 1542 | out.extend_from_slice(&nits(light.mastering_max)); |
| 1543 | out.extend_from_slice(&nits(light.mastering_min)); |
| 1544 | close(out, mdcv); |
| 1545 | } |
| 1546 | if light.max_cll.is_some() || light.max_fall.is_some() { |
| 1547 | let clli = open(out, b"clli"); |
| 1548 | out.extend_from_slice(&(light.max_cll.unwrap_or(0.0).round() as u16).to_be_bytes()); |
| 1549 | out.extend_from_slice(&(light.max_fall.unwrap_or(0.0).round() as u16).to_be_bytes()); |
| 1550 | close(out, clli); |
| 1551 | } |
| 1552 | } |
| 1553 | |
| 1554 | /// BT.2020 green, blue, red and D65, in the 0.00002 units an `mdcv` states them. |
| 1555 | const BT2020_PRIMARIES: [u16; 8] = [8500, 39850, 6550, 2300, 35400, 14600, 15635, 16450]; |
| 1556 | |
| 1557 | const UNITY_MATRIX: [u8; 36] = { |
| 1558 | let mut m = [0u8; 36]; |
| 1559 | m[0] = 0x00; |
| 1560 | m[1] = 0x01; |
| 1561 | m[16] = 0x00; |
| 1562 | m[17] = 0x01; |
| 1563 | m[32] = 0x40; |
| 1564 | m |
| 1565 | }; |
| 1566 | |
| 1567 | /// `(bytes per sample, little-endian)` of the PCM codecs QuickTime describes |
| 1568 | /// with a version 1 sound description and a `wave`/`enda`: `in24`, `in32`, `fl32`. |
| 1569 | fn qt_pcm(codec: CodecId) -> Option<(u32, bool)> { |
| 1570 | Some(match codec { |
| 1571 | CodecId::PcmS24Le => (3, true), |
| 1572 | CodecId::PcmS24Be => (3, false), |
| 1573 | CodecId::PcmS32Le | CodecId::PcmF32Le => (4, true), |
| 1574 | CodecId::PcmS32Be | CodecId::PcmF32Be => (4, false), |
| 1575 | _ => return None, |
| 1576 | }) |
| 1577 | } |
| 1578 | |
| 1579 | /// The QuickTime `chan` box for the layouts that have a stock one, as ffmpeg |
| 1580 | /// writes it: a layout tag for mono and stereo, a channel bitmap for 5.1. |
| 1581 | fn chan_box(out: &mut Vec<u8>, layout: &ec_core::ChannelLayout) { |
| 1582 | use ec_core::ChannelLayout; |
| 1583 | let (tag, bitmap) = match layout { |
| 1584 | ChannelLayout::Mono => (0x0064_0001u32, 0u32), |
| 1585 | ChannelLayout::Stereo => (0x0065_0002, 0), |
| 1586 | // UseChannelBitmap; L R C LFE Ls Rs. |
| 1587 | ChannelLayout::Surround5_1 => (0x0001_0000, 0x3f), |
| 1588 | _ => return, |
| 1589 | }; |
| 1590 | let at = open(out, b"chan"); |
| 1591 | full_head(out, 0, 0); |
| 1592 | out.extend_from_slice(&tag.to_be_bytes()); |
| 1593 | out.extend_from_slice(&bitmap.to_be_bytes()); |
| 1594 | out.extend_from_slice(&0u32.to_be_bytes()); // number of descriptions |
| 1595 | close(out, at); |
| 1596 | } |
| 1597 | |
| 1598 | fn audio_entry(codec: CodecId) -> Result<&'static [u8; 4]> { |
| 1599 | Ok(match codec { |
| 1600 | CodecId::Aac | CodecId::Mp3 => b"mp4a", |
| 1601 | CodecId::Ac3 => b"ac-3", |
| 1602 | CodecId::EAc3 => b"ec-3", |
| 1603 | CodecId::Dts => b"dtsc", |
| 1604 | CodecId::Alac => b"alac", |
| 1605 | CodecId::Flac => b"fLaC", |
| 1606 | CodecId::Opus => b"Opus", |
| 1607 | CodecId::PcmS16Le => b"sowt", |
| 1608 | CodecId::PcmS16Be => b"twos", |
| 1609 | CodecId::PcmU8 => b"raw ", |
| 1610 | CodecId::PcmS24Le | CodecId::PcmS24Be => b"in24", |
| 1611 | CodecId::PcmS32Le | CodecId::PcmS32Be => b"in32", |
| 1612 | CodecId::PcmF32Le | CodecId::PcmF32Be => b"fl32", |
| 1613 | _ => { |
| 1614 | return Err(Error::unsupported( |
| 1615 | format!("mp4: a {} audio track", codec.name()), |
| 1616 | "no ISOBMFF sample entry is defined for it", |
| 1617 | )); |
| 1618 | } |
| 1619 | }) |
| 1620 | } |
| 1621 | |
| 1622 | fn audio_config_box(codec: CodecId) -> &'static [u8; 4] { |
| 1623 | match codec { |
| 1624 | CodecId::Ac3 => b"dac3", |
| 1625 | CodecId::EAc3 => b"dec3", |
| 1626 | CodecId::Dts => b"ddts", |
| 1627 | CodecId::Flac => b"dfLa", |
| 1628 | CodecId::Alac => b"alac", |
| 1629 | _ => b"dOps", |
| 1630 | } |
| 1631 | } |
| 1632 | |
| 1633 | /// The `dOps` payload from an `OpusHead`: same fields, opposite byte order, and |
| 1634 | /// without the magic — the inverse of what the demuxer does on the way in. |
| 1635 | fn dops(head: &[u8]) -> Vec<u8> { |
| 1636 | let body = match head.starts_with(b"OpusHead") { |
| 1637 | true => &head[8..], |
| 1638 | false => head, |
| 1639 | }; |
| 1640 | let le16 = |at: usize| { |
| 1641 | u16::from_le_bytes([ |
| 1642 | body.get(at).copied().unwrap_or(0), |
| 1643 | body.get(at + 1).copied().unwrap_or(0), |
| 1644 | ]) |
| 1645 | }; |
| 1646 | let mut out = Vec::with_capacity(body.len()); |
| 1647 | out.push(0); // dOps version |
| 1648 | out.push(body.get(1).copied().unwrap_or(2)); // channel count |
| 1649 | out.extend_from_slice(&le16(2).to_be_bytes()); // pre-skip |
| 1650 | let rate = u32::from_le_bytes([ |
| 1651 | body.get(4).copied().unwrap_or(0), |
| 1652 | body.get(5).copied().unwrap_or(0), |
| 1653 | body.get(6).copied().unwrap_or(0), |
| 1654 | body.get(7).copied().unwrap_or(0), |
| 1655 | ]); |
| 1656 | out.extend_from_slice(&rate.to_be_bytes()); |
| 1657 | out.extend_from_slice(&le16(8).to_be_bytes()); // output gain |
| 1658 | out.extend_from_slice(&body[10.min(body.len())..]); |
| 1659 | out |
| 1660 | } |
| 1661 | |
| 1662 | /// Three lowercase letters into the five-bit-a-letter packing an `mdhd` states a |
| 1663 | /// language in; `und` where the track never said. |
| 1664 | fn pack_language(language: Option<&str>) -> u16 { |
| 1665 | let tag = language.filter(|l| l.len() == 3).unwrap_or("und"); |
| 1666 | tag.bytes().fold(0u16, |packed, b| { |
| 1667 | (packed << 5) | u16::from(b.to_ascii_lowercase().wrapping_sub(0x60) & 0x1F) |
| 1668 | }) |
| 1669 | } |
| 1670 | |
| 1671 | #[cfg(test)] |
| 1672 | mod tests { |
| 1673 | use super::*; |
| 1674 | use crate::Mp4Demuxer; |
| 1675 | use ec_core::{AudioParameters, Buf, ChannelLayout, CodecParameters, Demuxer, MediaParameters}; |
| 1676 | use std::io::Cursor; |
| 1677 | |
| 1678 | /// Ten AAC packets on a sound-only file: the `M4A ` brand is the first thing |
| 1679 | /// `ftyp` states, no `vide` handler exists anywhere in the file, and the file |
| 1680 | /// reads back as the same ten packets on one AAC track. |
| 1681 | #[test] |
| 1682 | fn an_audio_only_m4a_states_its_brand_and_holds_one_aac_track() { |
| 1683 | let mut params = CodecParameters::new(CodecId::Aac); |
| 1684 | params.extradata = Some(Buf::from(vec![0x12, 0x10])); |
| 1685 | params.media = MediaParameters::Audio(AudioParameters { |
| 1686 | sample_rate: 44_100, |
| 1687 | layout: ChannelLayout::from_count(2), |
| 1688 | ..Default::default() |
| 1689 | }); |
| 1690 | let mut muxer = Mp4Muxer::with_brands( |
| 1691 | Cursor::new(Vec::new()), |
| 1692 | *b"M4A ", |
| 1693 | &[*b"M4A ", *b"mp42", *b"isom"], |
| 1694 | ) |
| 1695 | .unwrap(); |
| 1696 | let stream = muxer |
| 1697 | .add_stream(StreamInfo::new(0, TimeBase::from_rate(44_100), params)) |
| 1698 | .unwrap(); |
| 1699 | for i in 0..10u8 { |
| 1700 | let mut packet = Packet::new(stream, TimeBase::from_rate(44_100), vec![0xAA, i, 0x55]); |
| 1701 | packet.dts = Some(i64::from(i) * 1024); |
| 1702 | packet.duration = Some(1024); |
| 1703 | packet.flags.keyframe = true; |
| 1704 | muxer.write_packet(&packet).unwrap(); |
| 1705 | } |
| 1706 | muxer.finish().unwrap(); |
| 1707 | let bytes = muxer.into_inner().into_inner(); |
| 1708 | |
| 1709 | assert_eq!(&bytes[4..8], b"ftyp"); |
| 1710 | assert_eq!(&bytes[8..12], b"M4A ", "the major brand"); |
| 1711 | assert!( |
| 1712 | !bytes.windows(4).any(|w| w == b"vide"), |
| 1713 | "an audio-only file has no video track" |
| 1714 | ); |
| 1715 | |
| 1716 | let mut demuxer = Mp4Demuxer::new(Cursor::new(bytes)).unwrap(); |
| 1717 | assert_eq!(demuxer.streams().len(), 1, "one track"); |
| 1718 | assert_eq!(demuxer.streams()[0].params.codec, CodecId::Aac); |
| 1719 | let mut back = Vec::new(); |
| 1720 | loop { |
| 1721 | match demuxer.next_packet() { |
| 1722 | Ok(packet) => back.push(packet.data.to_vec()), |
| 1723 | Err(Error::Eof) => break, |
| 1724 | Err(e) => panic!("{e}"), |
| 1725 | } |
| 1726 | } |
| 1727 | assert_eq!(back.len(), 10); |
| 1728 | assert_eq!(back[3], vec![0xAA, 3, 0x55]); |
| 1729 | } |
| 1730 | |
| 1731 | #[test] |
| 1732 | fn faststart_puts_the_moov_before_the_mdat_and_the_samples_still_read_back() { |
| 1733 | let mut params = CodecParameters::new(CodecId::Aac); |
| 1734 | params.extradata = Some(Buf::from(vec![0x12, 0x10])); |
| 1735 | params.media = MediaParameters::Audio(AudioParameters { |
| 1736 | sample_rate: 44_100, |
| 1737 | layout: ChannelLayout::from_count(2), |
| 1738 | ..Default::default() |
| 1739 | }); |
| 1740 | let mut muxer = Mp4Muxer::new(Cursor::new(Vec::new())).unwrap(); |
| 1741 | muxer.set_faststart(true); |
| 1742 | let stream = muxer |
| 1743 | .add_stream(StreamInfo::new(0, TimeBase::from_rate(44_100), params)) |
| 1744 | .unwrap(); |
| 1745 | for i in 0..10u8 { |
| 1746 | let mut packet = Packet::new(stream, TimeBase::from_rate(44_100), vec![0xAA, i, 0x55]); |
| 1747 | packet.dts = Some(i64::from(i) * 1024); |
| 1748 | packet.duration = Some(1024); |
| 1749 | packet.flags.keyframe = true; |
| 1750 | muxer.write_packet(&packet).unwrap(); |
| 1751 | } |
| 1752 | let bytes = muxer.finish_faststart().unwrap().into_inner(); |
| 1753 | |
| 1754 | let mut order = Vec::new(); |
| 1755 | let mut at = 0usize; |
| 1756 | while at + 8 <= bytes.len() { |
| 1757 | let size = u32::from_be_bytes([bytes[at], bytes[at + 1], bytes[at + 2], bytes[at + 3]]); |
| 1758 | order.push(String::from_utf8_lossy(&bytes[at + 4..at + 8]).into_owned()); |
| 1759 | at += match size { |
| 1760 | 1 => u64::from_be_bytes(bytes[at + 8..at + 16].try_into().unwrap()) as usize, |
| 1761 | _ => size as usize, |
| 1762 | }; |
| 1763 | } |
| 1764 | assert_eq!(order, ["ftyp", "moov", "mdat"]); |
| 1765 | |
| 1766 | let mut demuxer = Mp4Demuxer::new(Cursor::new(bytes)).unwrap(); |
| 1767 | let mut back = Vec::new(); |
| 1768 | loop { |
| 1769 | match demuxer.next_packet() { |
| 1770 | Ok(packet) => back.push(packet.data.to_vec()), |
| 1771 | Err(Error::Eof) => break, |
| 1772 | Err(e) => panic!("{e}"), |
| 1773 | } |
| 1774 | } |
| 1775 | let written: Vec<Vec<u8>> = (0..10u8).map(|i| vec![0xAA, i, 0x55]).collect(); |
| 1776 | assert_eq!(back, written); |
| 1777 | } |
| 1778 | |
| 1779 | #[test] |
| 1780 | fn language_packing_is_the_demuxers_inverse() { |
| 1781 | for tag in ["tur", "eng", "und"] { |
| 1782 | let packed = pack_language(Some(tag)); |
| 1783 | let back: String = (0..3) |
| 1784 | .rev() |
| 1785 | .map(|i| char::from(0x60 + ((packed >> (i * 5)) & 0x1F) as u8)) |
| 1786 | .collect(); |
| 1787 | assert_eq!(back, tag); |
| 1788 | } |
| 1789 | assert_eq!(pack_language(None), pack_language(Some("und"))); |
| 1790 | assert_eq!(pack_language(Some("nonsense")), pack_language(Some("und"))); |
| 1791 | } |
| 1792 | |
| 1793 | #[test] |
| 1794 | fn an_opus_head_round_trips_through_dops() { |
| 1795 | let head = crate::demux::opus_head(&[0, 2, 0x01, 0x38, 0, 0, 0xBB, 0x80, 0, 0, 1, 2, 3]); |
| 1796 | let back = dops(&head); |
| 1797 | assert_eq!(back[0], 0, "dOps version"); |
| 1798 | assert_eq!(back[1], 2, "channels"); |
| 1799 | assert_eq!(u16::from_be_bytes([back[2], back[3]]), 312); |
| 1800 | assert_eq!( |
| 1801 | u32::from_be_bytes([back[4], back[5], back[6], back[7]]), |
| 1802 | 48_000 |
| 1803 | ); |
| 1804 | assert_eq!(&back[10..], &[1, 2, 3], "mapping family and table"); |
| 1805 | } |
| 1806 | |
| 1807 | /// One second of silent AAC, with the chapters given, as bytes. |
| 1808 | fn one_aac_track(chapters: &[(u64, String)]) -> Result<Vec<u8>> { |
| 1809 | let mut params = CodecParameters::new(CodecId::Aac); |
| 1810 | params.extradata = Some(Buf::from(vec![0x12, 0x10])); |
| 1811 | params.media = MediaParameters::Audio(AudioParameters { |
| 1812 | sample_rate: 44_100, |
| 1813 | layout: ChannelLayout::from_count(2), |
| 1814 | ..Default::default() |
| 1815 | }); |
| 1816 | let mut muxer = Mp4Muxer::new(Cursor::new(Vec::new()))?; |
| 1817 | muxer.set_chapters(chapters)?; |
| 1818 | let stream = muxer.add_stream(StreamInfo::new(0, TimeBase::from_rate(44_100), params))?; |
| 1819 | for i in 0..43u8 { |
| 1820 | let mut packet = Packet::new(stream, TimeBase::from_rate(44_100), vec![0xAA, i, 0x55]); |
| 1821 | packet.dts = Some(i64::from(i) * 1024); |
| 1822 | packet.duration = Some(1024); |
| 1823 | packet.flags.keyframe = true; |
| 1824 | muxer.write_packet(&packet)?; |
| 1825 | } |
| 1826 | muxer.finish()?; |
| 1827 | Ok(muxer.into_inner().into_inner()) |
| 1828 | } |
| 1829 | |
| 1830 | fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> { |
| 1831 | haystack.windows(needle.len()).position(|w| w == needle) |
| 1832 | } |
| 1833 | |
| 1834 | #[test] |
| 1835 | fn chpl_is_version_one_in_hundred_nanoseconds_with_byte_counted_titles() { |
| 1836 | let chapters = vec![ |
| 1837 | (0u64, "Intro".to_string()), |
| 1838 | (2_000_000_000, "Ünï".to_string()), |
| 1839 | ]; |
| 1840 | let bytes = one_aac_track(&chapters).unwrap(); |
| 1841 | let at = find(&bytes, b"chpl").expect("a chpl box") - 4; |
| 1842 | let size = u32::from_be_bytes(bytes[at..at + 4].try_into().unwrap()) as usize; |
| 1843 | let body = &bytes[at + 8..at + size]; |
| 1844 | assert_eq!(body[0], 1, "chpl version 1"); |
| 1845 | assert_eq!(&body[1..4], &[0, 0, 0], "flags"); |
| 1846 | assert_eq!(&body[4..8], &[0, 0, 0, 0], "the version-1 reserved word"); |
| 1847 | assert_eq!(body[8], 2, "chapter count, one byte"); |
| 1848 | assert_eq!(u64::from_be_bytes(body[9..17].try_into().unwrap()), 0); |
| 1849 | assert_eq!(body[17], 5, "title length, one byte"); |
| 1850 | assert_eq!(&body[18..23], b"Intro"); |
| 1851 | assert_eq!( |
| 1852 | u64::from_be_bytes(body[23..31].try_into().unwrap()), |
| 1853 | 20_000_000, |
| 1854 | "2 s in 100 ns units" |
| 1855 | ); |
| 1856 | assert_eq!(body[31], 5, "'Ü' and 'ï' are two bytes each"); |
| 1857 | assert_eq!(&body[32..37], "Ünï".as_bytes()); |
| 1858 | } |
| 1859 | |
| 1860 | #[test] |
| 1861 | fn chapters_are_referenced_from_the_audio_track_and_run_to_the_end() { |
| 1862 | let chapters = vec![ |
| 1863 | (3_000_000_000, "Late".to_string()), |
| 1864 | (1_000_000_000, "Early".to_string()), |
| 1865 | ]; |
| 1866 | let bytes = one_aac_track(&chapters).unwrap(); |
| 1867 | let tref = find(&bytes, b"tref").expect("a tref box in the audio track"); |
| 1868 | // The tref sits inside the one audio trak, which comes before the chapter |
| 1869 | // track; tref/chap names track 2, the chapter track after the audio one. |
| 1870 | assert_eq!(&bytes[tref + 8..tref + 12], b"chap"); |
| 1871 | let id = u32::from_be_bytes(bytes[tref + 12..tref + 16].try_into().unwrap()); |
| 1872 | assert_eq!(id, 2); |
| 1873 | // The titles are stored sorted by start, so "Early" precedes "Late" in the mdat. |
| 1874 | let early = find(&bytes, b"Early").expect("the Early sample"); |
| 1875 | let late = find(&bytes, b"Late").expect("the Late sample"); |
| 1876 | assert!(early < late, "sorted by start"); |
| 1877 | } |
| 1878 | |
| 1879 | #[test] |
| 1880 | fn no_chapters_writes_no_chapter_boxes_or_track() { |
| 1881 | let bytes = one_aac_track(&[]).unwrap(); |
| 1882 | assert!(find(&bytes, b"chpl").is_none()); |
| 1883 | assert!(find(&bytes, b"tref").is_none()); |
| 1884 | assert!(find(&bytes, b"text").is_none()); |
| 1885 | assert!(find(&bytes, b"co64").is_none()); |
| 1886 | } |
| 1887 | |
| 1888 | #[test] |
| 1889 | fn more_than_255_chapters_omit_the_chpl_box_and_keep_the_track() { |
| 1890 | let chapters: Vec<(u64, String)> = (0..300u64) |
| 1891 | .map(|i| (i * 1_000_000_000, format!("c{i}"))) |
| 1892 | .collect(); |
| 1893 | let bytes = one_aac_track(&chapters).unwrap(); |
| 1894 | assert!(find(&bytes, b"chpl").is_none(), "the count is one byte"); |
| 1895 | assert!( |
| 1896 | find(&bytes, b"tref").is_some(), |
| 1897 | "the chapter track is still referenced" |
| 1898 | ); |
| 1899 | assert!( |
| 1900 | find(&bytes, b"c299").is_some(), |
| 1901 | "the last chapter's title is in the track" |
| 1902 | ); |
| 1903 | } |
| 1904 | |
| 1905 | #[test] |
| 1906 | fn clipped_titles_keep_their_characters_whole() { |
| 1907 | assert_eq!(clip("abc", 2), "ab"); |
| 1908 | assert_eq!( |
| 1909 | clip("aé", 2), |
| 1910 | "a", |
| 1911 | "a two-byte character does not fit in one byte" |
| 1912 | ); |
| 1913 | assert_eq!(clip("aé", 3), "aé"); |
| 1914 | } |
| 1915 | } |