forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB5c8eff8Tahinli2 months ago2949 commits

edith_surface.rs190 lines, 7.1 KiBHistoryRawDownload
1//! The call edith makes, verbatim in shape (engine/src/export.rs `write_wav`):
2//! `WavWriter::create(path, WavSpec { .. sample_format: Int })`, a run of
3//! `write_sample(x as i16)`, then `finalize()` — with the `?` conversion into
4//! edith's `Box<dyn Error + Send + Sync>` exercised too.
5
6type EdithError = Box<dyn std::error::Error + Send + Sync>;
7
8fn write_wav(
9 out: &std::path::Path,
10 samples: &[i32],
11 channels: u16,
12 rate: u32,
13) -> Result<(), EdithError> {
14 let mut writer = hound::WavWriter::create(
15 out,
16 hound::WavSpec {
17 channels,
18 sample_rate: rate,
19 bits_per_sample: 16,
20 sample_format: hound::SampleFormat::Int,
21 },
22 )?;
23 for &sample in samples {
24 writer.write_sample(sample as i16)?;
25 }
26 writer.finalize()?;
27 Ok(())
28}
29
30#[test]
31fn edith_write_wav_round_trips() {
32 let dir = std::path::Path::new(env!("CARGO_TARGET_TMPDIR"));
33 std::fs::create_dir_all(dir).unwrap();
34 for (channels, rate) in [(1u16, 44100u32), (2, 48000), (6, 48000)] {
35 let path = dir.join(format!("edith-{channels}ch-{rate}.wav"));
36 let samples: Vec<i32> = (0..usize::from(channels) * 512)
37 .map(|i| ((i as i32 * 733) % 65536) - 32768)
38 .collect();
39 write_wav(&path, &samples, channels, rate).unwrap();
40
41 let mut r = ec_riff::WavReader::open(&path).unwrap();
42 let spec = r.spec();
43 assert_eq!(spec.channels, channels);
44 assert_eq!(spec.sample_rate, rate);
45 assert_eq!(spec.bits_per_sample, 16);
46 assert_eq!(spec.sample_format, ec_riff::SampleType::Int);
47 assert_eq!(r.read_all_i32().unwrap(), samples);
48 }
49}
50
51/// The read half edith's tests make: `WavReader::open`, `spec()`, and
52/// `samples::<i16>()` collected — plus the two refusals hound answers with
53/// when the requested type cannot carry the file.
54#[test]
55fn edith_read_wav_round_trips() {
56 let dir = std::path::Path::new(env!("CARGO_TARGET_TMPDIR"));
57 std::fs::create_dir_all(dir).unwrap();
58 let path = dir.join("read-back.wav");
59 let samples: Vec<i32> = (0..2048).map(|i| ((i * 733) % 65536) - 32768).collect();
60 write_wav(&path, &samples, 2, 48000).unwrap();
61
62 let mut r = hound::WavReader::open(&path).unwrap();
63 let spec = r.spec();
64 assert_eq!(spec.channels, 2);
65 assert_eq!(spec.sample_rate, 48000);
66 assert_eq!(spec.bits_per_sample, 16);
67 assert_eq!(spec.sample_format, hound::SampleFormat::Int);
68 let read: Vec<i32> = r
69 .samples::<i16>()
70 .map(|s| i32::from(s.expect("a sample")))
71 .collect();
72 assert_eq!(read, samples);
73
74 // An integer file read as floats, and a 16-bit file read as 8: the two
75 // refusals, not silent conversions.
76 let mut r = hound::WavReader::open(&path).unwrap();
77 assert!(matches!(
78 r.samples::<f32>().next(),
79 Some(Err(hound::Error::InvalidSampleFormat))
80 ));
81 let mut r = hound::WavReader::open(&path).unwrap();
82 assert!(matches!(
83 r.samples::<i8>().next(),
84 Some(Err(hound::Error::TooWide))
85 ));
86}
87
88/// A `data` chunk that ends before its header said is hound's `IoError`
89/// (`UnexpectedEof`), never a short read the caller mistakes for the whole file.
90#[test]
91fn truncated_data_chunk_errors() {
92 let dir = std::path::Path::new(env!("CARGO_TARGET_TMPDIR"));
93 std::fs::create_dir_all(dir).unwrap();
94 let path = dir.join("truncated.wav");
95 let samples: Vec<i32> = (0..1024).map(|i| (i * 17) % 4096).collect();
96 write_wav(&path, &samples, 2, 48000).unwrap();
97
98 // Half the samples away, the header still promising all of them.
99 let bytes = std::fs::read(&path).unwrap();
100 std::fs::write(&path, &bytes[..bytes.len() - 1024]).unwrap();
101
102 let mut r = hound::WavReader::open(&path).unwrap();
103 let first = r.samples::<i16>().next();
104 assert!(
105 matches!(&first, Some(Err(hound::Error::IoError(e))) if e.kind() == std::io::ErrorKind::UnexpectedEof),
106 "expected UnexpectedEof, got {first:?}"
107 );
108}
109
110/// A minimal PCM WAVE header with `block_align` and `bits_per_sample` stated
111/// independently, so a padded container can be handed to the reader.
112fn wav_bytes(channels: u16, bits: u16, block_align: u16, data: &[u8]) -> Vec<u8> {
113 let mut v = Vec::new();
114 v.extend_from_slice(b"RIFF");
115 v.extend_from_slice(&(36 + data.len() as u32).to_le_bytes());
116 v.extend_from_slice(b"WAVEfmt ");
117 v.extend_from_slice(&16u32.to_le_bytes());
118 v.extend_from_slice(&1u16.to_le_bytes()); // WAVE_FORMAT_PCM
119 v.extend_from_slice(&channels.to_le_bytes());
120 v.extend_from_slice(&48000u32.to_le_bytes());
121 v.extend_from_slice(&(48000 * u32::from(block_align)).to_le_bytes());
122 v.extend_from_slice(&block_align.to_le_bytes());
123 v.extend_from_slice(&bits.to_le_bytes());
124 v.extend_from_slice(b"data");
125 v.extend_from_slice(&(data.len() as u32).to_le_bytes());
126 v.extend_from_slice(data);
127 v
128}
129
130/// The header pair the reader must not paper over: a container wider than the
131/// depth (hound: `Unsupported`) and a depth that is not whole bytes (hound:
132/// `FormatError`). Reading either as if it were packed would silently double
133/// the sample count and halve the duration.
134#[test]
135fn container_width_and_odd_depths_are_refused() {
136 let padded = wav_bytes(1, 8, 2, &[0x80, 0x00, 0x90, 0x00]);
137 assert!(
138 matches!(
139 hound::WavReader::new(std::io::Cursor::new(padded)),
140 Err(hound::Error::Unsupported)
141 ),
142 "8-bit samples in a 2-byte container must be refused"
143 );
144
145 for bits in [12u16, 20] {
146 let odd = wav_bytes(1, bits, bits.div_ceil(8), &[0; 8]);
147 assert!(
148 matches!(
149 hound::WavReader::new(std::io::Cursor::new(odd)),
150 Err(hound::Error::FormatError(_))
151 ),
152 "{bits}-bit must be a FormatError"
153 );
154 }
155
156 // The well-formed shape of the same helper still opens, so the refusals
157 // above are about the fields under test and not about the fixture.
158 let ok = wav_bytes(2, 16, 4, &[0; 16]);
159 let r = hound::WavReader::new(std::io::Cursor::new(ok)).expect("a packed 16-bit stereo header");
160 assert_eq!(r.spec().bits_per_sample, 16);
161}
162
163#[test]
164fn errors_carry_the_incumbent_variants() {
165 let dir = std::path::Path::new(env!("CARGO_TARGET_TMPDIR"));
166 let spec = hound::WavSpec {
167 channels: 2,
168 sample_rate: 48000,
169 bits_per_sample: 16,
170 sample_format: hound::SampleFormat::Int,
171 };
172 let mut w = hound::WavWriter::create(dir.join("errors.wav"), spec).unwrap();
173 // Wider than the declared depth, and the wrong sample family: the two
174 // failures callers of hound match on.
175 assert!(matches!(
176 w.write_sample(40_000i32),
177 Err(hound::Error::TooWide)
178 ));
179 assert!(matches!(
180 w.write_sample(0.5f32),
181 Err(hound::Error::InvalidSampleFormat)
182 ));
183 w.write_sample(1i16).unwrap();
184 assert!(matches!(w.finalize(), Err(hound::Error::UnfinishedSample)));
185 // A directory is not a file: I/O keeps its identity through the shim.
186 assert!(matches!(
187 hound::WavWriter::create(dir, spec),
188 Err(hound::Error::IoError(_))
189 ));
190}