Skip to main content

Crate cathar

Crate cathar 

Source
Expand description

Audio restoration toolbox — denoise, de-hum, de-click, de-clip, normalise.

Default denoising uses spectral subtraction (pure Rust, zero weights). Enable the ml feature for candle-based neural denoising (Demucs, DNS Challenge).

§Quick start

use cathar::{Denoiser, SpectralDenoiser, generate_wave};

let audio = generate_wave(44100, 440.0, 1.0, 0.2);
let denoiser = SpectralDenoiser::default();
let clean = denoiser.denoise(&audio)?;
assert_eq!(clean.channels[0].len(), audio.channels[0].len());

Structs§

AudioData
Decoded audio: a sample rate plus one f32 PCM buffer per channel (de-interleaved, sample values in [-1.0, 1.0]).
CqtSpec
A constant-Q magnitude spectrogram: a column per time frame, each holding bins log-spaced frequency rows in decibels.
NoisePrint
Pre-computed noise profile from a silence segment. Feed into SpectralDenoiser::with_noise_print instead of auto-detection.
SinusoidalModel
A sinusoidal model: the partials extracted from a signal.
SpectralDenoiser
STFT spectral-subtraction / Wiener denoiser (see Denoiser).
Spectrogram
A magnitude spectrogram: a column per time frame, each holding bins frequency rows (row 0 = DC, row bins-1 = Nyquist), in decibels.
Stats
Per-channel and aggregate audio statistics.

Enums§

Emphasis
A standard de-emphasis curve.
EnhanceMethod
Bandwidth-extension strategy for bandwidth_extend.
Error
Errors returned by cathar’s decode, encode, and processing routines.
StretchMode
Which time-stretch engine to use.

Traits§

Denoiser
A denoising strategy: turn noisy AudioData into a cleaner copy.

Functions§

