Input

Struct Input 

Source
pub struct Input { /* private fields */ }

Implementations§

Source§

impl Input

Source

pub fn new(url: impl Into<String>) -> Self

Source

pub fn new_by_read_callback<F>(read_callback: F) -> Self
where F: FnMut(&mut [u8]) -> i32 + 'static,

Creates a new Input instance with a custom read callback.

This method initializes an Input object that uses a provided read_callback function to supply data to the input stream. This is particularly useful for custom data sources such as in-memory buffers, network streams, or other non-standard input mechanisms.

§Parameters:
  • read_callback: fn(buf: &mut [u8]) -> i32: A function pointer that fills the provided mutable buffer with data and returns the number of bytes read.
§Return Value:
  • Returns a new Input instance configured with the specified read_callback.
§Behavior of read_callback:
  • Positive Value: Indicates the number of bytes successfully read.
  • ffmpeg_sys_next::AVERROR_EOF: Indicates the end of the stream. The library will stop requesting data.
  • Negative Value: Indicates an error occurred. For example:
    • ffmpeg_sys_next::AVERROR(ffmpeg_sys_next::EIO): Represents an input/output error.
    • Other custom-defined error codes can also be returned to signal specific issues.
§Example:
let input = Input::new_by_read_callback(move |buf| {
    let data = b"example custom data source";
    let len = data.len().min(buf.len());
    buf[..len].copy_from_slice(&data[..len]);
    len as i32 // Return the number of bytes written
});
Source

pub fn set_seek_callback<F>(self, seek_callback: F) -> Self
where F: FnMut(i64, i32) -> i64 + 'static,

Sets a custom seek callback for the input stream.

This function assigns a user-defined function that handles seeking within the input stream. It is required when using custom data sources that support random access, such as files, memory-mapped buffers, or seekable network streams.

FFmpeg may invoke seek_callback from different threads. If using a File as the data source, wrap it in Arc<Mutex<File>> to ensure thread-safe access across multiple threads.

§Parameters:
  • seek_callback: FnMut(i64, i32) -> i64: A function that handles seek operations.
    • offset: i64: The target seek position in the stream.
    • whence: i32: The seek mode, which determines how offset should be interpreted:
      • ffmpeg_sys_next::SEEK_SET (0) - Seek to an absolute position.
      • ffmpeg_sys_next::SEEK_CUR (1) - Seek relative to the current position.
      • ffmpeg_sys_next::SEEK_END (2) - Seek relative to the end of the stream.
      • ffmpeg_sys_next::SEEK_HOLE (3) - Find the next hole in a sparse file (Linux only).
      • ffmpeg_sys_next::SEEK_DATA (4) - Find the next data block in a sparse file (Linux only).
      • ffmpeg_sys_next::AVSEEK_FLAG_BYTE (2) - Seek using byte offset instead of timestamps.
      • ffmpeg_sys_next::AVSEEK_SIZE (65536) - Query the total size of the stream.
      • ffmpeg_sys_next::AVSEEK_FORCE (131072) - Force seeking, even if normally restricted.
§Return Value:
  • Returns Self, allowing for method chaining.
§Behavior of seek_callback:
  • Positive Value: The new offset position after seeking.
  • Negative Value: An error occurred, such as:
    • ffmpeg_sys_next::AVERROR(ffmpeg_sys_next::ESPIPE): Seek is not supported.
    • ffmpeg_sys_next::AVERROR(ffmpeg_sys_next::EIO): General I/O error.
§Example (Thread-safe seek callback using Arc<Mutex<File>>):

Since FFmpeg may call read_callback and seek_callback from different threads, use Arc<Mutex<File>> to ensure safe concurrent access.

use std::fs::File;
use std::io::{Read, Seek, SeekFrom};
use std::sync::{Arc, Mutex};

// ✅ Wrap the file in Arc<Mutex<>> for safe shared access
let file = Arc::new(Mutex::new(File::open("test.mp4").expect("Failed to open file")));

// ✅ Thread-safe read callback
let read_callback = {
    let file = Arc::clone(&file);
    move |buf: &mut [u8]| -> i32 {
        let mut file = file.lock().unwrap();
        match file.read(buf) {
            Ok(0) => {
                println!("Read EOF");
                ffmpeg_sys_next::AVERROR_EOF
            }
            Ok(bytes_read) => bytes_read as i32,
            Err(e) => {
                println!("Read error: {}", e);
                ffmpeg_sys_next::AVERROR(ffmpeg_sys_next::EIO)
            }
        }
    }
};

