Filters

This section covers several types of filters including fir filter, biquad filter, and linkwitzriley filter.

FIRFilter

class diffFx_pytorch.processors.filters.FIRFilter(fir_len=1023, processor_channel='mono', **backend_kwargs)[source]

Bases: Module

A finite impulse response (FIR) filter implementation that processes signals using a moving weighted sum of input samples. This type of filter offers linear phase response and inherent stability. The filter’s response is determined by its coefficients.

__init__(fir_len=1023, processor_channel='mono', **backend_kwargs)[source]

Initialize internal Module state, shared by both nn.Module and ScriptModule.

forward(input_signals, fir)[source]

Performs the convolution operation.

Parameters:
  • input_signals (:python:`FloatTensor`, \(B \times C_\mathrm{in} \times L_\mathrm{in}\)) – A batch of input audio signals.

  • fir (:python:`FloatTensor`, \(B \times C_\mathrm{filter} \times L_\mathrm{filter}\)) – A batch of FIR filters.

Returns:

A batch of convolved signals of shape \(B \times C_\mathrm{out} \times L_\mathrm{in}\) where \(C_\mathrm{out} = \max (C_\mathrm{in}, C_\mathrm{filter})\).

Return type:

:python:`FloatTensor`

BiquadFilter

class diffFx_pytorch.processors.filters.BiquadFilter(*args: Any, **kwargs: Any)[source]

Bases: ProcessorsBase

Differentiable implementation of a second-order IIR (biquad) filter.

This processor implements various types of biquad filters based on the Audio EQ Cookbook formulas. It supports multiple filter types including lowpass, highpass, bandpass, bandstop, allpass, peaking, and shelving filters. The filter is implemented using the following transfer function:

\[H(z) = \frac{b_0 + b_1z^{-1} + b_2z^{-2}}{a_0 + a_1z^{-1} + a_2z^{-2}}\]
Parameters:
  • sample_rate (int) – Audio sample rate in Hz. Defaults to 44100.

  • param_ranges (Dict[str, Tuple[str, EffectParam]]) – Optional parameter definitions to override defaults.

  • filter_type (str) – Type of filter to implement (see Filter Types below).

  • **kwargs – Additional arguments passed to IIRFilter

Parameters Details:
frequency: Center/cutoff frequency
  • Range: 20.0 to 20000.0 Hz

  • Controls filter’s frequency response

  • Meaning depends on filter type

q_factor: Quality factor
  • Range: 0.1 to 10.0

  • Controls bandwidth/resonance

  • Higher values = narrower/sharper response

gain_db: Gain for peak/shelf filters
  • Range: -12.0 to 12.0 dB

  • Only used by peak and shelf types

  • Controls amount of boost/cut

Filter Types:
Low-pass (LP):
  • Passes frequencies below cutoff

  • -12 dB/octave slope

High-pass (HP):
  • Passes frequencies above cutoff

  • -12 dB/octave slope

Band-pass (BP):
  • Passes frequencies around center

  • Constant skirt gain

Band-stop (BS):
  • Rejects frequencies around center

  • Also known as notch filter

All-pass (AP):
  • Maintains magnitude response

  • Adjusts phase response

Peak (PK):
  • Boosts/cuts around center

Low-shelf (LS):
  • Boosts/cuts below frequency

High-shelf (HS):
  • Boosts/cuts above frequency

Examples

Basic DSP Usage:
>>> # Create a lowpass filter
>>> lpf = BiquadFilter(
...     sample_rate=44100,
...     filter_type='LP'
... )
>>> # Process audio
>>> output = lpf(input_audio, dsp_params={
...     'frequency': 1000.0,  # 1 kHz cutoff
...     'q_factor': 0.707,    # Butterworth response
...     'gain_db': 0.0        # Not used for LP
... })
Neural Network Control:
>>> # 1. Simple parameter prediction
>>> class FilterController(nn.Module):
...     def __init__(self, input_size):
...         super().__init__()
...         self.net = nn.Sequential(
...             nn.Linear(input_size, 32),
...             nn.ReLU(),
...             nn.Linear(32, 3),  # 3 parameters
...             nn.Sigmoid()  # Ensures output is in [0,1] range
...         )
...
...     def forward(self, x):
...         return self.net(x)

A second-order infinite impulse response (IIR) filter implementation, also known as a biquad filter, that provides efficient filtering with configurable frequency response characteristics. It supports multiple filter types including lowpass, highpass, bandpass, notch, peaking, and shelving filters. Each filter type is controlled through parameters such as frequency, Q factor, and gain, allowing flexible frequency response shaping with minimal computational cost.

_register_default_parameters()[source]

Register filter parameters with ranges.

Sets up three parameters:
  • frequency: Center/cutoff in Hz (20.0 to 20000.0)

  • q_factor: Quality factor (0.1 to 10.0)

  • gain_db: Gain in dB (-12.0 to 12.0)

__init__(sample_rate=44100, param_range=None, filter_type='LP', **kwargs)[source]

Initialize the processor base.

Parameters:
  • sample_rate – Audio sample rate in Hz

  • param_range – Optional parameter definitions to override defaults

_map_filter_type_2_num(filter_type)[source]

Map filter type string to internal numeric representation.

Parameters:

filter_type (str) – Filter type identifier (see class docstring for supported types)

Returns:

Internal filter type number

Return type:

int

Raises:

ValueError – If filter type is not recognized

process(x, norm_params=None, dsp_params=None)[source]

Process input signal through the biquad filter.

Parameters:
  • x (torch.Tensor) – Input audio tensor. Shape: (batch, channels, samples)

  • norm_params (Dict[str, torch.Tensor]) – Normalized parameters (0 to 1)

  • dsp_params (Dict[str, torch.Tensor], optional) – Direct DSP parameters. If provided, norm_params must be None.

Returns:

Filtered audio tensor of same shape as input

Return type:

torch.Tensor

LinkwitzRileyFilter

class diffFx_pytorch.processors.filters.LinkwitzRileyFilter(*args: Any, **kwargs: Any)[source]

Bases: ProcessorsBase

Linkwitz-Riley crossover filter implementation using cascaded Butterworth filters

A specialized crossover filter implementation that provides precise frequency band splitting with optimal phase and magnitude response characteristics. It uses a cascaded design of two Butterworth filters to achieve -24 dB/octave slopes with flat magnitude response at the crossover point and zero phase difference between outputs. This makes it particularly suitable for audio crossover networks and multi-band processing applications.

__init__(sample_rate=44100, order=4)[source]

Initialize the processor base.

Parameters:
  • sample_rate – Audio sample rate in Hz

  • param_range – Optional parameter definitions to override defaults

process(x, norm_params, dsp_params=None)[source]

Process audio with the effect (to be implemented by subclasses).

Parameters:
  • x (Tensor) – Input audio tensor [batch, channels, samples]

  • norm_params (Dict[str, Tensor]) – Optional dictionary of normalized parameters

  • dsp_params (Optional[Dict[str, Tensor]]) – Optional dictionary of DSP parameters

Return type:

Tuple[Tensor, Tensor]

Returns:

Processed audio tensor