@motionscript/audio 0.0.0-stage → 0.1.0-alpha.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/CHANGELOG.md +75 -0
  2. package/LICENSE +201 -0
  3. package/NOTICE +49 -0
  4. package/README.md +91 -3
  5. package/dist/browser/chunks/chunk-DD3KHRUL.js +2 -0
  6. package/dist/browser/chunks/chunk-DD3KHRUL.js.map +7 -0
  7. package/dist/browser/index.js +2 -0
  8. package/dist/browser/index.js.map +7 -0
  9. package/dist/browser/kit.js +2 -0
  10. package/dist/browser/kit.js.map +7 -0
  11. package/dist/browser/manifest.json +13 -0
  12. package/dist/index.d.ts +3 -0
  13. package/dist/index.d.ts.map +1 -0
  14. package/dist/index.js +3 -0
  15. package/dist/index.js.map +1 -0
  16. package/dist/kit.d.ts +13 -0
  17. package/dist/kit.d.ts.map +1 -0
  18. package/dist/kit.js +11 -0
  19. package/dist/kit.js.map +1 -0
  20. package/dist/nodes.d.ts +16 -0
  21. package/dist/nodes.d.ts.map +1 -0
  22. package/dist/nodes.js +17 -0
  23. package/dist/nodes.js.map +1 -0
  24. package/dist/waveform/envelope.d.ts +120 -0
  25. package/dist/waveform/envelope.d.ts.map +1 -0
  26. package/dist/waveform/envelope.js +126 -0
  27. package/dist/waveform/envelope.js.map +1 -0
  28. package/dist/waveform/full-waveform.d.ts +118 -0
  29. package/dist/waveform/full-waveform.d.ts.map +1 -0
  30. package/dist/waveform/full-waveform.js +146 -0
  31. package/dist/waveform/full-waveform.js.map +1 -0
  32. package/dist/waveform/index.d.ts +23 -0
  33. package/dist/waveform/index.d.ts.map +1 -0
  34. package/dist/waveform/index.js +19 -0
  35. package/dist/waveform/index.js.map +1 -0
  36. package/dist/waveform/live-waveform.d.ts +129 -0
  37. package/dist/waveform/live-waveform.d.ts.map +1 -0
  38. package/dist/waveform/live-waveform.js +149 -0
  39. package/dist/waveform/live-waveform.js.map +1 -0
  40. package/dist/waveform/shared.d.ts +98 -0
  41. package/dist/waveform/shared.d.ts.map +1 -0
  42. package/dist/waveform/shared.js +149 -0
  43. package/dist/waveform/shared.js.map +1 -0
  44. package/package.json +72 -3
  45. package/registry.json +28 -0
  46. package/src/index.ts +2 -0
  47. package/src/kit.ts +22 -0
  48. package/src/nodes.ts +17 -0
  49. package/src/waveform/envelope.ts +176 -0
  50. package/src/waveform/full-waveform.ts +188 -0
  51. package/src/waveform/index.ts +30 -0
  52. package/src/waveform/live-waveform.ts +206 -0
  53. package/src/waveform/shared.ts +197 -0
