edith_codecs
Clone
https://git.tahinli.com/Tahinli/edith_codecs.git
0 watching·0 forks·Rust·370.3 MiB·00c1b3f·Tahinli·2 months ago·1999 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::{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 | /// One written sample, as the sample tables will state it. |
| 18 | struct Sample { |
| 19 | size: u32, |
| 20 | dts: i64, |
| 21 | cts: i64, |
| 22 | duration: u32, |
| 23 | sync: bool, |
| 24 | } |
| 25 | |
| 26 | /// One declared stream and everything written on it. |
| 27 | struct Track { |
| 28 | info: StreamInfo, |
| 29 | /// Ticks a second on this track: `time_base.den()`, so a `1001/24000` base |
| 30 | /// becomes a 24000 clock counting 1001 a frame — exact, never rounded. |
| 31 | timescale: u32, |
| 32 | time_base: TimeBase, |
| 33 | samples: Vec<Sample>, |
| 34 | /// `(file offset, sample count)` per chunk: a run of this track's samples |
| 35 | /// written back to back, which is what an interleaved file is made of. |
| 36 | chunks: Vec<(u64, u32)>, |
| 37 | /// Where the last sample of this track ended, to tell "same chunk" from "a |
| 38 | /// new one". |
| 39 | chunk_end: u64, |
| 40 | title: Option<String>, |
| 41 | /// An audio encoder's priming: samples it emits before the first audible |
| 42 | /// one (an AAC-LC encoder's 1024-sample delay), in this track's |
| 43 | /// timescale. Written the same way as a video track's reorder delay: an |
| 44 | /// `edts/elst` media_time shift, never a trim. |
| 45 | audio_delay: i64, |
| 46 | } |
| 47 | |
| 48 | /// An MP4 writer over anything seekable. |
| 49 | /// |
| 50 | /// **Layout: `mdat` first, `moov` last.** Samples are written the instant they |
| 51 | /// arrive, so muxing costs one pass and no temporary file, and the sample tables |
| 52 | /// — which cannot be written before the sizes they state are known — go at the |
| 53 | /// end. The cost is that a player streaming the file over HTTP has to reach the |
| 54 | /// end before it can start; a faststart (`moov` in front) writer would have to |
| 55 | /// copy the whole `mdat` a second time, and is not implemented here. |
| 56 | /// |
| 57 | /// Interleaving is the caller's: packets are written in the order they are |
| 58 | /// handed over, and the chunk table follows that order exactly. |
| 59 | pub struct Mp4Muxer<W> { |
| 60 | w: W, |
| 61 | tracks: Vec<Track>, |
| 62 | /// Current write offset. |
| 63 | pos: u64, |
| 64 | /// Offset of the `mdat` box header, patched with its real size at |
| 65 | /// [`Mp4Muxer::finish`]. |
| 66 | mdat_at: u64, |
| 67 | started: bool, |
| 68 | finished: bool, |
| 69 | title: Option<String>, |
| 70 | } |
| 71 | |
| 72 | impl<W: Write + Seek> Mp4Muxer<W> { |
| 73 | /// A writer over `w`, which is positioned at its start. |
| 74 | pub fn new(mut w: W) -> Result<Mp4Muxer<W>> { |
| 75 | let pos = w.seek(SeekFrom::Start(0))?; |
| 76 | Ok(Mp4Muxer { |
| 77 | w, |
| 78 | tracks: Vec::new(), |
| 79 | pos, |
| 80 | mdat_at: 0, |
| 81 | started: false, |
| 82 | finished: false, |
| 83 | title: None, |
| 84 | }) |
| 85 | } |
| 86 | |
| 87 | /// Name the movie: a `moov/udta/name` box. |
| 88 | pub fn set_title(&mut self, title: impl Into<String>) { |
| 89 | self.title = Some(title.into()); |
| 90 | } |
| 91 | |
| 92 | /// Name one track: a `trak/udta/name` box, which is what an mp4 calls a |
| 93 | /// subtitle track in a player's menu. |
| 94 | pub fn set_track_title(&mut self, stream: u32, title: impl Into<String>) -> Result<()> { |
| 95 | let track = self |
| 96 | .tracks |
| 97 | .get_mut(stream as usize) |
| 98 | .ok_or_else(|| Error::corrupt(format!("mp4: no stream {stream} to name")))?; |
| 99 | track.title = Some(title.into()); |
| 100 | Ok(()) |
| 101 | } |
| 102 | |
| 103 | /// Say what a video stream's samples mean after the stream was declared. |
| 104 | /// |
| 105 | /// The `colr` box is part of the sample entry and the sample entry is |
| 106 | /// written at [`Muxer::finish`], so this may be said any time before then — |
| 107 | /// which is what a caller that learns the source's colour space after it has |
| 108 | /// opened the file needs. |
| 109 | pub fn set_color(&mut self, stream: u32, color: ec_core::ColorInfo) -> Result<()> { |
| 110 | let track = self |
| 111 | .tracks |
| 112 | .get_mut(stream as usize) |
| 113 | .ok_or_else(|| Error::corrupt(format!("mp4: no stream {stream} to colour")))?; |
| 114 | match &mut track.info.params.media { |
| 115 | ec_core::MediaParameters::Video(video) => video.color = color, |
| 116 | _ => { |
| 117 | return Err(Error::corrupt(format!( |
| 118 | "mp4: stream {stream} is not a video track" |
| 119 | ))); |
| 120 | } |
| 121 | } |
| 122 | Ok(()) |
| 123 | } |
| 124 | |
| 125 | /// Declare an audio track's encoder delay: `priming_samples` produced |
| 126 | /// before the first audible one, in the track's own sample rate (which is |
| 127 | /// its timescale, so this is a sample count with no conversion). Written |
| 128 | /// as an `edts/elst` media_time shift at [`Muxer::finish`] — the same |
| 129 | /// mechanism a reordered video track's `elst` uses, and the ISO |
| 130 | /// 14496-14 convention for AAC priming. |
| 131 | pub fn set_audio_delay(&mut self, stream: u32, priming_samples: u32) -> Result<()> { |
| 132 | let track = self |
| 133 | .tracks |
| 134 | .get_mut(stream as usize) |
| 135 | .ok_or_else(|| Error::corrupt(format!("mp4: no stream {stream} to delay")))?; |
| 136 | track.audio_delay = i64::from(priming_samples); |
| 137 | Ok(()) |
| 138 | } |
| 139 | |
| 140 | /// Take the writer back once the file is finished. |
| 141 | pub fn into_inner(self) -> W { |
| 142 | self.w |
| 143 | } |
| 144 | |
| 145 | fn start(&mut self) -> Result<()> { |
| 146 | if self.started { |
| 147 | return Ok(()); |
| 148 | } |
| 149 | self.started = true; |
| 150 | let mut head = Vec::with_capacity(64); |
| 151 | let at = open(&mut head, b"ftyp"); |
| 152 | head.extend_from_slice(b"isom"); |
| 153 | head.extend_from_slice(&512u32.to_be_bytes()); |
| 154 | head.extend_from_slice(b"isom"); |
| 155 | head.extend_from_slice(b"iso2"); |
| 156 | for track in &self.tracks { |
| 157 | if let Some(brand) = video_entry(track.info.params.codec) { |
| 158 | head.extend_from_slice(brand); |
| 159 | } |
| 160 | } |
| 161 | head.extend_from_slice(b"mp41"); |
| 162 | close(&mut head, at); |
| 163 | self.mdat_at = head.len() as u64; |
| 164 | // The 64-bit form of an `mdat` header, always: a two-hour 4K export goes |
| 165 | // past 4 GB and the placeholder cannot grow later without moving every |
| 166 | // sample in the file. |
| 167 | head.extend_from_slice(&1u32.to_be_bytes()); |
| 168 | head.extend_from_slice(b"mdat"); |
| 169 | head.extend_from_slice(&0u64.to_be_bytes()); |
| 170 | self.w.write_all(&head)?; |
| 171 | self.pos = head.len() as u64; |
| 172 | Ok(()) |
| 173 | } |
| 174 | |
| 175 | /// Sample durations, resolved: a packet that stated one keeps it, and one |
| 176 | /// that did not gets the step to the next sample — which is what the last |
| 177 | /// sample has no next for, so it repeats the step before it. |
| 178 | fn resolve_durations(track: &mut Track) { |
| 179 | for i in 0..track.samples.len() { |
| 180 | if track.samples[i].duration != 0 { |
| 181 | continue; |
| 182 | } |
| 183 | let step = match track.samples.get(i + 1) { |
| 184 | Some(next) => next.dts - track.samples[i].dts, |
| 185 | None => i |
| 186 | .checked_sub(1) |
| 187 | .map_or(0, |prev| i64::from(track.samples[prev].duration)), |
| 188 | }; |
| 189 | track.samples[i].duration = u32::try_from(step.max(0)).unwrap_or(0); |
| 190 | } |
| 191 | } |
| 192 | |
| 193 | fn write_moov(&mut self) -> Result<()> { |
| 194 | let mut moov = Vec::with_capacity(4096); |
| 195 | let at = open(&mut moov, b"moov"); |
| 196 | let movie_base = TimeBase::from_rate(MOVIE_TIMESCALE); |
| 197 | let duration = self |
| 198 | .tracks |
| 199 | .iter() |
| 200 | .map(|t| { |
| 201 | t.time_base |
| 202 | .rescale(track_ticks(t), movie_base, Rounding::Up) |
| 203 | }) |
| 204 | .max() |
| 205 | .unwrap_or(0); |
| 206 | |
| 207 | let mvhd = open(&mut moov, b"mvhd"); |
| 208 | full_head(&mut moov, 0, 0); |
| 209 | moov.extend_from_slice(&0u32.to_be_bytes()); // creation |
| 210 | moov.extend_from_slice(&0u32.to_be_bytes()); // modification |
| 211 | moov.extend_from_slice(&MOVIE_TIMESCALE.to_be_bytes()); |
| 212 | moov.extend_from_slice(&(duration.max(0) as u32).to_be_bytes()); |
| 213 | moov.extend_from_slice(&0x0001_0000u32.to_be_bytes()); // rate 1.0 |
| 214 | moov.extend_from_slice(&0x0100u16.to_be_bytes()); // volume 1.0 |
| 215 | moov.extend_from_slice(&[0; 2 + 8]); |
| 216 | moov.extend_from_slice(&UNITY_MATRIX); |
| 217 | moov.extend_from_slice(&[0; 24]); // pre_defined |
| 218 | moov.extend_from_slice(&(self.tracks.len() as u32 + 1).to_be_bytes()); |
| 219 | close(&mut moov, mvhd); |
| 220 | |
| 221 | for i in 0..self.tracks.len() { |
| 222 | self.write_trak(&mut moov, i, duration)?; |
| 223 | } |
| 224 | if let Some(title) = &self.title { |
| 225 | let udta = open(&mut moov, b"udta"); |
| 226 | leaf(&mut moov, b"name", title.as_bytes()); |
| 227 | close(&mut moov, udta); |
| 228 | } |
| 229 | close(&mut moov, at); |
| 230 | self.w.write_all(&moov)?; |
| 231 | self.pos += moov.len() as u64; |
| 232 | Ok(()) |
| 233 | } |
| 234 | |
| 235 | fn write_trak(&self, out: &mut Vec<u8>, i: usize, movie_duration: i64) -> Result<()> { |
| 236 | let track = &self.tracks[i]; |
| 237 | let codec = track.info.params.codec; |
| 238 | let at = open(out, b"trak"); |
| 239 | |
| 240 | let tkhd = open(out, b"tkhd"); |
| 241 | full_head(out, 0, 0x7); // enabled, in movie, in preview |
| 242 | out.extend_from_slice(&0u32.to_be_bytes()); |
| 243 | out.extend_from_slice(&0u32.to_be_bytes()); |
| 244 | out.extend_from_slice(&(i as u32 + 1).to_be_bytes()); // track_ID |
| 245 | out.extend_from_slice(&0u32.to_be_bytes()); |
| 246 | out.extend_from_slice(&(movie_duration.max(0) as u32).to_be_bytes()); |
| 247 | out.extend_from_slice(&[0; 8]); |
| 248 | out.extend_from_slice(&0u16.to_be_bytes()); // layer |
| 249 | out.extend_from_slice(&0u16.to_be_bytes()); // alternate group |
| 250 | let volume: u16 = match codec.media_type() { |
| 251 | ec_core::MediaType::Audio => 0x0100, |
| 252 | _ => 0, |
| 253 | }; |
| 254 | out.extend_from_slice(&volume.to_be_bytes()); |
| 255 | out.extend_from_slice(&0u16.to_be_bytes()); |
| 256 | out.extend_from_slice(&UNITY_MATRIX); |
| 257 | let (width, height) = match track.info.params.video() { |
| 258 | Some(v) => (v.width, v.height), |
| 259 | None => (0, 0), |
| 260 | }; |
| 261 | out.extend_from_slice(&(width << 16).to_be_bytes()); |
| 262 | out.extend_from_slice(&(height << 16).to_be_bytes()); |
| 263 | close(out, tkhd); |
| 264 | |
| 265 | // An `elst`, where the first picture is not the first *decoded* one, or |
| 266 | // an audio track's encoder primed samples ahead of the first audible |
| 267 | // one (`set_audio_delay`): a reordered stream's earliest composition |
| 268 | // time is the reorder delay, and without an edit saying so every |
| 269 | // player starts the track that much late. This is where a demuxer's |
| 270 | // `media_time` comes from, and it is a shift, never a trim. |
| 271 | let priming = presentation_start(track).max(track.audio_delay); |
| 272 | if priming > 0 { |
| 273 | let edts = open(out, b"edts"); |
| 274 | let elst = open(out, b"elst"); |
| 275 | full_head(out, 0, 0); |
| 276 | out.extend_from_slice(&1u32.to_be_bytes()); |
| 277 | let movie_base = TimeBase::from_rate(MOVIE_TIMESCALE); |
| 278 | let segment = |
| 279 | track |
| 280 | .time_base |
| 281 | .rescale(track_ticks(track) - priming, movie_base, Rounding::Up); |
| 282 | out.extend_from_slice(&(segment.max(0) as u32).to_be_bytes()); |
| 283 | out.extend_from_slice(&(priming as u32).to_be_bytes()); |
| 284 | out.extend_from_slice(&0x0001_0000u32.to_be_bytes()); // media rate 1.0 |
| 285 | close(out, elst); |
| 286 | close(out, edts); |
| 287 | } |
| 288 | |
| 289 | let mdia = open(out, b"mdia"); |
| 290 | let mdhd = open(out, b"mdhd"); |
| 291 | full_head(out, 0, 0); |
| 292 | out.extend_from_slice(&0u32.to_be_bytes()); |
| 293 | out.extend_from_slice(&0u32.to_be_bytes()); |
| 294 | out.extend_from_slice(&track.timescale.to_be_bytes()); |
| 295 | out.extend_from_slice(&(track_ticks(track).max(0) as u32).to_be_bytes()); |
| 296 | out.extend_from_slice(&pack_language(track.info.language.as_deref()).to_be_bytes()); |
| 297 | out.extend_from_slice(&0u16.to_be_bytes()); // pre_defined |
| 298 | close(out, mdhd); |
| 299 | |
| 300 | let (handler, handler_name) = match codec.media_type() { |
| 301 | ec_core::MediaType::Video => (b"vide", "VideoHandler"), |
| 302 | ec_core::MediaType::Audio => (b"soun", "SoundHandler"), |
| 303 | ec_core::MediaType::Subtitle => (b"sbtl", "SubtitleHandler"), |
| 304 | }; |
| 305 | let hdlr = open(out, b"hdlr"); |
| 306 | full_head(out, 0, 0); |
| 307 | out.extend_from_slice(&0u32.to_be_bytes()); // pre_defined |
| 308 | out.extend_from_slice(handler); |
| 309 | out.extend_from_slice(&[0; 12]); // reserved |
| 310 | out.extend_from_slice(handler_name.as_bytes()); |
| 311 | out.push(0); |
| 312 | close(out, hdlr); |
| 313 | |
| 314 | let minf = open(out, b"minf"); |
| 315 | match codec.media_type() { |
| 316 | ec_core::MediaType::Video => { |
| 317 | let vmhd = open(out, b"vmhd"); |
| 318 | full_head(out, 0, 1); |
| 319 | out.extend_from_slice(&[0; 8]); // graphicsmode + opcolor |
| 320 | close(out, vmhd); |
| 321 | } |
| 322 | ec_core::MediaType::Audio => { |
| 323 | let smhd = open(out, b"smhd"); |
| 324 | full_head(out, 0, 0); |
| 325 | out.extend_from_slice(&[0; 4]); // balance + reserved |
| 326 | close(out, smhd); |
| 327 | } |
| 328 | ec_core::MediaType::Subtitle => { |
| 329 | let nmhd = open(out, b"nmhd"); |
| 330 | full_head(out, 0, 0); |
| 331 | close(out, nmhd); |
| 332 | } |
| 333 | } |
| 334 | let dinf = open(out, b"dinf"); |
| 335 | let dref = open(out, b"dref"); |
| 336 | full_head(out, 0, 0); |
| 337 | out.extend_from_slice(&1u32.to_be_bytes()); |
| 338 | let url = open(out, b"url "); |
| 339 | full_head(out, 0, 1); // flag 1: the media is in this very file |
| 340 | close(out, url); |
| 341 | close(out, dref); |
| 342 | close(out, dinf); |
| 343 | |
| 344 | let stbl = open(out, b"stbl"); |
| 345 | let stsd = open(out, b"stsd"); |
| 346 | full_head(out, 0, 0); |
| 347 | out.extend_from_slice(&1u32.to_be_bytes()); |
| 348 | sample_entry(out, &track.info)?; |
| 349 | close(out, stsd); |
| 350 | sample_tables(out, track); |
| 351 | close(out, stbl); |
| 352 | close(out, minf); |
| 353 | close(out, mdia); |
| 354 | |
| 355 | if let Some(title) = &track.title { |
| 356 | let udta = open(out, b"udta"); |
| 357 | leaf(out, b"name", title.as_bytes()); |
| 358 | close(out, udta); |
| 359 | } |
| 360 | close(out, at); |
| 361 | Ok(()) |
| 362 | } |
| 363 | } |
| 364 | |
| 365 | impl<W: Write + Seek + Send> Muxer for Mp4Muxer<W> { |
| 366 | /// Declare a stream — **at any point before [`Muxer::finish`]**, which is |
| 367 | /// more than the trait promises. Samples are written where they arrive and |
| 368 | /// the chunk table follows, so a track declared after the picture is |
| 369 | /// already in the `mdat` costs nothing: its `trak` is built at the end with |
| 370 | /// every other. That is what lets an export mix and encode its sound *while* |
| 371 | /// it writes the picture, and add its subtitles once the film's length is |
| 372 | /// known. |
| 373 | fn add_stream(&mut self, info: StreamInfo) -> Result<u32> { |
| 374 | let timescale = u32::try_from(info.time_base.den()).map_err(|_| { |
| 375 | Error::corrupt(format!( |
| 376 | "mp4: a time base of 1/{} does not fit a 32-bit timescale", |
| 377 | info.time_base.den() |
| 378 | )) |
| 379 | })?; |
| 380 | if timescale == 0 { |
| 381 | return Err(Error::corrupt("mp4: a stream with a zero timescale")); |
| 382 | } |
| 383 | let index = self.tracks.len() as u32; |
| 384 | self.tracks.push(Track { |
| 385 | info, |
| 386 | timescale, |
| 387 | time_base: TimeBase::from_rate(timescale), |
| 388 | samples: Vec::new(), |
| 389 | chunks: Vec::new(), |
| 390 | chunk_end: u64::MAX, |
| 391 | title: None, |
| 392 | audio_delay: 0, |
| 393 | }); |
| 394 | Ok(index) |
| 395 | } |
| 396 | |
| 397 | fn write_packet(&mut self, packet: &Packet) -> Result<()> { |
| 398 | self.start()?; |
| 399 | let pos = self.pos; |
| 400 | let track = self |
| 401 | .tracks |
| 402 | .get_mut(packet.stream as usize) |
| 403 | .ok_or_else(|| Error::corrupt(format!("mp4: no stream {}", packet.stream)))?; |
| 404 | let to = track.time_base; |
| 405 | let at = |ticks: i64| packet.time_base.rescale(ticks, to, Rounding::Nearest); |
| 406 | let dts = match (packet.dts, packet.pts) { |
| 407 | (Some(dts), _) => at(dts), |
| 408 | (None, Some(pts)) => at(pts), |
| 409 | // A stream that states no time at all is laid end to end, which is |
| 410 | // what a constant-rate audio track is anyway. |
| 411 | (None, None) => track |
| 412 | .samples |
| 413 | .last() |
| 414 | .map_or(0, |s| s.dts + i64::from(s.duration)), |
| 415 | }; |
| 416 | let cts = packet.pts.map_or(dts, at); |
| 417 | let size = u32::try_from(packet.data.len()) |
| 418 | .map_err(|_| Error::corrupt("mp4: a sample over 4 GB"))?; |
| 419 | track.samples.push(Sample { |
| 420 | size, |
| 421 | dts, |
| 422 | cts, |
| 423 | duration: packet.duration.map_or(0, |d| at(d).max(0) as u32), |
| 424 | sync: packet.flags.keyframe, |
| 425 | }); |
| 426 | match track.chunk_end == pos { |
| 427 | true => { |
| 428 | if let Some(chunk) = track.chunks.last_mut() { |
| 429 | chunk.1 += 1; |
| 430 | } |
| 431 | } |
| 432 | false => track.chunks.push((pos, 1)), |
| 433 | } |
| 434 | track.chunk_end = pos + u64::from(size); |
| 435 | self.w.write_all(&packet.data)?; |
| 436 | self.pos = pos + u64::from(size); |
| 437 | Ok(()) |
| 438 | } |
| 439 | |
| 440 | fn finish(&mut self) -> Result<()> { |
| 441 | if self.finished { |
| 442 | return Ok(()); |
| 443 | } |
| 444 | self.finished = true; |
| 445 | self.start()?; |
| 446 | // The mdat's real size, into the 64-bit field left for it. |
| 447 | let mdat_len = self.pos - self.mdat_at; |
| 448 | self.w.seek(SeekFrom::Start(self.mdat_at + 8))?; |
| 449 | self.w.write_all(&mdat_len.to_be_bytes())?; |
| 450 | self.w.seek(SeekFrom::Start(self.pos))?; |
| 451 | for track in &mut self.tracks { |
| 452 | Mp4Muxer::<W>::resolve_durations(track); |
| 453 | } |
| 454 | self.write_moov()?; |
| 455 | self.w.flush()?; |
| 456 | Ok(()) |
| 457 | } |
| 458 | } |
| 459 | |
| 460 | /// Total media ticks of a track: from the first sample's decode time to the end |
| 461 | /// of the last one. A span rather than an endpoint, because a track handed over |
| 462 | /// with an edit list already applied starts at a negative decode time and its |
| 463 | /// duration is still the whole of it. |
| 464 | fn track_ticks(track: &Track) -> i64 { |
| 465 | let first = track.samples.first().map_or(0, |s| s.dts); |
| 466 | track |
| 467 | .samples |
| 468 | .last() |
| 469 | .map_or(0, |s| s.dts + i64::from(s.duration) - first) |
| 470 | } |
| 471 | |
| 472 | /// Where the first *picture* is on the written timeline: decode times start at |
| 473 | /// zero in the file (`stts` states durations, not instants), so this is the |
| 474 | /// smallest composition offset — the reorder delay of a stream with B-frames and |
| 475 | /// zero for everything else. |
| 476 | fn presentation_start(track: &Track) -> i64 { |
| 477 | let first = track.samples.first().map_or(0, |s| s.dts); |
| 478 | track |
| 479 | .samples |
| 480 | .iter() |
| 481 | .map(|s| s.cts - first) |
| 482 | .min() |
| 483 | .unwrap_or(0) |
| 484 | } |
| 485 | |
| 486 | /// The `stts`/`ctts`/`stss`/`stsc`/`stsz` and chunk-offset tables of one track. |
| 487 | fn sample_tables(out: &mut Vec<u8>, track: &Track) { |
| 488 | // stts: runs of equal durations, which for constant-rate video is one entry |
| 489 | // for the whole film. |
| 490 | let stts = open(out, b"stts"); |
| 491 | full_head(out, 0, 0); |
| 492 | let count_at = out.len(); |
| 493 | out.extend_from_slice(&0u32.to_be_bytes()); |
| 494 | let mut runs = 0u32; |
| 495 | let mut i = 0; |
| 496 | while i < track.samples.len() { |
| 497 | let delta = track.samples[i].duration; |
| 498 | let mut run = 0u32; |
| 499 | while i < track.samples.len() && track.samples[i].duration == delta { |
| 500 | run += 1; |
| 501 | i += 1; |
| 502 | } |
| 503 | out.extend_from_slice(&run.to_be_bytes()); |
| 504 | out.extend_from_slice(&delta.to_be_bytes()); |
| 505 | runs += 1; |
| 506 | } |
| 507 | out[count_at..count_at + 4].copy_from_slice(&runs.to_be_bytes()); |
| 508 | close(out, stts); |
| 509 | |
| 510 | // ctts, only where something is actually reordered. |
| 511 | let offsets: Vec<i64> = track.samples.iter().map(|s| s.cts - s.dts).collect(); |
| 512 | if offsets.iter().any(|&o| o != 0) { |
| 513 | let negative = offsets.iter().any(|&o| o < 0); |
| 514 | let ctts = open(out, b"ctts"); |
| 515 | // Version 1 states the offset as signed, which is the only way to say |
| 516 | // that a picture is shown *before* it is decoded. |
| 517 | full_head(out, u8::from(negative), 0); |
| 518 | let count_at = out.len(); |
| 519 | out.extend_from_slice(&0u32.to_be_bytes()); |
| 520 | let mut runs = 0u32; |
| 521 | let mut i = 0; |
| 522 | while i < offsets.len() { |
| 523 | let offset = offsets[i]; |
| 524 | let mut run = 0u32; |
| 525 | while i < offsets.len() && offsets[i] == offset { |
| 526 | run += 1; |
| 527 | i += 1; |
| 528 | } |
| 529 | out.extend_from_slice(&run.to_be_bytes()); |
| 530 | out.extend_from_slice(&(offset as i32).to_be_bytes()); |
| 531 | runs += 1; |
| 532 | } |
| 533 | out[count_at..count_at + 4].copy_from_slice(&runs.to_be_bytes()); |
| 534 | close(out, ctts); |
| 535 | } |
| 536 | |
| 537 | // stss, only where some samples are not sync ones: no box at all means |
| 538 | // every sample is a random access point, which is the truth for audio. |
| 539 | if track.samples.iter().any(|s| !s.sync) { |
| 540 | let stss = open(out, b"stss"); |
| 541 | full_head(out, 0, 0); |
| 542 | let syncs: Vec<u32> = track |
| 543 | .samples |
| 544 | .iter() |
| 545 | .enumerate() |
| 546 | .filter(|(_, s)| s.sync) |
| 547 | .map(|(i, _)| i as u32 + 1) |
| 548 | .collect(); |
| 549 | out.extend_from_slice(&(syncs.len() as u32).to_be_bytes()); |
| 550 | for n in syncs { |
| 551 | out.extend_from_slice(&n.to_be_bytes()); |
| 552 | } |
| 553 | close(out, stss); |
| 554 | } |
| 555 | |
| 556 | // stsc: runs of chunks holding the same number of samples. |
| 557 | let stsc = open(out, b"stsc"); |
| 558 | full_head(out, 0, 0); |
| 559 | let count_at = out.len(); |
| 560 | out.extend_from_slice(&0u32.to_be_bytes()); |
| 561 | let mut runs = 0u32; |
| 562 | let mut first = 0usize; |
| 563 | while first < track.chunks.len() { |
| 564 | let per = track.chunks[first].1; |
| 565 | out.extend_from_slice(&(first as u32 + 1).to_be_bytes()); |
| 566 | out.extend_from_slice(&per.to_be_bytes()); |
| 567 | out.extend_from_slice(&1u32.to_be_bytes()); // sample_description_index |
| 568 | runs += 1; |
| 569 | first += 1; |
| 570 | while first < track.chunks.len() && track.chunks[first].1 == per { |
| 571 | first += 1; |
| 572 | } |
| 573 | } |
| 574 | out[count_at..count_at + 4].copy_from_slice(&runs.to_be_bytes()); |
| 575 | close(out, stsc); |
| 576 | |
| 577 | // stsz: one size for all, where they really are all one size. |
| 578 | let stsz = open(out, b"stsz"); |
| 579 | full_head(out, 0, 0); |
| 580 | let uniform = track |
| 581 | .samples |
| 582 | .first() |
| 583 | .map(|f| f.size) |
| 584 | .filter(|&size| track.samples.iter().all(|s| s.size == size)) |
| 585 | .unwrap_or(0); |
| 586 | out.extend_from_slice(&uniform.to_be_bytes()); |
| 587 | out.extend_from_slice(&(track.samples.len() as u32).to_be_bytes()); |
| 588 | if uniform == 0 { |
| 589 | for sample in &track.samples { |
| 590 | out.extend_from_slice(&sample.size.to_be_bytes()); |
| 591 | } |
| 592 | } |
| 593 | close(out, stsz); |
| 594 | |
| 595 | // co64 where the file is big enough to need it, stco where it is not. |
| 596 | let big = track.chunks.iter().any(|&(at, _)| at > u64::from(u32::MAX)); |
| 597 | let kind = if big { b"co64" } else { b"stco" }; |
| 598 | let chunks = open(out, kind); |
| 599 | full_head(out, 0, 0); |
| 600 | out.extend_from_slice(&(track.chunks.len() as u32).to_be_bytes()); |
| 601 | for &(at, _) in &track.chunks { |
| 602 | match big { |
| 603 | true => out.extend_from_slice(&at.to_be_bytes()), |
| 604 | false => out.extend_from_slice(&(at as u32).to_be_bytes()), |
| 605 | } |
| 606 | } |
| 607 | close(out, chunks); |
| 608 | } |
| 609 | |
| 610 | /// The sample entry name and configuration box of a video codec. |
| 611 | fn video_entry(codec: CodecId) -> Option<&'static [u8; 4]> { |
| 612 | Some(match codec { |
| 613 | CodecId::H264 => b"avc1", |
| 614 | // `hvc1` and not `hev1`: the parameter sets are in the `hvcC`, which is |
| 615 | // exactly what the `hvc1` name promises a reader. |
| 616 | CodecId::H265 => b"hvc1", |
| 617 | CodecId::Av1 => b"av01", |
| 618 | CodecId::Vp9 => b"vp09", |
| 619 | CodecId::Vp8 => b"vp08", |
| 620 | _ => return None, |
| 621 | }) |
| 622 | } |
| 623 | |
| 624 | fn config_box(codec: CodecId) -> &'static [u8; 4] { |
| 625 | match codec { |
| 626 | CodecId::H264 => b"avcC", |
| 627 | CodecId::H265 => b"hvcC", |
| 628 | CodecId::Av1 => b"av1C", |
| 629 | _ => b"vpcC", |
| 630 | } |
| 631 | } |
| 632 | |
| 633 | /// One `stsd` entry for `info`. |
| 634 | fn sample_entry(out: &mut Vec<u8>, info: &StreamInfo) -> Result<()> { |
| 635 | let codec = info.params.codec; |
| 636 | let extradata = info.params.extradata.as_deref(); |
| 637 | if let Some(name) = video_entry(codec) { |
| 638 | let video = info.params.video().ok_or_else(|| { |
| 639 | Error::corrupt("mp4: a video codec declared without video parameters") |
| 640 | })?; |
| 641 | let config = extradata.ok_or_else(|| { |
| 642 | Error::unsupported( |
| 643 | format!("mp4: a {} track with no codec configuration", codec.name()), |
| 644 | "an ISOBMFF video sample entry has to carry its avcC/hvcC/av1C/vpcC record", |
| 645 | ) |
| 646 | })?; |
| 647 | let at = open(out, name); |
| 648 | out.extend_from_slice(&[0; 6]); // reserved |
| 649 | out.extend_from_slice(&1u16.to_be_bytes()); // data_reference_index |
| 650 | out.extend_from_slice(&[0; 16]); // pre_defined + reserved |
| 651 | out.extend_from_slice(&(video.width as u16).to_be_bytes()); |
| 652 | out.extend_from_slice(&(video.height as u16).to_be_bytes()); |
| 653 | out.extend_from_slice(&0x0048_0000u32.to_be_bytes()); // 72 dpi |
| 654 | out.extend_from_slice(&0x0048_0000u32.to_be_bytes()); |
| 655 | out.extend_from_slice(&0u32.to_be_bytes()); // reserved |
| 656 | out.extend_from_slice(&1u16.to_be_bytes()); // frame_count |
| 657 | out.extend_from_slice(&[0; 32]); // compressorname |
| 658 | out.extend_from_slice(&0x0018u16.to_be_bytes()); // depth: colour, no alpha |
| 659 | out.extend_from_slice(&(-1i16).to_be_bytes()); // pre_defined |
| 660 | leaf(out, config_box(codec), config); |
| 661 | colour_boxes(out, video.color, video.light); |
| 662 | if let Some(sar) = video.sample_aspect_ratio { |
| 663 | let pasp = open(out, b"pasp"); |
| 664 | out.extend_from_slice(&(sar.num() as u32).to_be_bytes()); |
| 665 | out.extend_from_slice(&(sar.den() as u32).to_be_bytes()); |
| 666 | close(out, pasp); |
| 667 | } |
| 668 | close(out, at); |
| 669 | return Ok(()); |
| 670 | } |
| 671 | if codec == CodecId::Tx3g { |
| 672 | let at = open(out, b"tx3g"); |
| 673 | out.extend_from_slice(&[0; 6]); |
| 674 | out.extend_from_slice(&1u16.to_be_bytes()); |
| 675 | match extradata { |
| 676 | // Round-tripped from another mp4: the style it already stated. |
| 677 | Some(style) if style.len() >= 30 => out.extend_from_slice(style), |
| 678 | _ => { |
| 679 | out.extend_from_slice(&0u32.to_be_bytes()); // displayFlags |
| 680 | out.push(1); // horizontal justification: centred |
| 681 | out.push(0xFF); // vertical: bottom |
| 682 | out.extend_from_slice(&[0, 0, 0, 0]); // background: transparent |
| 683 | out.extend_from_slice(&[0; 8]); // text box: the whole picture |
| 684 | out.extend_from_slice(&0u16.to_be_bytes()); // startChar |
| 685 | out.extend_from_slice(&0u16.to_be_bytes()); // endChar |
| 686 | out.extend_from_slice(&1u16.to_be_bytes()); // font-ID |
| 687 | out.push(0); // face-style-flags |
| 688 | out.push(18); // font-size |
| 689 | out.extend_from_slice(&[0xFF; 4]); // text colour: opaque white |
| 690 | let ftab = open(out, b"ftab"); |
| 691 | out.extend_from_slice(&1u16.to_be_bytes()); |
| 692 | out.extend_from_slice(&1u16.to_be_bytes()); |
| 693 | out.push(5); |
| 694 | out.extend_from_slice(b"Serif"); |
| 695 | close(out, ftab); |
| 696 | } |
| 697 | } |
| 698 | close(out, at); |
| 699 | return Ok(()); |
| 700 | } |
| 701 | |
| 702 | let (name, audio) = match info.params.audio() { |
| 703 | Some(audio) => (audio_entry(codec)?, audio), |
| 704 | None => { |
| 705 | return Err(Error::unsupported( |
| 706 | format!("mp4: a {} track", codec.name()), |
| 707 | "this writer has a sample entry for video, AAC-family audio and tx3g text only; \ |
| 708 | Matroska carries the rest", |
| 709 | )); |
| 710 | } |
| 711 | }; |
| 712 | let at = open(out, name); |
| 713 | out.extend_from_slice(&[0; 6]); |
| 714 | out.extend_from_slice(&1u16.to_be_bytes()); // data_reference_index |
| 715 | out.extend_from_slice(&[0; 8]); // version, revision, vendor |
| 716 | out.extend_from_slice(&(audio.layout.channel_count() as u16).to_be_bytes()); |
| 717 | out.extend_from_slice(&(audio.bits_per_sample.unwrap_or(16) as u16).to_be_bytes()); |
| 718 | out.extend_from_slice(&0u16.to_be_bytes()); // pre_defined |
| 719 | out.extend_from_slice(&0u16.to_be_bytes()); // reserved |
| 720 | // 16.16, so a rate over 65535 is stated as its low half — which is what |
| 721 | // every writer does and what the `mdhd` timescale says exactly anyway. |
| 722 | out.extend_from_slice(&((audio.sample_rate as u16 as u32) << 16).to_be_bytes()); |
| 723 | match codec { |
| 724 | CodecId::Aac => { |
| 725 | let asc = extradata.ok_or_else(|| { |
| 726 | Error::unsupported( |
| 727 | "mp4: an AAC track with no AudioSpecificConfig", |
| 728 | "an esds descriptor is the only place an mp4 states an AAC track's setup", |
| 729 | ) |
| 730 | })?; |
| 731 | let esds = open(out, b"esds"); |
| 732 | out.extend_from_slice(&Esds::aac(asc).write()); |
| 733 | close(out, esds); |
| 734 | } |
| 735 | CodecId::Mp3 => { |
| 736 | let mut mp3 = Esds::aac(&[][..]); |
| 737 | mp3.object_type = object_type::MPEG1_AUDIO; |
| 738 | mp3.decoder_specific = None; |
| 739 | let esds = open(out, b"esds"); |
| 740 | out.extend_from_slice(&mp3.write()); |
| 741 | close(out, esds); |
| 742 | } |
| 743 | CodecId::Ac3 | CodecId::EAc3 | CodecId::Flac | CodecId::Opus | CodecId::Alac => { |
| 744 | let config = extradata.ok_or_else(|| { |
| 745 | Error::unsupported( |
| 746 | format!("mp4: a {} track with no codec configuration", codec.name()), |
| 747 | "its sample entry has to carry the codec's own configuration box", |
| 748 | ) |
| 749 | })?; |
| 750 | match codec { |
| 751 | // ALAC's cookie is carried with its box header, so it is written |
| 752 | // back exactly as it was read. |
| 753 | CodecId::Alac if config.len() > 8 && &config[4..8] == b"alac" => { |
| 754 | out.extend_from_slice(config) |
| 755 | } |
| 756 | CodecId::Opus => leaf(out, b"dOps", &dops(config)), |
| 757 | _ => leaf(out, audio_config_box(codec), config), |
| 758 | } |
| 759 | } |
| 760 | _ => {} |
| 761 | } |
| 762 | close(out, at); |
| 763 | Ok(()) |
| 764 | } |
| 765 | |
| 766 | /// `colr`, and the two HDR boxes where the grade stated them — metadata a remux |
| 767 | /// must not quietly drop, because nothing downstream can reconstruct it. |
| 768 | fn colour_boxes(out: &mut Vec<u8>, color: ec_core::ColorInfo, light: ContentLight) { |
| 769 | if color != ec_core::ColorInfo::default() { |
| 770 | let colr = open(out, b"colr"); |
| 771 | out.extend_from_slice(b"nclx"); |
| 772 | out.extend_from_slice(&u16::from(color.primaries).to_be_bytes()); |
| 773 | out.extend_from_slice(&u16::from(color.transfer).to_be_bytes()); |
| 774 | out.extend_from_slice(&u16::from(color.matrix).to_be_bytes()); |
| 775 | out.push(u8::from(color.full_range) << 7); |
| 776 | close(out, colr); |
| 777 | } |
| 778 | if light.mastering_max.is_some() || light.mastering_min.is_some() { |
| 779 | let mdcv = open(out, b"mdcv"); |
| 780 | // Display primaries and white point: not carried by [`ContentLight`], |
| 781 | // which holds the luminances a tone map needs. BT.2020 is what an HDR |
| 782 | // grade is mastered on and what every writer states here. |
| 783 | for xy in BT2020_PRIMARIES { |
| 784 | out.extend_from_slice(&xy.to_be_bytes()); |
| 785 | } |
| 786 | let nits = |v: Option<f32>| ((v.unwrap_or(0.0) * 10_000.0) as u32).to_be_bytes(); |
| 787 | out.extend_from_slice(&nits(light.mastering_max)); |
| 788 | out.extend_from_slice(&nits(light.mastering_min)); |
| 789 | close(out, mdcv); |
| 790 | } |
| 791 | if light.max_cll.is_some() || light.max_fall.is_some() { |
| 792 | let clli = open(out, b"clli"); |
| 793 | out.extend_from_slice(&(light.max_cll.unwrap_or(0.0) as u16).to_be_bytes()); |
| 794 | out.extend_from_slice(&(light.max_fall.unwrap_or(0.0) as u16).to_be_bytes()); |
| 795 | close(out, clli); |
| 796 | } |
| 797 | } |
| 798 | |
| 799 | /// BT.2020 green, blue, red and D65, in the 0.00002 units an `mdcv` states them. |
| 800 | const BT2020_PRIMARIES: [u16; 8] = [8500, 39850, 6550, 2300, 35400, 14600, 15635, 16450]; |
| 801 | |
| 802 | const UNITY_MATRIX: [u8; 36] = { |
| 803 | let mut m = [0u8; 36]; |
| 804 | m[0] = 0x00; |
| 805 | m[1] = 0x01; |
| 806 | m[16] = 0x00; |
| 807 | m[17] = 0x01; |
| 808 | m[32] = 0x40; |
| 809 | m |
| 810 | }; |
| 811 | |
| 812 | fn audio_entry(codec: CodecId) -> Result<&'static [u8; 4]> { |
| 813 | Ok(match codec { |
| 814 | CodecId::Aac | CodecId::Mp3 => b"mp4a", |
| 815 | CodecId::Ac3 => b"ac-3", |
| 816 | CodecId::EAc3 => b"ec-3", |
| 817 | CodecId::Alac => b"alac", |
| 818 | CodecId::Flac => b"fLaC", |
| 819 | CodecId::Opus => b"Opus", |
| 820 | CodecId::PcmS16Le => b"sowt", |
| 821 | CodecId::PcmS16Be => b"twos", |
| 822 | CodecId::PcmU8 => b"raw ", |
| 823 | _ => { |
| 824 | return Err(Error::unsupported( |
| 825 | format!("mp4: a {} audio track", codec.name()), |
| 826 | "no ISOBMFF sample entry is defined for it", |
| 827 | )); |
| 828 | } |
| 829 | }) |
| 830 | } |
| 831 | |
| 832 | fn audio_config_box(codec: CodecId) -> &'static [u8; 4] { |
| 833 | match codec { |
| 834 | CodecId::Ac3 => b"dac3", |
| 835 | CodecId::EAc3 => b"dec3", |
| 836 | CodecId::Flac => b"dfLa", |
| 837 | _ => b"dOps", |
| 838 | } |
| 839 | } |
| 840 | |
| 841 | /// The `dOps` payload from an `OpusHead`: same fields, opposite byte order, and |
| 842 | /// without the magic — the inverse of what the demuxer does on the way in. |
| 843 | fn dops(head: &[u8]) -> Vec<u8> { |
| 844 | let body = match head.starts_with(b"OpusHead") { |
| 845 | true => &head[8..], |
| 846 | false => head, |
| 847 | }; |
| 848 | let le16 = |at: usize| { |
| 849 | u16::from_le_bytes([ |
| 850 | body.get(at).copied().unwrap_or(0), |
| 851 | body.get(at + 1).copied().unwrap_or(0), |
| 852 | ]) |
| 853 | }; |
| 854 | let mut out = Vec::with_capacity(body.len()); |
| 855 | out.push(0); // dOps version |
| 856 | out.push(body.get(1).copied().unwrap_or(2)); // channel count |
| 857 | out.extend_from_slice(&le16(2).to_be_bytes()); // pre-skip |
| 858 | let rate = u32::from_le_bytes([ |
| 859 | body.get(4).copied().unwrap_or(0), |
| 860 | body.get(5).copied().unwrap_or(0), |
| 861 | body.get(6).copied().unwrap_or(0), |
| 862 | body.get(7).copied().unwrap_or(0), |
| 863 | ]); |
| 864 | out.extend_from_slice(&rate.to_be_bytes()); |
| 865 | out.extend_from_slice(&le16(8).to_be_bytes()); // output gain |
| 866 | out.extend_from_slice(&body[10.min(body.len())..]); |
| 867 | out |
| 868 | } |
| 869 | |
| 870 | /// Three lowercase letters into the five-bit-a-letter packing an `mdhd` states a |
| 871 | /// language in; `und` where the track never said. |
| 872 | fn pack_language(language: Option<&str>) -> u16 { |
| 873 | let tag = language.filter(|l| l.len() == 3).unwrap_or("und"); |
| 874 | tag.bytes().fold(0u16, |packed, b| { |
| 875 | (packed << 5) | u16::from(b.to_ascii_lowercase().wrapping_sub(0x60) & 0x1F) |
| 876 | }) |
| 877 | } |
| 878 | |
| 879 | #[cfg(test)] |
| 880 | mod tests { |
| 881 | use super::*; |
| 882 | |
| 883 | #[test] |
| 884 | fn language_packing_is_the_demuxers_inverse() { |
| 885 | for tag in ["tur", "eng", "und"] { |
| 886 | let packed = pack_language(Some(tag)); |
| 887 | let back: String = (0..3) |
| 888 | .rev() |
| 889 | .map(|i| char::from(0x60 + ((packed >> (i * 5)) & 0x1F) as u8)) |
| 890 | .collect(); |
| 891 | assert_eq!(back, tag); |
| 892 | } |
| 893 | assert_eq!(pack_language(None), pack_language(Some("und"))); |
| 894 | assert_eq!(pack_language(Some("nonsense")), pack_language(Some("und"))); |
| 895 | } |
| 896 | |
| 897 | #[test] |
| 898 | fn an_opus_head_round_trips_through_dops() { |
| 899 | let head = crate::demux::opus_head(&[0, 2, 0x01, 0x38, 0, 0, 0xBB, 0x80, 0, 0, 1, 2, 3]); |
| 900 | let back = dops(&head); |
| 901 | assert_eq!(back[0], 0, "dOps version"); |
| 902 | assert_eq!(back[1], 2, "channels"); |
| 903 | assert_eq!(u16::from_be_bytes([back[2], back[3]]), 312); |
| 904 | assert_eq!( |
| 905 | u32::from_be_bytes([back[4], back[5], back[6], back[7]]), |
| 906 | 48_000 |
| 907 | ); |
| 908 | assert_eq!(&back[10..], &[1, 2, 3], "mapping family and table"); |
| 909 | } |
| 910 | } |