forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

mux.rs788 lines, 32.4 KiBHistoryRawDownload
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
8use std::io::{Seek, SeekFrom, Write};
9
10use ec_core::{
11 CodecId, Error, MediaParameters, MediaType, Muxer, Packet, Result, Rounding, StreamInfo,
12 TimeBase,
13};
14
15use 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.
22const TIMESTAMP_SCALE_NS: u64 = 1_000_000;
23/// The time base that scale is: every packet is rescaled into it.
24pub 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.
28const 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.
31const 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`.
35const 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.
41pub const MAX_TRACKS: usize = 0x7E;
42
43struct 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 /// `TrackName`, where a caller named the track.
50 title: String,
51 /// `CodecDelay` in nanoseconds, where a caller stated one.
52 delay_ns: Option<u64>,
53 /// `FlagInterlaced`/`FieldOrder` on a video track; [`None`] writes neither.
54 field_order: Option<ec_core::Interlace>,
55}
56
57/// One `CuePoint` waiting for [`Muxer::finish`].
58struct CuePoint {
59 time: i64,
60 track: u64,
61 /// Offset of the cluster from the start of the segment's payload, which is
62 /// what `CueClusterPosition` states.
63 cluster: u64,
64 /// ...and of the block from the start of that cluster's payload.
65 relative: u64,
66}
67
68/// Writes Matroska (`.mkv`) or, with [`MatroskaMuxer::webm`], the WebM subset.
69///
70/// Streams are declared first and packets arrive in storage order; their
71/// timestamps are rescaled into milliseconds, which is the tick this writes.
72/// A new cluster opens at every video keyframe, so every cue point is one.
73pub struct MatroskaMuxer<W> {
74 w: W,
75 pos: u64,
76 webm: bool,
77 tracks: Vec<MuxTrack>,
78 streams: Vec<StreamInfo>,
79 /// Where the header's patchable fields landed.
80 segment_size_at: u64,
81 segment_body: u64,
82 seek_head_at: u64,
83 duration_at: u64,
84 info_at: u64,
85 tracks_at: u64,
86 cluster: Vec<u8>,
87 cluster_ts: i64,
88 cluster_at: u64,
89 cues: Vec<CuePoint>,
90 last_end: i64,
91 finished: bool,
92}
93
94impl<W: Write + Seek> MatroskaMuxer<W> {
95 /// A Matroska writer over anything seekable.
96 pub fn new(w: W) -> MatroskaMuxer<W> {
97 MatroskaMuxer {
98 w,
99 pos: 0,
100 webm: false,
101 tracks: Vec::new(),
102 streams: Vec::new(),
103 segment_size_at: 0,
104 segment_body: 0,
105 seek_head_at: 0,
106 duration_at: 0,
107 info_at: 0,
108 tracks_at: 0,
109 cluster: Vec::new(),
110 cluster_ts: 0,
111 cluster_at: 0,
112 cues: Vec::new(),
113 last_end: 0,
114 finished: false,
115 }
116 }
117
118 /// The same writer declaring the WebM subset in its EBML header. Every
119 /// stream must then be one WebM carries — VP8/VP9/AV1 beside Opus and
120 /// Vorbis — and anything else is refused by name at
121 /// [`Muxer::add_stream`] rather than written into a file no WebM reader
122 /// will open.
123 pub fn webm(w: W) -> MatroskaMuxer<W> {
124 MatroskaMuxer {
125 webm: true,
126 ..MatroskaMuxer::new(w)
127 }
128 }
129
130 /// Names a track: `TrackName`, the title a player's menu shows beside the
131 /// language ("Signs", "Commentary"). Must be set before the first packet,
132 /// which is when the `Tracks` element is written.
133 pub fn set_track_title(&mut self, stream: u32, title: &str) -> Result<()> {
134 let track = self
135 .tracks
136 .get_mut(stream as usize)
137 .ok_or_else(|| Error::corrupt(format!("Matroska: no stream {stream} to name")))?;
138 if self.pos > 0 {
139 return Err(Error::corrupt(
140 "Matroska: a track named after the first packet",
141 ));
142 }
143 track.title = title.to_string();
144 Ok(())
145 }
146
147 /// Say how a video track's pictures are scanned: `FlagInterlaced` and
148 /// `FieldOrder`. Every video track is `Some(Progressive)` until told
149 /// otherwise; [`None`] writes neither element. Before the first packet.
150 pub fn set_field_order(
151 &mut self,
152 stream: u32,
153 order: Option<ec_core::Interlace>,
154 ) -> Result<()> {
155 let track = self
156 .tracks
157 .get_mut(stream as usize)
158 .ok_or_else(|| Error::corrupt(format!("Matroska: no stream {stream} to scan")))?;
159 if self.pos > 0 {
160 return Err(Error::corrupt(
161 "Matroska: a field order set after the first packet",
162 ));
163 }
164 track.field_order = order;
165 Ok(())
166 }
167
168 /// States a track's encoder delay: `CodecDelay`, nanoseconds of decoded
169 /// output a player throws away before the audible stream starts.
170 ///
171 /// Opus needs no call — its `OpusHead` states the pre-skip and that is read
172 /// straight off the extradata. AAC does: its delay is one access unit and
173 /// nothing in the bitstream or the container says so, so an mp4 reader drops
174 /// it by convention while Matroska has to be told. A track written without
175 /// it plays ~21 ms early against the picture.
176 ///
177 /// Must be set before the first packet, which is when `Tracks` is written.
178 pub fn set_track_delay(&mut self, stream: u32, delay_ns: u64) -> Result<()> {
179 if self.pos > 0 {
180 return Err(Error::corrupt(
181 "Matroska: a track delayed after the first packet",
182 ));
183 }
184 let track = self
185 .tracks
186 .get_mut(stream as usize)
187 .ok_or_else(|| Error::corrupt(format!("Matroska: no stream {stream} to delay")))?;
188 track.delay_ns = Some(delay_ns);
189 Ok(())
190 }
191
192 /// State a video stream's HDR light levels: `MaxCLL` and `MaxFALL` and, in
193 /// `Colour/MasteringMetadata`, the mastering display's luminances and (where
194 /// [`ec_core::ContentLight::mastering_primaries`] is set) its primaries and
195 /// white point. Units are those of [`ec_core::ContentLight`]. Must be set
196 /// before the first packet, which is when `Tracks` is written; a track never
197 /// told writes none of these.
198 pub fn set_content_light(&mut self, stream: u32, light: ec_core::ContentLight) -> Result<()> {
199 if self.pos > 0 {
200 return Err(Error::corrupt(
201 "Matroska: HDR light levels set after the first packet",
202 ));
203 }
204 let info = self
205 .streams
206 .get_mut(stream as usize)
207 .ok_or_else(|| Error::corrupt(format!("Matroska: no stream {stream} to light")))?;
208 match &mut info.params.media {
209 ec_core::MediaParameters::Video(v) => v.light = light,
210 _ => {
211 return Err(Error::corrupt(format!(
212 "Matroska: stream {stream} is not a video track"
213 )));
214 }
215 }
216 Ok(())
217 }
218
219 fn write(&mut self, bytes: &[u8]) -> Result<()> {
220 self.w.write_all(bytes)?;
221 self.pos += bytes.len() as u64;
222 Ok(())
223 }
224
225 /// The EBML header, the `Segment`, the room its `SeekHead` will take, the
226 /// `Info` and the `Tracks`. Written when the first packet arrives, which is
227 /// the last moment every stream is known to have been declared.
228 fn write_header(&mut self) -> Result<()> {
229 if self.tracks.is_empty() {
230 return Err(Error::corrupt("Matroska: a file with no tracks"));
231 }
232 let mut head = Vec::new();
233 let mut header = Vec::new();
234 uint(&mut header, ebml::EBML_VERSION, 1);
235 uint(&mut header, ebml::EBML_READ_VERSION, 1);
236 uint(&mut header, ebml::EBML_MAX_ID_LENGTH, 4);
237 uint(&mut header, ebml::EBML_MAX_SIZE_LENGTH, 8);
238 elem(
239 &mut header,
240 ebml::DOC_TYPE,
241 if self.webm {
242 b"webm".as_slice()
243 } else {
244 b"matroska"
245 },
246 );
247 uint(
248 &mut header,
249 ebml::DOC_TYPE_VERSION,
250 if self.webm { 2 } else { 4 },
251 );
252 uint(&mut header, ebml::DOC_TYPE_READ_VERSION, 2);
253 elem(&mut head, ebml::EBML_HEADER, &header);
254
255 // The segment's size is only known at `finish`; it is reserved at the
256 // widest encoding (8 bytes) so patching it never moves a byte after it.
257 put_id(&mut head, ebml::SEGMENT);
258 self.segment_size_at = head.len() as u64;
259 head.extend_from_slice(&[0x01, 0, 0, 0, 0, 0, 0, 0]);
260 self.segment_body = head.len() as u64;
261
262 // Room for the `SeekHead`, whose entries name elements that are not
263 // written yet. A `Void` holds the space until then: a reader that meets
264 // this file half-written skips it rather than reading a table of zeros.
265 self.seek_head_at = head.len() as u64;
266 elem(&mut head, ebml::VOID, &[0u8; SEEK_HEAD_RESERVE]);
267
268 let mut info = Vec::new();
269 uint(&mut info, ebml::TIMESTAMP_SCALE, TIMESTAMP_SCALE_NS);
270 elem(&mut info, ebml::MUXING_APP, b"ec-matroska");
271 elem(&mut info, ebml::WRITING_APP, b"ec-matroska");
272 put_id(&mut info, ebml::DURATION);
273 put_size(&mut info, 8);
274 // Where those eight bytes land once `Info` is written into `head`, which
275 // is what `finish` seeks back to.
276 self.info_at = head.len() as u64;
277 self.duration_at =
278 (head.len() + elem_head_len(ebml::INFO, info.len() + 8) + info.len()) as u64;
279 info.extend_from_slice(&0f64.to_be_bytes());
280 elem(&mut head, ebml::INFO, &info);
281
282 self.tracks_at = head.len() as u64;
283 let mut tracks = Vec::new();
284 for (i, info) in self.streams.clone().iter().enumerate() {
285 let entry = self.track_entry(info, i)?;
286 elem(&mut tracks, ebml::TRACK_ENTRY, &entry);
287 }
288 elem(&mut head, ebml::TRACKS, &tracks);
289 self.write(&head)
290 }
291
292 fn track_entry(&self, info: &StreamInfo, track: usize) -> Result<Vec<u8>> {
293 let number = self.tracks[track].number;
294 let params = &info.params;
295 let codec = matroska_codec_id(params.codec)?;
296 if self.webm
297 && !matches!(
298 params.codec,
299 CodecId::Vp8 | CodecId::Vp9 | CodecId::Av1 | CodecId::Opus | CodecId::Vorbis
300 )
301 {
302 return Err(Error::unsupported(
303 format!("{} in a WebM file", params.codec.name()),
304 "WebM carries VP8/VP9/AV1 video and Opus/Vorbis audio only",
305 ));
306 }
307 let mut entry = Vec::new();
308 uint(&mut entry, ebml::TRACK_NUMBER, number);
309 uint(&mut entry, ebml::TRACK_UID, number);
310 uint(
311 &mut entry,
312 ebml::TRACK_TYPE,
313 match params.codec.media_type() {
314 MediaType::Video => 1,
315 MediaType::Audio => 2,
316 MediaType::Subtitle => 0x11,
317 },
318 );
319 // Nothing here writes a lace, and a reader is entitled to believe this.
320 uint(&mut entry, ebml::FLAG_LACING, 0);
321 elem(&mut entry, ebml::CODEC_ID, codec.as_bytes());
322 if let Some(extradata) = &params.extradata
323 && !extradata.is_empty()
324 {
325 elem(&mut entry, ebml::CODEC_PRIVATE, extradata);
326 }
327 if !self.tracks[track].title.is_empty() {
328 elem(
329 &mut entry,
330 ebml::TRACK_NAME,
331 self.tracks[track].title.as_bytes(),
332 );
333 }
334 // A track that states no language is English by spec, so a track whose
335 // source said nothing says `und` here rather than claiming a language.
336 elem(
337 &mut entry,
338 ebml::TRACK_LANGUAGE,
339 info.language.as_deref().unwrap_or("und").as_bytes(),
340 );
341 match &params.media {
342 MediaParameters::Video(v) => {
343 if let Some(rate) = v.frame_rate
344 && rate.num() > 0
345 {
346 let ns = TimeBase::new(1, 1_000_000_000);
347 uint(
348 &mut entry,
349 ebml::DEFAULT_DURATION,
350 rate.inverse().rescale(1, ns, Rounding::Nearest).max(1) as u64,
351 );
352 }
353 let mut dims = Vec::new();
354 // FlagInterlaced: 1 interlaced, 2 progressive. FieldOrder: 0
355 // progressive, 1 top first, 6 bottom first.
356 if let Some(order) = self.tracks[track].field_order {
357 let (flag, field) = match order {
358 ec_core::Interlace::Progressive => (2, 0),
359 ec_core::Interlace::TopFieldFirst => (1, 1),
360 ec_core::Interlace::BottomFieldFirst => (1, 6),
361 };
362 uint(&mut dims, ebml::FLAG_INTERLACED, flag);
363 uint(&mut dims, ebml::FIELD_ORDER, field);
364 }
365 uint(&mut dims, ebml::PIXEL_WIDTH, u64::from(v.width));
366 uint(&mut dims, ebml::PIXEL_HEIGHT, u64::from(v.height));
367 // Anamorphic content is shown at a size its samples are not
368 // square in; a file that states only the coded size plays
369 // stretched.
370 if let Some(sar) = v.sample_aspect_ratio
371 && sar.num() != sar.den()
372 && v.width > 0
373 {
374 let shown = u64::from(v.width) * sar.num() as u64 / sar.den() as u64;
375 uint(&mut dims, ebml::DISPLAY_WIDTH, shown.max(1));
376 uint(&mut dims, ebml::DISPLAY_HEIGHT, u64::from(v.height));
377 }
378 // What the samples in those pixels mean, written rather than
379 // left to a reader's own 720-line guess: an untagged file is how
380 // a 601 source ends up displayed as 709.
381 let mut colour = Vec::new();
382 uint(
383 &mut colour,
384 ebml::MATRIX_COEFFICIENTS,
385 u64::from(v.color.matrix),
386 );
387 // Matroska says the range as a code, not a flag: 1 limited, 2 full.
388 uint(&mut colour, ebml::RANGE, 1 + u64::from(v.color.full_range));
389 uint(
390 &mut colour,
391 ebml::TRANSFER_CHARACTERISTICS,
392 u64::from(v.color.transfer),
393 );
394 uint(&mut colour, ebml::PRIMARIES, u64::from(v.color.primaries));
395 if let Some(cll) = v.light.max_cll {
396 uint(&mut colour, ebml::MAX_CLL, cll.max(0.0).round() as u64);
397 }
398 if let Some(fall) = v.light.max_fall {
399 uint(&mut colour, ebml::MAX_FALL, fall.max(0.0).round() as u64);
400 }
401 // The mastering display, where the source stated one: a copied
402 // HDR film that loses its grading display is graded again by
403 // every tone map downstream. ffmpeg's order: primaries, white
404 // point, then the luminances; the chromaticities are the
405 // 0.00002 integers of an `mdcv` divided out to floats.
406 let light = v.light;
407 if light.mastering_max.is_some()
408 || light.mastering_min.is_some()
409 || light.mastering_primaries.is_some()
410 {
411 let mut mastering = Vec::new();
412 if let Some(p) = light.mastering_primaries {
413 let xy = |out: &mut Vec<u8>, id: u32, raw: u16| {
414 float(out, id, f64::from(raw) / 50_000.0)
415 };
416 xy(&mut mastering, ebml::PRIMARY_R_X, p.red.0);
417 xy(&mut mastering, ebml::PRIMARY_R_Y, p.red.1);
418 xy(&mut mastering, ebml::PRIMARY_G_X, p.green.0);
419 xy(&mut mastering, ebml::PRIMARY_G_Y, p.green.1);
420 xy(&mut mastering, ebml::PRIMARY_B_X, p.blue.0);
421 xy(&mut mastering, ebml::PRIMARY_B_Y, p.blue.1);
422 xy(&mut mastering, ebml::WHITE_POINT_X, p.white.0);
423 xy(&mut mastering, ebml::WHITE_POINT_Y, p.white.1);
424 }
425 // Rounded to the 0.0001 nit an `mdcv` has, so 0.005 is
426 // written as 0.005 and not as the f32 nearest to it.
427 let decimal = |v: f32| (f64::from(v) * 1e4).round() / 1e4;
428 if let Some(max) = light.mastering_max {
429 float(&mut mastering, ebml::LUMINANCE_MAX, decimal(max));
430 }
431 if let Some(min) = light.mastering_min {
432 float(&mut mastering, ebml::LUMINANCE_MIN, decimal(min));
433 }
434 elem(&mut colour, ebml::MASTERING_METADATA, &mastering);
435 }
436 elem(&mut dims, ebml::COLOUR, &colour);
437 elem(&mut entry, ebml::VIDEO, &dims);
438 }
439 MediaParameters::Audio(a) => {
440 let mut audio = Vec::new();
441 float(
442 &mut audio,
443 ebml::SAMPLING_FREQUENCY,
444 f64::from(a.sample_rate.max(1)),
445 );
446 uint(
447 &mut audio,
448 ebml::CHANNELS,
449 a.layout.channel_count().max(1) as u64,
450 );
451 if let Some(bits) = a.bits_per_sample {
452 uint(&mut audio, ebml::BIT_DEPTH, u64::from(bits));
453 }
454 // Opus states its own priming inside the `OpusHead` an mp4 or an
455 // Ogg page carries; Matroska has to be told it in nanoseconds,
456 // and a track written without it plays 6.5 ms early against the
457 // picture. The pre-roll is the 80 ms the spec asks a seek to
458 // decode and throw away.
459 // A caller that stated the delay outright is believed first:
460 // AAC's is one access unit and nothing in the file says so.
461 if let Some(ns) = self.tracks[track].delay_ns {
462 uint(&mut entry, ebml::CODEC_DELAY, ns);
463 } else if params.codec == CodecId::Opus
464 && let Some(head) = &params.extradata
465 && head.len() >= 12
466 && head.starts_with(b"OpusHead")
467 {
468 let pre_skip = u64::from(u16::from_le_bytes([head[10], head[11]]));
469 uint(
470 &mut entry,
471 ebml::CODEC_DELAY,
472 pre_skip * 1_000_000_000 / 48_000,
473 );
474 uint(&mut entry, ebml::SEEK_PRE_ROLL, 80_000_000);
475 }
476 elem(&mut entry, ebml::AUDIO, &audio);
477 }
478 MediaParameters::Subtitle => {}
479 }
480 Ok(entry)
481 }
482
483 /// One block into the cluster it belongs in.
484 fn put(
485 &mut self,
486 track: usize,
487 ts: i64,
488 duration: Option<i64>,
489 key: bool,
490 payload: &[u8],
491 ) -> Result<()> {
492 let video = self.tracks[track].media == MediaType::Video;
493 // A new cluster at every video keyframe — a seek lands on one, so a
494 // cluster is a whole GOP — and at the two limits a cluster has whatever
495 // the encoder keys: what it may weigh, and how far a 16-bit relative
496 // timestamp reaches.
497 if self.cluster.is_empty()
498 || (video && key)
499 || self.cluster.len() >= CLUSTER_BYTES
500 || (ts - self.cluster_ts).abs() >= CLUSTER_MS
501 {
502 self.flush()?;
503 self.cluster_ts = ts;
504 self.cluster_at = self.pos;
505 uint(&mut self.cluster, ebml::CLUSTER_TIMESTAMP, ts.max(0) as u64);
506 }
507 let relative = self.cluster.len() as u64;
508 let number = self.tracks[track].number;
509 let rel = i16::try_from(ts - self.cluster_ts).map_err(|_| {
510 Error::corrupt("Matroska: a block more than 32 seconds from its cluster")
511 })?;
512
513 let mut block = Vec::with_capacity(payload.len() + 4);
514 block.push(0x80 | number as u8); // the track number as a one-byte EBML integer
515 block.extend_from_slice(&rel.to_be_bytes());
516 match duration {
517 // A `SimpleBlock` has nowhere to put a duration, and a subtitle
518 // without one stays up until whatever a player decides — which is
519 // what a subtitle must never do. So a packet that states how long it
520 // lasts is written as a `BlockGroup` with the duration beside it.
521 Some(duration) if self.tracks[track].media == MediaType::Subtitle => {
522 // Not lacing, and "keyframe" is a `SimpleBlock` field a plain
523 // `Block` does not have at all.
524 block.push(0);
525 block.extend_from_slice(payload);
526 let mut group = Vec::new();
527 elem(&mut group, ebml::BLOCK, &block);
528 uint(&mut group, ebml::BLOCK_DURATION, duration.max(1) as u64);
529 elem(&mut self.cluster, ebml::BLOCK_GROUP, &group);
530 }
531 _ => {
532 block.push(if key { 0x80 } else { 0 });
533 block.extend_from_slice(payload);
534 elem(&mut self.cluster, ebml::SIMPLE_BLOCK, &block);
535 }
536 }
537 // One cue per keyframe of a video track (of the first track, in a file
538 // with no picture): an index naming every block of every track is three
539 // times too long and seeks no better.
540 let cued = match self.tracks.iter().any(|t| t.media == MediaType::Video) {
541 true => video && key,
542 false => track == 0 && key,
543 };
544 if cued {
545 self.cues.push(CuePoint {
546 time: ts,
547 track: number,
548 cluster: self.cluster_at - self.segment_body,
549 relative,
550 });
551 }
552 self.last_end = self.last_end.max(ts + duration.unwrap_or(0));
553 Ok(())
554 }
555
556 fn flush(&mut self) -> Result<()> {
557 if self.cluster.is_empty() {
558 return Ok(());
559 }
560 let mut head = Vec::new();
561 put_id(&mut head, ebml::CLUSTER);
562 put_size(&mut head, self.cluster.len() as u64);
563 let body = std::mem::take(&mut self.cluster);
564 self.write(&head)?;
565 self.write(&body)?;
566 Ok(())
567 }
568}
569
570impl<W: Write + Seek + Send> Muxer for MatroskaMuxer<W> {
571 fn add_stream(&mut self, info: StreamInfo) -> Result<u32> {
572 if self.pos > 0 {
573 return Err(Error::corrupt(
574 "Matroska: a stream declared after the first packet",
575 ));
576 }
577 if self.tracks.len() >= MAX_TRACKS {
578 return Err(Error::unsupported(
579 format!("{} tracks in one Matroska file", self.tracks.len() + 1),
580 "a block writes its track number in one byte",
581 ));
582 }
583 let index = self.tracks.len() as u32;
584 // Track numbers start at 1: zero is not a legal `TrackNumber`.
585 let number = u64::from(index) + 1;
586 let frame_ns = match &info.params.media {
587 MediaParameters::Video(v) => v.frame_rate.and_then(|r| {
588 r.inverse()
589 .checked_rescale(1, TimeBase::new(1, 1_000_000_000), Rounding::Nearest)
590 .map(|ns| ns.max(1) as u64)
591 }),
592 _ => None,
593 };
594 self.tracks.push(MuxTrack {
595 number,
596 media: info.params.codec.media_type(),
597 time_base: info.time_base,
598 frame_ns,
599 title: String::new(),
600 delay_ns: None,
601 field_order: Some(ec_core::Interlace::Progressive),
602 });
603 let mut info = info;
604 info.index = index;
605 self.streams.push(info);
606 Ok(index)
607 }
608
609 fn write_packet(&mut self, packet: &Packet) -> Result<()> {
610 let track = packet.stream as usize;
611 if track >= self.tracks.len() {
612 return Err(Error::corrupt(format!(
613 "Matroska: packet for stream {} of {}",
614 packet.stream,
615 self.tracks.len()
616 )));
617 }
618 if self.pos == 0 {
619 self.write_header()?;
620 }
621 // The packet's own base where it carries one, the stream's otherwise:
622 // a demuxer states both and an encoder often only the second.
623 let base = match packet.time_base.num() > 0 {
624 true => packet.time_base,
625 false => self.tracks[track].time_base,
626 };
627 let ts = match packet.pts {
628 Some(pts) => base.rescale(pts, MUX_TIME_BASE, Rounding::Nearest),
629 // A packet with no timestamp at all follows the one before it, by a
630 // frame where the track states a rate and by nothing where it does
631 // not — which is what a player would have to assume anyway.
632 None => self.last_end,
633 };
634 let duration = packet
635 .duration
636 .map(|d| base.rescale(d, MUX_TIME_BASE, Rounding::Nearest))
637 .or_else(|| {
638 self.tracks[track]
639 .frame_ns
640 .map(|ns| (ns / TIMESTAMP_SCALE_NS).max(1) as i64)
641 });
642 if packet.data.is_empty() {
643 return Err(Error::corrupt("Matroska: an empty block"));
644 }
645 self.put(track, ts, duration, packet.flags.keyframe, &packet.data)
646 }
647
648 fn finish(&mut self) -> Result<()> {
649 if self.finished {
650 return Ok(());
651 }
652 self.finished = true;
653 if self.pos == 0 {
654 self.write_header()?;
655 }
656 self.flush()?;
657
658 // The index, in the order a seek reads it. Kept as a file offset like
659 // the other two: the `SeekHead` below is what makes them all relative,
660 // and a position taken off the segment twice points at the middle of a
661 // cluster — where a reader that follows it finds an element that cannot
662 // be there and gives up on the file.
663 let cues_at = self.pos;
664 let mut cues = Vec::new();
665 for cue in std::mem::take(&mut self.cues) {
666 let mut positions = Vec::new();
667 uint(&mut positions, ebml::CUE_TRACK, cue.track);
668 uint(&mut positions, ebml::CUE_CLUSTER_POSITION, cue.cluster);
669 uint(&mut positions, ebml::CUE_RELATIVE_POSITION, cue.relative);
670 let mut point = Vec::new();
671 uint(&mut point, ebml::CUE_TIME, cue.time.max(0) as u64);
672 elem(&mut point, ebml::CUE_TRACK_POSITIONS, &positions);
673 elem(&mut cues, ebml::CUE_POINT, &point);
674 }
675 let mut element = Vec::new();
676 elem(&mut element, ebml::CUES, &cues);
677 self.write(&element)?;
678
679 let end = self.pos;
680 // The reserved 8-byte segment size: marker bit in the top byte, value
681 // under it.
682 let body = end - self.segment_body;
683 let size = (1u64 << 56) | body;
684 self.w.seek(SeekFrom::Start(self.segment_size_at))?;
685 self.w.write_all(&size.to_be_bytes())?;
686
687 // One tick past the last block shown, which is where the file really
688 // ends.
689 self.w.seek(SeekFrom::Start(self.duration_at))?;
690 self.w.write_all(&(self.last_end as f64).to_be_bytes())?;
691
692 // The `SeekHead`, into the room reserved for it, with a `Void` over
693 // whatever it did not need.
694 let mut entries = Vec::new();
695 for (id, at) in [
696 (ebml::INFO, self.info_at),
697 (ebml::TRACKS, self.tracks_at),
698 (ebml::CUES, cues_at),
699 ] {
700 let mut seek = Vec::new();
701 let mut id_bytes = Vec::new();
702 put_id(&mut id_bytes, id);
703 elem(&mut seek, ebml::SEEK_ID, &id_bytes);
704 // Fixed eight bytes, not the fewest that hold it: the table is
705 // written into a reservation, and a `SeekHead` whose length depends
706 // on how big the file turned out is one whose `Void` filler can land
707 // on a length EBML cannot spell.
708 put_id(&mut seek, ebml::SEEK_POSITION);
709 put_size(&mut seek, 8);
710 seek.extend_from_slice(&at.saturating_sub(self.segment_body).to_be_bytes());
711 elem(&mut entries, ebml::SEEK, &seek);
712 }
713 let mut head = Vec::new();
714 elem(&mut head, ebml::SEEK_HEAD, &entries);
715 let room = SEEK_HEAD_RESERVE + elem_head_len(ebml::VOID, SEEK_HEAD_RESERVE);
716 if head.len() > room {
717 return Err(Error::corrupt(
718 "Matroska: SeekHead larger than its reservation",
719 ));
720 }
721 // Whatever the table did not need becomes a `Void`, which needs two
722 // bytes of its own at the least. The three entries are fixed-width, so
723 // the leftover is a constant and this arithmetic is exact.
724 match room - head.len() {
725 0 => {}
726 1 => {
727 return Err(Error::corrupt(
728 "Matroska: one byte left over after the SeekHead",
729 ));
730 }
731 left => {
732 let payload = left - elem_head_len(ebml::VOID, left - 2);
733 elem(&mut head, ebml::VOID, &vec![0u8; payload]);
734 }
735 }
736 if head.len() != room {
737 return Err(Error::corrupt(
738 "Matroska: SeekHead reservation not filled exactly",
739 ));
740 }
741 self.w.seek(SeekFrom::Start(self.seek_head_at))?;
742 self.w.write_all(&head)?;
743 self.w.seek(SeekFrom::Start(end))?;
744 self.pos = end;
745 self.w.flush()?;
746 Ok(())
747 }
748}
749
750/// The Matroska codec id a [`CodecId`] is written as. The reverse of the
751/// reader's own table, and refusing rather than guessing is the point: a stream
752/// written under the wrong id is a file that opens and plays noise.
753pub(crate) fn matroska_codec_id(codec: CodecId) -> Result<&'static str> {
754 Ok(match codec {
755 CodecId::H264 => "V_MPEG4/ISO/AVC",
756 CodecId::H265 => "V_MPEGH/ISO/HEVC",
757 CodecId::Vp8 => "V_VP8",
758 CodecId::Vp9 => "V_VP9",
759 CodecId::Av1 => "V_AV1",
760 CodecId::Aac => "A_AAC",
761 CodecId::Ac3 => "A_AC3",
762 CodecId::EAc3 => "A_EAC3",
763 CodecId::TrueHd => "A_TRUEHD",
764 CodecId::Dts => "A_DTS",
765 CodecId::Alac => "A_ALAC",
766 CodecId::Flac => "A_FLAC",
767 CodecId::Mp3 => "A_MPEG/L3",
768 CodecId::Opus => "A_OPUS",
769 CodecId::Vorbis => "A_VORBIS",
770 CodecId::PcmU8 | CodecId::PcmS16Le | CodecId::PcmS24Le | CodecId::PcmS32Le => {
771 "A_PCM/INT/LIT"
772 }
773 CodecId::PcmS16Be => "A_PCM/INT/BIG",
774 CodecId::PcmF32Le => "A_PCM/FLOAT/IEEE",
775 CodecId::Srt => "S_TEXT/UTF8",
776 CodecId::WebVtt => "S_TEXT/WEBVTT",
777 CodecId::Ass => "S_TEXT/ASS",
778 CodecId::Pgs => "S_HDMV/PGS",
779 CodecId::DvdSub => "S_VOBSUB",
780 CodecId::DvbSub => "S_DVBSUB",
781 codec => {
782 return Err(Error::unsupported(
783 format!("{} in Matroska", codec.name()),
784 "the format defines no codec id for it",
785 ));
786 }
787 })
788}