align
Align signal to reference, returning the shifted signal (same length).
analyze_sms
Analyse signal into a SinusoidalModel.
azimuth_correct
Correct stereo azimuth skew: keep the left channel and shift the right to best align with it. Returns (left, corrected_right).
bandpass
Apply a band-pass biquad filter to a mono signal.
bandwidth_extend
Restore high-frequency content lost to compression or low sample rates.
bandwidth_extend_with_method
Like bandwidth_extend but selects the upsampling strategy.
bass
Apply a low-shelf filter: boost/cut gain_db below cutoff Hz.
breath_remove
Detect and attenuate breath sounds between speech segments.
compressor
Downward compressor with soft-knee. Reduces gain when the envelope exceeds threshold dBFS, by a ratio:1 slope. attack and release in seconds.
compute_stats
Compute comprehensive statistics for an audio buffer. Returns None if the signal is empty.
cqt
Compute the constant-Q transform of signal. bins_per_octave sets the log-frequency resolution (12 = semitones); f_min is the lowest frequency.
declick
Detect and interpolate impulse clicks.
declip
Reconstruct clipped samples with A-SPADE sparse declipping (Kitić, Bertin & Gribonval 2015) over a Hann-windowed, 4×-overlapping Gabor tight frame.
decrackle
Suppress dense low-level crackle. sensitivity in 1..=10 (higher removes more; 5 is a sensible default).
deemphasis
Apply the playback de-emphasis curve to a mono signal.
deess_multiband
Multiband, adaptive de-esser. The region above crossover_freq is split into bands sub-bands; each tracks its own short-term level (an exponential moving average) and is compressed by ratio only when its instantaneous level rises threshold_db above that adaptive average. Adapting per band and over time catches sibilance concentrated in part of the band and follows a speaker’s changing level, where a single fixed-threshold band over- or under-reacts. Falls back to a single band when bands <= 1.
deesser
Reduce sibilance (harsh “s”, “sh”, “ch” sounds) using HF compression.
dehum
Remove mains hum (50/60 Hz + harmonics) using cascaded notch filters.
dehum_adaptive
Adaptive mains-hum removal. base_freq is the nominal (50 or 60); num_harmonics harmonics are tracked and cancelled.
deplosive
Tame plosive pops — the low-frequency bursts on “p”/“b” sounds — by attenuating transient energy below ~250 Hz. strength 1–10 (higher removes more). Sustained low-frequency content is preserved.
dequantize
Reduce quantization grain from a signal assumed to have been recorded at bits bits per sample.
dereverb
Remove room reverb using spectral envelope decay gating.
derustle
Suppress lavalier / clothing rustle — transient bursts in the ~1.5–6 kHz band are scaled back toward the local temporal median. strength 1–10. Sustained speech in that band is left largely intact.
detect_pitch
Per-frame fundamental frequency (Hz), stepping by hop samples. 0.0 marks an unvoiced frame. An empty vector is returned for signals shorter than one analysis frame.
dewind
Remove low-frequency wind rumble with a 4th-order Butterworth high-pass (two cascaded biquads, ~24 dB/octave). cutoff_hz is the corner frequency (≈ 80 Hz suits most handheld/outdoor wind); content above it is untouched.
dewow
Correct wow & flutter. Returns a pitch-stabilised signal (~same length); if no stable reference pitch is found the input is returned unchanged.
dither
Apply triangular-probability-density-function (TPDF) dither at bits resolution. Adds two independent rectangular dithers of amplitude ±0.5 LSB to decorrelate quantisation noise from the signal. Intended for use before truncation to a lower bit depth.
elliptical_mono
Sum low frequencies to mono below crossover_hz while preserving the stereo image above the crossover. Tames out-of-phase vinyl rumble without collapsing the full mix.
equalizer
Apply a peaking (bell) EQ filter at freq Hz with gain_db boost/cut and bandwidth q.
estimate_lag
Estimate the lag (in samples, sub-sample precision) by which signal must be advanced to best align with reference, searching within ±max_ms.
fade
Apply a linear fade-in and/or fade-out to a mono signal. in_sec and out_sec specify the fade durations in seconds. Non-overlapping.
fundamental_hz
A single dominant fundamental for the whole clip: the median of the voiced frames. Returns None when nothing voiced is found.
gain_db
Multiply every sample by 10^(db/20). Positive dB boosts, negative cuts.
gate
Noise gate: attenuates the signal when the envelope falls below threshold_dbfs. attack and release in seconds.
generate_wave
Generate a mono test tone: a frequency-Hz sine at 0.5 amplitude plus uniform white noise scaled by noise_level, duration_secs long. Uses a fixed seed, so the output is deterministic.
highpass
Apply a high-pass biquad filter (12 dB/oct) to a mono signal.
hpss
Separate signal into (harmonic, percussive) components. kernel is the median-filter length (forced odd, ≥ 3) used in both time and frequency.
inpaint_auto
Detect interior runs of exact-zero or NaN samples (digital dropouts/mutes) up to max_gap_ms long and reconstruct each with inpaint_gap.
inpaint_gap
Reconstruct the span [start, start + len) of signal by AR interpolation, refined over iterations passes (3 is a good default). Returns a new buffer; out-of-range or empty spans return an unchanged copy.
integrated_loudness
Measure integrated loudness in LUFS per ITU-R BS.1770-4 / EBU R128: K-weighting, 400 ms blocks at 75 % overlap, the -70 LUFS absolute gate, then the -10 LU relative gate.
learn_noise_print
Learn a noise profile from an audio segment (should be silence/noise-only).
limiter
Brickwall limiter: hard-clips gain so output never exceeds ceiling_dbfs.
lowpass
Apply a low-pass biquad filter (12 dB/oct) to a mono signal.
normalize_peak
Scale to target peak level in dBFS (0 dBFS = ±1.0, -3 dBFS = ~±0.707).
pad
Pad a mono signal with silence at the start and/or end. start_sec and end_sec specify how many seconds of silence to prepend/append.
pitch_shift
Shift signal up by semitones (negative = down) while preserving duration. Implemented as time_stretch by the pitch ratio followed by resampling back to the original length.
remix
Remix channels: spec is a list of channel indices or mappings. input_channels are the original channels; output channels are built from spec. Each entry in spec is a list of (channel_index, gain) tuples. The output channel is the sum of input_channel[idx] * gain for each tuple.
resample
Resample one channel from from_rate to to_rate with a Kaiser-windowed sinc (arbitrary ratio). The cutoff tracks the lower of the two Nyquist limits, so downsampling is anti-aliased and upsampling adds no imaging; the filter support widens at low cutoffs to keep the stopband sharp. Returns the input unchanged when the rates already match.
reverse
Reverse a mono signal in time.
riaa_deemphasis
Apply the standard RIAA playback (de-emphasis) curve to a mono signal.
select_channels
Select a subset of channels by index.
silence_strip
Strip leading and trailing silence. A sample is “silent” if its magnitude is below threshold_amplitude. Runs shorter than min_duration_sec at the boundary are discarded; gaps shorter than min_duration_sec within non-silent audio are kept.
spectral_repair
Paint out isolated transient spectral artifacts — brief whistles, bursts, and glitches that appear in only a few STFT frames.
spectrogram
Compute the magnitude spectrogram of signal via a Hann-windowed STFT.
synthesize_sms
Resynthesise the signal from a SinusoidalModel by additive synthesis.
time_stretch
Stretch signal in time by ratio (output duration ÷ input duration): ratio > 1.0 lengthens (slows down), < 1.0 shortens (speeds up); pitch is preserved. Returns a buffer of length ≈ signal.len() * ratio.
treble
Apply a high-shelf filter: boost/cut gain_db above cutoff Hz.
trim
Extract a time slice from a mono signal. start and duration are in seconds; samples outside the original range are clamped to the boundary. Returns None if the requested slice is empty.
true_peak_dbtp
Estimate true-peak level in dBTP via 4× polyphase oversampling (the inter-sample-peak method of ITU-R BS.1770-4). Returns f32::NEG_INFINITY for digital silence. Oversampling is fixed at 4×, independent of sample rate.
vad
Simple energy-based voice activity detection: returns (start_sec, end_sec), where the signal rises above threshold_amplitude and stays for at least min_duration_sec. Returns None if no voice segment is found.
variance
Population variance of a sample buffer (mean of squared deviations).
vinyl_restore
RIAA de-emphasis with optional elliptical mono on a stereo pair.
voice_isolate
Isolate speech from background using energy-based VAD + spectral gating.
wiener_denoise
Wiener-filter denoiser — statistically optimal, better transients.
wpe
De-reverberate signal with WPE. taps (K) and delay (prediction gap, frames) control the amount removed; iterations refines the estimate.