[effects]docs
fx reference / fx.sound

Sound

A video's sound is a list of Sounds: audio files, or samples made by code, each placed at a time on the timeline and optionally trimmed, faded, sped up, reversed, filtered or automated. The renderer mixes them into one stereo track and puts it in the MP4; the editor plays the same mix. The second half of this page is the other direction: reading the hits out of a music file so the pictures can be cut to them.

Note: Decoding files, mixing and analysis run ffmpeg and are not part of the browser build, so most of this page is code. The pieces that are plain arithmetic (the limiter's curve, the filters) run below, and everything on the synth and music page can be played.

A sound#

Sound :: struct {
	name:     string, // shown in the editor; the key in timing.json when moved there
	file:     string, // relative to the project
	gen:      Generator, // or samples made by code (fx.whoosh, fx.boom …), dur long
	at:       f32, // video time where it starts
	from:     f32, // seconds into the file where playing starts
	dur:      f32, // how long it plays, in video time; 0 = until the file ends
	loop:     bool, // start over at the end of the file (and play to the video's end when dur is 0)
	volume:   Maybe(f32), // gain, 1 = unchanged
	pan:      f32, // -1 left … 1 right
	fade_in:  f32, // seconds
	fade_out: f32,
	speed:    f32, // playback rate, 0 = 1; changes the pitch like tape unless stretch
	stretch:  bool, // keep the pitch when speed ≠ 1
	reverse:  bool, // play the file backwards (from then counts from the file's end)
	lowpass:  f32, // Hz, 0 = off
	highpass: f32, // Hz, 0 = off
	// Automation, read every few milliseconds at video time t; nil = none.
	gain:     proc(t: f32) -> f32, // volume multiplier: ducking, swells, gaps
	rate:     proc(t: f32) -> f32, // speed multiplier: tape stops, slow-downs
	cutoff:   proc(t: f32) -> f32, // low-pass cutoff in Hz, 0 = open: muffled until the drop
}

Sounds go in Video.sounds. Like scenes and cues, the table must be a global:

SOUNDS := [?]fx.Sound {
	{name = "music", file = "assets/song.wav", from = 33.5, dur = 30, fade_out = 1, cutoff = muffled},
	{name = "boom", gen = fx.boom, at = 5.56, dur = 2, volume = 0.5},
	{name = "swell", file = "assets/crash.wav", at = 3, reverse = true, speed = 0.8},
	{name = "talk", file = "assets/interview.mp4", from = 61, at = 9, dur = 3, stretch = true, speed = 1.2},
}

@(export)
effects_video :: proc() -> ^fx.Video {
	return fx.video({name = "Spot", scenes = SCENES[:], sounds = SOUNDS[:]})
}

Video.audio = "audio/mix.wav" is short for one sound: fx.video puts Sound{name = "audio", file = "audio/mix.wav"} in front of the others, so the file plays from the start of the video until it ends. Use it when the soundtrack is finished elsewhere; use sounds for everything else. Both can be set.

Give every sound its own name. The editor shows it on the sound's bar, and when you drag a sound there its new at is saved in the project's timing.json under that name.

What plays#

Field Meaning
file An audio file, or anything else ffmpeg decodes: a video's soundtrack works too. The path is relative to the project directory. The file is decoded once per process, whole, to stereo 32-bit float at 48 kHz (about 23 MB of memory per minute).
gen Instead of a file, a Generator: a procedure that fills a buffer with samples. fx.whoosh, fx.boom, fx.riser, fx.click and fx.sub_drop are built in, and a whole score can be one (synth and music). It is called once, with a buffer dur seconds long, and the result is kept. Without a dur it gets 1 second.
at Video time of the first sample, in seconds.
from Where in the file playing starts, in seconds of the file.
dur How long the sound plays, in seconds of video time. 0 means the rest of the file.
loop At the end of the file, start again from its beginning. With dur = 0 a looped sound plays to the end of the video.
Sample    :: [2]f32                    // left, right
Generator :: #type proc(out: []Sample) // fills out with sound (stereo at RATE); its length is the sound's
RATE      :: 48000

Changing it#

Field Meaning
volume Linear gain. It is a Maybe(f32): leaving it out means 1, and volume = 0 really is silence.
pan -1..1. Turning right lowers the left channel (pan = 0.5 halves it, pan = 1 silences it) and leaves the right one as it is; channels are not moved across.
fade_in, fade_out Seconds of linear fade at the start and before the end of the sound's span.
speed Playback rate; 0 means 1. On its own it works like tape: speed = 0.5 is twice as long and an octave lower. A generator is asked for dur × speed seconds, so it still fills its span.
stretch With speed, keeps the pitch: the file is time-stretched by ffmpeg's atempo filter while decoding. It applies to files, not generators.
reverse Plays the file backwards. from then counts from the file's end, so from = 0 starts with its last sample.
lowpass, highpass Fixed filters in Hz (second order, 12 dB per octave). 0 is off.

dur is always video time and from always file time, whatever the speed: {from = 61, dur = 3, speed = 1.2} plays 3 seconds of video, covering 3.6 seconds of the file from second 61.

For each sample the mixer reads the source, runs highpass, lowpass and the automated cutoff in that order, multiplies by volume, gain and the fades, and applies pan.

Automation#

gain, rate and cutoff are procedures of video time, like everything else that moves:

// Low-pass until the drop at 5.56 s, then open.
muffled :: proc(t: f32) -> f32 {return t < 5.56 ? 700 : 0}

// The music steps back while someone talks from 9 s to 12 s.
under_voice :: proc(t: f32) -> f32 {return 1 - 0.7 * fx.win(t, 9, 12, 0.3, 0.5)}

// The record slows to a halt between 20 s and 21.2 s.
tape_stop :: proc(t: f32) -> f32 {return 1 - fx.ep(t, 20, 21.2, fx.ease_in)}

SOUNDS := [?]fx.Sound {
	{name = "music", file = "assets/song.wav", dur = 21.2, fade_out = 0.05, gain = under_voice, rate = tape_stop, cutoff = muffled},
}
Field Returns Use
gain A volume multiplier, on top of volume. Ducking under a voice, swells, gaps of silence.
rate A speed multiplier, on top of speed. Negative values count as 0. Tape stops, slow-downs, wind-ups. Always changes the pitch.
cutoff A low-pass cutoff in Hz; 0 (or anything above 21.6 kHz) turns the filter off. The muffled intro that opens on the drop, a build closing down.

The mixer works in blocks of 64 samples (1.3 ms). It asks gain at the edges of each block and interpolates between the two answers, and asks rate and cutoff once at the start of each block. So automation can be as fast as you like, and it should be cheap: it is called 750 times per second of sound.

t is video time, not time since the sound started. If a sound gets moved in the editor, its automation stays where it is; write it against a cue (fx.cue("drop")) when the two should move together.

Note: A stopped sound is not silent. While rate returns 0 the mixer keeps adding the one sample it stopped on, a constant offset in the mix. End the sound where the rate reaches 0 (dur, with a short fade_out, as above), or bring gain to 0 with it. dur is not stretched by rate: a slowed sound simply gets less far into its file.

The browser build has no mixer, so the two sounds below do by hand what the mixer does with cutoff and rate. sound_loop is two bars of a beat made with the synth, standing in for a file.

4.00 ssound-muffled
sound_muffled :: proc(out: []fx.Sample) {
    // What you would give Sound.cutoff: 700 Hz until the drop at 2 s, then open.
    muffled :: proc(t: f32) -> f32 {return t < 2 ? 700 : 0}

    sound_loop(out) // two bars of a beat, standing in for the file
    // What the mixer does with it: one low-pass, set again every 64 samples.
    lp: fx.Biquad
    for &x, i in out {
        if i % 64 == 0 do fx.biquad_set(&lp, .Low, muffled(f32(i) / fx.RATE))
        if lp.on do x = fx.biquad_run(&lp, x)
    }
}
4.00 ssound-tape-stop
sound_tape_stop :: proc(out: []fx.Sample) {
    // What you would give Sound.rate: full speed until 2 s, stopped at 3.4 s.
    tape_stop :: proc(t: f32) -> f32 {return 1 - fx.ep(t, 2, 3.4, fx.ease_in)}

    src := make([]fx.Sample, len(out))
    defer delete(src)
    sound_loop(src)
    // What the mixer does with it: the place it reads from moves by rate(t) a sample.
    pos, rate: f64
    for &x, i in out {
        t := f32(i) / fx.RATE
        if i % 64 == 0 do rate = f64(tape_stop(t))
        j := int(pos)
        x = src[j] + (src[j + 1] - src[j]) * f32(pos - f64(j)) // between two samples (the mixer uses four)
        x *= fx.clamp01((3.4 - t) / 0.05) // dur = 3.4, fade_out = 0.05
        pos += rate
    }
}

The mix#

mixdown    :: proc(v: ^Video, t0, t1: f32, allocator := context.allocator) -> []Sample
sound_span :: proc(v: ^Video, s: ^Sound) -> (start, dur: f32)
soft_clip  :: proc(x: f32) -> f32

mixdown is what the renderers call: it adds every sound of the video into a stereo float buffer covering [t0, t1) of video time, at 48 kHz, and then passes each channel of each sample through soft_clip. The buffer is exactly as long as the span asked for; a sound running past the end of the video is cut there. Sources are read at fractional positions with 4-point Hermite interpolation, which is what makes speed and rate sound clean.

soft_clip is the limiter on the sum. It leaves everything up to 0.8 alone and bends what is above it smoothly towards 0.89, which is -1 dBFS: the mix can never reach full scale, and there is room left for the overshoot of the AAC encoder. It is a safety net, not a mastering stage: a mix that lives above 0.8 is being distorted. Turn the sounds down, or limit a score before it gets here.

A frame of the sound-soft-clip demo
2.48 / 4.00 ssound-soft-clip
sound_soft_clip :: proc(s: fx.Shot) {
    fx.backdrop(.Night)
    gain := knob("gain", 1.3, 0.4, 2) // how loud the sounds are when added up; 1 = full scale
    mid, one := f32(540), f32(230) // the line of silence, and the height of 1.0
    for level in ([?]f32{0.8, 0.89}) {
        fx.hline(200, mid - one * level, 1300, fx.theme.nb, 2)
        fx.hline(200, mid + one * level, 1300, fx.theme.nb, 2)
    }
    fx.label("0.8", {1530, mid - one * 0.8 + 22}, fx.mono(30), fx.theme.nm, {0, 0.5})
    fx.label("0.89 = -1 dBFS", {1530, mid - one * 0.89 - 22}, fx.mono(30), fx.theme.nm, {0, 0.5})
    a, b, a0, b0: fx.Vec2
    for i in 0 ..= 325 {
        x := gain * math.sin((f32(i) / 325 * 2.5 - s.p) * math.TAU)
        a0, b0 = a, b
        a = {200 + f32(i) * 4, mid - one * x} // the sum of the sounds
        b = {200 + f32(i) * 4, mid - one * fx.soft_clip(x)} // what is written to the file
        if i > 0 {
            fx.line(a0, a, fx.theme.ns, 3)
            fx.line(b0, b, fx.theme.na, 6)
        }
    }
}

sound_span tells you when a sound plays, in video time: at, and either its dur, the time to the end of the video for a loop without one, or what is left of the file at its speed. It does not know about rate.

Hearing it without rendering#

build/effects mix projects/spot                       # → projects/spot/.effects/spot.wav
build/effects mix projects/spot --from 4 --to 9 --out /tmp/drop.wav

effects mix runs the same mixdown and writes a 32-bit float WAV, printing how many sounds it mixed, how long it took and the peak in dB. A peak above -1.9 dB (0.8) means the soft limiter was bending the signal. effects render does the same for the span it renders and has ffmpeg encode the result as AAC at 256 kbit/s.

Samples in your own hands#

pcm       :: proc(path: string, tempo: f32 = 1, reverse := false) -> []Sample
write_wav :: proc(path: string, s: []Sample) -> bool

pcm returns a file's audio as stereo samples at RATE, the same decoded copy the mixer uses (so do not change or free it). tempo other than 1 time-stretches it keeping the pitch, reverse turns it around. It returns nil and prints a message when the file is missing or cannot be decoded. Use it to draw a waveform:

wave :: proc(s: fx.Shot) {
	src := fx.pcm("assets/song.wav")
	i0 := int((33.5 + s.t) * fx.RATE) // the sample playing now: the sound's from, plus video time
	for x in 0 ..< 960 {
		i := i0 + (x - 480) * 8
		if i < 0 || i >= len(src) do continue
		h := 300 * abs(src[i][0] + src[i][1]) / 2
		fx.rect({f32(x) * 2, 540 - h, 2, 2 * h}, fx.theme.na)
	}
}

write_wav writes samples as a 32-bit float stereo WAV at 48 kHz and reports whether it could.

Filters#

Filter :: enum {Low, High, Band} // Band: constant 0 dB peak

biquad_set :: proc(q: ^Biquad, kind: Filter, hz: f32, Q: f32 = 0.7071)
biquad_run :: proc(q: ^Biquad, x: Sample) -> Sample

The second-order filter the mixer, the one-shot generators and the analysis share is public, for generators of your own. A zero Biquad is a filter that is off; biquad_set gives it a response without touching its state, so it can be called again while the sound runs to move the cutoff. hz <= 0, or at 21.6 kHz and above, turns it off: check q.on before running it, as the first sound on this page does. For cutoffs that move quickly, the synth's Svf is the stable one.

Finding the hits in a file#

To cut to music you need to know where its hits are. Three procedures read that out of an audio file; each result is computed once and cached.

Band :: enum {
	Bass, // kicks and 808s (below ~120 Hz)
	Full,
	High, // snares, claps, hats (above ~5 kHz)
}

Onset :: struct {
	t:        f32, // seconds into the file
	strength: f32, // how sharp the attack is (jump in log energy; drops: energy ratio)
	level:    f32, // loudness right after it, 0..1 of the file's loudest
}

onsets :: proc(file: string, band := Band.Bass, threshold: f32 = 0.35) -> []Onset
drops  :: proc(file: string, band := Band.Bass) -> []Onset

onsets finds attacks. It measures the loudness of one band of the file every 10 ms and reports the moments where that loudness jumps: the default .Bass listens below about 120 Hz and finds kicks and 808s, .High listens above about 5 kHz for snares, claps and hats, .Full takes the whole signal. threshold is the smallest jump (in the natural log of the energy) that counts: 0.35 finds most hits, 1 only the hard ones. Quiet attacks, below 12% of the file's loudest moment, are ignored, and of two hits closer than 120 ms the sharper one is kept. Times are in steps of 10 ms.

drops finds the few places where the band's energy jumps and stays up: the beat coming back in. It compares the 1.5 seconds after each moment with the 1.5 seconds before, keeps the places where the energy is at least 2.5 times higher and at least 40% of the loudest such stretch in the file, at most one within 4 seconds, and moves each onto the strongest hit within 0.4 seconds. In its results strength is that energy ratio. A file shorter than 3 seconds has none.

SPECTRUM_BANDS :: 16

spectrum    :: proc(file: string) -> [][SPECTRUM_BANDS]f32
spectrum_at :: proc(file: string, t: f32) -> [SPECTRUM_BANDS]f32

spectrum is the loudness of 16 bands, spaced evenly in pitch from 40 Hz to 12 kHz, for every 10 ms of the file. Each band is scaled on its own: 1 is that band's loud end (its 99th percentile), 0 is 42 dB below. Values fall by at most a tenth per step, so bars drawn from them drop smoothly instead of flickering. spectrum_at is the row at t seconds into the file:

bands := fx.spectrum_at("assets/song.wav", 33.5 + s.t)
for v, i in bands {
	h := 600 * v
	fx.rrect({400 + f32(i) * 70, 840 - h, 50, h}, 8, fx.theme.na)
}

Results are slices owned by the library: read them, do not free them. They are kept in memory for the process and written to .effects/analysis/ in the project, keyed by the file's path, size and modification time and by the arguments, so the first frame after changing a song takes a moment (the file is decoded and filtered) and every run after that reads a small file. HOP :: 480 is the size of an analysis step in samples.

build/effects beats assets/song.wav                    # --band bass, --threshold 0.35
build/effects beats assets/song.wav --band high --threshold 0.6

effects beats prints what onsets and drops find (time, strength and level of every hit, the most common gap between hits as a tempo guess, and the drops), which is the quickest way to pick a from, a threshold, and the moment a title should land on.

From hits to pictures#

Onset times are seconds into the file. fx.times moves them onto the video's timeline, the same way the Sound that plays the file is placed (from, at), and can keep only the strong or loud ones. The result is a plain []f32 of beat times, which is what fx.pulse and fx.beat take:

TRACK :: "assets/song.wav"
FROM  :: 33.5 // where in the song the video starts

BEATS: []f32

@(export)
effects_video :: proc() -> ^fx.Video {
	BEATS = fx.times(fx.onsets(TRACK, .Bass), from = FROM, to = FROM + 30)
	return fx.video({
		name = "Edit",
		sounds = SOUNDS[:], // {name = "music", file = TRACK, from = FROM, dur = 30}
		scenes = SCENES[:],
		marks = BEATS,
	})
}

title :: proc(s: fx.Shot) {
	k := fx.pulse(BEATS, s.t) // 1 on every kick, falling to 0
	if fx.group({s = 1 + 0.04 * k, origin = {960, 540}}) {
		fx.caption("LOUD", {960, 540}, 220, fx.theme.nt, {0.5, 0.5})
	}
}

fx.times allocates its result, so call it once and keep it, as here, not once a frame.

Video.marks is a list of times the editor draws on its ruler; scenes, cues and sounds snap to them when dragged. Putting the beats there turns the timeline into a grid of the song. The edit page has the rest: pulse, beat, hit, shakes, flashes and transitions.

Reference#

Name What it is
RATE 48000: the sample rate of everything.
Sample [2]f32, left and right.
Generator proc(out: []Sample): fills a buffer with sound.
Sound A file or generator on the timeline, with its changes and automation.
Video.audio A soundtrack file from 0: short for one Sound named "audio".
Video.sounds The video's sounds.
Video.marks Times the editor shows on its ruler and snaps to.
mixdown(v, t0, t1, allocator) The video's sounds mixed over [t0, t1), soft-limited.
sound_span(v, s) When a sound plays in video time: start and length.
soft_clip(x) The mix's limiter: unchanged to 0.8, never above 0.89.
pcm(path, tempo, reverse) A file's audio as samples at RATE, decoded once.
write_wav(path, s) Writes a 32-bit float stereo WAV.
Biquad, Filter, biquad_set(q, kind, hz, Q), biquad_run(q, x) A second-order low-, high- or band-pass filter.
Band .Bass, .Full, .High: what onsets and drops listen to.
Onset A hit: t, strength, level.
onsets(file, band, threshold) The attacks in a file.
drops(file, band) Where the energy jumps and stays up.
SPECTRUM_BANDS, spectrum(file), spectrum_at(file, t) 16 bands of loudness, 0..1, every 10 ms.
HOP 480 samples: one analysis step, 10 ms.
effects mix <project> Writes the mix as a WAV.
effects beats <file> Prints hits, a tempo guess and drops.

Edit this page · Plain Markdown · All docs in one file