Expand description
Safe, high-level audio/video/image processing for Rust.
avio is the facade crate for the ff-* crate family — a backend-agnostic
multimedia toolkit. It re-exports the public APIs of all member crates behind
feature flags, so users can depend on a single crate and opt into only the
functionality they need.
§Feature Flags
| Feature | Crate | Default | Implies |
|---|---|---|---|
probe | ff-probe | yes | — |
decode | ff-decode | yes | — |
encode | ff-encode | yes | — |
filter | ff-filter | no | — |
pipeline | ff-pipeline | no | filter |
preview | ff-preview | no | — |
preview-proxy | ff-preview | no | preview |
stream | ff-stream | no | pipeline |
tokio | ff-decode/encode | no | decode + encode |
§Usage
# Default: probe + decode + encode
[dependencies]
avio = "0.15"
# Add filtering
avio = { version = "0.15", features = ["filter"] }
# Full stack (implies filter + pipeline)
avio = { version = "0.15", features = ["stream"] }§Quick Start
§Probe
open is a free function (not a method) that reads metadata without
decoding:
use avio::open;
let info = open("video.mp4")?;
println!("duration: {:?}", info.duration());§Decode
All decoders follow the same builder pattern. Use
.output_format() / .output_sample_rate() to request automatic
format conversion inside the decoder:
use avio::{VideoDecoder, AudioDecoder, PixelFormat, SampleFormat};
// Video — request RGB24 output (FFmpeg converts internally)
let mut vdec = VideoDecoder::open("video.mp4")
.output_format(PixelFormat::Rgb24)
.build()?;
for result in &mut vdec { /* ... */ }
// Audio — resample to 16-bit 44.1 kHz
let mut adec = AudioDecoder::open("video.mp4")
.output_format(SampleFormat::I16)
.output_sample_rate(44_100)
.build()?;§Encode
There are three encode APIs, each suited to a different situation. Choosing the right one prevents unnecessary complexity.
§When to use Pipeline (feature: pipeline)
Use Pipeline when your source is an existing media file and you want
to transcode, filter, or repackage it with minimal boilerplate.
- You are transcoding a file to another codec or container.
- You want to apply filters (scale, trim, fade, tone-map, …).
- You want to concatenate multiple input files.
- You need progress reporting without managing the decode loop yourself.
- You are generating HLS or DASH output (
streamfeature).
use avio::{Pipeline, EncoderConfig, VideoCodec, AudioCodec, BitrateMode};
Pipeline::builder()
.input("input.mp4")
.output("output.mp4", EncoderConfig::builder()
.video_codec(VideoCodec::H264)
.audio_codec(AudioCodec::Aac)
.bitrate_mode(BitrateMode::Crf(23))
.build())
.build()?
.run()?;Examples: transcode, trim_and_scale, concat_clips,
extract_thumbnails, hls_output, abr_ladder.
§When to use VideoEncoder / AudioEncoder directly (feature: encode)
Use the encoder types directly when you need frame-level control or your frames come from a source other than a media file.
- You are generating frames programmatically (e.g., a game renderer, a signal generator, test patterns).
- You need to inspect or modify individual frames between decode and encode.
- You want per-frame metadata, custom PTS/DTS, or non-standard GOP structure.
- You need to react to
EncodeError::Cancelledmid-stream. - You want cancellable progress via
EncodeProgressCallback::should_cancel().
use avio::{VideoDecoder, VideoEncoder, VideoCodec};
let mut decoder = VideoDecoder::open("input.mp4").build()?;
let mut encoder = VideoEncoder::create("output.mp4")
.video(decoder.width(), decoder.height(), decoder.frame_rate())
.video_codec(VideoCodec::H264)
.build()?;
while let Ok(Some(frame)) = decoder.decode_one() {
// Inspect or modify `frame` here before encoding.
encoder.push_video(&frame)?;
}
encoder.finish()?;Examples: encode_video_direct, encode_audio_direct,
encode_with_progress, two_pass_encode, filter_direct.
§When to use AsyncVideoEncoder / AsyncAudioEncoder (feature: tokio)
Use the async encoders when your application runs on a Tokio runtime and you need back-pressure or concurrent decode/encode.
- You are writing an async application and cannot block the executor.
- Frames arrive from an async source (network, channel, microphone).
- You want the decoder and encoder to run concurrently on separate tasks.
- You rely on the bounded internal channel (capacity 8) to prevent unbounded memory growth when the encoder is slower than the producer.
use avio::{AsyncVideoDecoder, AsyncVideoEncoder, VideoEncoder, VideoCodec};
use futures::StreamExt;
let mut encoder = AsyncVideoEncoder::from_builder(
VideoEncoder::create("output.mp4")
.video(1920, 1080, 30.0)
.video_codec(VideoCodec::H264),
)?;
let stream = AsyncVideoDecoder::open("input.mp4").await?.into_stream();
tokio::pin!(stream);
while let Some(Ok(frame)) = stream.next().await {
encoder.push(frame).await?;
}
encoder.finish().await?;Examples: async_encode_video, async_encode_audio, async_transcode.
§Real-world Applications
§ascii-term — Terminal ASCII Art Video Player
ascii-term is a terminal media player
that renders video as colored ASCII art with synchronized audio. It was fully migrated
from ffmpeg-next / ffmpeg-sys-next to avio, with no direct unsafe FFmpeg code
remaining in the application.
Key patterns used:
VideoDecoderwith.output_format(PixelFormat::Rgb24)for per-pixel luminanceAudioDecoderwithSampleFormat::F32output, converted to interleaved PCM forrodioplayback- Dual-thread A/V sync via
crossbeam-channel
§Extension trait
VideoCodecEncodeExt adds encode-specific helpers (.default_extension(),
.is_lgpl_compatible()) to VideoCodec. Import the trait to call them:
use avio::{VideoCodec, VideoCodecEncodeExt};
let ext = VideoCodec::H264.default_extension(); // "mp4"Structs§
- AacOptions
- AAC per-codec options.
- AbrLadder
- Produces multi-rendition HLS or DASH output from a single input.
- AbrRendition
- One resolution/bitrate tier in an ABR ladder.
- Analyze
Options - Options for the first stabilization pass (motion analysis).
- Animation
Entry - A registered animation track for a specific filter parameter.
- Animation
Track - A sorted collection of keyframes with interpolated
value_at(t)lookup. - Async
Audio Decoder - Async wrapper around
AudioDecoder. - Async
Audio Decoder Builder - Async builder for
AsyncAudioDecoderthat mirrors the options available on the synchronousAudioDecoderBuilder. - Async
Audio Encoder - Async wrapper around
AudioEncoder. - Async
Image Decoder - Async wrapper around
ImageDecoder. - Async
Preview Player - Async wrapper around
PlayerHandle. - Async
Video Decoder - Async wrapper around
VideoDecoder. - Async
Video Decoder Builder - Async builder for
AsyncVideoDecoderthat mirrors the options available on the synchronousVideoDecoderBuilder. - Async
Video Encoder - Async wrapper around
VideoEncoder. - Audio
Adder - Mux an audio track into a silent (or existing) video file.
- Audio
Concatenator - Concatenates multiple audio clips into a single seamless output stream.
- Audio
Decoder - An audio decoder for extracting audio frames from media files.
- Audio
Encoder - Encodes audio frames to a file using FFmpeg.
- Audio
Encoder Config - Configuration for the audio stream of an export preset.
- Audio
Extractor - Demux an audio track from a media file and write it to a standalone audio file.
- Audio
Frame - A decoded audio frame.
- Audio
Mixer - Multi-track, constant-power-panned stereo mixer.
- Audio
Pipeline - High-level audio-only transcode pipeline.
- Audio
Replacement - Replace a video file’s audio track with audio from a separate source file.
- Audio
Stream Info - Information about an audio stream within a media file.
- Audio
Track - A single audio track in a
MultiTrackAudioMixermix. - Audio
Track Handle - Cloneable handle for filling a track and adjusting its gain from any thread.
- Av1Options
- AV1 per-codec options (libaom-av1).
- Black
Frame Detector - Detects black intervals in a video file and returns their start timestamps.
- Chapter
Info - Information about a chapter within a media file.
- Chapter
Info Builder - Builder for constructing
ChapterInfo. - Clip
- A single media clip on a timeline.
- Clip
Joiner - Joins two video clips with a cross-dissolve transition.
- Clip
Transition - Parameters for a cross-dissolve transition applied at the start of a
VideoLayer. - Container
Info - Container-level metadata extracted from
AVFormatContext. - Dash
Output - Builds and writes a DASH segmented output.
- Decode
Buffer - Pre-decodes frames from a video file into a ring buffer on a background thread.
- Decode
Buffer Builder - Builder for
DecodeBuffer. - Dnxhd
Options - Avid DNxHD / DNxHR per-codec options.
- Draw
Text Options - Options for the
drawtextfilter. - Encode
Progress - Encoding progress information.
- Encoder
Config - Codec and quality configuration for the pipeline output.
- Encoder
Config Builder - Consuming builder for
EncoderConfig. - Export
Preset - A named export preset combining video and audio encoder configuration.
- Fanout
Output - A
StreamOutputwrapper that fans frames out to multiple targets. - Filter
Graph - An
FFmpeglibavfilter filter graph. - Filter
Graph Builder - Builder for constructing a
FilterGraph. - Flac
Options - FLAC per-codec options.
- Frame
Extractor - Extracts one frame per time interval from a video file.
- Frame
Histogram - Per-channel color histogram for a single video frame.
- GifPreview
- Generates an animated GIF preview from a configurable time range.
- H264
Options - H.264 (AVC) per-codec options.
- H265
Options - H.265 (HEVC) per-codec options.
- Hdr10
Metadata - HDR10 static metadata (
MaxCLL+MaxFALL+ mastering display). - Histogram
- 256-bin luminance and per-channel RGB histogram.
- Histogram
Extractor - Extracts per-channel color histograms at configurable frame intervals.
- HlsOutput
- Builds and writes an HLS segmented output.
- Image
Decoder - Decodes a single still image into a
VideoFrame. - Image
Encoder - Encodes a single
VideoFrameto a still image file. - Keyframe
- A single keyframe in an animation track.
- Keyframe
Enumerator - Enumerates the timestamps of all keyframes in a video stream.
- Live
AbrLadder - Live ABR ladder: fans frames to multiple encoders at different resolutions.
- Live
Dash Output - Live DASH output: receives frames and writes a
manifest.mpdplaylist. - Live
HlsOutput - Live HLS output: receives frames and writes a sliding-window
.m3u8playlist. - Loudness
Meter - Measures EBU R128 integrated loudness, loudness range, and true peak.
- Loudness
Result - Result of an EBU R128 loudness measurement.
- Mastering
Display - Mastering display colour volume (SMPTE ST 2086).
- Media
Info - Information about a media file.
- Media
Info Builder - Builder for constructing
MediaInfo. - Mp3Options
- MP3 (libmp3lame) per-codec options.
- Multi
Track Audio Mixer - Mixes multiple audio tracks into a single output stream.
- Multi
Track Composer - Composes multiple video layers onto a solid-colour canvas.
- Network
Options - Shared network configuration for network-backed decoders and live outputs.
- Opus
Options - Opus (libopus) per-codec options.
- Pipeline
- A configured, ready-to-run transcode pipeline.
- Pipeline
Builder - Consuming builder for
Pipeline. - Playback
Clock - A monotonic clock that tracks elapsed playback time.
- Player
Handle - Shared, cloneable handle to a running
PlayerRunner. - Player
Runner - Exclusive owner of the decode pipeline. Move to a background thread and
call
run. - Preview
Player - Thin builder for a (
PlayerRunner,PlayerHandle) pair. - ProRes
Options - Apple ProRes per-codec options.
- Progress
- Progress information delivered to the caller on each processed frame.
- Proxy
Generator - Generates a lower-resolution proxy file from an original media file.
- Proxy
Job - A handle to a running background proxy generation job.
- Proxy
Source - A low-resolution proxy substitute for a
VideoLayer’s source. - Quality
Metrics - Computes video quality metrics between a reference and a distorted video.
- Rational
- A rational number represented as a fraction (numerator / denominator).
- Rendition
- A single resolution/bitrate rendition in an ABR ladder.
- Rgb
- An RGB colour value used by the three-way colour corrector.
- RgbParade
- Per-channel waveform monitor data (RGB parade).
- Rgba
Frame - A decoded video frame as contiguous RGBA bytes.
- Rgba
Sink - Reference
FrameSinkimplementation that stores the latest frame in a sharedArc<Mutex<Option<RgbaFrame>>>. - Rtmp
Output - Live RTMP output: encodes frames and pushes them to an RTMP ingest endpoint.
- Scene
Detector - Detects scene changes in a video file and returns their timestamps.
- Scope
Analyzer - Scope analysis utilities for decoded video frames.
- Silence
Detector - Detects silent intervals in an audio file and returns their time ranges.
- Silence
Range - A detected silent interval in an audio stream.
- Sprite
Sheet - Generates a thumbnail sprite sheet from a video file.
- SrtOutput
- Live SRT output: encodes frames as MPEG-TS and pushes them to an SRT destination.
- Stabilize
Options - Options for the second stabilization pass (transform application).
- Stabilizer
- Two-pass video stabilization using
FFmpeg’svidstabdetect/vidstabtransformfilters. - Stream
Copy Trim - Trim a media file to a time range using stream copy (no re-encode).
- Stream
Copy Trimmer - Trim a media file to a time range using stream copy (no re-encode).
- Subtitle
Event - A single subtitle event (cue).
- Subtitle
Stream Info - Information about a subtitle stream within a media file.
- Subtitle
Track - A parsed subtitle track containing ordered events.
- SvtAv1
Options - SVT-AV1 (libsvtav1) per-codec options.
- Thumbnail
Pipeline - Extracts still frames from a video file at requested timestamps.
- Thumbnail
Selector - Automatically selects the best thumbnail frame from a video file.
- Timeline
- An ordered layout of
Clipinstances across video and audio tracks. - Timeline
Builder - Builder for
Timeline. - Timeline
Player - Thin builder for a (
TimelineRunner,PlayerHandle) pair backed by aTimeline. - Timeline
Runner - Exclusive owner of the timeline decode pipeline.
- Timestamp
- A timestamp representing a point in time within a media stream.
- VecPool
- A simple frame pool backed by a
Vecof reusable buffers. - Video
Concatenator - Concatenates multiple video clips into a single seamless output stream.
- Video
Decoder - A video decoder for extracting frames from media files.
- Video
Effect Renderer - Reusable single-frame renderer for a
Clip’s video effect chain. - Video
Encoder - Encodes video (and optionally audio) frames to a file using FFmpeg.
- Video
Encoder Config - Configuration for the video stream of an export preset.
- Video
Frame - A decoded video frame.
- Video
Layer - A single video layer in a
MultiTrackComposercomposition. - Video
Pipeline - High-level video-only transcode pipeline.
- Video
Stream Info - Information about a video stream within a media file.
- Vp9Options
- VP9 (libvpx-vp9) per-codec options.
- Waveform
Analyzer - Computes peak and RMS amplitude per time interval for an audio file.
- Waveform
Sample - A single waveform measurement over a configurable time interval.
Enums§
- AacProfile
- AAC encoding profile.
- Alpha
Mode - Alpha modes.
- Animated
Value - A value that is either constant or animated over time.
- Audio
Codec - Audio codec identifier.
- Audio
Codec Options - Per-codec encoding options for audio.
- Av1Usage
- AV1 encoding usage mode.
- Bitrate
Mode - Bitrate control mode for video encoding.
- Blend
Mode - Specifies how two video layers are combined during compositing.
- Channel
Layout - Audio channel layout representing the speaker configuration.
- Color
Primaries - Color primaries defining the color gamut (the range of colors that can be represented).
- Color
Range - Color range defining the valid range of color values.
- Color
Space - Color space (matrix coefficients) for YUV to RGB conversion.
- Color
Transfer - Color transfer characteristic (opto-electronic transfer function).
- Composite
Op - Porter-Duff alpha-compositing operator for combining two video layers.
- Decode
Error - Errors that can occur during decoding operations.
- Dnxhd
Variant - DNxHD / DNxHR encoding variant.
- Easing
- Easing function applied to a keyframe interval.
- Encode
Error - Encoding error type.
- EqBand
- A single band for the parametric equalizer.
- Filter
Error - Errors that can occur during filter graph construction and processing.
- Filter
Step - A single step in a filter chain.
- Frame
Result - The result of a
DecodeBuffer::pop_framecall. - H264
Preset - libx264 encoding speed/quality preset.
- H264
Profile - H.264 encoding profile.
- H264
Tune - libx264 perceptual tuning parameter.
- H265
Profile - H.265 encoding profile.
- H265
Tier - H.265 encoding tier.
- Hardware
Accel - Hardware acceleration configuration.
- Hardware
Encoder - Hardware encoder type.
- HlsSegment
Format - Container format for individual HLS segments.
- HwAccel
- Hardware acceleration backend for filter graph operations.
- Interpolation
- Interpolation algorithm used by
Stabilizer::transform. - Lens
Profile - Predefined lens distortion correction profiles for common cameras.
- Live
AbrFormat - Output container format for the ABR ladder.
- Mp3Quality
- MP3 quality mode: VBR quality scale or CBR fixed bitrate.
- Noise
Type - Noise type used as the initial spectral model for
afftdn. - Opus
Application - Opus encoder application mode.
- Output
Container - Output container format for encoding.
- Pipeline
Error - Errors that can occur while building or running a pipeline.
- Pixel
Format - Pixel format for video frames.
- Player
Command - Commands sent from
PlayerHandletoPlayerRunnervia a bounded sync channel (capacity 64). - Player
Event - Events emitted by
PlayerRunner::runand delivered to callers viaPlayerHandle::poll_event. - Preset
- Encoding preset (speed vs quality tradeoff).
- Preview
Error - Errors that can occur during preview and proxy operations.
- ProRes
Profile - Apple ProRes encoding profile.
- Probe
Error - Error type for media probing operations.
- Proxy
Resolution - Output resolution for a proxy file, expressed as a fraction of the source.
- Sample
Format - Audio sample format for audio frames.
- Scale
Algorithm - Resampling algorithm for the
scalefilter. - Seek
Event - An event emitted by
DecodeBufferafter aseek_asynccompletes. - Seek
Mode - Seek mode for positioning the decoder.
- Stream
Error - Errors that can occur during streaming output operations.
- Subtitle
Codec - Subtitle codec identifier.
- Subtitle
Error - Error type for subtitle parsing operations.
- ToneMap
- Tone-mapping algorithm for HDR-to-SDR conversion.
- Video
Codec - Video codec identifier.
- Video
Codec Options - Per-codec encoding options.
- Xfade
Transition - Transition type for the
xfadecross-dissolve filter. - Yadif
Mode - Deinterlacing mode for the
yadiffilter.
Constants§
- CRF_MAX
- Maximum CRF value accepted by H.264/H.265 encoders.
Traits§
- Encode
Progress Callback - EncodeProgress callback trait for monitoring encoding progress.
- Frame
Pool - A trait for frame buffer pooling.
- Frame
Sink - A sink that receives decoded video frames as contiguous RGBA bytes.
- Lerp
- A value that supports linear component-wise interpolation.
- Stream
Output - Common interface for all live stream outputs.
- Video
Codec Encode Ext - Encode-specific methods for
VideoCodec.
Functions§
- open
- Opens a media file and extracts its metadata.
Type Aliases§
- Progress
Callback - Callback invoked on every processed frame to report progress.