forge
Explore
Log in

Don't you dare go Hollow

Flush the terminal Vorbis block through to Ogg's granule-stated end

Browse files at this commit

b966d5e46844baf5f1e9ad236ba1c8b705eff3abAhmet Kaan GümüşParent: 73af0e7
  • fix
    • flush the terminal Vorbis block through to Ogg's granule-stated end
Show full message
fix(aac-sbr-ogg): flush the terminal Vorbis block through to Ogg's granule-stated end

EOS was never signalled through ec-probe/the symphonia shim, so the last
Vorbis block's un-overlapped tail (and any un-overlapped audio still sitting
in the last decoded packet) never reached the caller: the reader now hands
every audio track one synthetic, empty terminal packet once the container
itself is exhausted, and AudioDecoder::flush() is what answers it.

Trimming to the container's own granule only ever trusts two points: the
very first packet's granule (a real front pre-roll, if the format has one)
and the last one, applied once at flush -- an interior page's granule marks
where the packet finishing on that page ends, not a ceiling every later
page's cumulative output must stay under, so it is never used as one.
Vorbis's last decoded packet is held back one call rather than handed out
immediately, so that final trim can still reach into it.
Cargo.lockmodified+2 -0
@@ -1240,7 +1240,9 @@ name = "symphonia"
1240 version = "0.6.0"1240 version = "0.6.0"
1241 dependencies = [1241 dependencies = [
1242 "ec-core",1242 "ec-core",
1243+ "ec-ogg",
1243 "ec-probe",1244 "ec-probe",
1245+ "ec-vorbis",
1244 "symphonia-codec-aac",1246 "symphonia-codec-aac",
1245 "symphonia-core",1247 "symphonia-core",
1246 ]1248 ]
crates/ec-probe/src/decoder.rsmodified+148 -0
@@ -31,6 +31,37 @@ pub struct AudioDecoder {
31 codec: CodecId,31 codec: CodecId,
32 channels: usize,32 channels: usize,
33 sample_rate: u32,33 sample_rate: u32,
34+ /// Raw interleaved frames the decoder has produced so far, before any
35+ /// trim — the running clock the front-offset calculation below measures
36+ /// against.
37+ produced: i64,
38+ /// Frames actually handed out to the caller so far.
39+ emitted: i64,
40+ /// `granule - produced` at the first packet whose granule is known: a
41+ /// Vorbis stream's very first pages account for the encoder's pre-roll in
42+ /// their granule, so this is the one-time head start (or catch-up) the
43+ /// decoder's own count needed to line up with the container's.
44+ ///
45+ /// This is a front offset only. An *interior* page's granule marks where
46+ /// the last packet completed *on that page* ends — not a ceiling every
47+ /// later page's cumulative output must stay under, since packets can span
48+ /// pages and pages can end mid-packet. Only the first granule (front) and
49+ /// the last one (tail, at [`Self::flush`]) are trustworthy trim points.
50+ trim_offset: Option<i64>,
51+ /// The last granule [`Self::decode`] saw, carried into [`Self::flush`]
52+ /// for the terminal packet's own trim: the flush call's packet (the
53+ /// reader's synthetic end-of-stream marker) carries no granule of its own.
54+ last_granule: Option<i64>,
55+ /// The most recently decoded packet's own audio, held back one call
56+ /// rather than handed to the caller straight away: Vorbis's terminal
57+ /// packet routinely decodes real samples past the container's true final
58+ /// granule (its own block reaches further than the stream actually
59+ /// runs), and so does [`Self::flush`]'s un-overlapped tail on top of it.
60+ /// Once a packet's audio has left this decoder there is nothing left to
61+ /// trim it from, so the last packet's audio waits here — combined with
62+ /// the flush tail — for [`Self::flush`] to cut both down to the file's
63+ /// real length in one go.
64+ held: Vec<f32>,
34 }65 }
35 66
36 impl std::fmt::Debug for AudioDecoder {67 impl std::fmt::Debug for AudioDecoder {
@@ -109,6 +140,11 @@ impl AudioDecoder {
109 CodecId::Opus => 48_000,140 CodecId::Opus => 48_000,
110 _ => sample_rate,141 _ => sample_rate,
111 },142 },
143+ produced: 0,
144+ emitted: 0,
145+ trim_offset: None,
146+ last_granule: None,
147+ held: Vec::new(),
112 })148 })
113 }149 }
114 150
@@ -160,9 +196,105 @@ impl AudioDecoder {
160 }196 }
161 Inner::Pcm(codec) => pcm(*codec, &packet.data, out),197 Inner::Pcm(codec) => pcm(*codec, &packet.data, out),
162 }198 }
199+ self.trim(ec_ogg::granule_of(packet), out);
200+ // Only Vorbis holds real, un-overlapped state across a packet
201+ // boundary that a stream-final granule can still need to reach into
202+ // (see `held`'s own doc); every other codec here releases its audio
203+ // the moment it is decoded, exactly as before, so a caller that never
204+ // calls `flush` still gets every packet's worth back.
205+ if matches!(self.inner, Inner::Vorbis(_)) {
206+ std::mem::swap(&mut self.held, out);
207+ }
208+ self.emitted += out.len() as i64 / self.channels.max(1) as i64;
209+ Ok(())
210+ }
211+
212+ /// The one-off front trim: only the very first packet this decoder ever
213+ /// sees can carry a legitimate pre-roll offset (`granule` at real stream
214+ /// position zero). Most containers' first *audio* packet carries no
215+ /// granule at all — pages tend to end well into the block run — so once
216+ /// any later packet is the first to reveal one, that granule is an
217+ /// interior page mark, not a front offset: subtracting it from what has
218+ /// already been decoded would blame ordinary block-to-block lag on a
219+ /// pre-roll that was never there, and can trim away a whole packet's
220+ /// worth of real audio. Every later packet passes through untouched — an
221+ /// interior page's granule is not a per-page ceiling (see
222+ /// [`Self::trim_offset`]); only [`Self::flush`]'s tail trim cuts again.
223+ fn trim(&mut self, granule: Option<i64>, out: &mut Vec<f32>) {
224+ let channels = self.channels.max(1) as i64;
225+ let raw_frames = out.len() as i64 / channels;
226+ if let Some(granule) = granule {
227+ self.last_granule = Some(granule);
228+ if self.trim_offset.is_none() {
229+ if self.produced == 0 {
230+ let offset = (granule - raw_frames).max(0);
231+ self.trim_offset = Some(offset);
232+ if offset > 0 {
233+ let drop = (offset.min(raw_frames) * channels) as usize;
234+ out.drain(0..drop);
235+ }
236+ } else {
237+ // Too late for a real front offset: this stream's first
238+ // audio packet already went by with no granule on it.
239+ self.trim_offset = Some(0);
240+ }
241+ }
242+ }
243+ self.produced += raw_frames;
244+ }
245+
246+ /// Signal end of stream and take whatever the decoder was holding back.
247+ ///
248+ /// Every codec here that overlaps blocks (Vorbis above all: its terminal
249+ /// block's un-overlapped right half is real audio up to the stream's
250+ /// final granule, and is otherwise always exactly one hop short) needs
251+ /// this told to it once the packets have run out, or the last hop never
252+ /// comes out at all. `out` is cleared first, same as [`Self::decode`].
253+ ///
254+ /// [`Self::held`] (the last packet's own audio, never yet released) is
255+ /// combined with whatever this call's own flush produces, and the pair
256+ /// are cut down together to the stream's real final granule — the last
257+ /// [`Self::decode`] call's packet is routinely the one this trim needs to
258+ /// reach into, and once its audio had left this decoder that was no
259+ /// longer possible.
260+ pub fn flush(&mut self, out: &mut Vec<f32>) -> Result<()> {
261+ out.clear();
262+ match &mut self.inner {
263+ Inner::Flac(d) => flush_drain(d.as_mut(), out)?,
264+ Inner::Mp3(d) => flush_drain(d.as_mut(), out)?,
265+ Inner::Vorbis(d) => flush_drain(d.as_mut(), out)?,
266+ Inner::Ac3(d) => flush_drain(d.as_mut(), out)?,
267+ // AAC, ALAC, Opus and PCM decode a packet at a time with nothing
268+ // held back across the end of the file.
269+ Inner::Aac(_) | Inner::Alac(_) | Inner::Opus(_) | Inner::Pcm(_) => {}
270+ }
271+ let channels = self.channels.max(1) as i64;
272+ self.produced += out.len() as i64 / channels;
273+ let mut combined = std::mem::take(&mut self.held);
274+ combined.append(out);
275+ self.trim_tail(&combined, out);
163 Ok(())276 Ok(())
164 }277 }
165 278
279+ /// The terminal trim: the stream's last granule minus the front offset
280+ /// is the file's true total frame count, so whatever `combined` (the
281+ /// held-back last packet plus the flush tail) still has past that is
282+ /// dropped rather than handed to the caller.
283+ fn trim_tail(&mut self, combined: &[f32], out: &mut Vec<f32>) {
284+ let channels = self.channels.max(1) as i64;
285+ let raw_frames = combined.len() as i64 / channels;
286+ let keep = match self.last_granule {
287+ Some(granule) => {
288+ let offset = self.trim_offset.unwrap_or(0);
289+ let target = (granule - offset).max(0);
290+ (target - self.emitted).clamp(0, raw_frames)
291+ }
292+ None => raw_frames,
293+ };
294+ out.extend_from_slice(&combined[..(keep * channels).max(0) as usize]);
295+ self.emitted += keep;
296+ }
297+
166 /// Drop everything buffered from before a seek.298 /// Drop everything buffered from before a seek.
167 pub fn reset(&mut self) {299 pub fn reset(&mut self) {
168 match &mut self.inner {300 match &mut self.inner {
@@ -175,6 +307,11 @@ impl AudioDecoder {
175 Inner::Opus(d) => d.reset(),307 Inner::Opus(d) => d.reset(),
176 Inner::Pcm(_) => {}308 Inner::Pcm(_) => {}
177 }309 }
310+ self.held.clear();
311+ self.produced = 0;
312+ self.emitted = 0;
313+ self.trim_offset = None;
314+ self.last_granule = None;
178 }315 }
179 }316 }
180 317
@@ -219,6 +356,17 @@ fn is_pcm(codec: CodecId) -> bool {
219 /// yields, converted to interleaved `f32`.356 /// yields, converted to interleaved `f32`.
220 fn drain(decoder: &mut dyn Decoder, packet: &Packet, out: &mut Vec<f32>) -> Result<()> {357 fn drain(decoder: &mut dyn Decoder, packet: &Packet, out: &mut Vec<f32>) -> Result<()> {
221 decoder.send_packet(packet)?;358 decoder.send_packet(packet)?;
359+ drain_frames(decoder, out)
360+}
361+
362+/// [`ec_core::Decoder::flush`], then every frame it releases because of it.
363+fn flush_drain(decoder: &mut dyn Decoder, out: &mut Vec<f32>) -> Result<()> {
364+ decoder.flush()?;
365+ drain_frames(decoder, out)
366+}
367+
368+/// Every frame currently ready, converted to interleaved `f32`.
369+fn drain_frames(decoder: &mut dyn Decoder, out: &mut Vec<f32>) -> Result<()> {
222 loop {370 loop {
223 match decoder.receive_frame() {371 match decoder.receive_frame() {
224 Ok(Frame::Audio(frame)) => interleave(&frame, out),372 Ok(Frame::Audio(frame)) => interleave(&frame, out),
shims/symphonia-core/src/packet.rsmodified+6 -0
@@ -13,6 +13,11 @@ pub struct Packet {
13 pub dur: Duration,13 pub dur: Duration,
14 /// The coded bytes.14 /// The coded bytes.
15 pub data: Box<[u8]>,15 pub data: Box<[u8]>,
16+ /// The container's own end-of-packet position, in the track's time base,
17+ /// when it states one — an Ogg page's granule above all, which is the
18+ /// only way a Vorbis (or FLAC-in-Ogg) stream's true, un-rounded length
19+ /// ever reaches the decoder: the codec's own bitstream never states it.
20+ pub granule: Option<i64>,
16 }21 }
17 22
18 impl Packet {23 impl Packet {
@@ -23,6 +28,7 @@ impl Packet {
23 pts,28 pts,
24 dur,29 dur,
25 data: data.to_vec().into_boxed_slice(),30 data: data.to_vec().into_boxed_slice(),
31+ granule: None,
26 }32 }
27 }33 }
28 34
shims/symphonia/Cargo.tomlmodified+2 -0
@@ -9,11 +9,13 @@ publish = false
9 9
10 [dependencies]10 [dependencies]
11 ec-core = { path = "../../crates/ec-core", version = "0.1.0" }11 ec-core = { path = "../../crates/ec-core", version = "0.1.0" }
12+ec-ogg = { path = "../../crates/ec-ogg", version = "0.1.0" }
12 ec-probe = { path = "../../crates/ec-probe", version = "0.1.0" }13 ec-probe = { path = "../../crates/ec-probe", version = "0.1.0" }
13 symphonia-core = { path = "../symphonia-core", version = "0.6.0" }14 symphonia-core = { path = "../symphonia-core", version = "0.6.0" }
14 15
15 [dev-dependencies]16 [dev-dependencies]
16 symphonia-codec-aac = { path = "../symphonia-codec-aac", version = "0.6.0" }17 symphonia-codec-aac = { path = "../symphonia-codec-aac", version = "0.6.0" }
18+ec-vorbis = { path = "../../crates/ec-vorbis", version = "0.1.0" }
17 19
18 # The incumbent's feature names, every one of them a no-op: a caller selects20 # The incumbent's feature names, every one of them a no-op: a caller selects
19 # codecs and containers there, and here `ec_probe` serves all of them21 # codecs and containers there, and here `ec_probe` serves all of them
shims/symphonia/src/reader.rsmodified+59 -13
@@ -17,6 +17,11 @@ use ec_core::registry::MediaType;
17 pub struct ProbeReader {17 pub struct ProbeReader {
18 inner: ec_probe::Reader,18 inner: ec_probe::Reader,
19 tracks: Vec<Track>,19 tracks: Vec<Track>,
20+ /// Audio track ids still owed their terminal, empty-data packet once the
21+ /// container itself has run out: `None` before that, then the queue,
22+ /// draining to empty rather than back to `None` so a second real EOF read
23+ /// hands out nothing more than once each.
24+ eos_pending: Option<std::vec::IntoIter<u32>>,
20 }25 }
21 26
22 impl ProbeReader {27 impl ProbeReader {
@@ -40,7 +45,11 @@ impl ProbeReader {
40 language: s.language.clone(),45 language: s.language.clone(),
41 })46 })
42 .collect();47 .collect();
43- ProbeReader { inner, tracks }48+ ProbeReader {
49+ inner,
50+ tracks,
51+ eos_pending: None,
52+ }
44 }53 }
45 54
46 /// The stream index behind a track id.55 /// The stream index behind a track id.
@@ -106,17 +115,44 @@ impl FormatReader for ProbeReader {
106 }115 }
107 116
108 fn next_packet(&mut self) -> Result<Option<Packet>> {117 fn next_packet(&mut self) -> Result<Option<Packet>> {
118+ if let Some(pending) = &mut self.eos_pending {
119+ // Empty data is the flush signal `EcAudioDecoder::decode` reads:
120+ // a real packet is never zero bytes for any codec this family
121+ // decodes.
122+ return Ok(pending
123+ .next()
124+ .map(|id| Packet::new(id, Timestamp::new(0), Duration::new(0), &[])));
125+ }
109 match self.inner.next_packet() {126 match self.inner.next_packet() {
110 Ok(packet) => {127 Ok(packet) => {
111 let id = self.inner.native_id(packet.stream) as u32;128 let id = self.inner.native_id(packet.stream) as u32;
112- Ok(Some(Packet::new(129+ let granule = ec_ogg::granule_of(&packet);
130+ let mut out = Packet::new(
113 id,131 id,
114 Timestamp::new(packet.pts.unwrap_or(0)),132 Timestamp::new(packet.pts.unwrap_or(0)),
115 Duration::new(packet.duration.unwrap_or(0).max(0) as u64),133 Duration::new(packet.duration.unwrap_or(0).max(0) as u64),
116 &packet.data,134 &packet.data,
117- )))135+ );
136+ out.granule = granule;
137+ Ok(Some(out))
138+ }
139+ Err(e) if e.is_eof() => {
140+ // The container itself is exhausted: give every audio track
141+ // one last, empty packet so its decoder is told to flush the
142+ // hop it has been holding back, then report real EOF.
143+ let ids: Vec<u32> = self
144+ .tracks
145+ .iter()
146+ .filter(|t| t.track_type == TrackType::Audio)
147+ .map(|t| t.id)
148+ .collect();
149+ let mut ids = ids.into_iter();
150+ let first = ids
151+ .next()
152+ .map(|id| Packet::new(id, Timestamp::new(0), Duration::new(0), &[]));
153+ self.eos_pending = Some(ids);
154+ Ok(first)
118 }155 }
119- Err(e) if e.is_eof() => Ok(None),
120 Err(e) => Err(e.into()),156 Err(e) => Err(e.into()),
121 }157 }
122 }158 }
@@ -144,15 +180,25 @@ impl EcAudioDecoder {
144 180
145 impl AudioDecoder for EcAudioDecoder {181 impl AudioDecoder for EcAudioDecoder {
146 fn decode(&mut self, packet: &Packet) -> Result<GenericAudioBufferRef<'_>> {182 fn decode(&mut self, packet: &Packet) -> Result<GenericAudioBufferRef<'_>> {
147- let rate = self.inner.sample_rate().max(1);183+ if packet.data.is_empty() {
148- let mut ec = ec_core::Packet::new(184+ // `ProbeReader::next_packet`'s terminal, empty packet: the file
149- packet.track_id,185+ // has run out, and this is the signal to release whatever the
150- ec_core::TimeBase::from_rate(rate),186+ // decoder was holding back rather than decode nothing.
151- packet.data.as_ref(),187+ self.inner.flush(&mut self.out)?;
152- );188+ } else {
153- ec.pts = Some(packet.pts.value());189+ let rate = self.inner.sample_rate().max(1);
154- ec.duration = Some(packet.dur.value() as i64);190+ let mut ec = ec_core::Packet::new(
155- self.inner.decode(&ec, &mut self.out)?;191+ packet.track_id,
192+ ec_core::TimeBase::from_rate(rate),
193+ packet.data.as_ref(),
194+ );
195+ ec.pts = Some(packet.pts.value());
196+ ec.duration = Some(packet.dur.value() as i64);
197+ if let Some(granule) = packet.granule {
198+ ec.side_data.push(ec_ogg::granule_side_data(granule));
199+ }
200+ self.inner.decode(&ec, &mut self.out)?;
201+ }
156 Ok(GenericAudioBufferRef::new(202 Ok(GenericAudioBufferRef::new(
157 &self.out,203 &self.out,
158 self.inner.channels().max(1),204 self.inner.channels().max(1),
shims/symphonia/tests/edith_surface.rsmodified+124 -1
@@ -320,6 +320,7 @@ fn cover_art_and_id3v1_tail_do_not_stop_the_probe() {
320 let mut decoder = track.decoder();320 let mut decoder = track.decoder();
321 let mut out = Vec::new();321 let mut out = Vec::new();
322 let mut decoded_packets = 0;322 let mut decoded_packets = 0;
323+ let mut total_samples = 0;
323 while let Some(packet) = track.reader.next_packet().expect("demux") {324 while let Some(packet) = track.reader.next_packet().expect("demux") {
324 if packet.track_id != track.track_id {325 if packet.track_id != track.track_id {
325 continue;326 continue;
@@ -328,13 +329,135 @@ fn cover_art_and_id3v1_tail_do_not_stop_the_probe() {
328 .decode(&packet)329 .decode(&packet)
329 .expect("decode")330 .expect("decode")
330 .copy_to_vec_interleaved::<f32>(&mut out);331 .copy_to_vec_interleaved::<f32>(&mut out);
332+ // The reader's terminal, empty flush packet legitimately decodes to
333+ // nothing for mp3 (nothing is held back across EOS), and it is always
334+ // the last one seen — `out` alone, checked only after the loop, would
335+ // read that packet's empty result rather than the file's real audio.
336+ total_samples += out.len();
331 decoded_packets += 1;337 decoded_packets += 1;
332 }338 }
333 assert!(decoded_packets > 0, "no audio packets decoded");339 assert!(decoded_packets > 0, "no audio packets decoded");
334- assert!(!out.is_empty(), "no samples decoded");340+ assert!(total_samples > 0, "no samples decoded");
335 let _ = std::fs::remove_file(&path);341 let _ = std::fs::remove_file(&path);
336 }342 }
337 343
344+/// Write `source` (one `Vec<f32>` per channel, all the same length) as an Ogg
345+/// Vorbis file through `ec_vorbis`/`ec_ogg` — the same two crates
346+/// `edith_replica::export::write_ogg` writes through — at scratch/`name`.
347+fn encode_ogg(source: &[Vec<f32>], rate: u32, path: &Path) {
348+ use ec_core::{
349+ AudioParameters, Buf, ChannelLayout, CodecId, CodecParameters, MediaParameters, Muxer,
350+ Packet, StreamInfo, TimeBase,
351+ };
352+ use ec_vorbis::{EncoderConfig, VorbisEncoder};
353+
354+ let channels = source.len() as u16;
355+ let mut encoder = VorbisEncoder::new(EncoderConfig {
356+ sample_rate: rate,
357+ channels,
358+ bitrate_bps: 128_000,
359+ quality: 0.6,
360+ })
361+ .expect("vorbis encoder");
362+ let borrowed: Vec<&[f32]> = source.iter().map(|c| &c[..]).collect();
363+ encoder.push_planar(&borrowed).expect("push");
364+ encoder.finish();
365+ let mut packets = Vec::new();
366+ loop {
367+ match encoder.next_packet() {
368+ Ok(p) => packets.push((p.data, p.granule)),
369+ Err(e) if e.is_eof() => break,
370+ Err(e) => panic!("encode: {e}"),
371+ }
372+ }
373+ eprintln!(
374+ "encode_ogg: {} packets, last granule {}",
375+ packets.len(),
376+ packets.last().map_or(0, |(_, g)| *g)
377+ );
378+
379+ let base = TimeBase::new(1, i64::from(rate));
380+ let mut params = CodecParameters::new(CodecId::Vorbis);
381+ params.media = MediaParameters::Audio(AudioParameters {
382+ sample_rate: rate,
383+ layout: ChannelLayout::from_count(usize::from(channels)),
384+ format: None,
385+ bits_per_sample: None,
386+ });
387+ params.extradata = Some(Buf::from_vec(encoder.extradata()));
388+ let file = File::create(path).expect("create");
389+ let mut muxer = ec_ogg::OggMuxer::new(file);
390+ muxer
391+ .add_stream(StreamInfo::new(0, base, params))
392+ .expect("add stream");
393+ muxer.write_headers().expect("headers");
394+ for (data, granule) in &packets {
395+ let mut packet = Packet::new(0, base, data.clone());
396+ packet.side_data.push(ec_ogg::granule_side_data(*granule));
397+ muxer.write_packet(&packet).expect("packet");
398+ }
399+ muxer.finish().expect("finish");
400+}
401+
402+/// The engine's own read door (`SymTrack` above, mirroring
403+/// `edith_replica::engine::audio::run_sym`): open, decode every packet to
404+/// EOF, count frames. This is what the export tests' `decode()` helper
405+/// measures against.
406+fn decode_all(path: &Path) -> u64 {
407+ let mut track = SymTrack::open(path).expect("track");
408+ let mut decoder = track.decoder();
409+ let mut out = Vec::new();
410+ let mut frames = 0u64;
411+ let mut n = 0;
412+ while let Some(packet) = track.reader.next_packet().expect("demux") {
413+ if packet.track_id != track.track_id {
414+ continue;
415+ }
416+ let before = frames;
417+ decoder
418+ .decode(&packet)
419+ .expect("decode")
420+ .copy_to_vec_interleaved::<f32>(&mut out);
421+ frames += (out.len() / usize::from(track.channels)) as u64;
422+ n += 1;
423+ eprintln!(
424+ "packet {n}: {} bytes in, {} frames out (running {frames})",
425+ packet.data.len(),
426+ frames - before
427+ );
428+ }
429+ frames
430+}
431+
432+/// The exact shape of `audio_export::exports_the_timeline_as_an_ogg_vorbis`
433+/// and `a_mono_timeline_exports_as_dual_mono_ogg` in `edith_replica`: write N
434+/// samples through the family's own Ogg Vorbis encoder, read them back
435+/// through this shim exactly as the engine's `SymTrack`/`run_sym` do, and the
436+/// count must come back to N — the terminal hop `VorbisDecoder::flush`
437+/// delivers has to actually reach the reader at EOS.
438+#[test]
439+fn ogg_vorbis_round_trip_reads_back_every_sample_written() {
440+ let rate = 44_100u32;
441+ for (name, channels, n) in [
442+ ("surface-mono-44100.ogg", 2usize, 44_100usize),
443+ ("surface-stereo-264600.ogg", 2, 264_600),
444+ ] {
445+ let source: Vec<Vec<f32>> = (0..channels)
446+ .map(|_| {
447+ (0..n)
448+ .map(|i| 0.2 * (i as f32 * 0.05).sin())
449+ .collect::<Vec<f32>>()
450+ })
451+ .collect();
452+ let path = std::env::temp_dir().join(format!("edith-surface-{}-{name}", std::process::id()));
453+ encode_ogg(&source, rate, &path);
454+ let frames = decode_all(&path);
455+ eprintln!("{name}: wrote {n} frames, read back {frames}");
456+ assert_eq!(frames, n as u64, "{name}: round trip sample count");
457+ let _ = std::fs::remove_file(&path);
458+ }
459+}
460+
338 /// ID3v2's syncsafe integer: 4 bytes, 7 significant bits each (top bit clear),461 /// ID3v2's syncsafe integer: 4 bytes, 7 significant bits each (top bit clear),
339 /// big-endian.462 /// big-endian.
340 fn syncsafe(mut n: u32) -> [u8; 4] {463 fn syncsafe(mut n: u32) -> [u8; 4] {