Skip to main content

AudioDecoder

Struct AudioDecoder 

Source
pub struct AudioDecoder { /* private fields */ }
Expand description

An audio decoder for extracting audio frames from media files.

The decoder provides frame-by-frame access to audio content with support for resampling and format conversion.

§Construction

Use AudioDecoder::open() to create a builder, then call AudioDecoderBuilder::build():

use ff_decode::AudioDecoder;
use ff_format::SampleFormat;

let decoder = AudioDecoder::open("audio.mp3")?
    .output_format(SampleFormat::F32)
    .output_sample_rate(48000)
    .build()?;

§Frame Decoding

Frames can be decoded one at a time or using an iterator:

// Decode one frame
if let Some(frame) = decoder.decode_one()? {
    println!("Frame with {} samples", frame.samples());
}

// Use iterator
for frame in decoder.frames().take(100) {
    let frame = frame?;
    // Process frame...
}

§Seeking

The decoder supports seeking to specific positions:

use std::time::Duration;

// Seek to 30 seconds
decoder.seek(Duration::from_secs(30))?;

Implementations§

Source§

impl AudioDecoder

Source

pub fn open(path: impl AsRef<Path>) -> AudioDecoderBuilder

Opens a media file and returns a builder for configuring the decoder.

This is the entry point for creating a decoder. The returned builder allows setting options before the decoder is fully initialized.

§Arguments
  • path - Path to the media file to decode.
§Examples
use ff_decode::AudioDecoder;

// Simple usage
let decoder = AudioDecoder::open("audio.mp3")?
    .build()?;

// With options
let decoder = AudioDecoder::open("audio.mp3")?
    .output_format(SampleFormat::F32)
    .output_sample_rate(48000)
    .build()?;
§Note

This method does not validate that the file exists or is a valid media file. Validation occurs when AudioDecoderBuilder::build() is called.

Source

pub fn stream_info(&self) -> &AudioStreamInfo

Returns the audio stream information.

This contains metadata about the audio stream including sample rate, channel count, codec, and format characteristics.

Source

pub fn sample_rate(&self) -> u32

Returns the sample rate in Hz.

Source

pub fn channels(&self) -> u32

Returns the number of audio channels.

Source

pub fn duration(&self) -> Duration

Returns the total duration of the audio.

Returns Duration::ZERO if duration is unknown.

Source

pub fn position(&self) -> Duration

Returns the current playback position.

Source

pub fn is_eof(&self) -> bool

Returns true if the end of stream has been reached.

Source

pub fn path(&self) -> &Path

Returns the file path being decoded.

Source

pub fn decode_one(&mut self) -> Result<Option<AudioFrame>, DecodeError>

Decodes the next audio frame.

This method reads and decodes a single frame from the audio stream.

§Returns
  • Ok(Some(frame)) - A frame was successfully decoded
  • Ok(None) - End of stream reached, no more frames
  • Err(_) - An error occurred during decoding
§Errors

Returns DecodeError if:

  • Reading from the file fails
  • Decoding the frame fails
  • Sample format conversion fails
§Examples
use ff_decode::AudioDecoder;

let mut decoder = AudioDecoder::open("audio.mp3")?.build()?;

while let Some(frame) = decoder.decode_one()? {
    println!("Frame with {} samples", frame.samples());
    // Process frame...
}
Source

pub fn frames( &mut self, ) -> impl Iterator<Item = Result<AudioFrame, DecodeError>> + '_

Returns an iterator over decoded frames.

This provides a convenient way to iterate over all frames in the audio. The iterator will continue until end of stream or an error occurs.

§Examples
use ff_decode::AudioDecoder;

let mut decoder = AudioDecoder::open("audio.mp3")?.build()?;

// Process first 100 frames
for frame in decoder.frames().take(100) {
    let frame = frame?;
    // Process frame...
}
Source

pub fn decode_all(&mut self) -> Result<Vec<u8>, DecodeError>

Decodes all frames and returns their raw PCM data.

This method decodes the entire audio file and returns all samples as a contiguous byte buffer.

§Performance
  • Memory scales with audio duration and quality
  • For 10 minutes of stereo 48kHz F32 audio: ~110 MB
§Returns

A byte vector containing all audio samples in the configured output format.

§Errors

Returns DecodeError if:

  • Decoding any frame fails
  • The file cannot be read
§Examples
use ff_decode::AudioDecoder;
use ff_format::SampleFormat;

let mut decoder = AudioDecoder::open("audio.mp3")?
    .output_format(SampleFormat::F32)
    .build()?;

let samples = decoder.decode_all()?;
println!("Decoded {} bytes", samples.len());
§Memory Usage

Stereo 48kHz F32 audio:

  • 1 minute: ~11 MB
  • 5 minutes: ~55 MB
  • 10 minutes: ~110 MB
Source

pub fn decode_range( &mut self, start: Duration, end: Duration, ) -> Result<Vec<u8>, DecodeError>

Decodes all frames within a specified time range.

This method seeks to the start position and decodes all frames until the end position is reached. Frames outside the range are skipped.

§Arguments
  • start - Start of the time range (inclusive).
  • end - End of the time range (exclusive).
§Returns

A byte vector containing audio samples within [start, end).

§Errors

Returns DecodeError if:

  • Seeking to the start position fails
  • Decoding frames fails
  • The time range is invalid (start >= end)
§Examples
use ff_decode::AudioDecoder;
use std::time::Duration;

let mut decoder = AudioDecoder::open("audio.mp3")?.build()?;

// Decode audio from 5s to 10s
let samples = decoder.decode_range(
    Duration::from_secs(5),
    Duration::from_secs(10),
)?;

println!("Decoded {} bytes", samples.len());
Source

pub fn seek( &mut self, position: Duration, mode: SeekMode, ) -> Result<(), DecodeError>

Seeks to a specified position in the audio stream.

This method performs efficient seeking without reopening the file.

§Arguments
  • position - Target position to seek to.
  • mode - Seek mode (Keyframe, Exact, or Backward).
§Errors

Returns DecodeError::SeekFailed if:

  • The target position is beyond the audio duration
  • The file format doesn’t support seeking
  • The seek operation fails internally
§Examples
use ff_decode::{AudioDecoder, SeekMode};
use std::time::Duration;

let mut decoder = AudioDecoder::open("audio.mp3")?.build()?;

// Seek to 30 seconds with keyframe mode (fast)
decoder.seek(Duration::from_secs(30), SeekMode::Keyframe)?;

// Seek to exact position (slower but precise)
decoder.seek(Duration::from_secs(45), SeekMode::Exact)?;

// Decode next frame
if let Some(frame) = decoder.decode_one()? {
    println!("Frame at {:?}", frame.timestamp().as_duration());
}
Source

pub fn flush(&mut self)

Flushes the decoder’s internal buffers.

This method clears any cached frames and resets the decoder state. The decoder is ready to receive new packets after flushing.

Auto Trait Implementations§

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.