forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB6828b15Tahinli3 months ago393 commits

lib.rs154 lines, 5.8 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//! Not covered: RF64/BW64 (>4 GiB), ADPCM and other compressed WAVE tags,
19//! 64-bit float, AVI video frames, and non-audio AVI chunks. Each unsupported
20//! WAVE tag is [`Error::Unsupported`] naming itself, never a silent misread.
21//!
22//! The crate stands alone — [`WavSpec`] is its own type — but converts into the
23//! family IR on request: [`WavSpec::sample_format`] and [`WavSpec::layout`].
24
25#![forbid(unsafe_code)]
26#![warn(missing_docs)]
27
28mod avi;
29mod read;
30mod write;
31
32pub use avi::{AviAudioStream, AviIndexPoint, AviPacket, AviReader};
33pub use ec_core::{Error, Result};
34pub use read::WavReader;
35pub use write::{Sample, WavWriter};
36
37/// Whether samples are stored as integers (`WAVE_FORMAT_PCM`) or as floats
38/// (`WAVE_FORMAT_IEEE_FLOAT`).
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
40pub enum SampleType {
41 /// Signed integers, except 8-bit which RIFF stores unsigned and biased.
42 Int,
43 /// IEEE floats, nominal range -1.0..=1.0.
44 Float,
45}
46
47/// What the `fmt ` chunk says about the audio.
48#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
49pub struct WavSpec {
50 /// Channel count, 1..=8 for the layouts this crate names.
51 pub channels: u16,
52 /// Sample rate in Hz; any rate the source states.
53 pub sample_rate: u32,
54 /// Bits per sample: 8, 16, 24 or 32 for [`SampleType::Int`], 32 for float.
55 pub bits_per_sample: u16,
56 /// Integer or float storage.
57 pub sample_format: SampleType,
58}
59
60/// `WAVE_FORMAT_PCM`.
61const FORMAT_PCM: u16 = 1;
62/// `WAVE_FORMAT_IEEE_FLOAT`.
63const FORMAT_FLOAT: u16 = 3;
64/// `WAVE_FORMAT_EXTENSIBLE`.
65const FORMAT_EXTENSIBLE: u16 = 0xFFFE;
66
67impl WavSpec {
68 /// Bytes one sample of one channel occupies in the file.
69 pub fn bytes_per_sample(&self) -> usize {
70 usize::from(self.bits_per_sample).div_ceil(8)
71 }
72
73 /// Bytes one frame (one sample of every channel) occupies.
74 pub fn block_align(&self) -> usize {
75 self.bytes_per_sample() * usize::from(self.channels)
76 }
77
78 /// The equivalent family sample format. 24-bit widens to
79 /// [`ec_core::SampleFormat::S32`], as the IR documents.
80 pub fn sample_format(&self) -> Result<ec_core::SampleFormat> {
81 use ec_core::SampleFormat as F;
82 match (self.sample_format, self.bits_per_sample) {
83 (SampleType::Int, 8) => Ok(F::U8),
84 (SampleType::Int, 16) => Ok(F::S16),
85 (SampleType::Int, 24 | 32) => Ok(F::S32),
86 (SampleType::Float, 32) => Ok(F::F32),
87 (t, b) => Err(Error::unsupported(
88 format!("{b}-bit {t:?} WAVE samples"),
89 "ec-riff carries 8/16/24/32-bit integer and 32-bit float PCM",
90 )),
91 }
92 }
93
94 /// The channel layout a bare channel count implies (mono, stereo, 5.1, 7.1).
95 pub fn layout(&self) -> ec_core::ChannelLayout {
96 ec_core::ChannelLayout::from_count(usize::from(self.channels))
97 }
98
99 /// Validate what a header must satisfy before either direction trusts it.
100 fn validate(&self) -> Result<()> {
101 if self.channels == 0 {
102 return Err(Error::corrupt("WAVE fmt: zero channels"));
103 }
104 if self.sample_rate == 0 {
105 return Err(Error::corrupt("WAVE fmt: zero sample rate"));
106 }
107 self.sample_format().map(|_| ())
108 }
109
110 /// `WAVE_FORMAT_EXTENSIBLE` is due for more than two channels or more than
111 /// 16 bits — the cases where a bare PCM tag is ambiguous about layout.
112 fn is_extensible(&self) -> bool {
113 self.channels > 2 || self.bits_per_sample > 16
114 }
115
116 /// The `dwChannelMask` for the implied layout; 0 when the count has no
117 /// standard mask, which is legal and means "unassigned".
118 fn channel_mask(&self) -> u32 {
119 use ec_core::ChannelPosition as P;
120 let layout = self.layout();
121 let mut mask = 0u32;
122 for p in layout.positions() {
123 mask |= match p {
124 P::FrontLeft => 0x1,
125 P::FrontRight => 0x2,
126 P::FrontCenter => 0x4,
127 P::Lfe => 0x8,
128 P::BackLeft => 0x10,
129 P::BackRight => 0x20,
130 P::FrontLeftOfCenter => 0x40,
131 P::FrontRightOfCenter => 0x80,
132 P::BackCenter => 0x100,
133 P::SideLeft => 0x200,
134 P::SideRight => 0x400,
135 };
136 }
137 // `ChannelLayout::from_count` fills unknown counts with repeated
138 // FrontCenter, which would collapse to a one-bit mask claiming fewer
139 // channels than the header. Unassigned is the honest answer there.
140 if mask.count_ones() as u16 != self.channels {
141 0
142 } else {
143 mask
144 }
145 }
146
147 /// The `wFormatTag` (or extensible sub-format tag) for this spec.
148 fn format_tag(&self) -> u16 {
149 match self.sample_format {
150 SampleType::Int => FORMAT_PCM,
151 SampleType::Float => FORMAT_FLOAT,
152 }
153 }
154}