@@ -0,0 +1,206 @@
1
+ import {
2
+ Types,
3
+ component2d,
4
+ fillOps,
5
+ type Fill,
6
+ type FillResolved,
7
+ type NodeOf,
8
+ type RenderContext,
9
+ // Named so the emitted declaration reaches these through the sdk, not core.
10
+ type Node2D as _Node2D,
11
+ type Node2DProps as _Node2DProps,
12
+ } from "@motionscript/sdk"
13
+
14
+ import {
15
+ EMPTY_ENVELOPE,
16
+ forSpeaker,
17
+ sampleEnvelope,
18
+ type AudioEnvelope,
19
+ type EnvelopeBar,
20
+ } from "./envelope"
21
+ import {
22
+ clamp01,
23
+ groupByPaint,
24
+ layOutBars,
25
+ livePaintKey,
26
+ paintBars,
27
+ voiceColor,
28
+ type WaveformAlignment,
29
+ type WaveformStyle,
30
+ } from "./shared"
31
+
32
+ /**
33
+ * A **live audio visualiser**: bars that move with the recording as it plays.
34
+ *
35
+ * The thing every podcast-to-video tool puts beside the artwork. It is not a
36
+ * picture of the file — that is {@link FullWaveform} — it is a picture of *this
37
+ * moment*, and what it is for is making a static frame of a talking head feel
38
+ * like it is playing.
39
+ *
40
+ * ## "Live" without listening
41
+ *
42
+ * Nothing here reads an audio device. The bars are sampled out of a baked
43
+ * envelope at the node's own elapsed time, which is what makes the visualiser
44
+ * survive the thing it exists for: an **export**, where there is no playback to
45
+ * analyse and frames may be rendered out of order or in parallel. A frame is a
46
+ * pure function of its time, so scrubbing back and forth over the visualiser
47
+ * redraws exactly what it drew the first time — which an analyser node, by
48
+ * construction, cannot promise. See {@link AudioEnvelope}.
49
+ *
50
+ * ## The speaker filter
51
+ *
52
+ * `speaker` narrows the node to one voice of a diarized recording, and it
53
+ * is the reason this node knows about transcripts at all. Two visualisers beside
54
+ * two headshots, each filtered to its own host, is a podcast edit that would
55
+ * otherwise be done by hand for every turn — and because the filter *silences*
56
+ * rather than skips (see {@link forSpeaker}), the quiet host visibly stops
57
+ * talking instead of vanishing. Nothing about that requires the words: only who
58
+ * is talking when, which is what the diarizer produces.
59
+ *
60
+ * A filter naming a voice the recording doesn't have draws a resting row rather
61
+ * than everything — a picture of "this person never speaks here", which is
62
+ * true, where falling back to the unfiltered mix would be a silent lie about
63
+ * whose voice you were watching.
64
+ */
65
+ export const LiveWaveform = component2d({
66
+ key: "liveWaveform",
67
+ state: {
68
+ /** The baked recording. See {@link AudioEnvelope} for why it is baked. */
69
+ envelope: Types.custom<AudioEnvelope>(EMPTY_ENVELOPE),
70
+ /** How many bars the visualiser is made of. */
71
+ bars: 48,
72
+ /** Space between bars, as a fraction of the pitch. */
73
+ gap: 0.35,
74
+ radius: 4,
75
+ /** How many seconds of audio are on screen at once. */
76
+ window: 3,
77
+ /** Seconds into the file the node's first frame shows. */
78
+ offset: 0,
79
+ /** Advance with the scene clock. Off freezes the picture at `offset`. */
80
+ playing: true,
81
+ /** Multiplies every magnitude before it is clamped. */
82
+ gain: 1.4,
83
+ /** How much of the box a silent bar still occupies, `0`–`1`. */
84
+ floor: 0.04,
85
+ align: Types.custom<WaveformAlignment>("center"),
86
+ style: Types.custom<WaveformStyle>("bars"),
87
+ /**
88
+ * Show only this voice's activity, by index into the recording's own
89
+ * numbering. `-1` — the default — is every voice.
90
+ */
91
+ speaker: -1,
92
+ /** Colour each bar by whoever is speaking in it. */
93
+ byVoice: false,
94
+ /** A colour per voice index. Short or empty falls back to the palette. */
95
+ voiceColors: Types.custom<string[]>([]),
96
+ fill: Types.custom<Fill, FillResolved[]>("#6366f1", { resolve: fillOps.resolve, lerp: fillOps.lerp }),
97
+ },
98
+ // Nothing declares a component's paints but itself.
99
+ load: (loader, state) => loader.fill(state.fill),
100
+ render: (ctx, state) => {
101
+ drawBars(ctx, state)
102
+ ctx.children()
103
+ },
104
+ })
105
+
106
+ export type LiveWaveform = NodeOf<typeof LiveWaveform>
107
+ export type LiveWaveformProps = NonNullable<Parameters<typeof LiveWaveform>[0]>
108
+
109
+ interface LiveState {
110
+ readonly envelope: AudioEnvelope
111
+ readonly bars: number
112
+ readonly gap: number
113
+ readonly radius: number
114
+ readonly window: number
115
+ readonly offset: number
116
+ readonly playing: boolean
117
+ readonly gain: number
118
+ readonly floor: number
119
+ readonly align: WaveformAlignment
120
+ readonly style: WaveformStyle
121
+ readonly speaker: number
122
+ readonly byVoice: boolean
123
+ readonly voiceColors: string[]
124
+ readonly fill: FillResolved[]
125
+ }
126
+
127
+ /**
128
+ * The second of the recording the visualiser is showing.
129
+ *
130
+ * Off the node's own clock rather than the scene's, which is what "from the
131
+ * moment this node appeared" means — the same clock the engine's own
132
+ * `Video` times its picture from, and the same one that makes a node dropped
133
+ * halfway through a clip start its recording at its entrance rather than
134
+ * partway in.
135
+ */
136
+ function at(ctx: RenderContext, s: LiveState): number {
137
+ return s.offset + (s.playing ? Math.max(0, ctx.time.elapsed) : 0)
138
+ }
139
+
140
+ function drawBars(ctx: RenderContext, s: LiveState): void {
141
+ const { width, height } = ctx.size
142
+ if (width <= 0 || height <= 0) return
143
+
144
+ const count = Math.max(1, Math.round(s.bars))
145
+ const span = Math.max(0.05, s.window)
146
+ const now = at(ctx, s)
147
+ const voice = s.speaker < 0 ? null : Math.round(s.speaker)
148
+
149
+ // The window is centred on the playhead, so the bars run *toward* the
150
+ // middle and away again — the arrangement every mixer's meter uses, and the
151
+ // one that reads as sound arriving rather than as a strip scrolling past.
152
+ const sampled = forSpeaker(
153
+ sampleEnvelope(s.envelope, now - span / 2, now + span / 2, count),
154
+ voice
155
+ )
156
+
157
+ const shaped = s.style === "line" ? taper(sampled) : sampled
158
+ const boxes = layOutBars(shaped, {
159
+ width,
160
+ height,
161
+ gap: s.style === "blocks" ? 0.12 : s.gap,
162
+ align: s.align,
163
+ gain: s.gain,
164
+ floor: s.floor,
165
+ })
166
+ if (boxes.length === 0) return
167
+
168
+ const groups = groupByPaint(boxes, (i) =>
169
+ livePaintKey(shaped[i].speaker, s.byVoice, voice)
170
+ )
171
+
172
+ for (const [key, run] of groups) {
173
+ const graphics = paintBars(run, paintFor(s, key), s.radius)
174
+ if (graphics) ctx.draw(graphics)
175
+ }
176
+ }
177
+
178
+ /** See `FullWaveform`'s paints — a voice is a hue, never a gradient. */
179
+ function paintFor(s: LiveState, key: string): Fill {
180
+ if (key === "all") return s.fill
181
+ const voice = Number(key.slice("voice:".length))
182
+ if (!Number.isFinite(voice) || voice < 0) return s.fill
183
+ return s.voiceColors[voice] ?? voiceColor(voice)
184
+ }
185
+
186
+ /**
187
+ * Rolls the ends of a window off toward silence.
188
+ *
189
+ * What separates the `line` style from `bars`: a hard-edged window makes the
190
+ * loud bar entering at the right edge appear from nothing, which reads as a
191
+ * glitch rather than as sound arriving. Fading the outer fifth turns the same
192
+ * data into a shape that grows out of the baseline — the profile a spectrum
193
+ * display has, and the reason it looks like one object rather than a row of
194
+ * separate meters.
195
+ */
196
+ function taper(bars: readonly EnvelopeBar[]): EnvelopeBar[] {
197
+ const count = bars.length
198
+ if (count < 3) return [...bars]
199
+ const edge = Math.max(1, Math.floor(count / 5))
200
+
201
+ return bars.map((bar, i) => {
202
+ const fromEnd = Math.min(i, count - 1 - i)
203
+ const weight = clamp01(fromEnd / edge)
204
+ return { magnitude: bar.magnitude * weight, speaker: bar.speaker }
205
+ })
206
+ }
@@ -0,0 +1,197 @@
1
+ import { Graphics2D, type Fill, type FillResolved } from "@motionscript/sdk"
2
+
3
+ import type { EnvelopeBar } from "./envelope"
4
+
5
+ /**
6
+ * Geometry and paint shared by the two waveform nodes.
7
+ *
8
+ * They draw the same object — a row of bars whose heights are loudness — and
9
+ * differ only in what decides the heights: the whole file for one, a window
10
+ * around the playhead for the other. Everything about *how a row of bars is
11
+ * laid out and painted* is therefore common, and lives here so the two cannot
12
+ * drift into looking like different components.
13
+ */
14
+
15
+ /** How a bar is grown out of its baseline. */
16
+ export const WAVEFORM_ALIGNMENTS = ["center", "bottom"] as const
17
+ export type WaveformAlignment = (typeof WAVEFORM_ALIGNMENTS)[number]
18
+
19
+ /** What the bars are shaped like. */
20
+ export const WAVEFORM_STYLES = ["bars", "line", "blocks"] as const
21
+ export type WaveformStyle = (typeof WAVEFORM_STYLES)[number]
22
+
23
+ /**
24
+ * The colours voices are drawn in when nobody has assigned any.
25
+ *
26
+ * Eight hues that can be told apart at a glance, handed out by voice index. They
27
+ * are literals rather than looked up, because a scene has to build in a
28
+ * headless render with no database in scope; a host that names its voices
29
+ * supplies its own colours instead.
30
+ */
31
+ export const VOICE_PALETTE = [
32
+ "#6366f1",
33
+ "#14b8a6",
34
+ "#f59e0b",
35
+ "#ec4899",
36
+ "#22c55e",
37
+ "#3b82f6",
38
+ "#f97316",
39
+ "#a855f7",
40
+ ] as const
41
+
42
+ /** The colour a voice takes, wrapping past the end of the palette. */
43
+ export function voiceColor(index: number): string {
44
+ return VOICE_PALETTE[
45
+ ((index % VOICE_PALETTE.length) + VOICE_PALETTE.length) %
46
+ VOICE_PALETTE.length
47
+ ]
48
+ }
49
+
50
+ /**
51
+ * Where one bar sits and how tall it came out: its top-left corner and size, in
52
+ * the node's own pixels with **y pointing down** from the middle of the box.
53
+ * {@link paintBars} turns that into the centred, y-up rect the renderer draws.
54
+ */
55
+ export interface BarBox {
56
+ x: number
57
+ y: number
58
+ width: number
59
+ height: number
60
+ }
61
+
62
+ /**
63
+ * Lays a row of bars out across a box.
64
+ *
65
+ * The gap is stated as a *fraction of the pitch* rather than in pixels, and
66
+ * that is the one decision here worth stating out loud: the bar count is a
67
+ * control, so a gap in pixels would silently become a solid block at 200 bars
68
+ * and a picket fence at 20. As a fraction, the row keeps the same rhythm at
69
+ * every density — which is what lets the count be a slider anyone can drag.
70
+ *
71
+ * A bar is never thinner than a hairline and never shorter than one either: a
72
+ * silent passage has to read as "audio, and nothing here" rather than as a hole
73
+ * in the drawing.
74
+ */
75
+ export function layOutBars(
76
+ bars: readonly EnvelopeBar[],
77
+ options: {
78
+ width: number
79
+ height: number
80
+ gap: number
81
+ align: WaveformAlignment
82
+ /** Multiplies every magnitude before it is clamped back into 0…1. */
83
+ gain: number
84
+ /** Fraction of the box a silent bar still occupies. */
85
+ floor: number
86
+ }
87
+ ): BarBox[] {
88
+ const { width, height, gap, align, gain, floor } = options
89
+ const count = bars.length
90
+ if (count === 0 || width <= 0 || height <= 0) return []
91
+
92
+ const pitch = width / count
93
+ const barWidth = Math.max(1, pitch * (1 - clamp01(gap)))
94
+ // The tallest a bar may be. Centre-aligned bars grow both ways from the
95
+ // middle, so the *half* is what a magnitude of 1 fills.
96
+ const full = align === "center" ? height / 2 : height
97
+
98
+ const out: BarBox[] = new Array(count)
99
+ for (let i = 0; i < count; i++) {
100
+ const magnitude = clamp01(bars[i].magnitude * gain)
101
+ const reach = Math.max(full * clamp01(floor), full * magnitude)
102
+ const x = -width / 2 + pitch * i + (pitch - barWidth) / 2
103
+
104
+ // A hairline minimum, taken before the position so the bar stays inside the
105
+ // box: a silent bar 1px tall that kept the position of a zero-height one
106
+ // would hang half a pixel (centred) or a whole pixel (bottom) outside it.
107
+ const h = Math.max(1, align === "center" ? reach * 2 : reach)
108
+ out[i] =
109
+ align === "center"
110
+ ? { x, y: -h / 2, width: barWidth, height: h }
111
+ : { x, y: height / 2 - h, width: barWidth, height: h }
112
+ }
113
+ return out
114
+ }
115
+
116
+ /**
117
+ * Draws a run of bars in one paint.
118
+ *
119
+ * Batched by colour by the caller, and this is why: every `Graphics2D` handed to
120
+ * `ctx.draw` is a surface the renderer composites, so a bar apiece would be a
121
+ * thousand surfaces a frame. Chaining the rects of one colour into a single
122
+ * `Graphics2D` before filling makes it one — and, as a bonus, a gradient fill
123
+ * maps across the whole run rather than restarting inside every bar, which is
124
+ * the behaviour anyone reaching for a gradient here actually wants.
125
+ */
126
+ export function paintBars(
127
+ boxes: readonly BarBox[],
128
+ fill: Fill,
129
+ radius: number
130
+ ): Graphics2D | null {
131
+ if (boxes.length === 0) return null
132
+ if ((fill as FillResolved[]).length === 0) return null
133
+
134
+ const graphics = new Graphics2D()
135
+ for (const box of boxes) {
136
+ graphics.rect({
137
+ x: box.x + box.width / 2,
138
+ // The box is stated y-down and the rect is drawn y-up. A centred bar is
139
+ // symmetric about the middle, so only a bottom-aligned one shows the flip.
140
+ y: -(box.y + box.height / 2),
141
+ width: box.width,
142
+ height: box.height,
143
+ // Never rounder than the bar is wide, or a thin bar becomes a lozenge
144
+ // whose ends taper away to nothing.
145
+ cornerRadius: Math.min(radius, box.width / 2, box.height / 2),
146
+ })
147
+ }
148
+ return graphics.fill(fill)
149
+ }
150
+
151
+ /**
152
+ * Groups bars by the paint they take, preserving order within each group.
153
+ *
154
+ * The seam that makes {@link paintBars} worth batching: a diarized waveform has
155
+ * as many colours as it has voices, not as many as it has bars, so a
156
+ * conversation of two people is two draws however long it runs.
157
+ */
158
+ export function groupByPaint<K>(
159
+ boxes: readonly BarBox[],
160
+ keyOf: (index: number) => K
161
+ ): Map<K, BarBox[]> {
162
+ const groups = new Map<K, BarBox[]>()
163
+ for (let i = 0; i < boxes.length; i++) {
164
+ const key = keyOf(i)
165
+ const run = groups.get(key)
166
+ if (run) run.push(boxes[i])
167
+ else groups.set(key, [boxes[i]])
168
+ }
169
+ return groups
170
+ }
171
+
172
+ export function clamp01(value: number): number {
173
+ return value < 0 ? 0 : value > 1 ? 1 : value
174
+ }
175
+
176
+ /**
177
+ * The {@link groupByPaint} key one bar of a live visualiser takes.
178
+ *
179
+ * Filtered to one voice, every bar is that voice regardless of `byVoice` or
180
+ * whose turn the bucket originally belonged to. That second part is the one
181
+ * worth spelling out: {@link forSpeaker} silences a bar by zeroing its
182
+ * magnitude but leaves `speaker` exactly as it was, so a bar sitting in the
183
+ * middle of a *different* voice's turn is still stamped with that voice's
184
+ * index — grouping by `byVoice`'s usual per-bar key would paint those silent
185
+ * stretches in whoever used to be talking there, in flickers too short to
186
+ * read as anything but noise. Forcing every bar under the filtered voice's own
187
+ * key is the true picture instead: the node is drawing exactly one person, on
188
+ * or off, never anyone else's colour.
189
+ */
190
+ export function livePaintKey(
191
+ barSpeaker: number,
192
+ byVoice: boolean,
193
+ filteredVoice: number | null
194
+ ): string {
195
+ if (filteredVoice !== null) return `voice:${filteredVoice}`
196
+ return byVoice ? `voice:${barSpeaker}` : "all"
197
+ }