// ✅ Thread-safe seek callback
let seek_callback = {
    let file = Arc::clone(&file);
    Box::new(move |offset: i64, whence: i32| -> i64 {
        let mut file = file.lock().unwrap();

        // ✅ Handle AVSEEK_SIZE: Return total file size
        if whence == ffmpeg_sys_next::AVSEEK_SIZE {
            if let Ok(size) = file.metadata().map(|m| m.len() as i64) {
                println!("FFmpeg requested stream size: {}", size);
                return size;
            }
            return ffmpeg_sys_next::AVERROR(ffmpeg_sys_next::EIO) as i64;
        }

        // ✅ Ignore AVSEEK_FORCE flag
        let actual_whence = whence & !ffmpeg_sys_next::AVSEEK_FORCE;

        // ✅ Handle AVSEEK_FLAG_BYTE: Perform byte-based seek
        if actual_whence & ffmpeg_sys_next::AVSEEK_FLAG_BYTE != 0 {
            println!("FFmpeg requested byte-based seeking. Seeking to byte offset: {}", offset);
            if let Ok(new_pos) = file.seek(SeekFrom::Start(offset as u64)) {
                return new_pos as i64;
            }
            return ffmpeg_sys_next::AVERROR(ffmpeg_sys_next::EIO) as i64;
        }

        // ✅ Handle SEEK_HOLE and SEEK_DATA (Linux only)
        #[cfg(target_os = "linux")]
        if actual_whence == ffmpeg_sys_next::SEEK_HOLE {
            println!("FFmpeg requested SEEK_HOLE, but Rust std::fs does not support it.");
            return ffmpeg_sys_next::AVERROR(ffmpeg_sys_next::ESPIPE) as i64;
        }
        #[cfg(target_os = "linux")]
        if actual_whence == ffmpeg_sys_next::SEEK_DATA {
            println!("FFmpeg requested SEEK_DATA, but Rust std::fs does not support it.");
            return ffmpeg_sys_next::AVERROR(ffmpeg_sys_next::ESPIPE) as i64;
        }

        // ✅ Standard seek modes
        let seek_result = match actual_whence {
            ffmpeg_sys_next::SEEK_SET => file.seek(SeekFrom::Start(offset as u64)),
            ffmpeg_sys_next::SEEK_CUR => file.seek(SeekFrom::Current(offset)),
            ffmpeg_sys_next::SEEK_END => file.seek(SeekFrom::End(offset)),
            _ => {
                println!("Unsupported seek mode: {}", whence);
                return ffmpeg_sys_next::AVERROR(ffmpeg_sys_next::ESPIPE) as i64;
            }
        };

        match seek_result {
            Ok(new_pos) => {
                println!("Seek successful, new position: {}", new_pos);
                new_pos as i64
            }
            Err(e) => {
                println!("Seek failed: {}", e);
                ffmpeg_sys_next::AVERROR(ffmpeg_sys_next::EIO) as i64
            }
        }
    })
};

let input = Input::new_by_read_callback(read_callback).set_seek_callback(seek_callback);
Source

pub fn set_frame_pipelines( self, frame_pipelines: Vec<impl Into<FramePipeline>>, ) -> Self

Replaces the entire frame-processing pipeline with a new sequence of transformations for post-decoding frames on this Input.

This method clears any previously set pipelines and replaces them with the provided list.

§Parameters
  • frame_pipelines - A list of FramePipeline instances defining the transformations to apply to decoded frames.
§Returns
  • Self - Returns the modified Input, enabling method chaining.
§Example
let input = Input::from("my_video.mp4")
    .set_frame_pipelines(vec![
        FramePipelineBuilder::new(AVMediaType::AVMEDIA_TYPE_VIDEO).filter("opengl", Box::new(my_filter)),
        // Additional pipelines...
    ]);
Source

pub fn add_frame_pipeline( self, frame_pipeline: impl Into<FramePipeline>, ) -> Self

Adds a single FramePipeline to the existing pipeline list.

If no pipelines are currently defined, this method creates a new pipeline list. Otherwise, it appends the provided pipeline to the existing transformations.

§Parameters
§Returns
  • Self - Returns the modified Input, enabling method chaining.
§Example
let input = Input::from("my_video.mp4")
    .add_frame_pipeline(FramePipelineBuilder::new(AVMediaType::AVMEDIA_TYPE_VIDEO).filter("opengl", Box::new(my_filter)).build())
    .add_frame_pipeline(FramePipelineBuilder::new(AVMediaType::AVMEDIA_TYPE_AUDIO).filter("my_custom_filter1", Box::new(...)).filter("my_custom_filter2", Box::new(...)).build());
Source

pub fn set_format(self, format: impl Into<String>) -> Self

Sets the input format for the container or device.

By default, if no format is specified, FFmpeg will attempt to detect the format automatically. However, certain use cases require specifying the format explicitly:

  • Using device-specific inputs (e.g., avfoundation on macOS, dshow on Windows).
  • Handling raw streams or formats that FFmpeg may not detect automatically.
§Parameters:
  • format: A string specifying the desired input format (e.g., mp4, flv, avfoundation).
