Decoder

Struct Decoder 

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

A unified video decoder that can handle multiple video formats and sources.

The Decoder provides a consistent interface for decoding video frames from various sources and formats. It automatically selects the most appropriate decoding backend based on the input format and available features.

§Supported Formats

  • Y4M files (always available): Raw Y4M format files with .y4m or .yuv extensions
  • General video files (requires ffmpeg feature): Most common video formats via FFmpeg
  • Advanced video processing (requires vapoursynth feature): Enhanced format support via VapourSynth

§Backend Priority

The decoder automatically selects backends in this order of preference:

  1. Y4M parser - Used for Y4M files (fastest, lowest overhead)
  2. FFmpeg - Used when available for faster decoding of a variety of formats
  3. VapourSynth - Used as fallback when VapourSynth not available

§Examples

use av_decoders::Decoder;

// Decode from a file
let mut decoder = Decoder::from_file("video.y4m")?;
let details = decoder.get_video_details();
println!("Video: {}x{} @ {} fps", details.width, details.height, details.frame_rate);

// Read frames
while let Ok(frame) = decoder.read_video_frame::<u8>() {
    // Process the frame...
}

// Decode from stdin
let mut stdin_decoder = Decoder::from_stdin()?;
let frame = stdin_decoder.read_video_frame::<u8>()?;

Implementations§

Source§

impl Decoder

Source

pub fn from_file<P>(input: P) -> Result<Decoder, DecoderError>
where P: AsRef<Path>,

Creates a new decoder from a file path.

This method automatically detects the input format and selects the most appropriate decoder backend. It will prioritize Y4M files for performance, then Ffms2 for speed, followed by Ffmpeg, and finally Vapoursynth.

§Arguments
  • input - A path to the video file. Can be any type that implements AsRef<Path>, such as &str, String, Path, or PathBuf.
§Returns

Returns a Result containing:

  • Ok(Decoder<BufReader<File>>) - A successfully initialized decoder
  • Err(DecoderError) - An error if the file cannot be read or decoded
§Errors

This method will return an error if:

  • The file cannot be opened or read (DecoderError::FileReadError)
  • No suitable decoder backend is available (DecoderError::NoDecoder)
  • The file format is not supported or corrupted (DecoderError::GenericDecodeError)
  • Required features are not enabled for the file format
§Examples
use av_decoders::Decoder;
use std::path::Path;

// From string path
let decoder = Decoder::from_file("video.y4m")?;

// From Path
let path = Path::new("video.mp4");
let decoder = Decoder::from_file(path)?;

// From PathBuf
let pathbuf = std::env::current_dir()?.join("video.mkv");
let decoder = Decoder::from_file(pathbuf)?;
Source

pub fn from_stdin() -> Result<Decoder, DecoderError>

Creates a new decoder that reads from standard input (stdin).

This method is useful for processing video data in pipelines or when the video data is being streamed. Currently, only Y4M format is supported for stdin input.

§Returns

Returns a Result containing:

  • Ok(Decoder<BufReader<Stdin>>) - A successfully initialized decoder reading from stdin
  • Err(DecoderError) - An error if stdin cannot be read or the data is not valid Y4M
§Errors

This method will return an error if:

  • The input stream is not in Y4M format
  • The Y4M header is malformed or missing (DecoderError::GenericDecodeError)
  • End of file is reached immediately (DecoderError::EndOfFile)
§Examples
use av_decoders::Decoder;

// Read Y4M data from stdin
let mut decoder = Decoder::from_stdin()?;

// Process frames as they arrive
loop {
    match decoder.read_video_frame::<u8>() {
        Ok(frame) => {
            // Process the frame
            println!("Received frame: {}x{}", frame.y_plane.width(), frame.y_plane.height());
        }
        Err(av_decoders::DecoderError::EndOfFile) => break,
        Err(e) => return Err(e),
    }
}
§Command Line Usage

This is commonly used with command-line pipelines:

# Pipe Y4M data to your application
ffmpeg -i input.mp4 -f yuv4mpegpipe - | your_app

# Or directly from Y4M files
cat video.y4m | your_app
Source

pub fn from_decoder_impl( decoder_impl: DecoderImpl, ) -> Result<Decoder, DecoderError>

Creates a new decoder from an existing decoder implementation.

This method provides a way to construct a Decoder from a specific DecoderImpl variant when you need direct control over the decoder backend selection. This is typically used for advanced use cases where you want to bypass the automatic format detection and backend selection logic of the other constructor methods.

The method will extract the video metadata from the provided decoder implementation and create a fully initialized Decoder instance ready for frame reading.

§Arguments
  • decoder_impl - A specific decoder implementation variant (DecoderImpl). This can be one of:
    • DecoderImpl::Y4m for Y4M format decoding
    • DecoderImpl::Vapoursynth for VapourSynth-based decoding (requires vapoursynth feature)
    • DecoderImpl::Ffmpeg for FFmpeg-based decoding (requires ffmpeg feature)
    • DecoderImpl::Ffms2 for FFMS2-based decoding (requires ffms2 feature)
