decibri_decode/error.rs
1//! The one error type this crate returns.
2
3use std::fmt;
4
5use decibri_resampler::ResamplerError;
6
7use crate::codec::{CodecId, FourCc};
8
9/// Every way decoding can fail.
10///
11/// The variant list is closed by design rather than grown as codecs land. Each
12/// variant decibri surfaces has to be registered by name, code and sample
13/// instance in the `error_identity!` table in decibri's `error.rs`, and that
14/// macro has no catch-all arm, so a variant added later is a change in two
15/// crates and a new stable code on decibri's frozen error surface. Settling the
16/// list while the crate is empty costs nothing; growing it later costs a
17/// version bump in both crates.
18///
19/// The four `Unsupported*` variants are split rather than folded into one for
20/// the reason recorded on [`CodecId`]: "unsupported" alone does not tell a
21/// caller which encoding they hit or what to do about it.
22///
23/// This enum is `#[non_exhaustive]`: consumers pattern-matching on it must
24/// include a `_ =>` catch-all arm so future variant additions are not
25/// source-breaking.
26#[derive(Debug)]
27#[non_exhaustive]
28pub enum DecodeError {
29 /// The container format was not recognised.
30 ///
31 /// Carries the identifying bytes that were seen at the start of the input,
32 /// so a caller can tell "this is not audio at all" from "this is audio in a
33 /// container this build does not carry".
34 UnsupportedContainer {
35 /// The leading bytes read where a container magic was expected.
36 tag: FourCc,
37 },
38
39 /// The container parsed and named a codec this build does not support.
40 ///
41 /// Distinct from [`UnsupportedContainer`](Self::UnsupportedContainer): the
42 /// file is well-formed and its structure was understood. Only the payload
43 /// encoding is out of reach.
44 UnsupportedCodec {
45 /// The codec identity exactly as the container stated it.
46 codec: CodecId,
47 },
48
49 /// A recognised codec in a sample format this build does not support.
50 ///
51 /// Distinct from [`UnsupportedCodec`](Self::UnsupportedCodec): the codec
52 /// itself is carried, but not at this width or in this representation,
53 /// 24-bit PCM where only 16- and 32-bit are implemented, for instance.
54 UnsupportedSampleFormat {
55 /// The format tag, in the form the container stated it.
56 format: CodecId,
57 /// Bits per sample as declared by the container.
58 bits_per_sample: u16,
59 },
60
61 /// The channel count or layout is not one this build can decode.
62 UnsupportedChannelLayout {
63 /// The channel count the container declared.
64 channels: u16,
65 },
66
67 /// A parse failure: the bytes at a known position were not what the format
68 /// requires there.
69 ///
70 /// Distinct from [`Truncated`](Self::Truncated), which is about running out
71 /// of input rather than finding the wrong input.
72 Malformed {
73 /// What the parser required at that position, as a short literal.
74 expected: &'static str,
75 /// Byte offset from the start of the input where the parse failed.
76 offset: u64,
77 },
78
79 /// The input ended part-way through a frame, a header or a declared
80 /// length.
81 ///
82 /// From a file this means the file is short. From a stream it means the
83 /// stream was finished while a frame was still incomplete: a stream that
84 /// simply has not received the rest yet is not an error, and the stream
85 /// adapter holds the partial frame instead of reporting one.
86 Truncated {
87 /// How much of the incomplete item was needed. Bytes on every path
88 /// but one: a FLAC stream holding fewer samples than its streaminfo
89 /// declares reports the two counts in interchannel samples, because
90 /// samples are the unit the declaration is in.
91 expected: u64,
92 /// How much was actually available, in the same unit as `expected`.
93 available: u64,
94 },
95
96 /// The container declares one codec and the payload is another.
97 ///
98 /// Reached when both identities parse and disagree, a WAVE header claiming
99 /// integer PCM over a payload whose frames are mu-law, say. Reported
100 /// separately from the `Unsupported*` variants because nothing here is
101 /// unsupported: the file is internally inconsistent and no single decoder
102 /// choice is correct.
103 ContainerCodecMismatch {
104 /// What the container's header said the payload is.
105 declared: CodecId,
106 /// What the payload actually turned out to be.
107 found: CodecId,
108 },
109
110 /// Rate conversion failed.
111 ///
112 /// The only variant that chains a source. This crate contains no resampling
113 /// logic; it calls `decibri-resampler` and passes its failure through
114 /// unaltered.
115 Resample(ResamplerError),
116}
117
118impl fmt::Display for DecodeError {
119 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
120 match self {
121 Self::UnsupportedContainer { tag } => {
122 write!(f, "unrecognised container, leading bytes were '{tag}'")
123 }
124 Self::UnsupportedCodec { codec } => {
125 write!(f, "container names {codec}, which this build cannot decode")
126 }
127 Self::UnsupportedSampleFormat {
128 format,
129 bits_per_sample,
130 } => write!(
131 f,
132 "{format} at {bits_per_sample} bits per sample is not a supported sample format"
133 ),
134 Self::UnsupportedChannelLayout { channels } => {
135 write!(f, "{channels}-channel audio is not a supported layout")
136 }
137 Self::Malformed { expected, offset } => {
138 write!(f, "malformed input at byte {offset}: expected {expected}")
139 }
140 Self::Truncated {
141 expected,
142 available,
143 } => write!(
144 f,
145 "input ended early: {expected} needed, {available} available"
146 ),
147 Self::ContainerCodecMismatch { declared, found } => write!(
148 f,
149 "container declares {declared} but the payload is {found}"
150 ),
151 Self::Resample(source) => write!(f, "resampling failed: {source}"),
152 }
153 }
154}
155
156impl std::error::Error for DecodeError {
157 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
158 match self {
159 Self::Resample(source) => Some(source),
160 _ => None,
161 }
162 }
163}
164
165impl From<ResamplerError> for DecodeError {
166 fn from(source: ResamplerError) -> Self {
167 Self::Resample(source)
168 }
169}
170
171#[cfg(test)]
172mod tests {
173 use super::*;
174
175 /// One instance of every variant. If a variant is added without a line
176 /// here the match below stops compiling, which is the point: no variant
177 /// gets to be unreachable, and every one of them has a `Display` string
178 /// somebody has looked at.
179 fn one_of_each() -> Vec<DecodeError> {
180 vec![
181 DecodeError::UnsupportedContainer {
182 tag: FourCc(*b"\x00\x01\x02\x03"),
183 },
184 DecodeError::UnsupportedCodec {
185 codec: CodecId::WaveFormatTag(0x0011),
186 },
187 DecodeError::UnsupportedSampleFormat {
188 format: CodecId::WaveFormatTag(1),
189 bits_per_sample: 24,
190 },
191 DecodeError::UnsupportedChannelLayout { channels: 8 },
192 DecodeError::Malformed {
193 expected: "a 'data' chunk header",
194 offset: 36,
195 },
196 DecodeError::Truncated {
197 expected: 4096,
198 available: 1200,
199 },
200 DecodeError::ContainerCodecMismatch {
201 declared: CodecId::WaveFormatTag(1),
202 found: CodecId::WaveFormatTag(7),
203 },
204 DecodeError::Resample(ResamplerError::ProcessAfterFlush),
205 ]
206 }
207
208 #[test]
209 fn every_variant_is_constructible() {
210 // The exhaustive match is the assertion: adding a variant to the enum
211 // without adding it to `one_of_each` fails to compile here.
212 for error in one_of_each() {
213 match error {
214 DecodeError::UnsupportedContainer { .. }
215 | DecodeError::UnsupportedCodec { .. }
216 | DecodeError::UnsupportedSampleFormat { .. }
217 | DecodeError::UnsupportedChannelLayout { .. }
218 | DecodeError::Malformed { .. }
219 | DecodeError::Truncated { .. }
220 | DecodeError::ContainerCodecMismatch { .. }
221 | DecodeError::Resample(_) => {}
222 }
223 }
224 }
225
226 #[test]
227 fn display_names_the_specific_thing() {
228 assert_eq!(
229 DecodeError::UnsupportedSampleFormat {
230 format: CodecId::WaveFormatTag(1),
231 bits_per_sample: 24,
232 }
233 .to_string(),
234 "WAVE format tag 0x0001 at 24 bits per sample is not a supported sample format"
235 );
236 assert_eq!(
237 DecodeError::UnsupportedCodec {
238 codec: CodecId::WaveFormatTag(7),
239 }
240 .to_string(),
241 "container names WAVE format tag 0x0007, which this build cannot decode"
242 );
243 // Three encodings decibri's current WAV reader rejects with one shared
244 // reason string. Here they are three distinguishable messages.
245 let mulaw = DecodeError::UnsupportedCodec {
246 codec: CodecId::WaveFormatTag(7),
247 }
248 .to_string();
249 let alaw = DecodeError::UnsupportedCodec {
250 codec: CodecId::WaveFormatTag(6),
251 }
252 .to_string();
253 let pcm24 = DecodeError::UnsupportedSampleFormat {
254 format: CodecId::WaveFormatTag(1),
255 bits_per_sample: 24,
256 }
257 .to_string();
258 assert_ne!(mulaw, alaw);
259 assert_ne!(alaw, pcm24);
260 assert_ne!(mulaw, pcm24);
261 }
262
263 #[test]
264 fn no_display_string_is_empty_or_generic() {
265 for error in one_of_each() {
266 let text = error.to_string();
267 assert!(!text.is_empty());
268 assert!(
269 !text.eq_ignore_ascii_case("unsupported"),
270 "variant reported a bare category: {text}"
271 );
272 }
273 }
274
275 #[test]
276 fn only_the_resample_variant_chains_a_source() {
277 use std::error::Error as _;
278
279 for error in one_of_each() {
280 let chains = error.source().is_some();
281 assert_eq!(
282 chains,
283 matches!(error, DecodeError::Resample(_)),
284 "source chaining is for the Resample variant only: {error}"
285 );
286 }
287 }
288
289 #[test]
290 fn resampler_errors_convert() {
291 let error: DecodeError = ResamplerError::ZeroSampleRate.into();
292 assert!(matches!(error, DecodeError::Resample(_)));
293 assert_eq!(
294 error.to_string(),
295 "resampling failed: sample rate must be greater than 0"
296 );
297 }
298
299 #[test]
300 fn the_error_crosses_threads() {
301 // Decoders run off the audio thread, so their failures have to be
302 // sendable. Asserted at compile time.
303 fn assert_send_sync<T: Send + Sync + 'static>() {}
304 assert_send_sync::<DecodeError>();
305 }
306}