From be3c76d9d811193232eab09b7226088e7d8937e7 Mon Sep 17 00:00:00 2001 From: _ <> Date: Sat, 13 Nov 2021 17:37:55 +0000 Subject: [PATCH] :shirt: refactor: hide ffmpeg audio frame from public decoder API --- src/decoder.rs | 59 ++++++++++++++++++++++++++++++++------------------ src/main.rs | 5 ++--- 2 files changed, 40 insertions(+), 24 deletions(-) diff --git a/src/decoder.rs b/src/decoder.rs index 1acb702..4f7276c 100644 --- a/src/decoder.rs +++ b/src/decoder.rs @@ -24,12 +24,39 @@ use ffmpeg_next::{ self, Sample, }, - frame::Audio as AudioFrame, + frame::Audio as FfAudioFrame, }, }; pub const SAMPLE_RATE: u32 = 48000; +pub struct AudioFrame { + frame: FfAudioFrame, +} + +impl AudioFrame { + pub fn data (&self) -> &[u8] { + // Hard-coded because I'm only support f32 interleaved stereo + &self.frame.data (0) [0..self.frame.samples () * 4 * 2] + } + + pub fn rate (&self) -> u32 { + self.frame.rate () + } + + pub fn samples (&self) -> usize { + self.frame.samples () + } +} + +impl From for AudioFrame { + fn from (frame: FfAudioFrame) -> Self { + Self { + frame, + } + } +} + #[derive (Default)] pub struct PcmBuffers { buffers: Vec >, @@ -70,6 +97,8 @@ impl PcmBuffers { let mut b = vec! [0.0f32; new_buffer.len () / 4]; let mut rdr = Cursor::new (new_buffer); + // Pointless memcpy. I can get rid of it later by changing PcmBuffers' + // internal format rdr.read_f32_into:: (&mut b).unwrap (); self.produce (b); @@ -88,7 +117,7 @@ pub struct Decoder { pub resampler: ResamplingContext, best_stream_idx: usize, - dummy_frame: Option , + dummy_frame: Option , } impl Decoder { @@ -117,8 +146,8 @@ impl Decoder { }) } - fn new_frame () -> AudioFrame { - let mut x = AudioFrame::empty (); + fn new_frame () -> FfAudioFrame { + let mut x = FfAudioFrame::empty (); x.set_channel_layout (ChannelLayout::STEREO); x.set_format (Sample::F32 (sample::Type::Packed)); x @@ -129,18 +158,6 @@ impl Decoder { assert_eq! (frame.rate (), 48000); assert! (frame.samples () > 0); - let actual_bytes = frame.data (0).len (); - let expected_bytes = frame.samples () * 4 * 2; - - assert! (actual_bytes >= expected_bytes); - - if actual_bytes > expected_bytes { - let extra_bytes = actual_bytes - expected_bytes; - let extra_samples = extra_bytes / 4 / 2; - // tracing::debug! ("Extra bytes: {}", extra_bytes); - // tracing::debug! ("Extra samples: {}", extra_samples); - } - Some (frame) } else { @@ -191,7 +208,7 @@ impl Decoder { Ok (if frame_resampled.samples () > 0 { // tracing::trace! ("Pulled from resampler FIFO"); - Some (frame_resampled) + Some (frame_resampled.into ()) } else { None @@ -199,13 +216,13 @@ impl Decoder { } pub fn pump_decoder (&mut self) -> Result