Matroska/WebM muxer with SeekHead and Cues
Browse files at this commit550709bae4a81c3398556724dae29bf4c96fc3d1Parent: 4888147- feat
- Matroska/WebM muxer with SeekHead and Cues
2 changed files +643 -3
crates/ec-matroska/src/lib.rsmodified+6 -3
| @@ -1,8 +1,9 @@ | ||
| 1 | 1 | //! Matroska (`.mkv`, `.mka`, `.mks`, `.mk3d`) and WebM, both directions. |
| 2 | 2 | //! |
| 3 | -//! [`MatroskaDemuxer`] reads a container into [`ec_core::Packet`]s through the | |
| 4 | -//! [`ec_core::Demuxer`] contract, so nothing above it knows which container it | |
| 5 | -//! is holding. | |
| 3 | +//! [`MatroskaDemuxer`] reads a container into [`ec_core::Packet`]s and | |
| 4 | +//! [`MatroskaMuxer`] writes them back out; both speak the [`ec_core::Demuxer`] | |
| 5 | +//! and [`ec_core::Muxer`] contracts, so nothing above them knows which container | |
| 6 | +//! it is holding. | |
| 6 | 7 | //! |
| 7 | 8 | //! Contracts worth knowing before implementing against this crate: |
| 8 | 9 | //! |
| @@ -35,8 +36,10 @@ | ||
| 35 | 36 | |
| 36 | 37 | mod demux; |
| 37 | 38 | mod ebml; |
| 39 | +mod mux; | |
| 38 | 40 | |
| 39 | 41 | pub use demux::MatroskaDemuxer; |
| 42 | +pub use mux::{MAX_TRACKS, MUX_TIME_BASE, MatroskaMuxer}; | |
| 40 | 43 | |
| 41 | 44 | /// True when `head` starts with an EBML header, which is what a Matroska or |
| 42 | 45 | /// WebM file begins with and what a probe needs to see to hand a file here. |
crates/ec-matroska/src/mux.rsadded+637 -0
| @@ -0,0 +1,637 @@ | ||
| 1 | +//! The Matroska/WebM writer: EBML header, one `Segment` of clusters, and the | |
| 2 | +//! `SeekHead` + `Cues` a player seeks with. | |
| 3 | +//! | |
| 4 | +//! The file is patched three times at [`Muxer::finish`] — the segment size, the | |
| 5 | +//! duration and the `SeekHead` reserved in front of the `Info` — so a killed | |
| 6 | +//! process leaves an unfinished file rather than a wrong one. | |
| 7 | + | |
| 8 | +use std::io::{Seek, SeekFrom, Write}; | |
| 9 | + | |
| 10 | +use ec_core::{ | |
| 11 | + CodecId, Error, MediaParameters, MediaType, Muxer, Packet, Result, Rounding, StreamInfo, | |
| 12 | + TimeBase, | |
| 13 | +}; | |
| 14 | + | |
| 15 | +use crate::ebml::{self, elem, elem_head_len, float, put_id, put_size, uint}; | |
| 16 | + | |
| 17 | +/// One millisecond, the tick every Matroska muxer writes and this one's block | |
| 18 | +/// timestamps are in. The *rate* is not derived from it — `DefaultDuration` is, | |
| 19 | +/// in exact nanoseconds — so a millisecond is precise enough for the | |
| 20 | +/// presentation times and coarse enough to keep a cluster's 16-bit relative | |
| 21 | +/// timestamp covering half a minute. | |
| 22 | +const TIMESTAMP_SCALE_NS: u64 = 1_000_000; | |
| 23 | +/// The time base that scale is: every packet is rescaled into it. | |
| 24 | +pub const MUX_TIME_BASE: TimeBase = TimeBase::new(1, 1_000); | |
| 25 | +/// A cluster is buffered whole (its size is a header field), so it is flushed | |
| 26 | +/// at the first keyframe past this — a ceiling on what the muxer holds, not a | |
| 27 | +/// target. | |
| 28 | +const CLUSTER_BYTES: usize = 4 << 20; | |
| 29 | +/// ...and on how far a block's timestamp may sit from its cluster's: the field | |
| 30 | +/// is a signed 16-bit millisecond count. | |
| 31 | +const CLUSTER_MS: i64 = 30_000; | |
| 32 | +/// Bytes reserved in front of the `Info` for the `SeekHead` written at | |
| 33 | +/// [`Muxer::finish`]: three entries need about 60, and whatever is left over is | |
| 34 | +/// filled with a `Void`. | |
| 35 | +const SEEK_HEAD_RESERVE: usize = 128; | |
| 36 | +/// A block writes its track number as a one-byte EBML integer (`0x80 | track`), | |
| 37 | +/// and 127 is one number too far: its byte is `0xFF`, the all-ones | |
| 38 | +/// variable-length integer EBML spells *unknown* with. The numbers therefore run | |
| 39 | +/// `1..=126`, and a file asking for more is refused by name rather than written | |
| 40 | +/// with a byte that means another track, or none. | |
| 41 | +pub const MAX_TRACKS: usize = 0x7E; | |
| 42 | + | |
| 43 | +struct MuxTrack { | |
| 44 | + number: u64, | |
| 45 | + media: MediaType, | |
| 46 | + time_base: TimeBase, | |
| 47 | + /// Nanoseconds a frame lasts, where the stream stated a rate. | |
| 48 | + frame_ns: Option<u64>, | |
| 49 | +} | |
| 50 | + | |
| 51 | +/// One `CuePoint` waiting for [`Muxer::finish`]. | |
| 52 | +struct CuePoint { | |
| 53 | + time: i64, | |
| 54 | + track: u64, | |
| 55 | + /// Offset of the cluster from the start of the segment's payload, which is | |
| 56 | + /// what `CueClusterPosition` states. | |
| 57 | + cluster: u64, | |
| 58 | + /// ...and of the block from the start of that cluster's payload. | |
| 59 | + relative: u64, | |
| 60 | +} | |
| 61 | + | |
| 62 | +/// Writes Matroska (`.mkv`) or, with [`MatroskaMuxer::webm`], the WebM subset. | |
| 63 | +/// | |
| 64 | +/// Streams are declared first and packets arrive in storage order; their | |
| 65 | +/// timestamps are rescaled into milliseconds, which is the tick this writes. | |
| 66 | +/// A new cluster opens at every video keyframe, so every cue point is one. | |
| 67 | +pub struct MatroskaMuxer<W> { | |
| 68 | + w: W, | |
| 69 | + pos: u64, | |
| 70 | + webm: bool, | |
| 71 | + tracks: Vec<MuxTrack>, | |
| 72 | + streams: Vec<StreamInfo>, | |
| 73 | + /// Where the header's patchable fields landed. | |
| 74 | + segment_size_at: u64, | |
| 75 | + segment_body: u64, | |
| 76 | + seek_head_at: u64, | |
| 77 | + duration_at: u64, | |
| 78 | + info_at: u64, | |
| 79 | + tracks_at: u64, | |
| 80 | + cluster: Vec<u8>, | |
| 81 | + cluster_ts: i64, | |
| 82 | + cluster_at: u64, | |
| 83 | + cues: Vec<CuePoint>, | |
| 84 | + last_end: i64, | |
| 85 | + finished: bool, | |
| 86 | +} | |
| 87 | + | |
| 88 | +impl<W: Write + Seek> MatroskaMuxer<W> { | |
| 89 | + /// A Matroska writer over anything seekable. | |
| 90 | + pub fn new(w: W) -> MatroskaMuxer<W> { | |
| 91 | + MatroskaMuxer { | |
| 92 | + w, | |
| 93 | + pos: 0, | |
| 94 | + webm: false, | |
| 95 | + tracks: Vec::new(), | |
| 96 | + streams: Vec::new(), | |
| 97 | + segment_size_at: 0, | |
| 98 | + segment_body: 0, | |
| 99 | + seek_head_at: 0, | |
| 100 | + duration_at: 0, | |
| 101 | + info_at: 0, | |
| 102 | + tracks_at: 0, | |
| 103 | + cluster: Vec::new(), | |
| 104 | + cluster_ts: 0, | |
| 105 | + cluster_at: 0, | |
| 106 | + cues: Vec::new(), | |
| 107 | + last_end: 0, | |
| 108 | + finished: false, | |
| 109 | + } | |
| 110 | + } | |
| 111 | + | |
| 112 | + /// The same writer declaring the WebM subset in its EBML header. Every | |
| 113 | + /// stream must then be one WebM carries — VP8/VP9/AV1 beside Opus and | |
| 114 | + /// Vorbis — and anything else is refused by name at | |
| 115 | + /// [`Muxer::add_stream`] rather than written into a file no WebM reader | |
| 116 | + /// will open. | |
| 117 | + pub fn webm(w: W) -> MatroskaMuxer<W> { | |
| 118 | + MatroskaMuxer { | |
| 119 | + webm: true, | |
| 120 | + ..MatroskaMuxer::new(w) | |
| 121 | + } | |
| 122 | + } | |
| 123 | + | |
| 124 | + fn write(&mut self, bytes: &[u8]) -> Result<()> { | |
| 125 | + self.w.write_all(bytes)?; | |
| 126 | + self.pos += bytes.len() as u64; | |
| 127 | + Ok(()) | |
| 128 | + } | |
| 129 | + | |
| 130 | + /// The EBML header, the `Segment`, the room its `SeekHead` will take, the | |
| 131 | + /// `Info` and the `Tracks`. Written when the first packet arrives, which is | |
| 132 | + /// the last moment every stream is known to have been declared. | |
| 133 | + fn write_header(&mut self) -> Result<()> { | |
| 134 | + if self.tracks.is_empty() { | |
| 135 | + return Err(Error::corrupt("Matroska: a file with no tracks")); | |
| 136 | + } | |
| 137 | + let mut head = Vec::new(); | |
| 138 | + let mut header = Vec::new(); | |
| 139 | + uint(&mut header, ebml::EBML_VERSION, 1); | |
| 140 | + uint(&mut header, ebml::EBML_READ_VERSION, 1); | |
| 141 | + uint(&mut header, ebml::EBML_MAX_ID_LENGTH, 4); | |
| 142 | + uint(&mut header, ebml::EBML_MAX_SIZE_LENGTH, 8); | |
| 143 | + elem( | |
| 144 | + &mut header, | |
| 145 | + ebml::DOC_TYPE, | |
| 146 | + if self.webm { | |
| 147 | + b"webm".as_slice() | |
| 148 | + } else { | |
| 149 | + b"matroska" | |
| 150 | + }, | |
| 151 | + ); | |
| 152 | + uint( | |
| 153 | + &mut header, | |
| 154 | + ebml::DOC_TYPE_VERSION, | |
| 155 | + if self.webm { 2 } else { 4 }, | |
| 156 | + ); | |
| 157 | + uint(&mut header, ebml::DOC_TYPE_READ_VERSION, 2); | |
| 158 | + elem(&mut head, ebml::EBML_HEADER, &header); | |
| 159 | + | |
| 160 | + // The segment's size is only known at `finish`; it is reserved at the | |
| 161 | + // widest encoding (8 bytes) so patching it never moves a byte after it. | |
| 162 | + put_id(&mut head, ebml::SEGMENT); | |
| 163 | + self.segment_size_at = head.len() as u64; | |
| 164 | + head.extend_from_slice(&[0x01, 0, 0, 0, 0, 0, 0, 0]); | |
| 165 | + self.segment_body = head.len() as u64; | |
| 166 | + | |
| 167 | + // Room for the `SeekHead`, whose entries name elements that are not | |
| 168 | + // written yet. A `Void` holds the space until then: a reader that meets | |
| 169 | + // this file half-written skips it rather than reading a table of zeros. | |
| 170 | + self.seek_head_at = head.len() as u64; | |
| 171 | + elem(&mut head, ebml::VOID, &[0u8; SEEK_HEAD_RESERVE]); | |
| 172 | + | |
| 173 | + let mut info = Vec::new(); | |
| 174 | + uint(&mut info, ebml::TIMESTAMP_SCALE, TIMESTAMP_SCALE_NS); | |
| 175 | + elem(&mut info, ebml::MUXING_APP, b"ec-matroska"); | |
| 176 | + elem(&mut info, ebml::WRITING_APP, b"ec-matroska"); | |
| 177 | + put_id(&mut info, ebml::DURATION); | |
| 178 | + put_size(&mut info, 8); | |
| 179 | + // Where those eight bytes land once `Info` is written into `head`, which | |
| 180 | + // is what `finish` seeks back to. | |
| 181 | + self.info_at = head.len() as u64; | |
| 182 | + self.duration_at = | |
| 183 | + (head.len() + elem_head_len(ebml::INFO, info.len() + 8) + info.len()) as u64; | |
| 184 | + info.extend_from_slice(&0f64.to_be_bytes()); | |
| 185 | + elem(&mut head, ebml::INFO, &info); | |
| 186 | + | |
| 187 | + self.tracks_at = head.len() as u64; | |
| 188 | + let mut tracks = Vec::new(); | |
| 189 | + for (i, info) in self.streams.clone().iter().enumerate() { | |
| 190 | + let entry = self.track_entry(info, self.tracks[i].number)?; | |
| 191 | + elem(&mut tracks, ebml::TRACK_ENTRY, &entry); | |
| 192 | + } | |
| 193 | + elem(&mut head, ebml::TRACKS, &tracks); | |
| 194 | + self.write(&head) | |
| 195 | + } | |
| 196 | + | |
| 197 | + fn track_entry(&self, info: &StreamInfo, number: u64) -> Result<Vec<u8>> { | |
| 198 | + let params = &info.params; | |
| 199 | + let codec = matroska_codec_id(params.codec)?; | |
| 200 | + if self.webm | |
| 201 | + && !matches!( | |
| 202 | + params.codec, | |
| 203 | + CodecId::Vp8 | CodecId::Vp9 | CodecId::Av1 | CodecId::Opus | CodecId::Vorbis | |
| 204 | + ) | |
| 205 | + { | |
| 206 | + return Err(Error::unsupported( | |
| 207 | + format!("{} in a WebM file", params.codec.name()), | |
| 208 | + "WebM carries VP8/VP9/AV1 video and Opus/Vorbis audio only", | |
| 209 | + )); | |
| 210 | + } | |
| 211 | + let mut entry = Vec::new(); | |
| 212 | + uint(&mut entry, ebml::TRACK_NUMBER, number); | |
| 213 | + uint(&mut entry, ebml::TRACK_UID, number); | |
| 214 | + uint( | |
| 215 | + &mut entry, | |
| 216 | + ebml::TRACK_TYPE, | |
| 217 | + match params.codec.media_type() { | |
| 218 | + MediaType::Video => 1, | |
| 219 | + MediaType::Audio => 2, | |
| 220 | + MediaType::Subtitle => 0x11, | |
| 221 | + }, | |
| 222 | + ); | |
| 223 | + // Nothing here writes a lace, and a reader is entitled to believe this. | |
| 224 | + uint(&mut entry, ebml::FLAG_LACING, 0); | |
| 225 | + elem(&mut entry, ebml::CODEC_ID, codec.as_bytes()); | |
| 226 | + if let Some(extradata) = ¶ms.extradata | |
| 227 | + && !extradata.is_empty() | |
| 228 | + { | |
| 229 | + elem(&mut entry, ebml::CODEC_PRIVATE, extradata); | |
| 230 | + } | |
| 231 | + // A track that states no language is English by spec, so a track whose | |
| 232 | + // source said nothing says `und` here rather than claiming a language. | |
| 233 | + elem( | |
| 234 | + &mut entry, | |
| 235 | + ebml::TRACK_LANGUAGE, | |
| 236 | + info.language.as_deref().unwrap_or("und").as_bytes(), | |
| 237 | + ); | |
| 238 | + match ¶ms.media { | |
| 239 | + MediaParameters::Video(v) => { | |
| 240 | + if let Some(rate) = v.frame_rate | |
| 241 | + && rate.num() > 0 | |
| 242 | + { | |
| 243 | + let ns = TimeBase::new(1, 1_000_000_000); | |
| 244 | + uint( | |
| 245 | + &mut entry, | |
| 246 | + ebml::DEFAULT_DURATION, | |
| 247 | + rate.inverse().rescale(1, ns, Rounding::Nearest).max(1) as u64, | |
| 248 | + ); | |
| 249 | + } | |
| 250 | + let mut dims = Vec::new(); | |
| 251 | + uint(&mut dims, ebml::PIXEL_WIDTH, u64::from(v.width)); | |
| 252 | + uint(&mut dims, ebml::PIXEL_HEIGHT, u64::from(v.height)); | |
| 253 | + // Anamorphic content is shown at a size its samples are not | |
| 254 | + // square in; a file that states only the coded size plays | |
| 255 | + // stretched. | |
| 256 | + if let Some(sar) = v.sample_aspect_ratio | |
| 257 | + && sar.num() != sar.den() | |
| 258 | + && v.width > 0 | |
| 259 | + { | |
| 260 | + let shown = u64::from(v.width) * sar.num() as u64 / sar.den() as u64; | |
| 261 | + uint(&mut dims, ebml::DISPLAY_WIDTH, shown.max(1)); | |
| 262 | + uint(&mut dims, ebml::DISPLAY_HEIGHT, u64::from(v.height)); | |
| 263 | + } | |
| 264 | + // What the samples in those pixels mean, written rather than | |
| 265 | + // left to a reader's own 720-line guess: an untagged file is how | |
| 266 | + // a 601 source ends up displayed as 709. | |
| 267 | + let mut colour = Vec::new(); | |
| 268 | + uint( | |
| 269 | + &mut colour, | |
| 270 | + ebml::MATRIX_COEFFICIENTS, | |
| 271 | + u64::from(v.color.matrix), | |
| 272 | + ); | |
| 273 | + // Matroska says the range as a code, not a flag: 1 limited, 2 full. | |
| 274 | + uint(&mut colour, ebml::RANGE, 1 + u64::from(v.color.full_range)); | |
| 275 | + uint( | |
| 276 | + &mut colour, | |
| 277 | + ebml::TRANSFER_CHARACTERISTICS, | |
| 278 | + u64::from(v.color.transfer), | |
| 279 | + ); | |
| 280 | + uint(&mut colour, ebml::PRIMARIES, u64::from(v.color.primaries)); | |
| 281 | + if let Some(cll) = v.light.max_cll { | |
| 282 | + uint(&mut colour, ebml::MAX_CLL, cll.max(0.0) as u64); | |
| 283 | + } | |
| 284 | + if let Some(fall) = v.light.max_fall { | |
| 285 | + uint(&mut colour, ebml::MAX_FALL, fall.max(0.0) as u64); | |
| 286 | + } | |
| 287 | + // The mastering display, where the source stated one: a copied | |
| 288 | + // HDR film that loses its grading display is graded again by | |
| 289 | + // every tone map downstream. | |
| 290 | + if v.light.mastering_max.is_some() || v.light.mastering_min.is_some() { | |
| 291 | + let mut mastering = Vec::new(); | |
| 292 | + if let Some(max) = v.light.mastering_max { | |
| 293 | + float(&mut mastering, ebml::LUMINANCE_MAX, f64::from(max)); | |
| 294 | + } | |
| 295 | + if let Some(min) = v.light.mastering_min { | |
| 296 | + float(&mut mastering, ebml::LUMINANCE_MIN, f64::from(min)); | |
| 297 | + } | |
| 298 | + elem(&mut colour, ebml::MASTERING_METADATA, &mastering); | |
| 299 | + } | |
| 300 | + elem(&mut dims, ebml::COLOUR, &colour); | |
| 301 | + elem(&mut entry, ebml::VIDEO, &dims); | |
| 302 | + } | |
| 303 | + MediaParameters::Audio(a) => { | |
| 304 | + let mut audio = Vec::new(); | |
| 305 | + float( | |
| 306 | + &mut audio, | |
| 307 | + ebml::SAMPLING_FREQUENCY, | |
| 308 | + f64::from(a.sample_rate.max(1)), | |
| 309 | + ); | |
| 310 | + uint( | |
| 311 | + &mut audio, | |
| 312 | + ebml::CHANNELS, | |
| 313 | + a.layout.channel_count().max(1) as u64, | |
| 314 | + ); | |
| 315 | + if let Some(bits) = a.bits_per_sample { | |
| 316 | + uint(&mut audio, ebml::BIT_DEPTH, u64::from(bits)); | |
| 317 | + } | |
| 318 | + // Opus states its own priming inside the `OpusHead` an mp4 or an | |
| 319 | + // Ogg page carries; Matroska has to be told it in nanoseconds, | |
| 320 | + // and a track written without it plays 6.5 ms early against the | |
| 321 | + // picture. The pre-roll is the 80 ms the spec asks a seek to | |
| 322 | + // decode and throw away. | |
| 323 | + if params.codec == CodecId::Opus | |
| 324 | + && let Some(head) = ¶ms.extradata | |
| 325 | + && head.len() >= 12 | |
| 326 | + && head.starts_with(b"OpusHead") | |
| 327 | + { | |
| 328 | + let pre_skip = u64::from(u16::from_le_bytes([head[10], head[11]])); | |
| 329 | + uint( | |
| 330 | + &mut entry, | |
| 331 | + ebml::CODEC_DELAY, | |
| 332 | + pre_skip * 1_000_000_000 / 48_000, | |
| 333 | + ); | |
| 334 | + uint(&mut entry, ebml::SEEK_PRE_ROLL, 80_000_000); | |
| 335 | + } | |
| 336 | + elem(&mut entry, ebml::AUDIO, &audio); | |
| 337 | + } | |
| 338 | + MediaParameters::Subtitle => {} | |
| 339 | + } | |
| 340 | + Ok(entry) | |
| 341 | + } | |
| 342 | + | |
| 343 | + /// One block into the cluster it belongs in. | |
| 344 | + fn put( | |
| 345 | + &mut self, | |
| 346 | + track: usize, | |
| 347 | + ts: i64, | |
| 348 | + duration: Option<i64>, | |
| 349 | + key: bool, | |
| 350 | + payload: &[u8], | |
| 351 | + ) -> Result<()> { | |
| 352 | + let video = self.tracks[track].media == MediaType::Video; | |
| 353 | + // A new cluster at every video keyframe — a seek lands on one, so a | |
| 354 | + // cluster is a whole GOP — and at the two limits a cluster has whatever | |
| 355 | + // the encoder keys: what it may weigh, and how far a 16-bit relative | |
| 356 | + // timestamp reaches. | |
| 357 | + if self.cluster.is_empty() | |
| 358 | + || (video && key) | |
| 359 | + || self.cluster.len() >= CLUSTER_BYTES | |
| 360 | + || (ts - self.cluster_ts).abs() >= CLUSTER_MS | |
| 361 | + { | |
| 362 | + self.flush()?; | |
| 363 | + self.cluster_ts = ts; | |
| 364 | + self.cluster_at = self.pos; | |
| 365 | + uint(&mut self.cluster, ebml::CLUSTER_TIMESTAMP, ts.max(0) as u64); | |
| 366 | + } | |
| 367 | + let relative = self.cluster.len() as u64; | |
| 368 | + let number = self.tracks[track].number; | |
| 369 | + let rel = i16::try_from(ts - self.cluster_ts).map_err(|_| { | |
| 370 | + Error::corrupt("Matroska: a block more than 32 seconds from its cluster") | |
| 371 | + })?; | |
| 372 | + | |
| 373 | + let mut block = Vec::with_capacity(payload.len() + 4); | |
| 374 | + block.push(0x80 | number as u8); // the track number as a one-byte EBML integer | |
| 375 | + block.extend_from_slice(&rel.to_be_bytes()); | |
| 376 | + match duration { | |
| 377 | + // A `SimpleBlock` has nowhere to put a duration, and a subtitle | |
| 378 | + // without one stays up until whatever a player decides — which is | |
| 379 | + // what a subtitle must never do. So a packet that states how long it | |
| 380 | + // lasts is written as a `BlockGroup` with the duration beside it. | |
| 381 | + Some(duration) if self.tracks[track].media == MediaType::Subtitle => { | |
| 382 | + // Not lacing, and "keyframe" is a `SimpleBlock` field a plain | |
| 383 | + // `Block` does not have at all. | |
| 384 | + block.push(0); | |
| 385 | + block.extend_from_slice(payload); | |
| 386 | + let mut group = Vec::new(); | |
| 387 | + elem(&mut group, ebml::BLOCK, &block); | |
| 388 | + uint(&mut group, ebml::BLOCK_DURATION, duration.max(1) as u64); | |
| 389 | + elem(&mut self.cluster, ebml::BLOCK_GROUP, &group); | |
| 390 | + } | |
| 391 | + _ => { | |
| 392 | + block.push(if key { 0x80 } else { 0 }); | |
| 393 | + block.extend_from_slice(payload); | |
| 394 | + elem(&mut self.cluster, ebml::SIMPLE_BLOCK, &block); | |
| 395 | + } | |
| 396 | + } | |
| 397 | + // One cue per keyframe of a video track (of the first track, in a file | |
| 398 | + // with no picture): an index naming every block of every track is three | |
| 399 | + // times too long and seeks no better. | |
| 400 | + let cued = match self.tracks.iter().any(|t| t.media == MediaType::Video) { | |
| 401 | + true => video && key, | |
| 402 | + false => track == 0 && key, | |
| 403 | + }; | |
| 404 | + if cued { | |
| 405 | + self.cues.push(CuePoint { | |
| 406 | + time: ts, | |
| 407 | + track: number, | |
| 408 | + cluster: self.cluster_at - self.segment_body, | |
| 409 | + relative, | |
| 410 | + }); | |
| 411 | + } | |
| 412 | + self.last_end = self.last_end.max(ts + duration.unwrap_or(0)); | |
| 413 | + Ok(()) | |
| 414 | + } | |
| 415 | + | |
| 416 | + fn flush(&mut self) -> Result<()> { | |
| 417 | + if self.cluster.is_empty() { | |
| 418 | + return Ok(()); | |
| 419 | + } | |
| 420 | + let mut head = Vec::new(); | |
| 421 | + put_id(&mut head, ebml::CLUSTER); | |
| 422 | + put_size(&mut head, self.cluster.len() as u64); | |
| 423 | + let body = std::mem::take(&mut self.cluster); | |
| 424 | + self.write(&head)?; | |
| 425 | + self.write(&body)?; | |
| 426 | + Ok(()) | |
| 427 | + } | |
| 428 | +} | |
| 429 | + | |
| 430 | +impl<W: Write + Seek + Send> Muxer for MatroskaMuxer<W> { | |
| 431 | + fn add_stream(&mut self, info: StreamInfo) -> Result<u32> { | |
| 432 | + if self.pos > 0 { | |
| 433 | + return Err(Error::corrupt( | |
| 434 | + "Matroska: a stream declared after the first packet", | |
| 435 | + )); | |
| 436 | + } | |
| 437 | + if self.tracks.len() >= MAX_TRACKS { | |
| 438 | + return Err(Error::unsupported( | |
| 439 | + format!("{} tracks in one Matroska file", self.tracks.len() + 1), | |
| 440 | + "a block writes its track number in one byte", | |
| 441 | + )); | |
| 442 | + } | |
| 443 | + let index = self.tracks.len() as u32; | |
| 444 | + // Track numbers start at 1: zero is not a legal `TrackNumber`. | |
| 445 | + let number = u64::from(index) + 1; | |
| 446 | + let frame_ns = match &info.params.media { | |
| 447 | + MediaParameters::Video(v) => v.frame_rate.and_then(|r| { | |
| 448 | + r.inverse() | |
| 449 | + .checked_rescale(1, TimeBase::new(1, 1_000_000_000), Rounding::Nearest) | |
| 450 | + .map(|ns| ns.max(1) as u64) | |
| 451 | + }), | |
| 452 | + _ => None, | |
| 453 | + }; | |
| 454 | + self.tracks.push(MuxTrack { | |
| 455 | + number, | |
| 456 | + media: info.params.codec.media_type(), | |
| 457 | + time_base: info.time_base, | |
| 458 | + frame_ns, | |
| 459 | + }); | |
| 460 | + let mut info = info; | |
| 461 | + info.index = index; | |
| 462 | + self.streams.push(info); | |
| 463 | + Ok(index) | |
| 464 | + } | |
| 465 | + | |
| 466 | + fn write_packet(&mut self, packet: &Packet) -> Result<()> { | |
| 467 | + let track = packet.stream as usize; | |
| 468 | + if track >= self.tracks.len() { | |
| 469 | + return Err(Error::corrupt(format!( | |
| 470 | + "Matroska: packet for stream {} of {}", | |
| 471 | + packet.stream, | |
| 472 | + self.tracks.len() | |
| 473 | + ))); | |
| 474 | + } | |
| 475 | + if self.pos == 0 { | |
| 476 | + self.write_header()?; | |
| 477 | + } | |
| 478 | + // The packet's own base where it carries one, the stream's otherwise: | |
| 479 | + // a demuxer states both and an encoder often only the second. | |
| 480 | + let base = match packet.time_base.num() > 0 { | |
| 481 | + true => packet.time_base, | |
| 482 | + false => self.tracks[track].time_base, | |
| 483 | + }; | |
| 484 | + let ts = match packet.pts { | |
| 485 | + Some(pts) => base.rescale(pts, MUX_TIME_BASE, Rounding::Nearest), | |
| 486 | + // A packet with no timestamp at all follows the one before it, by a | |
| 487 | + // frame where the track states a rate and by nothing where it does | |
| 488 | + // not — which is what a player would have to assume anyway. | |
| 489 | + None => self.last_end, | |
| 490 | + }; | |
| 491 | + let duration = packet | |
| 492 | + .duration | |
| 493 | + .map(|d| base.rescale(d, MUX_TIME_BASE, Rounding::Nearest)) | |
| 494 | + .or_else(|| { | |
| 495 | + self.tracks[track] | |
| 496 | + .frame_ns | |
| 497 | + .map(|ns| (ns / TIMESTAMP_SCALE_NS).max(1) as i64) | |
| 498 | + }); | |
| 499 | + if packet.data.is_empty() { | |
| 500 | + return Err(Error::corrupt("Matroska: an empty block")); | |
| 501 | + } | |
| 502 | + self.put(track, ts, duration, packet.flags.keyframe, &packet.data) | |
| 503 | + } | |
| 504 | + | |
| 505 | + fn finish(&mut self) -> Result<()> { | |
| 506 | + if self.finished { | |
| 507 | + return Ok(()); | |
| 508 | + } | |
| 509 | + self.finished = true; | |
| 510 | + if self.pos == 0 { | |
| 511 | + self.write_header()?; | |
| 512 | + } | |
| 513 | + self.flush()?; | |
| 514 | + | |
| 515 | + // The index, in the order a seek reads it. | |
| 516 | + let cues_at = self.pos - self.segment_body; | |
| 517 | + let mut cues = Vec::new(); | |
| 518 | + for cue in std::mem::take(&mut self.cues) { | |
| 519 | + let mut positions = Vec::new(); | |
| 520 | + uint(&mut positions, ebml::CUE_TRACK, cue.track); | |
| 521 | + uint(&mut positions, ebml::CUE_CLUSTER_POSITION, cue.cluster); | |
| 522 | + uint(&mut positions, ebml::CUE_RELATIVE_POSITION, cue.relative); | |
| 523 | + let mut point = Vec::new(); | |
| 524 | + uint(&mut point, ebml::CUE_TIME, cue.time.max(0) as u64); | |
| 525 | + elem(&mut point, ebml::CUE_TRACK_POSITIONS, &positions); | |
| 526 | + elem(&mut cues, ebml::CUE_POINT, &point); | |
| 527 | + } | |
| 528 | + let mut element = Vec::new(); | |
| 529 | + elem(&mut element, ebml::CUES, &cues); | |
| 530 | + self.write(&element)?; | |
| 531 | + | |
| 532 | + let end = self.pos; | |
| 533 | + // The reserved 8-byte segment size: marker bit in the top byte, value | |
| 534 | + // under it. | |
| 535 | + let body = end - self.segment_body; | |
| 536 | + let size = (1u64 << 56) | body; | |
| 537 | + self.w.seek(SeekFrom::Start(self.segment_size_at))?; | |
| 538 | + self.w.write_all(&size.to_be_bytes())?; | |
| 539 | + | |
| 540 | + // One tick past the last block shown, which is where the file really | |
| 541 | + // ends. | |
| 542 | + self.w.seek(SeekFrom::Start(self.duration_at))?; | |
| 543 | + self.w.write_all(&(self.last_end as f64).to_be_bytes())?; | |
| 544 | + | |
| 545 | + // The `SeekHead`, into the room reserved for it, with a `Void` over | |
| 546 | + // whatever it did not need. | |
| 547 | + let mut entries = Vec::new(); | |
| 548 | + for (id, at) in [ | |
| 549 | + (ebml::INFO, self.info_at), | |
| 550 | + (ebml::TRACKS, self.tracks_at), | |
| 551 | + (ebml::CUES, cues_at), | |
| 552 | + ] { | |
| 553 | + let mut seek = Vec::new(); | |
| 554 | + let mut id_bytes = Vec::new(); | |
| 555 | + put_id(&mut id_bytes, id); | |
| 556 | + elem(&mut seek, ebml::SEEK_ID, &id_bytes); | |
| 557 | + // Fixed eight bytes, not the fewest that hold it: the table is | |
| 558 | + // written into a reservation, and a `SeekHead` whose length depends | |
| 559 | + // on how big the file turned out is one whose `Void` filler can land | |
| 560 | + // on a length EBML cannot spell. | |
| 561 | + put_id(&mut seek, ebml::SEEK_POSITION); | |
| 562 | + put_size(&mut seek, 8); | |
| 563 | + seek.extend_from_slice(&at.saturating_sub(self.segment_body).to_be_bytes()); | |
| 564 | + elem(&mut entries, ebml::SEEK, &seek); | |
| 565 | + } | |
| 566 | + let mut head = Vec::new(); | |
| 567 | + elem(&mut head, ebml::SEEK_HEAD, &entries); | |
| 568 | + let room = SEEK_HEAD_RESERVE + elem_head_len(ebml::VOID, SEEK_HEAD_RESERVE); | |
| 569 | + if head.len() > room { | |
| 570 | + return Err(Error::corrupt( | |
| 571 | + "Matroska: SeekHead larger than its reservation", | |
| 572 | + )); | |
| 573 | + } | |
| 574 | + // Whatever the table did not need becomes a `Void`, which needs two | |
| 575 | + // bytes of its own at the least. The three entries are fixed-width, so | |
| 576 | + // the leftover is a constant and this arithmetic is exact. | |
| 577 | + match room - head.len() { | |
| 578 | + 0 => {} | |
| 579 | + 1 => { | |
| 580 | + return Err(Error::corrupt( | |
| 581 | + "Matroska: one byte left over after the SeekHead", | |
| 582 | + )); | |
| 583 | + } | |
| 584 | + left => { | |
| 585 | + let payload = left - elem_head_len(ebml::VOID, left - 2); | |
| 586 | + elem(&mut head, ebml::VOID, &vec![0u8; payload]); | |
| 587 | + } | |
| 588 | + } | |
| 589 | + if head.len() != room { | |
| 590 | + return Err(Error::corrupt( | |
| 591 | + "Matroska: SeekHead reservation not filled exactly", | |
| 592 | + )); | |
| 593 | + } | |
| 594 | + self.w.seek(SeekFrom::Start(self.seek_head_at))?; | |
| 595 | + self.w.write_all(&head)?; | |
| 596 | + self.w.seek(SeekFrom::Start(end))?; | |
| 597 | + self.pos = end; | |
| 598 | + self.w.flush()?; | |
| 599 | + Ok(()) | |
| 600 | + } | |
| 601 | +} | |
| 602 | + | |
| 603 | +/// The Matroska codec id a [`CodecId`] is written as. The reverse of the | |
| 604 | +/// reader's own table, and refusing rather than guessing is the point: a stream | |
| 605 | +/// written under the wrong id is a file that opens and plays noise. | |
| 606 | +pub(crate) fn matroska_codec_id(codec: CodecId) -> Result<&'static str> { | |
| 607 | + Ok(match codec { | |
| 608 | + CodecId::H264 => "V_MPEG4/ISO/AVC", | |
| 609 | + CodecId::H265 => "V_MPEGH/ISO/HEVC", | |
| 610 | + CodecId::Vp8 => "V_VP8", | |
| 611 | + CodecId::Vp9 => "V_VP9", | |
| 612 | + CodecId::Av1 => "V_AV1", | |
| 613 | + CodecId::Aac => "A_AAC", | |
| 614 | + CodecId::Ac3 => "A_AC3", | |
| 615 | + CodecId::EAc3 => "A_EAC3", | |
| 616 | + CodecId::Alac => "A_ALAC", | |
| 617 | + CodecId::Flac => "A_FLAC", | |
| 618 | + CodecId::Mp3 => "A_MPEG/L3", | |
| 619 | + CodecId::Opus => "A_OPUS", | |
| 620 | + CodecId::Vorbis => "A_VORBIS", | |
| 621 | + CodecId::PcmU8 | CodecId::PcmS16Le | CodecId::PcmS24Le | CodecId::PcmS32Le => { | |
| 622 | + "A_PCM/INT/LIT" | |
| 623 | + } | |
| 624 | + CodecId::PcmS16Be => "A_PCM/INT/BIG", | |
| 625 | + CodecId::PcmF32Le => "A_PCM/FLOAT/IEEE", | |
| 626 | + CodecId::Srt => "S_TEXT/UTF8", | |
| 627 | + CodecId::WebVtt => "S_TEXT/WEBVTT", | |
| 628 | + CodecId::Ass => "S_TEXT/ASS", | |
| 629 | + CodecId::Pgs => "S_HDMV/PGS", | |
| 630 | + codec => { | |
| 631 | + return Err(Error::unsupported( | |
| 632 | + format!("{} in Matroska", codec.name()), | |
| 633 | + "the format defines no codec id for it", | |
| 634 | + )); | |
| 635 | + } | |
| 636 | + }) | |
| 637 | +} |