decibri_decode/codec.rs
1//! Identities for containers, codecs and sample formats.
2//!
3//! These types exist so that [`DecodeError`](crate::DecodeError) can name the
4//! specific thing it rejected rather than a category. The step-0 audit found
5//! decibri's WAV reader rejecting mu-law, A-law and 24-bit PCM with the same
6//! reason string, leaving a caller unable to tell which unsupported encoding
7//! they hit or what to do about it. Every rejection this crate emits carries
8//! enough detail to act on.
9
10use std::fmt;
11
12/// A four-character code, as used by RIFF, AIFF, ISO base media and friends to
13/// name a chunk, a container or a codec.
14///
15/// Stored as the four bytes actually seen, never as an interpretation of them.
16/// [`Display`](fmt::Display) prints them as ASCII when all four are printable
17/// and as `0x` hex otherwise, so a garbage tag is reported as the bytes it was
18/// rather than as mojibake.
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
20pub struct FourCc(pub [u8; 4]);
21
22impl FourCc {
23 /// The four bytes as seen on the wire.
24 pub const fn as_bytes(&self) -> &[u8; 4] {
25 &self.0
26 }
27}
28
29impl From<[u8; 4]> for FourCc {
30 fn from(bytes: [u8; 4]) -> Self {
31 Self(bytes)
32 }
33}
34
35impl fmt::Display for FourCc {
36 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37 if self.0.iter().all(|b| b.is_ascii_graphic() || *b == b' ') {
38 // Every byte is printable ASCII, so the tag is readable as text.
39 for b in &self.0 {
40 write!(f, "{}", *b as char)?;
41 }
42 Ok(())
43 } else {
44 write!(
45 f,
46 "0x{:02x}{:02x}{:02x}{:02x}",
47 self.0[0], self.0[1], self.0[2], self.0[3]
48 )
49 }
50 }
51}
52
53/// How a container named the codec or sample format of its payload.
54///
55/// Containers identify codecs in incompatible ways, so this carries the
56/// identity in the form it was read in rather than mapping it to a normalised
57/// enum that would have to grow a variant for every codec the crate does not
58/// support. A caller reading a [`DecodeError`](crate::DecodeError) sees the
59/// same value the file contained.
60///
61/// In WAV the codec identity and the sample-format identity are the same field
62/// (`wFormatTag`: 1 is integer PCM, 3 is IEEE float, 6 is A-law, 7 is mu-law),
63/// which is why one type serves both.
64///
65/// This enum is `#[non_exhaustive]`: consumers matching on it must include a
66/// `_ =>` catch-all arm so a future container's identity scheme is not
67/// source-breaking to add.
68#[derive(Debug, Clone, PartialEq, Eq, Hash)]
69#[non_exhaustive]
70pub enum CodecId {
71 /// A RIFF/WAVE `wFormatTag`, as read from the `fmt ` chunk.
72 WaveFormatTag(u16),
73 /// A four-character code, as used by AIFF-C `COMM` compression types and
74 /// ISO base media sample entries.
75 FourCc(FourCc),
76 /// A textual codec name, for containers that name codecs as strings.
77 ///
78 /// Owned rather than borrowed because the whole point of reaching this
79 /// variant is that the name came out of the file and is not one of a set
80 /// the build knows.
81 Name(String),
82}
83
84impl fmt::Display for CodecId {
85 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
86 match self {
87 Self::WaveFormatTag(tag) => write!(f, "WAVE format tag 0x{tag:04x}"),
88 Self::FourCc(code) => write!(f, "four-CC '{code}'"),
89 Self::Name(name) => write!(f, "codec '{name}'"),
90 }
91 }
92}
93
94#[cfg(test)]
95mod tests {
96 use super::*;
97
98 #[test]
99 fn printable_four_cc_displays_as_text() {
100 assert_eq!(FourCc(*b"RIFF").to_string(), "RIFF");
101 // A trailing space is part of many real tags and must survive.
102 assert_eq!(FourCc(*b"fmt ").to_string(), "fmt ");
103 }
104
105 #[test]
106 fn unprintable_four_cc_displays_as_hex() {
107 assert_eq!(FourCc([0x00, 0x01, 0xff, 0x7f]).to_string(), "0x0001ff7f");
108 }
109
110 #[test]
111 fn codec_id_names_the_specific_identity() {
112 assert_eq!(
113 CodecId::WaveFormatTag(7).to_string(),
114 "WAVE format tag 0x0007"
115 );
116 assert_eq!(
117 CodecId::FourCc(FourCc(*b"alaw")).to_string(),
118 "four-CC 'alaw'"
119 );
120 assert_eq!(
121 CodecId::Name("opus".to_string()).to_string(),
122 "codec 'opus'"
123 );
124 }
125
126 #[test]
127 fn four_cc_exposes_the_bytes_it_was_built_from() {
128 let tag = FourCc::from(*b"fLaC");
129 assert_eq!(tag.as_bytes(), b"fLaC");
130 }
131}