§Return Value:
  • Returns the Input instance with the newly set format.
Source

pub fn set_video_codec(self, video_codec: impl Into<String>) -> Self

Sets the video codec to be used for decoding.

By default, FFmpeg will automatically select an appropriate video codec based on the input format and available decoders. However, this method allows you to override that selection and force a specific codec.

§Common Video Codecs:
CodecDescription
h264H.264 (AVC), widely supported and efficient
hevcH.265 (HEVC), better compression at higher complexity
vp9VP9, open-source alternative to H.265
av1AV1, newer open-source codec with improved compression
mpeg4MPEG-4 Part 2, older but still used in some cases
§Arguments
  • video_codec - A string representing the desired video codec (e.g., "h264", "hevc").
§Returns
  • Self - Returns the modified Input struct, allowing for method chaining.
§Example:
let input = Input::from("video.mp4").set_video_codec("h264");
Source

pub fn set_audio_codec(self, audio_codec: impl Into<String>) -> Self

Sets the audio codec to be used for decoding.

By default, FFmpeg will automatically select an appropriate audio codec based on the input format and available decoders. However, this method allows you to specify a preferred codec.

§Common Audio Codecs:
CodecDescription
aacAAC, commonly used for MP4 and streaming
mp3MP3, widely supported but lower efficiency
opusOpus, high-quality open-source codec
vorbisVorbis, used in Ogg containers
flacFLAC, lossless audio format
§Arguments
  • audio_codec - A string representing the desired audio codec (e.g., "aac", "mp3").
§Returns
  • Self - Returns the modified Input struct, allowing for method chaining.
§Example:
let input = Input::from("audio.mp3").set_audio_codec("aac");
Source

pub fn set_subtitle_codec(self, subtitle_codec: impl Into<String>) -> Self

Sets the subtitle codec to be used for decoding.

By default, FFmpeg will automatically select an appropriate subtitle codec based on the input format and available decoders. This method lets you specify a particular subtitle codec.

§Common Subtitle Codecs:
CodecDescription
assAdvanced SubStation Alpha (ASS) subtitles
srtSubRip Subtitle format (SRT)
mov_textSubtitles in MP4 containers
subripPlain-text subtitle format
§Arguments
  • subtitle_codec - A string representing the desired subtitle codec (e.g., "mov_text", "ass", "srt").
§Returns
  • Self - Returns the modified Input struct, allowing for method chaining.
§Example:
let input = Input::from("movie.mkv").set_subtitle_codec("ass");
Source

pub fn set_exit_on_error(self, exit_on_error: bool) -> Self

Enables or disables exit on error behavior for the input.

If set to true, FFmpeg will exit (stop processing) if it encounters any decoding or demuxing error on this input. If set to false (the default), FFmpeg may attempt to continue despite errors, skipping damaged portions.

§Parameters
  • exit_on_error: true to stop on errors, false to keep going.
§Returns
  • Self - allowing method chaining.
§Example
let input = Input::from("test.mp4")
    .set_exit_on_error(true);
Source

pub fn set_readrate(self, rate: f32) -> Self

Sets a read rate for this input, controlling how quickly frames are read.

  • If set to 1.0, frames are read at their native frame rate.
  • If set to another value (e.g., 0.5 or 2.0), FFmpeg may attempt to read slower or faster, simulating changes in real-time playback speed.
§Parameters
  • rate: A floating-point value indicating the read rate multiplier.
§Returns
  • Self - allowing method chaining.
§Example
let input = Input::from("video.mp4")
    .set_readrate(0.5); // read at half speed
Source

pub fn set_start_time_us(self, start_time_us: i64) -> Self

Sets the start time (in microseconds) from which to begin reading.

FFmpeg will skip all data before this timestamp. This can be used to implement “input seeking” or to only process a portion of the input.

§Parameters
  • start_time_us: The timestamp (in microseconds) at which to start reading.
§Returns
  • Self - allowing method chaining.
§Example
let input = Input::from("long_clip.mp4")
    .set_start_time_us(2_000_000); // Start at 2 seconds
Source

pub fn set_recording_time_us(self, recording_time_us: i64) -> Self

Sets the recording time (in microseconds) for this input.

FFmpeg will only read for the specified duration, ignoring data past this limit. This can be used to trim or limit how much of the input is processed.

§Parameters
  • recording_time_us: The number of microseconds to read from the input.
§Returns
  • Self - allowing method chaining.
§Example
let input = Input::from("long_clip.mp4")
    .set_recording_time_us(5_000_000); // Only read 5 seconds
Source

pub fn set_stop_time_us(self, stop_time_us: i64) -> Self

Sets a stop time (in microseconds) beyond which input data will be ignored.

This is similar to set_recording_time_us but specifically references an absolute timestamp in the stream. Once this timestamp is reached, FFmpeg stops reading.

