Skip to main content

Decoder

Struct Decoder 

Source
pub struct Decoder<B> { /* private fields */ }
Expand description

Decodes WAV, FLAC, MP3, Ogg Vorbis or Ogg Opus in memory a chunk at a time.

The bytes can be anything that holds them: &'static [u8] from include_bytes!, a Vec<u8> read from a file, or an Arc<[u8]> shared with other decoders. Apart from them, the decoder’s memory is bounded: it holds at most one block of the input format (a FLAC block, an MP3 frame, an IMA ADPCM block or chunk_frames of PCM), the MP3 bit reservoir, or bounded Ogg packet, table and DSP scratch storage, all allocated when it opens. Decoder::read allocates nothing, so it can run on an audio thread.

The concatenated output equals what decode gives for the same bytes, sample for sample.

Decoder::seek moves to any frame. WAV seeks directly. FLAC starts from the nearest SEEKTABLE point at or before the frame, or decodes forward from the start or the current position when there is no table. MP3 restarts a few frames earlier, enough to refill the bit reservoir and the filter state, so the samples after a seek equal those of a whole decode. Decoder::rewind returns to the start at once, for looping music. Ogg validates page framing/granules at open and prepares bounded packet DSP storage. Seeking replays from the first audio packet with existing storage; it is exact but O(distance from the start). Chained/multiplexed links are rejected.

use audiobox::{Audio, AudioFormat, encode, stream::Decoder};
let tone: Vec<f32> = (0..10_000).map(|i| (i as f32 * 0.05).sin() * 0.5).collect();
let bytes = encode(&Audio::new(vec![tone], 44_100)?, AudioFormat::Flac)?;

let mut decoder = Decoder::new(bytes)?;
assert_eq!((decoder.sample_rate(), decoder.channels()), (44_100, 1));
let mut buffer = [0.0f32; 1024];
let mut frames = 0;
loop {
    let n = decoder.read(&mut buffer)?;
    if n == 0 {
        break;
    }
    frames += n;
}
assert_eq!(frames, 10_000);
decoder.rewind()?;
assert_eq!(decoder.position(), 0);

Implementations§

Source§

impl<B: AsRef<[u8]>> Decoder<B>

Source

pub fn new(bytes: B) -> Result<Self>

Source

pub fn with_options(bytes: B, options: &DecoderOptions) -> Result<Self>

Source

pub fn format(&self) -> AudioFormat

Source

pub fn sample_rate(&self) -> u32

Source

pub fn channels(&self) -> usize

Source

pub fn frames(&self) -> Option<u64>

The stream’s length in frames, when the container declares it or the decoder can count it on opening (always for WAV and MP3, and for FLAC with a sample count).

Source

pub fn position(&self) -> u64

The index of the next frame that Decoder::read returns.

Source

pub fn into_inner(self) -> B

Returns the bytes the decoder was created with.

Source

pub fn read(&mut self, out: &mut [f32]) -> Result<usize>

Fills out with interleaved frames and returns how many frames were written: out.len() / channels unless the stream ends first, and 0 at its end. A remainder of out shorter than a frame is left untouched.

After an error, every later call returns the same error until a seek or rewind.

Source

pub fn next_chunk(&mut self) -> Result<Option<Audio>>

Returns up to chunk_frames frames, or None at the end of the stream.

Source

pub fn seek(&mut self, frame: u64) -> Result<()>

Moves to frame, so that the next read starts there. A frame past the end moves to the end.

Source

pub fn rewind(&mut self) -> Result<()>

Returns to the first frame without decoding anything.

Trait Implementations§

Source§

impl<B> Debug for Decoder<B>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<B: AsRef<[u8]> + Send + 'static> From<Decoder<B>> for Sound

Source§

fn from(decoder: Decoder<B>) -> Self

Converts to this type from the input type.
Source§

impl<B: AsRef<[u8]> + Send + 'static> Stream for Decoder<B>

Source§

fn sample_rate(&self) -> u32

Source§

fn channels(&self) -> usize

1 or 2.
Source§

fn frames(&self) -> Option<u64>

The stream’s length in frames, if known.
Source§

fn read(&mut self, out: &mut [f32]) -> Result<usize>

Fills out with interleaved frames and returns how many; 0 at the end. ErrorCode::Underrun is temporary: the mixer emits silence and retries next render segment, preserving source position. Other errors fail the voice.
Source§

fn seek(&mut self, frame: u64) -> Result<()>

Moves to frame, for loops.

Auto Trait Implementations§

§

impl<B> Freeze for Decoder<B>
where B: Freeze,

§

impl<B> RefUnwindSafe for Decoder<B>
where B: RefUnwindSafe,

§

impl<B> Send for Decoder<B>
where B: Send,

§

impl<B> Sync for Decoder<B>
where B: Sync,

§

impl<B> Unpin for Decoder<B>
where B: Unpin,

§

impl<B> UnsafeUnpin for Decoder<B>
where B: UnsafeUnpin,

§

impl<B> UnwindSafe for Decoder<B>
where B: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.