Skip to main content

moq_mux/container/mkv/
mod.rs

1//! Matroska / WebM.
2//!
3//! An EBML-based file format. moq-mux uses it as an external interchange
4//! format only, not as a wire format: [`Import`] parses MKV byte streams
5//! into a broadcast and [`Export`] does the reverse.
6
7mod ebml;
8mod export;
9mod hvcc;
10mod import;
11
12pub use export::*;
13pub use import::*;
14
15#[cfg(test)]
16mod export_test;
17#[cfg(test)]
18mod import_test;
19
20/// MKV parsing and emission errors.
21#[derive(Debug, Clone, thiserror::Error)]
22#[non_exhaustive]
23pub enum Error {
24	/// A track field is outside the catalog's numeric range.
25	#[error("MKV {0} is outside the catalog's numeric range")]
26	ValueOutOfRange(&'static str),
27
28	/// Container display metadata has no valid catalog aspect ratio.
29	#[error("invalid display aspect: {0}")]
30	InvalidAspect(&'static str),
31
32	/// A subtitle track cannot be imported in one pass: a WebVTT cue's length depends on its
33	/// content, so it cannot stream into a frame of a declared size.
34	#[error("MKV subtitle track {0} is unsupported: its cues cannot stream")]
35	SubtitleTrack(String),
36
37	/// A video Block neither follows a ReferenceBlock nor ends its BlockGroup, so whether it starts
38	/// a group would wait on fields after its payload.
39	#[error("video BlockGroup with fields after its Block is unsupported: a later ReferenceBlock decides its group")]
40	TrailingReference,
41
42	/// CMAF output needs a `moof` describing each payload before it, but MKV import streams payloads.
43	#[error("MKV import cannot write CMAF; select Legacy or LOC")]
44	StreamedCmaf,
45
46	/// The input ended inside an element.
47	#[error("truncated MKV element")]
48	Truncated,
49
50	/// The EBML header declares an unsupported DocType.
51	#[error("unsupported EBML DocType: {0}")]
52	UnsupportedDocType(String),
53
54	/// The EBML header has no DocType.
55	#[error("EBML header missing DocType")]
56	MissingDocType,
57
58	/// The SimpleBlock payload is malformed.
59	#[error("invalid SimpleBlock")]
60	InvalidSimpleBlock,
61
62	/// The Block payload is malformed.
63	#[error("invalid Block payload")]
64	InvalidBlock,
65
66	/// A laced Block's lace sizes do not fit its payload.
67	#[error("invalid MKV lacing")]
68	InvalidLacing,
69
70	/// A laced Block has no BlockDuration before it, nor a track DefaultDuration, to time the frames
71	/// after its first.
72	#[error("MKV lacing requires a positive BlockDuration before the Block, or TrackEntry DefaultDuration")]
73	LacingDuration,
74
75	/// The block timestamp precedes the start of the timeline.
76	#[error("negative block timestamp")]
77	NegativeBlockTimestamp,
78
79	/// A timestamp calculation overflowed.
80	#[error("timestamp overflow")]
81	TimestampOverflow,
82
83	/// A TrackEntry ended after the catalog was published, by the first block or by a Tracks
84	/// element declaring none, so its rendition could never join the catalog's first snapshot.
85	#[error("Tracks after the catalog was published")]
86	LateTracks,
87
88	/// The TrackEntry has no TrackNumber.
89	#[error("TrackEntry missing TrackNumber")]
90	MissingTrackNumber,
91
92	/// The TrackEntry has no TrackType.
93	#[error("TrackEntry missing TrackType")]
94	MissingTrackType,
95
96	/// The TrackEntry has no CodecID.
97	#[error("TrackEntry missing CodecID")]
98	MissingCodecId,
99
100	/// The video track declares an unsupported CodecID.
101	#[error("unsupported video CodecID: {0}")]
102	UnsupportedVideoCodec(String),
103
104	/// The audio track declares an unsupported CodecID.
105	#[error("unsupported audio CodecID: {0}")]
106	UnsupportedAudioCodec(String),
107
108	/// The codec lacks the private data required for the stated purpose.
109	#[error("{codec_id} missing CodecPrivate ({purpose})")]
110	MissingCodecPrivate {
111		/// The codec requiring private data.
112		codec_id: &'static str,
113		/// The operation requiring that private data.
114		purpose: &'static str,
115	},
116
117	/// A TrackEntry's CodecPrivate came before its CodecID, which decides how it is read.
118	#[error("MKV CodecPrivate before CodecID is unsupported")]
119	CodecPrivateBeforeCodecId,
120
121	/// The CodecPrivate holds more than the codec's supported configuration.
122	#[error("{0} CodecPrivate is outside its supported configuration")]
123	UnsupportedCodecPrivate(String),
124
125	/// The HEVCDecoderConfigurationRecord is malformed.
126	#[error("invalid HEVCDecoderConfigurationRecord")]
127	InvalidHvcc,
128
129	/// The AV1CodecConfigurationRecord is malformed.
130	#[error("invalid AV1CodecConfigurationRecord")]
131	InvalidAv1c,
132
133	/// A `Colour` element value has no catalog representation.
134	#[error("invalid Colour {0}")]
135	InvalidColour(&'static str),
136
137	/// A `StereoMode` or `Projection` element the catalog cannot describe, or a malformed one.
138	#[error("unsupported spherical video: {0}")]
139	UnsupportedSpatial(&'static str),
140
141	/// The named track joined after the MKV header was emitted, with no failed track of its
142	/// kind to continue.
143	#[error("MKV track layout changed after header was emitted: track '{0}' added")]
144	HeaderAddedTrack(String),
145
146	/// The named rendition moved to a track the header's TrackEntry does not describe.
147	#[error("MKV track '{0}' moved to a track whose codec configuration differs from the header's")]
148	TrackChanged(String),
149
150	/// The named CMAF track cannot be exported as MKV.
151	#[error("MKV export does not support CMAF {kind} track '{name}'")]
152	UnsupportedCmafTrack {
153		/// The track media kind.
154		kind: String,
155		/// The track name.
156		name: String,
157	},
158
159	/// The named video codec cannot be exported as MKV.
160	#[error("MKV export does not support video codec {0}")]
161	UnsupportedVideoExport(String),
162
163	/// The named audio codec cannot be exported as MKV.
164	#[error("MKV export does not support audio codec {0}")]
165	UnsupportedAudioExport(String),
166
167	/// The AAC track has no AudioSpecificConfig description.
168	#[error("AAC track missing AudioSpecificConfig (description)")]
169	MissingAacDescription,
170
171	/// The FLAC track has no STREAMINFO description.
172	#[error("FLAC track missing STREAMINFO (description)")]
173	MissingFlacDescription,
174
175	/// The H.264 track has no AVCDecoderConfigurationRecord.
176	#[error("H.264 track missing AVCDecoderConfigurationRecord")]
177	MissingH264Avcc,
178
179	/// The H.265 track has no HEVCDecoderConfigurationRecord.
180	#[error("H.265 track missing HEVCDecoderConfigurationRecord")]
181	MissingH265Hvcc,
182
183	/// The block timestamp offset from its cluster overflows.
184	#[error("cluster underflow")]
185	ClusterUnderflow,
186
187	/// The block timestamp does not fit the signed 16-bit relative field.
188	#[error("block timestamp doesn't fit in i16")]
189	BlockTimestampOverflow,
190
191	/// The frame references an unavailable track.
192	#[error("missing track")]
193	MissingTrack,
194
195	/// The timestamp does not fit an unsigned 64-bit millisecond count.
196	#[error("timestamp doesn't fit in u64 ms")]
197	TimestampU64,
198
199	/// The named video track is absent from the tracks map.
200	#[error("video track {0} missing in tracks map")]
201	MissingVideoTrack(String),
202
203	/// The named audio track is absent from the tracks map.
204	#[error("audio track {0} missing in tracks map")]
205	MissingAudioTrack(String),
206
207	/// No catalog snapshot is available to declare the tracks.
208	#[error("no catalog snapshot")]
209	NoCatalogSnapshot,
210
211	/// The Matroska stream could not be parsed.
212	#[error("matroska parse error")]
213	MatroskaParse,
214
215	/// The Matroska stream could not be written.
216	#[error("matroska write error: {0}")]
217	MatroskaWrite(String),
218
219	/// Building the Opus codec-private OpusHead for an audio track failed.
220	#[error(transparent)]
221	Opus(#[from] crate::codec::opus::Error),
222}
223
224// Flattened to its message so webm-iterable stays out of this crate's public API. The chain
225// matters here: `TagWriterError::WriteError` displays only "Error writing to destination." and
226// keeps the `io::Error` saying whether the disk filled or the pipe broke in `source()`.
227impl From<webm_iterable::errors::TagWriterError> for Error {
228	fn from(err: webm_iterable::errors::TagWriterError) -> Self {
229		Error::MatroskaWrite(crate::error::message(err))
230	}
231}
232
233/// A result using this module's error type.
234pub type Result<T> = std::result::Result<T, Error>;
235
236#[cfg(test)]
237mod error_tests {
238	use super::*;
239
240	/// `TagWriterError::WriteError` displays only "Error writing to destination.", so the
241	/// `io::Error` naming the actual failure has to come through the source chain or an export
242	/// failure is undiagnosable.
243	#[test]
244	fn matroska_write_keeps_the_io_cause() {
245		let source = std::io::Error::new(std::io::ErrorKind::StorageFull, "no space left on device");
246		let err = Error::from(webm_iterable::errors::TagWriterError::WriteError { source });
247
248		let message = err.to_string();
249		assert!(message.contains("no space left on device"), "{message}");
250	}
251}