Skip to main content

FilterGraph

Struct FilterGraph 

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

An FFmpeg libavfilter filter graph.

Constructed via FilterGraph::builder(). The underlying AVFilterGraph is initialised lazily on the first push call, deriving format information from the first frame.

§Examples

use ff_filter::FilterGraph;

let mut graph = FilterGraph::builder()
    .scale(1280, 720)
    .build()?;

// Push decoded frames in …
graph.push_video(0, &video_frame)?;

// … and pull filtered frames out.
while let Some(frame) = graph.pull_video()? {
    // use frame
}

Implementations§

Source§

impl FilterGraph

Source

pub fn noise_reduce(&mut self, nt: NoiseType, nr_level: f32) -> &mut Self

Reduce noise using a statistical noise-type model.

nr_level is the noise reduction amount in dB, clamped to [0.0, 97.0].

Uses FFmpeg’s afftdn filter.

Source

pub fn noise_reduce_profile( &mut self, profile_duration_secs: f32, nr_level: f32, ) -> &mut Self

Capture a noise profile from the first profile_duration_secs seconds, then reduce noise in the full stream.

nr_level is the reduction amount in dB, clamped to [0.0, 97.0]. profile_duration_secs is clamped to a minimum of 0.1 seconds.

Uses FFmpeg’s afftdn filter with the pl profile-length option.

Source

pub fn speed_change(&mut self, factor: f64) -> Result<&mut Self, FilterError>

Change audio speed and pitch simultaneously by factor.

Equivalent to playing a tape at a different speed: factor > 1.0 makes audio faster and higher-pitched; factor < 1.0 makes it slower and lower.

Uses FFmpeg’s asetrate filter. Range: 0.1–10.0.

§Errors

Returns FilterError::Ffmpeg if factor is outside 0.1–10.0.

Source

pub fn pitch_shift(&mut self, semitones: f32) -> Result<&mut Self, FilterError>

Shift audio pitch by semitones without changing playback speed.

Range: −12.0 to +12.0 semitones. Uses asetrate to change the decoded sample rate followed by atempo to restore original duration.

§Errors

Returns FilterError::Ffmpeg if semitones is outside −12.0..=12.0.

Source

pub fn time_stretch(&mut self, factor: f32) -> Result<&mut Self, FilterError>

Stretch or compress audio duration by factor without pitch change.

factor < 1.0 = slower (longer duration); factor > 1.0 = faster (shorter duration). Range: 0.1–10.0.

Uses FFmpeg’s atempo filter (WSOLA algorithm). Values outside [0.5, 2.0] are realised by chaining multiple atempo instances.

§Errors

Returns FilterError::Ffmpeg if factor is outside 0.1–10.0.

Source

pub fn reverb_echo( &mut self, in_gain: f32, out_gain: f32, delays: &[f32], decays: &[f32], ) -> Result<&mut Self, FilterError>

Add algorithmic echo/reverb with configurable delay taps.

in_gain and out_gain are amplitude multipliers clamped to [0.0, 1.0]. delays is a list of delay times in milliseconds. decays is the corresponding decay factor for each delay, clamped to [0.0, 1.0]. delays and decays must have equal length (1–8 taps).

Uses FFmpeg’s aecho filter.

§Errors

Returns FilterError::Ffmpeg if lengths differ or tap count is outside 1–8.

Source

pub fn duck( &mut self, threshold_db: f32, ratio: f32, attack_ms: f32, release_ms: f32, ) -> Result<&mut Self, FilterError>

Reduce background audio level when foreground signal exceeds a threshold (audio ducking via sidechain compression).

Push background audio to slot 0 and foreground (sidechain trigger) audio to slot 1. When the foreground signal rises above threshold_db, the background is attenuated by ratio:1 over attack_ms milliseconds; it recovers over release_ms milliseconds when the foreground drops below the threshold.

threshold_db is the trigger level in dBFS (e.g., −20.0). It is converted to a linear amplitude ratio before being passed to the filter. ratio must be ≥ 1.0. attack_ms and release_ms must be ≥ 0.0.

Uses FFmpeg’s sidechaincompress filter.

§Errors

Returns FilterError::Ffmpeg if ratio < 1.0 or either time value is negative.

Source

pub fn reverb_ir( &mut self, ir_path: &Path, wet: f32, dry: f32, pre_delay_ms: u32, ) -> Result<&mut Self, FilterError>

Add convolution reverb using an impulse response (IR) audio file.

ir_path is a path to a .wav or .flac impulse response file. wet and dry are mix levels clamped to [0.0, 1.0]. pre_delay_ms inserts silence before the reverb tail (clamped to 0–500 ms).

Uses FFmpeg’s amovie (to load the IR) and afir (convolution) filters.

Call this method after FilterGraph::builder() / FilterGraphBuilder::build() but before the first FilterGraph::push_audio() call.

§Errors

Returns FilterError::Ffmpeg if ir_path does not exist. The afir filter availability is checked at graph build time; if not available the graph build returns FilterError::BuildFailed.

Source§

impl FilterGraph

Source

pub fn motion_blur( &mut self, shutter_angle_degrees: f32, sub_frames: u8, ) -> Result<&mut Self, FilterError>

Simulate motion blur by blending multiple consecutive frames.

shutter_angle_degrees controls the blend ratio (360° = full frame-period exposure). sub_frames sets the number of frames blended and must be in [2, 16].