§Returns

Returns a Result containing:

  • Ok(Decoder) - A successfully initialized decoder using the provided implementation
  • Err(DecoderError) - An error if video details cannot be extracted from the implementation
§Errors

This method will return an error if:

  • The decoder implementation is not properly initialized
  • Video metadata cannot be extracted from the implementation (DecoderError::GenericDecodeError)
  • The implementation is in an invalid state
§Examples
use av_decoders::{Decoder, DecoderImpl, Y4mDecoder};
use std::fs::File;
use std::io::{BufReader, Read};

// Create a Y4M decoder implementation directly
let file = File::open("video.y4m")?;
let reader = BufReader::new(file);
let y4m_decoder = Y4mDecoder::new(Box::new(reader) as Box<dyn Read>)?;
let decoder_impl = DecoderImpl::Y4m(y4m_decoder);

// Create a Decoder from the implementation
let decoder = Decoder::from_decoder_impl(decoder_impl)?;
let details = decoder.get_video_details();
println!("Video: {}x{}", details.width, details.height);
§Use Cases

This method is particularly useful when:

  • You need to pre-configure a specific decoder backend
  • You want to bypass automatic format detection
  • You’re implementing custom decoder initialization logic
  • You need to reuse or transfer decoder implementations between contexts
§Note

This is an advanced method that exposes internal decoder implementation details. In most cases, you should prefer using from_file(), from_script(), or from_stdin() which provide safer, higher-level interfaces with automatic format detection and backend selection.

Source

pub fn get_video_details(&self) -> &VideoDetails

Returns the video metadata and configuration details.

This method provides access to the essential video properties that were detected during decoder initialization. The returned reference is valid for the lifetime of the decoder and the values will not change during decoding.

§Returns

Returns a reference to VideoDetails containing:

  • width and height - Frame dimensions in pixels
  • bit_depth - Bits per color component (8, 10, 12, etc.)
  • chroma_sampling - Color subsampling format (4:2:0, 4:2:2, 4:4:4)
  • frame_rate - Frames per second as a rational number
§Examples
use av_decoders::Decoder;
use v_frame::chroma::ChromaSubsampling;

let decoder = Decoder::from_file("video.y4m").unwrap();
let details = decoder.get_video_details();

println!("Resolution: {}x{}", details.width, details.height);
println!("Bit depth: {} bits", details.bit_depth);
println!("Frame rate: {} fps", details.frame_rate);

match details.chroma_sampling {
    ChromaSubsampling::Yuv420 => println!("4:2:0 chroma subsampling"),
    ChromaSubsampling::Yuv422 => println!("4:2:2 chroma subsampling"),
    ChromaSubsampling::Yuv444 => println!("4:4:4 chroma subsampling"),
    _ => println!("Other chroma subsampling"),
}
Source

pub fn set_luma_only(&mut self, enabled: bool)

Sets the decoder to only fetch the luma planes from the video. This may improve performance for applications that do not need chroma data.

Source

pub fn read_video_frame<T>(&mut self) -> Result<Frame<T>, DecoderError>
where T: Pixel,

Reads and decodes the next video frame from the input.

This method advances the decoder to the next frame and returns it as a Frame<T> where T is the pixel type. The pixel type must be compatible with the video’s bit depth and the decoder backend being used.

§Type Parameters
  • T - The pixel type to use for the decoded frame. Must implement the Pixel trait. Types include:
    • u8 for 8-bit video
    • u16 for 10-bit to 16-bit video
§Returns

Returns a Result containing:

  • Ok(Frame<T>) - The decoded video frame
  • Err(DecoderError) - An error if the frame cannot be read or decoded
§Errors

This method will return an error if:

  • End of file/stream is reached (DecoderError::EndOfFile)
  • The frame data is corrupted or invalid (DecoderError::GenericDecodeError)
  • There’s an I/O error reading the input (DecoderError::FileReadError)
  • The pixel type is incompatible with the video format
§Examples
use av_decoders::Decoder;

let mut decoder = Decoder::from_file("video.y4m").unwrap();
let details = decoder.get_video_details();

// Read video frames, dynamically detecting the pixel type
if details.bit_depth > 8 {
    while let Ok(frame) = decoder.read_video_frame::<u16>() {
        println!("Frame size: {}x{}",
            frame.y_plane.width(),
            frame.y_plane.height()
        );
        // Process frame data...
    }
} else {
    while let Ok(frame) = decoder.read_video_frame::<u8>() {
        println!("Frame size: {}x{}",
            frame.y_plane.width(),
            frame.y_plane.height()
        );
        // Process frame data...
    }
}
§Performance Notes
  • Frames are decoded sequentially; seeking may not be supported by all backends
  • Each frame contains uncompressed pixel values, which results in heavy memory usage; avoid keeping frames in memory for longer than needed

Auto Trait Implementations§

§

impl Freeze for Decoder

§

impl !RefUnwindSafe for Decoder

§

impl !Send for Decoder

§

impl !Sync for Decoder

§

impl Unpin for Decoder

§

impl !UnwindSafe for Decoder

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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
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.