forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

lib.rs227 lines, 8.3 KiBHistoryRawDownload
1//! RIFF/WAVE and AVI audio chunk reading.
2//!
3//! [`WavWriter`] streams samples as they arrive and patches the RIFF, `data`
4//! and `fact` sizes in [`WavWriter::finalize`] — a dropped writer therefore
5//! leaves a file whose header lies, which is why finalizing is fallible and
6//! explicit. [`WavReader`] walks the chunk list rather than assuming
7//! `fmt `-then-`data`, so `LIST`/`INFO`, `fact`, `bext` and any other chunk a
8//! recorder inserted are skipped, odd-sized chunks included (RIFF pads them to
9//! an even boundary and the padding byte is not part of the chunk).
10//!
11//! Covered: 8/16/24/32-bit integer PCM and 32-bit float, 1 to 8 channels
12//! (mono through 7.1), any sample rate. `WAVE_FORMAT_EXTENSIBLE` is written
13//! whenever the file has more than two channels or more than 16 bits per
14//! sample — the depth/layout combinations where players are entitled to
15//! distrust a plain `WAVE_FORMAT_PCM` header — and is read whatever the file
16//! declares.
17//!
18//! RF64 and BW64 (>4 GiB) are written when [`WavOptions::expected_frames`] says the
19//! data will not fit in 32 bits, and read whatever the size fields say.
20//!
21//! [`AviDemuxer`] is the full AVI audio+video demuxer (OpenDML, idx1 or linear scan, keyframes,
22//! field order); [`AviReader`] is the older audio-only reader.
23//!
24//! Not covered: ADPCM and other compressed WAVE tags,
25//! 64-bit float, and non-audio/video AVI chunks. Each unsupported
26//! WAVE tag is [`Error::Unsupported`] naming itself, never a silent misread.
27//!
28//! The crate stands alone — [`WavSpec`] is its own type — but converts into the
29//! family IR on request: [`WavSpec::sample_format`] and [`WavSpec::layout`].
30
31#![forbid(unsafe_code)]
32#![warn(missing_docs)]
33
34mod avi;
35mod demux;
36mod rawvideo;
37mod read;
38mod write;
39
40pub use avi::{AviAudioStream, AviIndexPoint, AviPacket, AviReader};
41pub use demux::{AviDemuxer, AviIndexKind, AviTrackInfo, is_avi};
42pub use ec_core::{Error, Result};
43pub use rawvideo::{MOV_MARKER, RawVideoDecoder};
44pub use read::WavReader;
45pub use write::{RF64_THRESHOLD, Sample, WavOptions, WavWriter};
46
47/// Whether samples are stored as integers (`WAVE_FORMAT_PCM`) or as floats
48/// (`WAVE_FORMAT_IEEE_FLOAT`).
49#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
50pub enum SampleType {
51 /// Signed integers, except 8-bit which RIFF stores unsigned and biased.
52 Int,
53 /// IEEE floats, nominal range -1.0..=1.0.
54 Float,
55}
56
57/// What the `fmt ` chunk says about the audio.
58#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
59pub struct WavSpec {
60 /// Channel count, 1..=8 for the layouts this crate names.
61 pub channels: u16,
62 /// Sample rate in Hz; any rate the source states.
63 pub sample_rate: u32,
64 /// Bits per sample: 8, 16, 24 or 32 for [`SampleType::Int`], 32 for float.
65 pub bits_per_sample: u16,
66 /// Integer or float storage.
67 pub sample_format: SampleType,
68}
69
70/// `WAVE_FORMAT_PCM`.
71const FORMAT_PCM: u16 = 1;
72/// `WAVE_FORMAT_IEEE_FLOAT`.
73const FORMAT_FLOAT: u16 = 3;
74/// `WAVE_FORMAT_EXTENSIBLE`.
75const FORMAT_EXTENSIBLE: u16 = 0xFFFE;
76
77impl WavSpec {
78 /// Bytes one sample of one channel occupies in the file.
79 pub fn bytes_per_sample(&self) -> usize {
80 usize::from(self.bits_per_sample).div_ceil(8)
81 }
82
83 /// Bytes one frame (one sample of every channel) occupies.
84 pub fn block_align(&self) -> usize {
85 self.bytes_per_sample() * usize::from(self.channels)
86 }
87
88 /// The equivalent family sample format. 24-bit widens to
89 /// [`ec_core::SampleFormat::S32`], as the IR documents.
90 pub fn sample_format(&self) -> Result<ec_core::SampleFormat> {
91 use ec_core::SampleFormat as F;
92 match (self.sample_format, self.bits_per_sample) {
93 (SampleType::Int, 8) => Ok(F::U8),
94 (SampleType::Int, 16) => Ok(F::S16),
95 (SampleType::Int, 24 | 32) => Ok(F::S32),
96 (SampleType::Float, 32) => Ok(F::F32),
97 (t, b) => Err(Error::unsupported(
98 format!("{b}-bit {t:?} WAVE samples"),
99 "ec-riff carries 8/16/24/32-bit integer and 32-bit float PCM",
100 )),
101 }
102 }
103
104 /// The channel layout a bare channel count implies (mono, stereo, 5.1, 7.1).
105 pub fn layout(&self) -> ec_core::ChannelLayout {
106 ec_core::ChannelLayout::from_count(usize::from(self.channels))
107 }
108
109 /// Validate what a header must satisfy before either direction trusts it.
110 fn validate(&self) -> Result<()> {
111 if self.channels == 0 {
112 return Err(Error::corrupt("WAVE fmt: zero channels"));
113 }
114 if self.sample_rate == 0 {
115 return Err(Error::corrupt("WAVE fmt: zero sample rate"));
116 }
117 self.sample_format().map(|_| ())
118 }
119
120 /// `WAVE_FORMAT_EXTENSIBLE` is due for more than two channels or more than
121 /// 16 bits — the cases where a bare PCM tag is ambiguous about layout.
122 fn is_extensible(&self) -> bool {
123 self.channels > 2 || self.bits_per_sample > 16
124 }
125
126 /// The `dwChannelMask` for the implied layout; 0 when the count has no
127 /// standard mask, which is legal and means "unassigned".
128 fn channel_mask(&self) -> u32 {
129 use ec_core::ChannelPosition as P;
130 let layout = self.layout();
131 let mut mask = 0u32;
132 for p in layout.positions() {
133 mask |= match p {
134 P::FrontLeft => 0x1,
135 P::FrontRight => 0x2,
136 P::FrontCenter => 0x4,
137 P::Lfe => 0x8,
138 P::BackLeft => 0x10,
139 P::BackRight => 0x20,
140 P::FrontLeftOfCenter => 0x40,
141 P::FrontRightOfCenter => 0x80,
142 P::BackCenter => 0x100,
143 P::SideLeft => 0x200,
144 P::SideRight => 0x400,
145 };
146 }
147 // `ChannelLayout::from_count` fills unknown counts with repeated
148 // FrontCenter, which would collapse to a one-bit mask claiming fewer
149 // channels than the header. Unassigned is the honest answer there.
150 if mask.count_ones() as u16 != self.channels {
151 0
152 } else {
153 mask
154 }
155 }
156
157 /// The `wFormatTag` (or extensible sub-format tag) for this spec.
158 fn format_tag(&self) -> u16 {
159 match self.sample_format {
160 SampleType::Int => FORMAT_PCM,
161 SampleType::Float => FORMAT_FLOAT,
162 }
163 }
164}
165
166
167/// A non-PCM WAVE/AVI audio format this family can decode: IMA ADPCM
168/// (`0x0011`), MS ADPCM (`0x0002`), A-law (`0x0006`) and mu-law (`0x0007`).
169#[derive(Debug, Clone, PartialEq, Eq)]
170pub struct WavCompressed {
171 /// The `wFormatTag`.
172 pub tag: u16,
173 /// Channel count.
174 pub channels: u16,
175 /// `nBlockAlign`: bytes per coded block (the packet size for ADPCM).
176 pub block_align: u16,
177 /// Decoded samples per channel in one full block.
178 pub samples_per_block: u32,
179 /// The `cbSize` tail of the `fmt ` chunk (samples per block, plus the MS
180 /// ADPCM coefficient table), passed to the decoder as extradata.
181 pub extra: Vec<u8>,
182}
183
184impl WavCompressed {
185 /// The codec a tag names, if it is one of the four.
186 pub fn codec_of(tag: u16) -> Option<ec_core::registry::CodecId> {
187 use ec_core::registry::CodecId;
188 match tag {
189 0x0011 => Some(CodecId::ImaAdpcmWav),
190 0x0002 => Some(CodecId::MsAdpcm),
191 0x0006 => Some(CodecId::PcmAlaw),
192 0x0007 => Some(CodecId::PcmMulaw),
193 _ => None,
194 }
195 }
196
197 /// Build from the fields of a `fmt ` chunk.
198 pub fn new(tag: u16, channels: u16, block_align: u16, extra: &[u8]) -> Option<WavCompressed> {
199 Self::codec_of(tag)?;
200 let ch = u32::from(channels.max(1));
201 let ba = u32::from(block_align);
202 let spb = match tag {
203 0x0011 => (ba.saturating_sub(4 * ch) / (4 * ch)) * 8 + 1,
204 0x0002 => ba.saturating_sub(6 * ch) * 2 / ch,
205 _ => 1,
206 };
207 Some(WavCompressed {
208 tag,
209 channels,
210 block_align,
211 samples_per_block: spb,
212 extra: extra.to_vec(),
213 })
214 }
215
216 /// Frames (samples per channel) in `bytes` bytes of coded data.
217 pub fn frames_in(&self, bytes: u64) -> u64 {
218 let ch = u64::from(self.channels.max(1));
219 match self.tag {
220 0x0006 | 0x0007 => bytes / ch,
221 _ => {
222 let ba = u64::from(self.block_align.max(1));
223 bytes / ba * u64::from(self.samples_per_block)
224 }
225 }
226 }
227}