§Parameters
  • stop_time_us: The absolute timestamp (in microseconds) at which to stop reading.
§Returns
  • Self - allowing method chaining.
§Example
let input = Input::from("long_clip.mp4")
    .set_stop_time_us(10_000_000); // Stop reading at 10 seconds
Source

pub fn set_stream_loop(self, count: i32) -> Self

Sets the number of loops to perform on this input stream.

If FFmpeg reaches the end of the input, it can loop back and start from the beginning, effectively repeating the content stream_loop times. A negative value may indicate infinite looping (depending on FFmpeg’s actual behavior).

§Parameters
  • count: How many times to loop (e.g. 1 means one loop, -1 might mean infinite).
§Returns
  • Self - allowing method chaining.
§Example
let input = Input::from("music.mp3")
    .set_stream_loop(2); // play the input 2 extra times
Source

pub fn set_hwaccel(self, hwaccel_name: impl Into<String>) -> Self

Specifies a hardware acceleration name for decoding this input.

Common values might include "cuda", "vaapi", "dxva2", "videotoolbox", etc. Whether it works depends on your FFmpeg build and the hardware you have available.

§Parameters
  • hwaccel_name: A string naming the hardware accel to use.
§Returns
  • Self - allowing method chaining.
§Example
let input = Input::from("video.mp4")
    .set_hwaccel("cuda");
Source

pub fn set_hwaccel_device(self, device: impl Into<String>) -> Self

Selects a hardware acceleration device for decoding.

For example, if you have multiple GPUs or want to specify a device node (like "/dev/dri/renderD128" on Linux for VAAPI), you can pass it here. This option must match the hardware accel you set via set_hwaccel if you expect decoding to succeed.

§Parameters
  • device: A string indicating the device path or identifier.
§Returns
  • Self - allowing method chaining.
§Example
let input = Input::from("video.mp4")
    .set_hwaccel("vaapi")
    .set_hwaccel_device("/dev/dri/renderD128");
Source

pub fn set_hwaccel_output_format(self, format: impl Into<String>) -> Self

Sets the output pixel format to be used with hardware-accelerated decoding.

Certain hardware decoders can produce various output pixel formats. This option lets you specify which format (e.g., "nv12", "vaapi", etc.) is used during the decode process. Must be compatible with the chosen hardware accel and device.

§Parameters
  • format: A string naming the desired output pixel format (e.g. "nv12").
§Returns
  • Self - allowing method chaining.
§Example
let input = Input::from("video.mp4")
    .set_hwaccel("cuda")
    .set_hwaccel_output_format("cuda");
Source

pub fn set_input_opt( self, key: impl Into<String>, value: impl Into<String>, ) -> Self

Sets a single input option for avformat_open_input.

This method configures options that will be passed to FFmpeg’s avformat_open_input() function. The options can control behavior at different levels including format detection, protocol handling, device configuration, and general input processing.

Example Usage:

let input = Input::new("avfoundation:0")
    .set_input_opt("framerate", "30")
    .set_input_opt("probesize", "5000000");
§Parameters:
  • key: The option name (e.g., "framerate", "probesize", "timeout").
  • value: The option value (e.g., "30", "5000000", "10000000").
§Return Value:
  • Returns the modified Input instance for method chaining.
Source

pub fn set_input_opts( self, opts: Vec<(impl Into<String>, impl Into<String>)>, ) -> Self

Sets multiple input options at once for avformat_open_input.

This method allows setting multiple options in a single call, which will all be passed to FFmpeg’s avformat_open_input() function. Each key-value pair will be inserted into the options map, overwriting any existing keys with the same name.

Example Usage:

let input = Input::new("http://example.com/stream.m3u8")
    .set_input_opts(vec![
        ("user_agent", "MyApp/1.0"),
        ("timeout", "10000000"),
        ("probesize", "5000000"),
    ]);
§Parameters:
  • opts: A vector of key-value pairs representing input options.
§Return Value:
  • Returns the modified Input instance for method chaining.

Trait Implementations§

Source§

impl From<&str> for Input

Source§

fn from(url: &str) -> Self

Converts to this type from the input type.
Source§

impl From<Box<dyn FnMut(&mut [u8]) -> i32>> for Input

Source§

fn from(read_callback: Box<dyn FnMut(&mut [u8]) -> i32>) -> Self

Converts to this type from the input type.
Source§

impl From<String> for Input

Source§

fn from(url: String) -> Self

Converts to this type from the input type.
Source§

impl Send for Input

Auto Trait Implementations§

§

impl Freeze for Input

§

impl !RefUnwindSafe for Input

§

impl !Sync for Input

§

impl Unpin for Input

§

impl !UnwindSafe for Input

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

Source§

type Output = T

Should always be Self
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.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V