forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB03dc6e9Tahinli3 months ago178 commits

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