Uses FFmpeg’s tblend filter with all_expr: the normalised shutter angle becomes the weight for the previous frame (B), and its complement weights the current frame (A).

Call this method after FilterGraph::builder() / build() but before the first push_video call.

§Errors

Returns FilterError::Ffmpeg if sub_frames is outside [2, 16].

Source

pub fn lens_correction( &mut self, k1: f32, k2: f32, ) -> Result<&mut Self, FilterError>

Correct radial lens distortion using two polynomial coefficients.

k1 and k2 are the first- and second-order radial distortion coefficients. Negative values correct barrel distortion; positive values correct pincushion distortion.

Uses FFmpeg’s lenscorrection filter.

Call this method after FilterGraph::builder() / build() but before the first push_video call.

§Errors

Returns FilterError::Ffmpeg if either coefficient is outside [−1.0, 1.0].

Source

pub fn film_grain( &mut self, luma_strength: f32, chroma_strength: f32, ) -> &mut Self

Add random per-frame film grain to luma and chroma channels.

luma_strength and chroma_strength control grain intensity and are clamped to [0.0, 100.0]. The allf=t flag varies the noise seed each frame to simulate real film grain temporal variation.

Uses FFmpeg’s noise filter with alls (luma), c0s/c1s (Cb/Cr), and allf=t (per-frame seed).

Call this method after FilterGraph::builder() / build() but before the first push_video call.

Source

pub fn fix_chromatic_aberration( &mut self, red_scale: f32, blue_scale: f32, ) -> Result<&mut Self, FilterError>

Reduce lateral chromatic aberration by independently scaling R and B channels.

red_scale and blue_scale are fractional adjustments relative to 1.0 (e.g. red_scale = 1.002 scales R by 0.2%). Valid range for each: 0.9–1.1.

The scale deviation is converted to an integer pixel shift for FFmpeg’s rgbashift filter: shift = ((scale - 1.0) * 100.0).round().

Uses FFmpeg’s rgbashift filter with edge=smear.

Call this method after FilterGraph::builder() / build() but before the first push_video call.

§Errors

Returns FilterError::Ffmpeg if either scale is outside [0.9, 1.1].

Source

pub fn glow(&mut self, threshold: f32, radius: f32, intensity: f32) -> &mut Self

Add a glow / bloom effect by blending blurred highlights back over the image.

threshold controls which luminance level triggers glow (clamped to [0.0, 1.0]). radius is the Gaussian blur sigma in pixels (clamped to [0.5, 50.0]). intensity is the additive blend strength (clamped to [0.0, 2.0]).

Values outside the valid ranges are silently clamped — no error is returned.

Uses FFmpeg’s split, curves, gblur, and blend filters.

Call this method after FilterGraph::builder() / build() but before the first push_video call.

Source

pub fn lens_profile(&mut self, profile: LensProfile) -> &mut Self

Apply a predefined camera lens distortion correction profile.

Looks up the radial coefficients (k1, k2) and scale from the profile and pushes a lenscorrection step followed by a scale step that zooms slightly to hide the warped border pixels.

Uses FFmpeg’s lenscorrection and scale filters.

Call this method after FilterGraph::builder() / build() but before the first push_video call.

Source§

impl FilterGraph

Source

pub fn builder() -> FilterGraphBuilder

Create a new builder.

Source

pub fn tick(&mut self, t: Duration)

Applies all registered animation entries at time t.

Call this before each pull_video on source-only graphs (e.g. from MultiTrackComposer) to update animated filter parameters for the next frame.

On graphs that use push_video, animations are applied automatically at the pushed frame’s PTS — tick is not needed.

Source

pub fn output_resolution(&self) -> Option<(u32, u32)>

Returns the output resolution produced by this graph’s scale filter step, if one was configured.

When multiple scale steps are chained, the last one’s dimensions are returned. Returns None when no scale step was added.

Source

pub fn push_video( &mut self, slot: usize, frame: &VideoFrame, ) -> Result<(), FilterError>

Push a video frame into input slot slot.

On the first call the filter graph is initialised using this frame’s format, resolution, and time base.

All registered animation entries are evaluated at the frame’s PTS and applied to the live graph via avfilter_graph_send_command before the frame is pushed.

§Errors
Source

pub fn pull_video(&mut self) -> Result<Option<VideoFrame>, FilterError>

Pull the next filtered video frame, if one is available.

Returns None when the internal FFmpeg buffer is empty (EAGAIN) or at end-of-stream.

§Errors

Returns FilterError::ProcessFailed on an unexpected FFmpeg error.

Source

pub fn push_audio( &mut self, slot: usize, frame: &AudioFrame, ) -> Result<(), FilterError>

Push an audio frame into input slot slot.

On the first call the audio filter graph is initialised using this frame’s format, sample rate, and channel count.

All registered animation entries are evaluated at the frame’s PTS and applied to the live graph via avfilter_graph_send_command before the frame is pushed.

§Errors
Source

pub fn pull_audio(&mut self) -> Result<Option<AudioFrame>, FilterError>

Pull the next filtered audio frame, if one is available.

Returns None when the internal FFmpeg buffer is empty (EAGAIN) or at end-of-stream.

§Errors

Returns FilterError::ProcessFailed on an unexpected FFmpeg error.

Trait Implementations§

Source§

impl Debug for FilterGraph

Source§

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

Formats the value using the given formatter. Read more

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.