foley.audio#
Audio I/O and DSP primitives for foley.
The foundation every other foley layer decodes/encodes/transforms audio through. It commits to a small, explicit set of representations (report 09):
Working (in RAM, between DSP ops): a
float32NumPy array at48 kHz— shape(frames,)mono or(frames, channels). This is the lingua franca ofsoundfile/librosa/soxrand exactly what CLAP expects.Archive (bytes at rest): FLAC, source sample-rate and bit-depth preserved — lossless, ~40-60% smaller than WAV, self-describing.
Delivery / preview (derived): Opus by default (not implemented in the foundation — an FFmpeg/
foley[ffmpeg]concern surfaced later).
Design rules honoured here:
Zero-dep import. This module imports only the stdlib at top level; the heavy libraries (
numpy,soundfile,soxr,librosa, themixing.loudnessmeter) are lazy-imported inside the functions that need them, so
import foley.audioalways succeeds on a bare install and only the function you call pays for (and requires) its dependency.No magic numbers. Every default (sample rate, dtype, archive subtype, resample quality, trim/fade/loudness targets) is a named module-level constant used as a keyword-only argument default.
Never bundle FFmpeg / pydub / torchaudio. MP3/AAC/Opus transcode is an optional external-tool concern, not part of this royalty-free core.
All ops assume the working representation (float array, time on axis 0). load
is the one function that produces it from arbitrary sources (path, raw bytes, or
a file-like object).
Module Attributes
wide enough that PCM up to 24 bits survives a decode/encode round trip sample-exact (FLAC archive -> WAV export keeps the samples). |
|
a filesystem path, raw encoded bytes, or an already-open binary file-like object (e.g. |
|
The PCM subtypes, with their bit depths (what |
|
consumers of an export ( |
|
a name from |
|
the shared component's numpy BS.1770-4 meter (foley#91), so foley needs no meter library of its own. |
|
a sound effect that punctuates, under dialogue and music. |
|
The clip starts at the first sample within this many dB of its loudest window. |
|
The clip keeps its decay down to this many dB under its loudest window. |
|
The window the start and the tail are judged on (a transient's scale). |
|
A declick at the start, short enough to keep the transient. |
|
The fade that ends the kept decay. |
|
The sample-peak ceiling an accent is levelled under (dBFS). |
Functions
|
An accent-ready clip: its transient at t=0, its decay kept, its level set. |
|
The |
|
|
|
Encode |
|
Coerce |
|
The PCM subtype an export as |
|
Apply in/out gain ramps to |
|
Integrated loudness (LUFS, BS.1770-4) of |
|
Whether re-encoding |
|
Attenuate |
|
Decode audio into a float working array. |
The shared loudness component, |
|
|
The one loudness-gain rule: |
|
Loudness-normalize to |
|
Seconds to the first sample within |
|
Resample |
|
|
|
Write |
|
Down-mix to mono by averaging channels; 1-D input passes through. |
|
Produce the canonical CLAP/QC working array from an arbitrary clip. |
|
Re-encode |
|
Strip leading/trailing silence, returning the clip and its kept span. |
Classes
|
What |
- foley.audio.ACCENT_FADE_IN_S: float = 0.003#
A declick at the start, short enough to keep the transient.
- foley.audio.ACCENT_PEAK_CEILING_DBFS: float = -3.0#
The sample-peak ceiling an accent is levelled under (dBFS).
- foley.audio.ACCENT_START_DB: float = 35.0#
The clip starts at the first sample within this many dB of its loudest window.
- foley.audio.ACCENT_TAIL_DB: float = 50.0#
The clip keeps its decay down to this many dB under its loudest window.
- foley.audio.ACCENT_TARGET_LUFS: float = -30.0#
a sound effect that punctuates, under dialogue and music.
- Type:
An accent’s level
- foley.audio.ACCENT_WINDOW_S: float = 0.002#
The window the start and the tail are judged on (a transient’s scale).
- class foley.audio.AccentReport(duration_s, lufs, lufs_padded, peak_dbfs, onset_s, trimmed_start_s, gain_db)[source]#
Bases:
objectWhat
accent()made, measured on the clip it returns.lufsof a clip shorter than one BS.1770 block (0.4 s) is measured with the clip padded with silence to one block (lufs_padded): a convention that lets a one-shot be levelled at all, not a BS.1770 measurement.onset_sis where the transient lands in the clip (0.0unlesspre_skept a lead-in);trimmed_start_sis how much lead-in was cut from the source.
- foley.audio.AudioSource#
a filesystem path, raw encoded bytes, or an already-open binary file-like object (e.g.
io.BytesIO).- Type:
A source
loadcan decode
- foley.audio.DEFAULT_METER: str = 'numpy'#
the shared component’s numpy BS.1770-4 meter (foley#91), so foley needs no meter library of its own.
- Type:
The meter foley measures with when none is given
- foley.audio.EXPORT_PCM_SUBTYPE: str = 'PCM_24'#
consumers of an export (
an) take PCM only, and 24 bits is the archive’s own depth.- Type:
What a non-PCM source (
FLOAT/DOUBLE) is exported as
- foley.audio.Meter#
a name from
mixing.loudness.METERS("numpy", the default;"ffmpeg_ebur128";"pyloudnorm") or any(samples, sample_rate) -> integrated LUFScallable (time on axis 0).- Type:
A loudness meter
- foley.audio.PCM_BITS: dict[str, int] = {'PCM_16': 16, 'PCM_24': 24, 'PCM_32': 32, 'PCM_S8': 8, 'PCM_U8': 8}#
The PCM subtypes, with their bit depths (what
is_lossless_conversion()reads).
- foley.audio.TRANSCODE_DTYPE: str = 'float64'#
wide enough that PCM up to 24 bits survives a decode/encode round trip sample-exact (FLAC archive -> WAV export keeps the samples).
- Type:
The decode dtype of
transcode()
- foley.audio.accent(samples, sample_rate, *, target_lufs=-30.0, start_db=35.0, tail_db=50.0, window_s=0.002, pre_s=0.0, fade_in_s=0.003, fade_out_s=0.04, max_len_s=None, peak_ceiling_dbfs=-3.0, min_block_s=0.4, meter=None)[source]#
An accent-ready clip: its transient at t=0, its decay kept, its level set.
A late transient makes a sound feel late on its cue, a trim that cuts the decay makes it clipped, and a one-shot shorter than one BS.1770 block is left unlevelled by
loudness_normalize(). In order:start: the first sample within
start_dbof the loudestwindow_swindow (onset_offset_s()), keepingpre_sbefore it;tail: up to the last window within
tail_dbof the loudest, so the decay stays; then at mostmax_len_s;fades:
fade_in_s(a declick) andfade_out_s;level: to
target_lufsbyloudness_gain_db()(silent and near-silent clips are not amplified; the sample peak stays underpeak_ceiling_dbfs); a clip shorter thanmin_block_sis measured padded with silence to one block, and the report says so (lufs_padded).
- Parameters:
samples (
ndarray) – Working array (mono or multichannel, time on axis 0).sample_rate (
int) – Sample rate in Hz.
- Returns:
the clip in
samples’ dtype, and anAccentReportmeasured on it. A silent clip comes back unchanged withgain_db0.- Return type:
tuple[ndarray,AccentReport]
Lazy dependencies:
numpy,mixing.loudness(the meter).
- foley.audio.container_of(data)[source]#
The
(format, subtype)of encodeddata, as lowercase / libsndfile names.Lazy dependency:
soundfile.
- foley.audio.duration_s(src)[source]#
src’s duration in seconds, read from its header (nothing is decoded).srcis a path or raw encodedbytes(a file-like object would be left moved, so decode it withload()instead).Lazy dependency:
soundfile.- Return type:
- foley.audio.encode(samples, sample_rate, *, fmt='flac', subtype='PCM_24')[source]#
Encode
samplesfully in memory and return the container bytes.This is the producer for the content-addressed byte store: default output is the FLAC archive form.
- Parameters:
- Return type:
- Returns:
The encoded audio as
bytes.
Lazy dependency:
soundfile.
- foley.audio.ensure_channels(samples, *, channels)[source]#
Coerce
samplesto exactlychannelschannels.Mappings: mono -> N by duplication; N -> mono by mean; N -> M (N != M, both > 1) by collapsing to mono then tiling up to M.
- Parameters:
samples (
ndarray) – Mono or multichannel working array.channels (
int) – Target channel count (must be >= 1).
- Return type:
ndarray- Returns:
A
(frames,)array whenchannels == 1, else a(frames, channels)array.- Raises:
ValueError – If
channels < 1.
Lazy dependency:
numpy(only for the up-mix / tile path).
- foley.audio.export_subtype(fmt, src_subtype)[source]#
The PCM subtype an export as
fmtuses forsrc_subtypesamples.The source’s own when it is PCM and
fmtholds it, elseEXPORT_PCM_SUBTYPEwhenfmtholds that, elsefmt’s default.Lazy dependency:
soundfile.- Return type:
- foley.audio.fade(samples, sample_rate, *, fade_in_s=0.01, fade_out_s=0.01, kind='linear')[source]#
Apply in/out gain ramps to
samples(a short declick by default).Ramp lengths are clamped to at most
len(samples) // 2so the in- and out-ramps never overlap on tiny inputs.- Parameters:
- Return type:
ndarray- Returns:
A new array with the fade envelope applied (input is not mutated).
Lazy dependency:
numpy.
- foley.audio.integrated_lufs(samples, sample_rate, *, min_block_s=0.4, meter=None)[source]#
Integrated loudness (LUFS, BS.1770-4) of
samples;-infwhen too short to gate.The one measurer
loudness_gain_db()and the WEAVE master share. The length guard usesmath.ceil(notint(round)) to mirror pyloudnorm’s float thresholdn < block_size*rateat every sample rate, including rates where0.4*sris not integral; identical toint(round)at all standard (÷5) rates.meter(defaultDEFAULT_METER) picks the BS.1770 implementation (seeMeter); the too-short guard stays here, outside the meter, so every meter sees the same clips.Lazy dependency:
mixing.loudness(seeloudness_component()).- Return type:
- foley.audio.is_lossless_conversion(src_subtype, dst_subtype)[source]#
Whether re-encoding
src_subtypesamples asdst_subtypekeeps them exactly.>>> is_lossless_conversion("PCM_16", "PCM_24"), is_lossless_conversion("FLOAT", "PCM_24") (True, False)
- Return type:
- foley.audio.limit_true_peak(samples, sample_rate, *, ceiling_dbtp=-1.0, oversample=None)[source]#
Attenuate
samplesso their inter-sample true peak sits at or belowceiling_dbtp.A static gain — the whole clip is turned down by one factor, never boosted — which is transparent and exactly what a Tier-0 range fault needs: after it, a flat-topped run or an over-ceiling peak is no longer at full scale. It is not a dynamic look-ahead limiter (that is
mixing.loudness.limit_peaks(), the WEAVE master’s default), so the distortion of a heavily clipped clip stays in the waveform; that is whyfoley.repairapplies it only to a clip just over the clipping gate.- Parameters:
samples (
ndarray) – Working array (mono or multichannel).sample_rate (
int) – Sample rate in Hz (passed to the true-peak measurement).ceiling_dbtp (
float) – The true-peak ceiling in dBTP (default: foley’s -1 dBTP).oversample (
Optional[int]) – Oversampling factor for the true-peak estimate (default: the QC table’strue_peak_oversample,None: mixing’s own).
- Return type:
- Returns:
(attenuated, gain_db).gain_dbis0.0— andsamplescomes back as is — when the clip is already under the ceiling or is silent.
Lazy dependency:
mixing[loudness](viafoley.qc.true_peak_dbtp()).
- foley.audio.load(src, *, target_sr=None, mono=False, dtype='float32')[source]#
Decode audio into a float working array.
srcmay be a filesystem path, raw encodedbytes(wrapped in aBytesIOso nothing touches disk), or any binary file-like object.- Parameters:
src (
Union[str,PathLike,bytes,BinaryIO]) – Path, raw bytes, or file-like object to decode.target_sr (
Optional[int]) – If given, resample the decoded audio to this rate (viaresample()); otherwise the native rate is returned.mono (
bool) – IfTrue, down-mix multichannel audio to mono.dtype (
str) – NumPy dtype string for the returned array (defaultfloat32).
- Return type:
- Returns:
A
(samples, sample_rate)tuple.sampleshas shape(frames,)(mono) or(frames, channels);sample_ratereflects any resample.
Lazy dependencies:
soundfile(andsoxrwhentarget_srdiffers).
- foley.audio.loudness_component()[source]#
The shared loudness component,
mixing.loudness(foley#91).Raises
ImportErrornaming the install line when it, or the scipy its meter and limiter filter with, is missing.
- foley.audio.loudness_gain_db(samples, sample_rate, *, target_lufs, peak_ceiling_dbfs=-1.0, short_peak_dbfs=None, max_boost_db=None, min_block_s=0.4, gate_floor_lufs=-70.0, silent_peak_dbfs=-80.0, meter=None)[source]#
The one loudness-gain rule:
(gain_db, measured_lufs)to bring a clip to a target.The policy for short, near-silent and high-crest clips lives here, and
loudness_normalize()andfoley.level.reference_gain_db()both apply it:a silent (peak at or under
silent_peak_dbfs) or non-finite clip:0.0;integrated loudness (BS.1770-4, gated) at or under
gate_floor_lufs: near-silent,0.0(flag, don’t amplify);a clip shorter than one gating block (
min_block_s) cannot be measured (measured = -inf): withshort_peak_dbfsit is levelled by its sample peak to that level, without it0.0;otherwise
target_lufs - measured;
and a non-zero gain is capped so the sample peak stays at or under
peak_ceiling_dbfs(a high-crest clip is held back) and, whenmax_boost_dbis given, the boost at that many dB.meterswaps the loudness measurer (seeMeter). Pure and deterministic.- Return type:
- Returns:
(gain_db, measured_lufs);measured_lufsis-inffor a clip too short to measure, a value at or underLUFS_GATE_FLOORfor a near-silent one.
Lazy dependencies:
mixing.loudness(+numpy).
- foley.audio.loudness_normalize(samples, sample_rate, *, target_lufs=-16.0, peak_ceiling_dbfs=-1.0, min_block_s=0.4, meter=None)[source]#
Loudness-normalize to
target_lufs, then keep it peak-safe.Integrated loudness is measured (ITU-R BS.1770-4 / EBU R128), the signal is scaled to
target_lufs, and finally attenuated so its sample peak sits at or belowpeak_ceiling_dbfs: the gain isloudness_gain_db(). Inputs are returned unchanged (flag them, don’t amplify) when silent or non-finite, near-silent (measured loudness at or belowLUFS_GATE_FLOOR), or shorter than one BS.1770 gating block (min_block_s) — which a gated meter cannot measure (routine for one-shots: clicks, blips, gunshots).- Parameters:
samples (
ndarray) – Working array (mono or multichannel, time on axis 0).sample_rate (
int) – Sample rate in Hz.target_lufs (
float) – Desired integrated loudness (default = foley’s podcast target).peak_ceiling_dbfs (
float) – Sample-peak ceiling (dBFS) applied after loudness normalization. Note this is a sample-peak limit, not an inter-sample true-peak (dBTP) limit — seefoley.qc.true_peak_dbtp()for the oversampled measurement.min_block_s (
float) – Minimum clip length (seconds) that can be loudness-measured; shorter clips are returned unchanged withmeasured = -inf.meter (
Union[str,Callable[[ndarray,int],float],None]) – AMeter(defaultDEFAULT_METER).
- Return type:
- Returns:
(normalized, measured_input_lufs). When the input is near-silent or too short to measure,normalizedis the unchanged input andmeasured_input_lufsis at or belowLUFS_GATE_FLOOR(-inffor the too-short case).
Lazy dependencies:
mixing.loudness(+numpy).
- foley.audio.onset_offset_s(samples, sample_rate, *, within_db=35.0, window_s=0.002)[source]#
Seconds to the first sample within
within_dbof the clip’s loudest window: where its transient starts (0.0for a silent clip).Sample-exact, unlike a hop-based trim (librosa’s starts up to a hop early).
>>> import numpy as np >>> x = np.zeros(1000); x[250:] = 0.5 >>> onset_offset_s(x, 1000) 0.25
- Return type:
- foley.audio.resample(samples, sample_rate, *, target_sr=48000, quality='HQ')[source]#
Resample
samplestotarget_sr(a no-op when already there).- Parameters:
- Return type:
ndarray- Returns:
The resampled array (the input unchanged when
sample_rate == target_sr). dtype is preserved by soxr.
Lazy dependency:
soxr.
- foley.audio.resolve_meter(meter=None)[source]#
meter, orDEFAULT_METERforNone; an unknown name raisesValueError.Callers that read a meter error as “not measurable” resolve first, so a typo is never mistaken for an unreadable clip. A name is checked only when the component is installed (measuring reports a missing one).
- foley.audio.save(samples, sample_rate, dst, *, fmt='flac', subtype='PCM_24')[source]#
Write
samplestodstasfmt/subtype(default = FLAC archive).- Parameters:
samples (
ndarray) – The working array to write (shape(frames,)or(frames, channels)).sample_rate (
int) – Sample rate in Hz.dst (
Union[str,PathLike,BinaryIO]) – Destination path or writable binary file-like object.fmt (
str) – Container/codec name (case-insensitive; passed to libsndfile).subtype (
str) – Sample subtype (e.g.PCM_24,PCM_16,FLOAT).
- Return type:
Lazy dependency:
soundfile.
- foley.audio.to_mono(samples)[source]#
Down-mix to mono by averaging channels; 1-D input passes through.
- Parameters:
samples (
ndarray) – Mono(frames,)or multichannel(frames, channels)array.- Return type:
ndarray- Returns:
A 1-D mono array (dtype preserved).
- foley.audio.to_working(samples, sample_rate, *, mono=True, target_sr=48000, dtype='float32')[source]#
Produce the canonical CLAP/QC working array from an arbitrary clip.
Down-mixes (when
mono), resamples totarget_sr, and casts todtype— thefloat32@ 48 kHz mono array every embedder/tagger/QC check consumes.- Parameters:
- Return type:
ndarray- Returns:
The canonical working array.
Lazy dependency:
soxr(only whensample_rate != target_sr).
- foley.audio.transcode(data, *, fmt, subtype=None, dtype='float64')[source]#
Re-encode
dataasfmtwithsubtype(default:export_subtype()).dataalready infmtand that subtype comes back unchanged, byte for byte. Otherwise it is decoded atdtypeand encoded: a FLACPCM_24archive gives a sample-exactPCM_24WAV; aFLOATsource givesPCM_24(quantised: seeis_lossless_conversion()).Lazy dependency:
soundfile.- Return type:
- foley.audio.trim_silence(samples, sample_rate, *, top_db=30.0)[source]#
Strip leading/trailing silence, returning the clip and its kept span.
Silence detection runs on a transient mono down-mix (so librosa’s time-last convention never clashes with foley’s time-first
(frames, channels)layout); the returned sample indices then slice the original array along axis 0, preserving its channel layout.- Parameters:
- Return type:
- Returns:
(trimmed, (start_sample, end_sample)). On all-silent (or otherwise degenerate) input the original array is returned unchanged with a full-length span(0, len(samples)).
Lazy dependency:
librosa.