# Cutting to music


An edit that follows its music needs two things: the times of the hits, and something that happens on them. This page covers both. A beat here is nothing more than a time in seconds, and a track's beats are a sorted `[]f32`. Everything else turns "how long since the last one" into a number between 0 and 1 that you multiply into a scale, an offset, an opacity or a filter amount.

## Where beats come from

In a film the list comes from the music itself. [`onsets`](/docs/sound/) finds the hits in an audio file, and `times` moves them from the file's clock to the video's:

```odin
times :: proc(hits: []Onset, from: f32 = 0, at: f32 = 0, to: f32 = max(f32), strength: f32 = 0, level: f32 = 0) -> []f32
```

The file plays from `from` seconds into it at video time `at`, so a hit at file time `h` lands at `h - from + at`. Only hits inside `[from, to)` of the file are kept, and of those only the ones whose `strength` (how sharp the attack is) and `level` (how loud, 0..1 of the file's loudest) are at least what you ask for. Raise `strength` to keep only the hard hits.

The result is allocated with `context.allocator` and nothing frees it, so build the list once and keep it, not once per frame:

```odin
KICKS: []f32
kicks_once: sync.Once

kicks :: proc() -> []f32 {
	sync.once_do(&kicks_once, proc() {
		found := fx.onsets("assets/song.wav", .Bass)   // analysed once, cached under .effects/analysis
		KICKS = fx.times(found, from = 33.5, at = 0)   // the song starts 33.5 s in, at the start of the video
	})
	return KICKS
}
```

Put the same list in `Video.marks` and the editor draws it on its ruler and snaps scenes to it.

Audio analysis reads files, so it does not exist in the browser build. The demos on this page write their beats by hand, usually one every half second (120 bpm). A list is a list: code that works on these works on analysed ones, and a score written in code (see [/docs/music/](/docs/music/)) already has its note times as lists.

## Beat and pulse

```odin
beat  :: proc(beats: []f32, t: f32) -> (i: int, since: f32)
pulse :: proc(beats: []f32, t: f32, dur: f32 = 0.25, e: Ease = ease_out) -> f32
hit   :: proc(t, t0, dur: f32, e: Ease = ease_out) -> f32
```

`beat` finds the last beat at or before `t` with a binary search: `i` is its index and `since` the seconds since it. Before the first beat `i` is -1 and `since` is `t` itself. Use the index to step through things (which card is lit, which shot of a list is showing) and `since` to animate inside the beat.

`pulse` is the value you will use most: 1 on each beat, falling to 0 over `dur` seconds along the ease, and 0 before the first beat. With the default `ease_out` it drops quickly and settles gently, like a drum. A `dur` longer than the gap between beats never reaches 0; the next beat sets it back to 1.

`hit` is `pulse` for a single moment `t0`: 0 before it, 1 at it, 0 again `dur` later. Use it for the one drop of a piece or for the first frame of a scene (`fx.hit(s.t, s.start, 0.5)`).

```odin
edit_pulse :: proc(s: fx.Shot) {
	fx.backdrop(.Night)
	beats := [?]f32{0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5} // written by hand here; fx.onsets finds them in a film
	i, since := fx.beat(beats[:], s.lt) // which beat we are in, and for how long
	k := fx.pulse(beats[:], s.lt, knob("dur", 0.25, 0.05, 0.5)) // 1 on the beat, 0 after dur
	for _, j in beats {
		c := fx.Vec2{400 + f32(j) * 160, 800}
		fx.circle(c, 18, j == i ? fx.theme.na : fx.theme.nb)
	}
	fx.circle({960, 420}, 130 + 90 * k, fx.theme.nt)
	fx.label(fmt.tprintf("beat %d + %.2f s	pulse %.2f", i, since, k), {960, 930}, fx.mono(36), fx.theme.nm, {0.5, 0.5})
}
```

The list must be sorted, as `beat` searches it. `pulse` and `hit` return plain numbers, so combining them is arithmetic: `0.6 * fx.pulse(kicks, t) + 0.4 * fx.pulse(snares, t, 0.12)`.

## Flash

```odin
flash :: proc(a: f32, c: Color = 0xffffffff)
```

Covers the stage in color `c` at opacity `a` (0..1). It draws nothing below an opacity of 0.003, so it costs nothing while it is off. Call it last in a scene so it lands on top. Driven by `hit` it is the white frame on a drop; driven by `ep` it is a fade from or to a color.

```odin
edit_flash :: proc(s: fx.Shot) {
	fx.backdrop(.Night)
	DROP :: 1.5
	if s.lt < DROP {
		fx.label("wait for it", {960, 540}, fx.mono(48), fx.theme.ns, {0.5, 0.5})
	} else {
		fx.caption("the drop", {960, 540}, 260, fx.theme.nt, {0.5, 0.5})
	}
	// a white frame on the hit, gone half a second later
	fx.flash(fx.hit(s.lt, DROP, 0.5) * knob("amount", 0.9, 0, 1), fx.theme.nt)
	// the same procedure fades a scene from and to black
	fx.flash(1 - fx.ep(s.lt, 0, 0.4), 0xff000000)
	fx.flash(fx.ep(s.lt, 3.5, 3.95, fx.ease_in), 0xff000000)
}
```

## Shake

```odin
shake  :: proc(t: f32, amount: f32, freq: f32 = 14, seed: f32 = 0) -> Vec2
noise1 :: proc(x: f32, seed: f32 = 0) -> f32
```

`shake` returns an offset in pixels: up to `amount` in each direction, changing direction `freq` times a second. It is a pure function of `t`, so the same frame always shakes the same way. Give two things different `seed`s to shake them independently. An `amount` of 0 returns `{}` without doing any work, so multiplying the amount by a pulse is cheap while the pulse is 0.

Put the offset into a group's `x` and `y` to shake what is drawn inside it:

```odin
edit_shake :: proc(s: fx.Shot) {
	fx.backdrop(.Night)
	beats := [?]f32{0, 1, 2, 3}
	k := fx.pulse(beats[:], s.lt, 0.5) // the shake dies away after each beat
	off := fx.shake(s.t, knob("amount", 40, 0, 120) * k, knob("freq", 14, 2, 40))
	if fx.group({x = off.x, y = off.y}) {
		fx.rrect({560, 290, 800, 500}, 40, fx.theme.nt)
		fx.caption("shake", {960, 540}, 200, fx.theme.night, {0.5, 0.5})
	}
}
```

`noise1` is what `shake` is made of: smooth value noise in -1..1, one new random value per whole step of `x`, eased between them. It is jumpier than [`wob`](/docs/anim/#random-but-the-same-every-time), which drifts; use `noise1` for hand-held jitter and flicker, `wob` for slow floating.

## Camera

```odin
camera :: proc(zoom: f32 = 1, offset := Vec2{}, rot: f32 = 0) -> Xf
```

Returns the `Xf` of a camera over the whole stage: scaled by `zoom` and rotated by `rot` degrees around the stage's center, then moved by `offset` in stage pixels. Wrap a scene in `fx.group(fx.camera(…))` and everything in it moves together. A punch-in on the beat is `zoom = 1 + 0.1 * pulse`; a hand-held look is a small `shake` as the offset.

```odin
edit_camera :: proc(s: fx.Shot) {
	beats := [?]f32{0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5}
	i, _ := fx.beat(beats[:], s.lt)
	k := fx.pulse(beats[:], s.lt, 0.4)
	zoom := 1 + knob("punch", 0.12, 0, 0.4) * k // a punch-in on every beat
	tilt := knob("tilt", 2, 0, 10) * k * (i % 2 == 0 ? 1 : -1) // leaning left, then right
	if fx.group(fx.camera(zoom, fx.shake(s.t, 10 * k), tilt)) {
		fx.backdrop(.Night)
		for j in 0 ..< 4 {
			r := fx.Rect{270 + f32(j) * 360, 340, 300, 400}
			fx.rrect(r, 28, j == i % 4 ? fx.theme.na : fx.theme.nt)
		}
	}
}
```

The background has to be inside the group, or it stays still while the picture moves. Rotating or shaking uncovers the corners of the stage, so keep the zoom a little above 1 whenever you do either. To move a whole film instead of one scene, return the camera from [`Video.master`](/docs/scenes/).

## Letterbox

```odin
letterbox :: proc(amount: f32 = 1, ratio: f32 = 2.39, c: Color = 0xff000000)
```

Two bars, top and bottom, that crop the stage to the aspect `ratio` (width over height; 2.39 is CinemaScope, 1.85 the flat cinema format). `amount` slides them in from 0 (no bars) to 1 (fully in), so animating it opens or closes the frame. A ratio narrower than the stage's own draws nothing. Call it after the picture; for bars over a whole film, call it in `Video.overlay`.

```odin
edit_letterbox :: proc(s: fx.Shot) {
	fx.image(fx.load_image("assets/frame.jpg"), fx.stage(), zoom = 1 + 0.04 * s.p)
	// bars slide in, hold, and leave again before the loop
	amount := fx.ep(s.lt, 0.5, 1.3, fx.ease_in_out) - fx.ep(s.lt, 3.8, 4.6, fx.ease_in_out)
	fx.letterbox(amount, knob("ratio", 2.39, 1.78, 3.5))
}
```

## Transitions

A transition happens between two scenes that are both on screen for a moment. You make that moment by letting the scenes overlap on the timeline: start the next scene `dur` seconds before this one ends. Each scene then wraps what it draws in a group whose `Xf` comes from `transition`:

```odin
transition :: proc(s: Shot, enter, leave: Transition, dur: f32 = 0.4) -> Xf
```

For the first `dur` seconds of the scene it returns the incoming half of `enter`, for the last `dur` seconds the outgoing half of `leave`, and `{}` (no change) in between. `.Cut` on either side means nothing happens there. The two scenes of a pair must name the same kind, this one as its `leave` and the next one as its `enter`, and use the same `dur` as the overlap:

```odin
SCENES := [?]fx.Scene {
	{name = "a", start = 0.0, dur = 2.5, draw = a},
	{name = "b", start = 2.0, dur = 2.5, draw = b}, // starts 0.5 s before a ends
}

a :: proc(s: fx.Shot) {
	if fx.group(fx.transition(s, .Cut, .Whip_Left, 0.5)) {
		// everything a draws, background included
	}
}
b :: proc(s: fx.Shot) {
	if fx.group(fx.transition(s, .Whip_Left, .Whip_Up, 0.5)) {
		// everything b draws
	}
}
```

The demo below does the same inside one procedure, because a demo is a single scene: it builds the `Shot` of each entry by hand, as the renderer does for a scene list, and draws the first scene a second time at the end so the loop closes.

```odin
edit_transition :: proc(s: fx.Shot) {
	D :: 0.5 // every scene starts D before the one before it ends
	list := [?]struct {
		name:		 string,
		start:		f32,
		enter, leave: fx.Transition,
	}{{"A", -D, .Whip_Up, .Whip_Left}, {"B", 2 - D, .Whip_Left, .Whip_Up}, {"A", 4 - D, .Whip_Up, .Whip_Left}}
	for sc in list {
		// what the renderer does with a scene list: a Shot for each scene that is on
		shot := fx.Shot{t = s.t, lt = s.t - sc.start, start = sc.start, dur = 2 + D}
		if shot.lt < 0 || shot.lt >= shot.dur do continue
		// what a scene does: everything it draws goes inside the transition's group
		if fx.group(fx.transition(shot, sc.enter, sc.leave, D)) {
			fx.backdrop(sc.name == "A" ? .Night : .Paper)
			fx.caption(sc.name, {960, 540}, 520, sc.name == "A" ? fx.theme.nt : fx.theme.ink, {0.5, 0.5})
		}
	}
}
```

```odin
Transition :: enum {
	Cut,
	Fade,
	Whip_Left,
	Whip_Right,
	Whip_Up,
	Whip_Down,
	Zoom,
	Spin,
	Glitch,
	Blur,
}
```

| Kind | What happens across the overlap |
| --- | --- |
| `Cut` | Nothing. The scenes are drawn as they are. |
| `Fade` | The incoming scene's opacity goes from 0 to 1 over the outgoing one, which does not change. The incoming scene must come later in the scene list, so it is drawn on top. |
| `Whip_Left`, `Whip_Right`, `Whip_Up`, `Whip_Down` | Both scenes slide a full stage width (or height) in that direction, side by side, eased in and out. Each is motion-blurred along the move by 0.35 of the distance it travels per frame, at most 140 px. |
| `Zoom` | First half: the outgoing scene rushes toward the viewer (scale 1 to 2.6) under a radial blur. Second half: the incoming one settles from scale 1.9 to 1 as the blur clears. |
| `Spin` | First half: the outgoing scene turns a quarter turn clockwise, growing to 1.4 and blurring. Second half: the incoming one arrives from a quarter turn the other way. The corners a turning scene uncovers show the video's `background`. |
| `Glitch` | The [`glitch`](/docs/post/) filter (slices and color split) and a sideways jitter of up to 20 px rise to the middle, where the picture switches, and fall again. |
| `Blur` | The outgoing scene goes out of focus (blur up to 40), brightening by up to 40% and growing by 6%; the picture switches in the middle and the incoming one comes back into focus. |

`Zoom`, `Spin`, `Glitch` and `Blur` are hidden cuts: the outgoing scene is drawn for the first half of the overlap only, the incoming one for the second half only. The whips and `Fade` show both scenes all the way through.

Each card below names the transition that brought it in. `dur` is both the overlap and the length of the transition.

```odin
edit_transitions :: proc(s: fx.Shot) {
	kinds := [?]fx.Transition{.Fade, .Whip_Left, .Whip_Right, .Whip_Up, .Whip_Down, .Zoom, .Spin, .Glitch, .Blur}
	D := knob("dur", 0.4, 0.15, 1.2)
	EVERY :: 1.4
	for k in 0 ..= len(kinds) {
		enter := kinds[(k + len(kinds) - 1) % len(kinds)] // the same kind as the scene before leaves with
		leave := kinds[k % len(kinds)]
		shot := fx.Shot{t = s.t, lt = s.t - (f32(k) * EVERY - D), dur = EVERY + D}
		if shot.lt < 0 || shot.lt >= shot.dur do continue
		if fx.group(fx.transition(shot, enter, leave, D)) {
			paper := k % 3 == 1
			if k % 3 == 2 do fx.rect(fx.stage(), fx.theme.na)
			else do fx.backdrop(paper ? .Paper : .Night)
			ink := paper ? fx.theme.ink : fx.theme.nt
			fx.label("came in with", {960, 376}, fx.caps(30, 0.16), fx.alpha(ink, 0.6), {0.5, 0.5})
			fx.caption(fmt.tprint(enter), {960, 540}, 220, ink, {0.5, 0.5})
		}
	}
}
```

The blurred kinds draw the scene into a layer first, and `Zoom` and `Glitch` also run a pixel filter over it, so the frames inside a transition cost more than the ones around it (a filter that reads each pixel a few times is about 0.05 s per 1080p frame on one CPU thread). Outside its two windows `transition` returns `{}` and the group costs nothing.

```odin
trans_xf :: proc(k: Transition, p: f32, incoming: bool, dur: f32) -> Xf
```

`trans_xf` is what `transition` calls: one side of transition `k` at progress `p` (0..1 across the overlap). Call it yourself when the change is not at a scene's edges, for example between two halves of one scene. `dur` is the length in seconds; the whips need it to work out their motion blur.

```odin
p := fx.prog(s.lt, 3.0, 3.4) // a spin, 3 s into the scene
if p < 1 {
	if fx.group(fx.trans_xf(.Spin, p, false, 0.4)) do first_half(s)
}
if p > 0 {
	if fx.group(fx.trans_xf(.Spin, p, true, 0.4)) do second_half(s)
}
```

The outgoing side is the unchanged picture at `p = 0` and the incoming side at `p = 1`, so there is no jump where the transition starts and ends.

## Speed ramps

```odin
ramp :: proc(lt: f32, ks: []Key) -> f32
```

A speed ramp plays a clip fast, drops into slow motion for the moment that matters and speeds up again. `ramp` does the bookkeeping: given how long the clip has been on screen (`lt`) and its playback speed over that time as keyframes, it returns how far into the source the clip is, which is the time to ask the footage for.

Each [`Key`](/docs/anim/#keyframes) is `{t, v}`: at clip time `t` the speed is `v` (1 = real time, 2 = double speed, 0 = a freeze frame). Between keys the speed changes linearly; before the first key and after the last it holds their value. With no keys the result is `lt`.

```odin
keys := [?]fx.Key{{0.8, 2}, {1.1, 0.15}, {2.6, 0.15}, {2.9, 2}}
fx.footage("assets/jump.mp4", 12 + fx.ramp(s.lt, keys[:]), fx.stage()) // the clip starts 12 s into the file
```

There is no footage in the browser, so the "clip" in the demo is a ball whose position depends on source time. The pale copies are the 14 frames before the current one: far apart where the clip runs fast, bunched up in the slow motion.

```odin
edit_ramp :: proc(s: fx.Shot) {
	fx.backdrop(.Night)
	slow := knob("slow", 0.15, 0, 1)
	// double speed, slow motion from 1.1 s to 2.6 s, double speed again
	keys := [?]fx.Key{{0.8, 2}, {1.1, slow}, {2.6, slow}, {2.9, 2}}
	for j := 14; j >= 0; j -= 1 {
		// the "clip" is a ball whose place depends on source time; older frames trail behind it
		src := fx.ramp(s.lt - f32(j) / 30, keys[:])
		p := fx.Vec2{-120 + 440 * src, 700 - 420 * abs(math.sin(src * 2.1))}
		fx.circle(p, 40, j == 0 ? fx.theme.na : fx.alpha(fx.theme.nt, 0.22 - 0.014 * f32(j)))
	}
	fx.hline(0, 742, 1920, fx.theme.nb, 2)
	readout := fmt.tprintf("clip %.2f s	source %.2f s", s.lt, fx.ramp(s.lt, keys[:]))
	fx.label(readout, {960, 900}, fx.mono(36), fx.theme.nm, {0.5, 0.5})
}
```

`ramp` only chooses a time; it does not make new frames. At speed 0.15, footage shot at 30 fps shows a new picture about every seventh frame of a 30 fps video. [/docs/footage/](/docs/footage/) covers `footage` itself.

## Titles

```odin
slam    :: proc(s: string, p: Vec2, f: Font, c: Color, t, t0: f32, dur: f32 = 0.16, anchor := Vec2{0.5, 0.5}) -> Rect
outline :: proc(s: string, p: Vec2, f: Font, c: Color, width: f32 = 2, anchor := Vec2{0.5, 0.5}) -> Rect
```

`slam` draws text that lands at time `t0`: nothing before it, then a copy 1.5 times the size, blurred and fading in, that drops onto its place within `dur` seconds. The default 0.16 s is about ten frames at 60 fps, short enough to read as an impact. `t` is the current time on the same clock as `t0`. The text is placed like [`label`](/docs/draw/) by `p` and `anchor`, except that the default anchor is the center, which is also the point it scales around. It returns the text's rect, or an empty rect before `t0`.

`outline` draws the text as a stroke of `width` pixels with no fill, placed the same way. It is a still picture; use it for the hollow copy of a word that is filled on the beat, or for stacked echoes behind a title.

```odin
edit_slam :: proc(s: fx.Shot) {
	fx.backdrop(.Night)
	words := [?]string{"CUT", "TO", "MUSIC"}
	beats := [?]f32{0.5, 1.0, 1.5}
	f := fx.sans(270, 700, -0.03)
	off := fx.shake(s.t, 24 * fx.pulse(beats[:], s.lt, 0.3)) // every slam shakes the frame
	out := fx.ep(s.lt, 3.3, 3.8, fx.ease_in)
	if fx.group({x = off.x, y = off.y, o = 1 - out}) {
		for w, i in words {
			p := fx.Vec2{960, 250 + f32(i) * 290}
			fx.outline(w, p, f, fx.theme.ns, knob("width", 3, 1, 10)) // the empty word waits
			fx.slam(w, p, f, i == 2 ? fx.theme.na : fx.theme.nt, s.lt, beats[i], knob("dur", 0.16, 0.05, 0.8))
		}
	}
}
```

## Reference

| Name | What it is |
| --- | --- |
| `times(hits, from, at, to, strength, level)` | Onsets of a file as video times, filtered. Allocates; call once. |
| `beat(beats, t)` | Index of the last beat at or before `t` (-1 before the first) and the seconds since it. |
| `pulse(beats, t, dur, e)` | 1 on each beat, falling to 0 over `dur`. |
| `hit(t, t0, dur, e)` | 1 at `t0`, falling to 0 over `dur`; 0 before. |
| `noise1(x, seed)` | Smooth value noise in -1..1. |
| `shake(t, amount, freq, seed)` | Offset in px, up to `amount` on each axis. |
| `camera(zoom, offset, rot)` | `Xf` that zooms and rotates around the stage center and moves by `offset`. |
| `flash(a, c)` | The stage covered in `c` at opacity `a`. |
| `letterbox(amount, ratio, c)` | Bars cropping the stage to `ratio`, slid in by `amount`. |
| `Transition` | `Cut`, `Fade`, `Whip_Left`, `Whip_Right`, `Whip_Up`, `Whip_Down`, `Zoom`, `Spin`, `Glitch`, `Blur`. |
| `transition(s, enter, leave, dur)` | `Xf` for a scene that enters and leaves with transitions at its edges. |
| `trans_xf(k, p, incoming, dur)` | `Xf` of one side of a transition at progress `p`. |
| `ramp(lt, ks)` | Source time of a clip after `lt` seconds at the speeds in `ks`. |
| `slam(s, p, f, c, t, t0, dur, anchor)` | Text that drops into place at `t0`. |
| `outline(s, p, f, c, width, anchor)` | Text drawn as an outline. |
