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§
- Audio
Data - Decoded audio: a sample rate plus one
f32PCM 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
binslog-spaced frequency rows in decibels. - Noise
Print - Pre-computed noise profile from a silence segment.
Feed into
SpectralDenoiser::with_noise_printinstead of auto-detection. - Sinusoidal
Model - A sinusoidal model: the partials extracted from a signal.
- Spectral
Denoiser - STFT spectral-subtraction / Wiener denoiser (see
Denoiser). - Spectrogram
- A magnitude spectrogram: a column per time frame, each holding
binsfrequency rows (row 0 = DC, rowbins-1= Nyquist), in decibels. - Stats
- Per-channel and aggregate audio statistics.
Enums§
- Emphasis
- A standard de-emphasis curve.
- Enhance
Method - Bandwidth-extension strategy for
bandwidth_extend. - Error
- Errors returned by cathar’s decode, encode, and processing routines.
- Stretch
Mode - Which time-stretch engine to use.
Traits§
Functions§
- align
- Align
signaltoreference, returning the shiftedsignal(same length). - analyze_
sms - Analyse
signalinto aSinusoidalModel. - 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_extendbut selects the upsampling strategy. - bass
- Apply a low-shelf filter: boost/cut
gain_dbbelowcutoffHz. - breath_
remove - Detect and attenuate breath sounds between speech segments.
- compressor
- Downward compressor with soft-knee. Reduces gain when the envelope exceeds
thresholddBFS, by aratio:1 slope.attackandreleasein seconds. - compute_
stats - Compute comprehensive statistics for an audio buffer. Returns
Noneif the signal is empty. - cqt
- Compute the constant-Q transform of
signal.bins_per_octavesets the log-frequency resolution (12 = semitones);f_minis 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.
sensitivityin1..=10(higher removes more; 5 is a sensible default). - deemphasis
- Apply the playback de-emphasis
curveto a mono signal. - deess_
multiband - Multiband, adaptive de-esser. The region above
crossover_freqis split intobandssub-bands; each tracks its own short-term level (an exponential moving average) and is compressed byratioonly when its instantaneous level risesthreshold_dbabove 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 whenbands <= 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_freqis the nominal (50 or 60);num_harmonicsharmonics are tracked and cancelled. - deplosive
- Tame plosive pops — the low-frequency bursts on “p”/“b” sounds — by
attenuating transient energy below ~250 Hz.
strength1–10 (higher removes more). Sustained low-frequency content is preserved. - dequantize
- Reduce quantization grain from a signal assumed to have been recorded at
bitsbits 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.
strength1–10. Sustained speech in that band is left largely intact. - detect_
pitch - Per-frame fundamental frequency (Hz), stepping by
hopsamples.0.0marks 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_hzis 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
bitsresolution. 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_hzwhile 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
freqHz withgain_dbboost/cut and bandwidthq. - estimate_
lag - Estimate the lag (in samples, sub-sample precision) by which
signalmust be advanced to best align withreference, searching within±max_ms. - fade
- Apply a linear fade-in and/or fade-out to a mono signal.
in_secandout_secspecify the fade durations in seconds. Non-overlapping. - fundamental_
hz - A single dominant fundamental for the whole clip: the median of the voiced
frames. Returns
Nonewhen 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.attackandreleasein seconds. - generate_
wave - Generate a mono test tone: a
frequency-Hz sine at 0.5 amplitude plus uniform white noise scaled bynoise_level,duration_secslong. 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
signalinto(harmonic, percussive)components.kernelis 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_mslong and reconstruct each withinpaint_gap. - inpaint_
gap - Reconstruct the span
[start, start + len)ofsignalby AR interpolation, refined overiterationspasses (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_secandend_secspecify how many seconds of silence to prepend/append. - pitch_
shift - Shift
signalup bysemitones(negative = down) while preserving duration. Implemented astime_stretchby the pitch ratio followed by resampling back to the original length. - remix
- Remix channels:
specis a list of channel indices or mappings.input_channelsare the original channels; output channels are built fromspec. Each entry inspecis a list of(channel_index, gain)tuples. The output channel is the sum ofinput_channel[idx] * gainfor each tuple. - resample
- Resample one channel from
from_ratetoto_ratewith 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 thanmin_duration_secat the boundary are discarded; gaps shorter thanmin_duration_secwithin 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
signalvia a Hann-windowed STFT. - synthesize_
sms - Resynthesise the signal from a
SinusoidalModelby additive synthesis. - time_
stretch - Stretch
signalin time byratio(output duration ÷ input duration):ratio > 1.0lengthens (slows down),< 1.0shortens (speeds up); pitch is preserved. Returns a buffer of length ≈signal.len() * ratio. - treble
- Apply a high-shelf filter: boost/cut
gain_dbabovecutoffHz. - trim
- Extract a time slice from a mono signal.
startanddurationare in seconds; samples outside the original range are clamped to the boundary. ReturnsNoneif 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_INFINITYfor 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 abovethreshold_amplitudeand stays for at leastmin_duration_sec. ReturnsNoneif 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
signalwith WPE.taps(K) anddelay(prediction gap, frames) control the amount removed;iterationsrefines the estimate.