@motionscript/audio 0.1.0-alpha.7 → 0.1.0-alpha.9

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.
@@ -1 +1 @@
1
- {"version":3,"file":"shared.js","sourceRoot":"","sources":["../../src/waveform/shared.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAgC,MAAM,mBAAmB,CAAA;AAI5E;;;;;;;;GAQG;AAEH,8CAA8C;AAC9C,MAAM,CAAC,MAAM,mBAAmB,GAAG,CAAC,QAAQ,EAAE,QAAQ,CAAU,CAAA;AAGhE,qCAAqC;AACrC,MAAM,CAAC,MAAM,eAAe,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,CAAU,CAAA;AAGlE;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,aAAa,GAAG;IAC3B,SAAS;IACT,SAAS;IACT,SAAS;IACT,SAAS;IACT,SAAS;IACT,SAAS;IACT,SAAS;IACT,SAAS;CACD,CAAA;AAEV,sEAAsE;AACtE,MAAM,UAAU,UAAU,CAAC,KAAa;IACtC,OAAO,aAAa,CAClB,CAAC,CAAC,KAAK,GAAG,aAAa,CAAC,MAAM,CAAC,GAAG,aAAa,CAAC,MAAM,CAAC;QACrD,aAAa,CAAC,MAAM,CACvB,CAAA;AACH,CAAC;AAcD;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,UAAU,CACxB,IAA4B,EAC5B,OASC;IAED,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,OAAO,CAAA;IAC1D,MAAM,KAAK,GAAG,IAAI,CAAC,MAAM,CAAA;IACzB,IAAI,KAAK,KAAK,CAAC,IAAI,KAAK,IAAI,CAAC,IAAI,MAAM,IAAI,CAAC;QAAE,OAAO,EAAE,CAAA;IAEvD,MAAM,KAAK,GAAG,KAAK,GAAG,KAAK,CAAA;IAC3B,MAAM,QAAQ,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MAAM,GAAG,GAAG,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,CAAA;QAC3B,IAAI,GAAG;YAAE,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAA;;YACtB,MAAM,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;IAClC,CAAC;IACD,OAAO,MAAM,CAAA;AACf,CAAC;AAED,MAAM,UAAU,OAAO,CAAC,KAAa;IACnC,OAAO,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAA;AAC9C,CAAC;AAED;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,YAAY,CAC1B,UAAkB,EAClB,OAAgB,EAChB,aAA4B;IAE5B,IAAI,aAAa,KAAK,IAAI;QAAE,OAAO,SAAS,aAAa,EAAE,CAAA;IAC3D,OAAO,OAAO,CAAC,CAAC,CAAC,SAAS,UAAU,EAAE,CAAC,CAAC,CAAC,KAAK,CAAA;AAChD,CAAC","sourcesContent":["import { Graphics2D, type Fill, type FillResolved } from \"@motionscript/sdk\"\r\n\r\nimport type { EnvelopeBar } from \"./envelope\"\r\n\r\n/**\r\n * Geometry and paint shared by the two waveform nodes.\r\n *\r\n * They draw the same object — a row of bars whose heights are loudness — and\r\n * differ only in what decides the heights: the whole file for one, a window\r\n * around the playhead for the other. Everything about *how a row of bars is\r\n * laid out and painted* is therefore common, and lives here so the two cannot\r\n * drift into looking like different components.\r\n */\r\n\r\n/** How a bar is grown out of its baseline. */\r\nexport const WAVEFORM_ALIGNMENTS = [\"center\", \"bottom\"] as const\r\nexport type WaveformAlignment = (typeof WAVEFORM_ALIGNMENTS)[number]\r\n\r\n/** What the bars are shaped like. */\r\nexport const WAVEFORM_STYLES = [\"bars\", \"line\", \"blocks\"] as const\r\nexport type WaveformStyle = (typeof WAVEFORM_STYLES)[number]\r\n\r\n/**\r\n * The colours voices are drawn in when nobody has assigned any.\r\n *\r\n * Eight hues that can be told apart at a glance, handed out by voice index. They\r\n * are literals rather than looked up, because a scene has to build in a\r\n * headless render with no database in scope; a host that names its voices\r\n * supplies its own colours instead.\r\n */\r\nexport const VOICE_PALETTE = [\r\n \"#6366f1\",\r\n \"#14b8a6\",\r\n \"#f59e0b\",\r\n \"#ec4899\",\r\n \"#22c55e\",\r\n \"#3b82f6\",\r\n \"#f97316\",\r\n \"#a855f7\",\r\n] as const\r\n\r\n/** The colour a voice takes, wrapping past the end of the palette. */\r\nexport function voiceColor(index: number): string {\r\n return VOICE_PALETTE[\r\n ((index % VOICE_PALETTE.length) + VOICE_PALETTE.length) %\r\n VOICE_PALETTE.length\r\n ]\r\n}\r\n\r\n/**\r\n * Where one bar sits and how tall it came out: its top-left corner and size, in\r\n * the node's own pixels with **y pointing down** from the middle of the box.\r\n * {@link paintBars} turns that into the centred, y-up rect the renderer draws.\r\n */\r\nexport interface BarBox {\r\n x: number\r\n y: number\r\n width: number\r\n height: number\r\n}\r\n\r\n/**\r\n * Lays a row of bars out across a box.\r\n *\r\n * The gap is stated as a *fraction of the pitch* rather than in pixels, and\r\n * that is the one decision here worth stating out loud: the bar count is a\r\n * control, so a gap in pixels would silently become a solid block at 200 bars\r\n * and a picket fence at 20. As a fraction, the row keeps the same rhythm at\r\n * every density — which is what lets the count be a slider anyone can drag.\r\n *\r\n * A bar is never thinner than a hairline and never shorter than one either: a\r\n * silent passage has to read as \"audio, and nothing here\" rather than as a hole\r\n * in the drawing.\r\n */\r\nexport function layOutBars(\r\n bars: readonly EnvelopeBar[],\r\n options: {\r\n width: number\r\n height: number\r\n gap: number\r\n align: WaveformAlignment\r\n /** Multiplies every magnitude before it is clamped back into 0…1. */\r\n gain: number\r\n /** Fraction of the box a silent bar still occupies. */\r\n floor: number\r\n }\r\n): BarBox[] {\r\n const { width, height, gap, align, gain, floor } = options\r\n const count = bars.length\r\n if (count === 0 || width <= 0 || height <= 0) return []\r\n\r\n const pitch = width / count\r\n const barWidth = Math.max(1, pitch * (1 - clamp01(gap)))\r\n // The tallest a bar may be. Centre-aligned bars grow both ways from the\r\n // middle, so the *half* is what a magnitude of 1 fills.\r\n const full = align === \"center\" ? height / 2 : height\r\n\r\n const out: BarBox[] = new Array(count)\r\n for (let i = 0; i < count; i++) {\r\n const magnitude = clamp01(bars[i].magnitude * gain)\r\n const reach = Math.max(full * clamp01(floor), full * magnitude)\r\n const x = -width / 2 + pitch * i + (pitch - barWidth) / 2\r\n\r\n // A hairline minimum, taken before the position so the bar stays inside the\r\n // box: a silent bar 1px tall that kept the position of a zero-height one\r\n // would hang half a pixel (centred) or a whole pixel (bottom) outside it.\r\n const h = Math.max(1, align === \"center\" ? reach * 2 : reach)\r\n out[i] =\r\n align === \"center\"\r\n ? { x, y: -h / 2, width: barWidth, height: h }\r\n : { x, y: height / 2 - h, width: barWidth, height: h }\r\n }\r\n return out\r\n}\r\n\r\n/**\r\n * Draws a run of bars in one paint.\r\n *\r\n * Batched by colour by the caller, and this is why: every `Graphics2D` handed to\r\n * `ctx.draw` is a surface the renderer composites, so a bar apiece would be a\r\n * thousand surfaces a frame. Chaining the rects of one colour into a single\r\n * `Graphics2D` before filling makes it one — and, as a bonus, a gradient fill\r\n * maps across the whole run rather than restarting inside every bar, which is\r\n * the behaviour anyone reaching for a gradient here actually wants.\r\n */\r\nexport function paintBars(\r\n boxes: readonly BarBox[],\r\n fill: Fill,\r\n radius: number\r\n): Graphics2D | null {\r\n if (boxes.length === 0) return null\r\n if ((fill as FillResolved[]).length === 0) return null\r\n\r\n const graphics = new Graphics2D()\r\n for (const box of boxes) {\r\n graphics.rect({\r\n x: box.x + box.width / 2,\r\n // The box is stated y-down and the rect is drawn y-up. A centred bar is\r\n // symmetric about the middle, so only a bottom-aligned one shows the flip.\r\n y: -(box.y + box.height / 2),\r\n width: box.width,\r\n height: box.height,\r\n // Never rounder than the bar is wide, or a thin bar becomes a lozenge\r\n // whose ends taper away to nothing.\r\n cornerRadius: Math.min(radius, box.width / 2, box.height / 2),\r\n })\r\n }\r\n return graphics.fill(fill)\r\n}\r\n\r\n/**\r\n * Groups bars by the paint they take, preserving order within each group.\r\n *\r\n * The seam that makes {@link paintBars} worth batching: a diarized waveform has\r\n * as many colours as it has voices, not as many as it has bars, so a\r\n * conversation of two people is two draws however long it runs.\r\n */\r\nexport function groupByPaint<K>(\r\n boxes: readonly BarBox[],\r\n keyOf: (index: number) => K\r\n): Map<K, BarBox[]> {\r\n const groups = new Map<K, BarBox[]>()\r\n for (let i = 0; i < boxes.length; i++) {\r\n const key = keyOf(i)\r\n const run = groups.get(key)\r\n if (run) run.push(boxes[i])\r\n else groups.set(key, [boxes[i]])\r\n }\r\n return groups\r\n}\r\n\r\nexport function clamp01(value: number): number {\r\n return value < 0 ? 0 : value > 1 ? 1 : value\r\n}\r\n\r\n/**\r\n * The {@link groupByPaint} key one bar of a live visualiser takes.\r\n *\r\n * Filtered to one voice, every bar is that voice regardless of `byVoice` or\r\n * whose turn the bucket originally belonged to. That second part is the one\r\n * worth spelling out: {@link forSpeaker} silences a bar by zeroing its\r\n * magnitude but leaves `speaker` exactly as it was, so a bar sitting in the\r\n * middle of a *different* voice's turn is still stamped with that voice's\r\n * index — grouping by `byVoice`'s usual per-bar key would paint those silent\r\n * stretches in whoever used to be talking there, in flickers too short to\r\n * read as anything but noise. Forcing every bar under the filtered voice's own\r\n * key is the true picture instead: the node is drawing exactly one person, on\r\n * or off, never anyone else's colour.\r\n */\r\nexport function livePaintKey(\r\n barSpeaker: number,\r\n byVoice: boolean,\r\n filteredVoice: number | null\r\n): string {\r\n if (filteredVoice !== null) return `voice:${filteredVoice}`\r\n return byVoice ? `voice:${barSpeaker}` : \"all\"\r\n}\r\n"]}
1
+ {"version":3,"file":"shared.js","sourceRoot":"","sources":["../../src/waveform/shared.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAgC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AClC,CAAC;IACD,OAAO,MAAM,CAAA;AACf,CAAC;AAED,MAAM,UAAU,OAAO,CAAC,KAAa;IACnC,OAAO,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAA;AAC9C,CAAC;AAED;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,YAAY,CAC1B,UAAkB,EAClB,OAAgB,EAChB,aAA4B;IAE5B,IAAI,aAAa,KAAK,IAAI;QAAE,OAAO,SAAS,aAAa,EAAE,CAAA;IAC3D,OAAO,OAAO,CAAC,CAAC,CAAC,SAAS,UAAU,EAAE,CAAC,CAAC,CAAC,KAAK,CAAA;AAChD,CAAC","sourcesContent":["import { Graphics2D, type Fill, type FillResolved } from \"@motionscript/sdk\"\n\nimport type { EnvelopeBar } from \"./envelope\"\n\n/**\n * Geometry and paint shared by the two waveform nodes.\n *\n * They draw the same object — a row of bars whose heights are loudness — and\n * differ only in what decides the heights: the whole file for one, a window\n * around the playhead for the other. Everything about *how a row of bars is\n * laid out and painted* is therefore common, and lives here so the two cannot\n * drift into looking like different components.\n */\n\n/** How a bar is grown out of its baseline. */\nexport const WAVEFORM_ALIGNMENTS = [\"center\", \"bottom\"] as const\nexport type WaveformAlignment = (typeof WAVEFORM_ALIGNMENTS)[number]\n\n/** What the bars are shaped like. */\nexport const WAVEFORM_STYLES = [\"bars\", \"line\", \"blocks\"] as const\nexport type WaveformStyle = (typeof WAVEFORM_STYLES)[number]\n\n/**\n * The colours voices are drawn in when nobody has assigned any.\n *\n * Eight hues that can be told apart at a glance, handed out by voice index. They\n * are literals rather than looked up, because a scene has to build in a\n * headless render with no database in scope; a host that names its voices\n * supplies its own colours instead.\n */\nexport const VOICE_PALETTE = [\n \"#6366f1\",\n \"#14b8a6\",\n \"#f59e0b\",\n \"#ec4899\",\n \"#22c55e\",\n \"#3b82f6\",\n \"#f97316\",\n \"#a855f7\",\n] as const\n\n/** The colour a voice takes, wrapping past the end of the palette. */\nexport function voiceColor(index: number): string {\n return VOICE_PALETTE[\n ((index % VOICE_PALETTE.length) + VOICE_PALETTE.length) %\n VOICE_PALETTE.length\n ]\n}\n\n/**\n * Where one bar sits and how tall it came out: its top-left corner and size, in\n * the node's own pixels with **y pointing down** from the middle of the box.\n * {@link paintBars} turns that into the centred, y-up rect the renderer draws.\n */\nexport interface BarBox {\n x: number\n y: number\n width: number\n height: number\n}\n\n/**\n * Lays a row of bars out across a box.\n *\n * The gap is stated as a *fraction of the pitch* rather than in pixels, and\n * that is the one decision here worth stating out loud: the bar count is a\n * control, so a gap in pixels would silently become a solid block at 200 bars\n * and a picket fence at 20. As a fraction, the row keeps the same rhythm at\n * every density — which is what lets the count be a slider anyone can drag.\n *\n * A bar is never thinner than a hairline and never shorter than one either: a\n * silent passage has to read as \"audio, and nothing here\" rather than as a hole\n * in the drawing.\n */\nexport function layOutBars(\n bars: readonly EnvelopeBar[],\n options: {\n width: number\n height: number\n gap: number\n align: WaveformAlignment\n /** Multiplies every magnitude before it is clamped back into 0…1. */\n gain: number\n /** Fraction of the box a silent bar still occupies. */\n floor: number\n }\n): BarBox[] {\n const { width, height, gap, align, gain, floor } = options\n const count = bars.length\n if (count === 0 || width <= 0 || height <= 0) return []\n\n const pitch = width / count\n const barWidth = Math.max(1, pitch * (1 - clamp01(gap)))\n // The tallest a bar may be. Centre-aligned bars grow both ways from the\n // middle, so the *half* is what a magnitude of 1 fills.\n const full = align === \"center\" ? height / 2 : height\n\n const out: BarBox[] = new Array(count)\n for (let i = 0; i < count; i++) {\n const magnitude = clamp01(bars[i].magnitude * gain)\n const reach = Math.max(full * clamp01(floor), full * magnitude)\n const x = -width / 2 + pitch * i + (pitch - barWidth) / 2\n\n // A hairline minimum, taken before the position so the bar stays inside the\n // box: a silent bar 1px tall that kept the position of a zero-height one\n // would hang half a pixel (centred) or a whole pixel (bottom) outside it.\n const h = Math.max(1, align === \"center\" ? reach * 2 : reach)\n out[i] =\n align === \"center\"\n ? { x, y: -h / 2, width: barWidth, height: h }\n : { x, y: height / 2 - h, width: barWidth, height: h }\n }\n return out\n}\n\n/**\n * Draws a run of bars in one paint.\n *\n * Batched by colour by the caller, and this is why: every `Graphics2D` handed to\n * `ctx.draw` is a surface the renderer composites, so a bar apiece would be a\n * thousand surfaces a frame. Chaining the rects of one colour into a single\n * `Graphics2D` before filling makes it one — and, as a bonus, a gradient fill\n * maps across the whole run rather than restarting inside every bar, which is\n * the behaviour anyone reaching for a gradient here actually wants.\n */\nexport function paintBars(\n boxes: readonly BarBox[],\n fill: Fill,\n radius: number\n): Graphics2D | null {\n if (boxes.length === 0) return null\n if ((fill as FillResolved[]).length === 0) return null\n\n const graphics = new Graphics2D()\n for (const box of boxes) {\n graphics.rect({\n x: box.x + box.width / 2,\n // The box is stated y-down and the rect is drawn y-up. A centred bar is\n // symmetric about the middle, so only a bottom-aligned one shows the flip.\n y: -(box.y + box.height / 2),\n width: box.width,\n height: box.height,\n // Never rounder than the bar is wide, or a thin bar becomes a lozenge\n // whose ends taper away to nothing.\n cornerRadius: Math.min(radius, box.width / 2, box.height / 2),\n })\n }\n return graphics.fill(fill)\n}\n\n/**\n * Groups bars by the paint they take, preserving order within each group.\n *\n * The seam that makes {@link paintBars} worth batching: a diarized waveform has\n * as many colours as it has voices, not as many as it has bars, so a\n * conversation of two people is two draws however long it runs.\n */\nexport function groupByPaint<K>(\n boxes: readonly BarBox[],\n keyOf: (index: number) => K\n): Map<K, BarBox[]> {\n const groups = new Map<K, BarBox[]>()\n for (let i = 0; i < boxes.length; i++) {\n const key = keyOf(i)\n const run = groups.get(key)\n if (run) run.push(boxes[i])\n else groups.set(key, [boxes[i]])\n }\n return groups\n}\n\nexport function clamp01(value: number): number {\n return value < 0 ? 0 : value > 1 ? 1 : value\n}\n\n/**\n * The {@link groupByPaint} key one bar of a live visualiser takes.\n *\n * Filtered to one voice, every bar is that voice regardless of `byVoice` or\n * whose turn the bucket originally belonged to. That second part is the one\n * worth spelling out: {@link forSpeaker} silences a bar by zeroing its\n * magnitude but leaves `speaker` exactly as it was, so a bar sitting in the\n * middle of a *different* voice's turn is still stamped with that voice's\n * index — grouping by `byVoice`'s usual per-bar key would paint those silent\n * stretches in whoever used to be talking there, in flickers too short to\n * read as anything but noise. Forcing every bar under the filtered voice's own\n * key is the true picture instead: the node is drawing exactly one person, on\n * or off, never anyone else's colour.\n */\nexport function livePaintKey(\n barSpeaker: number,\n byVoice: boolean,\n filteredVoice: number | null\n): string {\n if (filteredVoice !== null) return `voice:${filteredVoice}`\n return byVoice ? `voice:${barSpeaker}` : \"all\"\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@motionscript/audio",
3
- "version": "0.1.0-alpha.7",
3
+ "version": "0.1.0-alpha.9",
4
4
  "type": "module",
5
5
  "description": "Waveform components for Motion Script: a full recording drawn as bars, and a live meter that moves with playback. Both draw a loudness envelope the host supplies.",
6
6
  "repository": {
@@ -48,8 +48,9 @@
48
48
  "animation"
49
49
  ],
50
50
  "license": "Apache-2.0",
51
+ "author": "Motionscript",
51
52
  "peerDependencies": {
52
- "@motionscript/sdk": "^0.1.0-alpha.7"
53
+ "@motionscript/sdk": "^0.1.0-alpha.9"
53
54
  },
54
55
  "devDependencies": {
55
56
  "@types/node": "^25.6.2",
@@ -60,8 +61,8 @@
60
61
  "typescript": "^6.0.3",
61
62
  "typescript-eslint": "^8.48.0",
62
63
  "vitest": "^4.1.5",
63
- "@motionscript/core": "0.1.0-alpha.7",
64
- "@motionscript/sdk": "0.1.0-alpha.7"
64
+ "@motionscript/core": "0.1.0-alpha.9",
65
+ "@motionscript/sdk": "0.1.0-alpha.9"
65
66
  },
66
67
  "scripts": {
67
68
  "build": "tsc -p tsconfig.build.json && tsc-alias -p tsconfig.build.json --resolve-full-paths && node ../../../scripts/build-browser.mjs",
package/registry.json CHANGED
@@ -1,28 +1,28 @@
1
- {
2
- "kit": {
3
- "barrel": "src/kit.ts",
4
- "specifier": "@motionscript/audio/kit"
5
- },
6
- "items": [
7
- {
8
- "name": "full-waveform",
9
- "description": "A whole recording drawn as bars, with a played portion that advances.",
10
- "root": "src/waveform",
11
- "files": [
12
- "envelope.ts",
13
- "full-waveform.ts",
14
- "shared.ts"
15
- ]
16
- },
17
- {
18
- "name": "live-waveform",
19
- "description": "A visualiser whose bars move with the recording as it plays, coloured by voice.",
20
- "root": "src/waveform",
21
- "files": [
22
- "envelope.ts",
23
- "live-waveform.ts",
24
- "shared.ts"
25
- ]
26
- }
27
- ]
28
- }
1
+ {
2
+ "kit": {
3
+ "barrel": "src/kit.ts",
4
+ "specifier": "@motionscript/audio/kit"
5
+ },
6
+ "items": [
7
+ {
8
+ "name": "full-waveform",
9
+ "description": "A whole recording drawn as bars, with a played portion that advances.",
10
+ "root": "src/waveform",
11
+ "files": [
12
+ "envelope.ts",
13
+ "full-waveform.ts",
14
+ "shared.ts"
15
+ ]
16
+ },
17
+ {
18
+ "name": "live-waveform",
19
+ "description": "A visualiser whose bars move with the recording as it plays, coloured by voice.",
20
+ "root": "src/waveform",
21
+ "files": [
22
+ "envelope.ts",
23
+ "live-waveform.ts",
24
+ "shared.ts"
25
+ ]
26
+ }
27
+ ]
28
+ }
package/src/index.ts CHANGED
@@ -1,2 +1,2 @@
1
- export * from "./waveform"
2
- export { NODES } from "./nodes";
1
+ export * from "./waveform"
2
+ export { NODES } from "./nodes";
package/src/kit.ts CHANGED
@@ -1,22 +1,22 @@
1
- /**
2
- * What the two waveform nodes share, importable without copying it.
3
- *
4
- * A registry item copies `envelope.ts` and `shared.ts` beside its node: they
5
- * hold no class and no registered state, so a fork owning its own copy splits
6
- * no identity. This is the same surface for a host that samples envelopes or
7
- * lays bars out itself, and for a fork that keeps only its node file.
8
- */
9
- export { EMPTY_ENVELOPE, forSpeaker, sampleEnvelope } from "./waveform/envelope"
10
- export type { AudioEnvelope, EnvelopeBar } from "./waveform/envelope"
11
- export {
12
- VOICE_PALETTE,
13
- WAVEFORM_ALIGNMENTS,
14
- WAVEFORM_STYLES,
15
- clamp01,
16
- groupByPaint,
17
- layOutBars,
18
- livePaintKey,
19
- paintBars,
20
- voiceColor,
21
- } from "./waveform/shared"
22
- export type { BarBox, WaveformAlignment, WaveformStyle } from "./waveform/shared"
1
+ /**
2
+ * What the two waveform nodes share, importable without copying it.
3
+ *
4
+ * A registry item copies `envelope.ts` and `shared.ts` beside its node: they
5
+ * hold no class and no registered state, so a fork owning its own copy splits
6
+ * no identity. This is the same surface for a host that samples envelopes or
7
+ * lays bars out itself, and for a fork that keeps only its node file.
8
+ */
9
+ export { EMPTY_ENVELOPE, forSpeaker, sampleEnvelope } from "./waveform/envelope"
10
+ export type { AudioEnvelope, EnvelopeBar } from "./waveform/envelope"
11
+ export {
12
+ VOICE_PALETTE,
13
+ WAVEFORM_ALIGNMENTS,
14
+ WAVEFORM_STYLES,
15
+ clamp01,
16
+ groupByPaint,
17
+ layOutBars,
18
+ livePaintKey,
19
+ paintBars,
20
+ voiceColor,
21
+ } from "./waveform/shared"
22
+ export type { BarBox, WaveformAlignment, WaveformStyle } from "./waveform/shared"
package/src/nodes.ts CHANGED
@@ -1,17 +1,17 @@
1
- import { FullWaveform } from "./waveform/full-waveform";
2
- import { LiveWaveform } from "./waveform/live-waveform";
3
-
4
- /**
5
- * Every node type this package publishes.
6
- *
7
- * A host registers these by handing the array to an engine —
8
- * `new Engine(platform, { nodes: NODES })` — which reads each component's key.
9
- * Defining a component only *declares* that key: nothing is registered by
10
- * importing a module, so a registry holds exactly what its owner asked for.
11
- *
12
- * Listing the component **values** is also what survives bundling: this package
13
- * declares `sideEffects: false`, and a document names a node type by string, so
14
- * an import kept only for its side effect is exactly what gets shaken out.
15
- */
16
- // Typed by name, so the declaration names each component rather than spelling out its type through core.
17
- export const NODES: (typeof FullWaveform | typeof LiveWaveform)[] = [FullWaveform, LiveWaveform];
1
+ import { FullWaveform } from "./waveform/full-waveform";
2
+ import { LiveWaveform } from "./waveform/live-waveform";
3
+
4
+ /**
5
+ * Every node type this package publishes.
6
+ *
7
+ * A host registers these by handing the array to an engine —
8
+ * `new Engine(platform, { nodes: NODES })` — which reads each component's key.
9
+ * Defining a component only *declares* that key: nothing is registered by
10
+ * importing a module, so a registry holds exactly what its owner asked for.
11
+ *
12
+ * Listing the component **values** is also what survives bundling: this package
13
+ * declares `sideEffects: false`, and a document names a node type by string, so
14
+ * an import kept only for its side effect is exactly what gets shaken out.
15
+ */
16
+ // Typed by name, so the declaration names each component rather than spelling out its type through core.
17
+ export const NODES: (typeof FullWaveform | typeof LiveWaveform)[] = [FullWaveform, LiveWaveform];
@@ -1,176 +1,176 @@
1
- /**
2
- * The shape of a recording, as the waveform nodes draw it.
3
- *
4
- * ## How an envelope reaches a node: the host supplies it
5
- *
6
- * Nothing in the engine, and nothing in this kit, decodes audio. A waveform node
7
- * does not read a `sound` node's `src`, declares no audio asset and is not tied
8
- * to a clip: it draws the {@link AudioEnvelope} it is handed in its `envelope`
9
- * prop. Decoding a file into an envelope is the host's job, done once per file
10
- * before the document is built. Where the recording sits on the audio lane is
11
- * the author's timing too, which is why `FullWaveform.follow` is opt-in.
12
- *
13
- * ### The JSON form
14
- *
15
- * A document holds the envelope as plain JSON, because a prop value in a
16
- * document is JSON. The typed arrays in {@link AudioEnvelope} are one spelling of
17
- * it; `ArrayLike<number>` also accepts the plain arrays a document stores:
18
- *
19
- * ```json
20
- * {
21
- * "magnitude": [0, 0.25, 0.5, 1, 0.5, 0],
22
- * "duration": 6,
23
- * "speaker": [0, 0, 0, 1, 1, -1],
24
- * "speakers": 2
25
- * }
26
- * ```
27
- *
28
- * `magnitude` is the peak loudness, `0`…`1`, of buckets that divide `duration`
29
- * seconds evenly. `speaker` is `null` when nobody was identified; otherwise it is parallel to `magnitude`, one voice
30
- * index per bucket, `-1` for "nobody". `speakers` is the voice count, `0` when
31
- * `speaker` is `null`. A `Float32Array` or `Int16Array` is not JSON-serialisable
32
- * (`JSON.stringify` writes an object of indices), so a host that holds the typed
33
- * form converts with `Array.from` before storing it in a document.
34
- *
35
- * ## Why the data is baked rather than listened to
36
- *
37
- * A scene has to render identically in the preview and in a headless export,
38
- * and an export has no audio device, no `AudioContext` and no playback to
39
- * analyse. So a "live" visualiser cannot read a Web Audio analyser: what it
40
- * reads is a *pre-computed envelope*, indexed by the scene clock. The picture is
41
- * then a pure function of time, which is what makes scrubbing backwards, jumping
42
- * to frame 900, and rendering out of order all produce the same frame.
43
- *
44
- * The decode happens in the host, once per file, and arrives here through the
45
- * build — the same arrangement a chart's rows and a protein's atoms already use,
46
- * and for the same reason: the build is synchronous and cannot await a fetch.
47
- *
48
- * ## Why magnitude rather than min/max
49
- *
50
- * An editor's waveform is drawn from per-bucket minima *and* maxima, because an
51
- * editor is a measuring instrument. These nodes are neither — they are a bar
52
- * chart of loudness that happens to be shaped like a recording — and audio is
53
- * near enough symmetric that a mirrored magnitude is indistinguishable at the
54
- * size a node draws. Half the numbers, and one array to reason about.
55
- */
56
-
57
- /**
58
- * A decoded recording, reduced to a uniform grid of loudness — plus, when the
59
- * host knows it, who is talking in each bucket.
60
- *
61
- * The speaker track is **not** something a decoder can produce; it comes from a
62
- * diarized transcript and is folded in by the host before the build. It lives
63
- * here rather than in a parallel structure because every reader of it is also a
64
- * reader of the magnitudes at the same index, and two arrays that must stay the
65
- * same length are better as one object than as two arguments.
66
- */
67
- export interface AudioEnvelope {
68
- /**
69
- * Peak magnitude per bucket, 0…1. Buckets span {@link duration} evenly. A
70
- * `Float32Array`, or the plain `number[]` a document stores.
71
- */
72
- magnitude: ArrayLike<number>
73
- /** The decoded length in seconds. */
74
- duration: number
75
- /**
76
- * Which voice is speaking in each bucket, as an index into the recording's
77
- * own numbering, or `-1` for "nobody identified". Parallel to
78
- * {@link magnitude}, or `null` when the track was never diarized.
79
- */
80
- speaker: ArrayLike<number> | null
81
- /** How many distinct voices the diarizer found. Zero when it did not run. */
82
- speakers: number
83
- }
84
-
85
- /** The envelope of a track that hasn't loaded — or isn't there. */
86
- export const EMPTY_ENVELOPE: AudioEnvelope = {
87
- magnitude: new Float32Array(0),
88
- duration: 0,
89
- speaker: null,
90
- speakers: 0,
91
- }
92
-
93
- /** One drawn bar: how loud, and whose. */
94
- export interface EnvelopeBar {
95
- /** 0…1. */
96
- magnitude: number
97
- /** The voice index, or -1. */
98
- speaker: number
99
- }
100
-
101
- /**
102
- * Resamples `[from, to)` seconds of an envelope down to `bars` columns.
103
- *
104
- * Peak-preserving rather than averaging, which is the whole difference between
105
- * a waveform and a blur: averaging a hundred buckets into one column flattens
106
- * every transient, and transients are what makes a drawn recording read as
107
- * speech rather than as noise. The speaker of a column is the speaker of its
108
- * *loudest* bucket, on the same reasoning — a column straddling a turn belongs
109
- * to whoever is actually audible in it.
110
- *
111
- * A window past either end of the recording yields silent, unattributed
112
- * columns rather than clamping onto the nearest real one. That matters for the
113
- * live visualiser, which is handed a window centred on the playhead and would
114
- * otherwise smear the first bucket across the whole run-up to a track's start.
115
- */
116
- export function sampleEnvelope(
117
- envelope: AudioEnvelope,
118
- from: number,
119
- to: number,
120
- bars: number
121
- ): EnvelopeBar[] {
122
- const count = Math.max(0, Math.floor(bars))
123
- const out: EnvelopeBar[] = new Array(count)
124
- for (let i = 0; i < count; i++) out[i] = { magnitude: 0, speaker: -1 }
125
-
126
- const buckets = envelope.magnitude.length
127
- if (count === 0 || buckets === 0 || envelope.duration <= 0) return out
128
-
129
- const perSecond = buckets / envelope.duration
130
- const span = (to - from) / count
131
-
132
- for (let i = 0; i < count; i++) {
133
- const start = (from + span * i) * perSecond
134
- const end = (from + span * (i + 1)) * perSecond
135
-
136
- // At least one bucket per column, so a window zoomed in past the grid draws
137
- // the sample it is standing on rather than an empty band.
138
- const first = Math.floor(start)
139
- const last = Math.max(first, Math.ceil(end) - 1)
140
-
141
- let loudest = 0
142
- let speaker = -1
143
- for (let b = first; b <= last; b++) {
144
- if (b < 0 || b >= buckets) continue
145
- const value = envelope.magnitude[b]
146
- if (value < loudest) continue
147
- loudest = value
148
- speaker = envelope.speaker ? envelope.speaker[b] : -1
149
- }
150
-
151
- out[i] = { magnitude: loudest, speaker }
152
- }
153
-
154
- return out
155
- }
156
-
157
- /**
158
- * The same window, with everything that isn't `voice` silenced.
159
- *
160
- * The point of the speaker filter, and the reason it silences rather than
161
- * *drops*: a podcast visualiser filtered to one host should go quiet while the
162
- * other one talks, not compress their turn out of existence. Keeping the bars
163
- * and zeroing them is what makes the picture read as "this person is not
164
- * speaking right now" instead of as a jump cut.
165
- *
166
- * `voice` of `null` returns the bars untouched, which is the unfiltered node.
167
- */
168
- export function forSpeaker(
169
- bars: EnvelopeBar[],
170
- voice: number | null
171
- ): EnvelopeBar[] {
172
- if (voice === null) return bars
173
- return bars.map((bar) =>
174
- bar.speaker === voice ? bar : { magnitude: 0, speaker: bar.speaker }
175
- )
176
- }
1
+ /**
2
+ * The shape of a recording, as the waveform nodes draw it.
3
+ *
4
+ * ## How an envelope reaches a node: the host supplies it
5
+ *
6
+ * Nothing in the engine, and nothing in this kit, decodes audio. A waveform node
7
+ * does not read a `sound` node's `src`, declares no audio asset and is not tied
8
+ * to a clip: it draws the {@link AudioEnvelope} it is handed in its `envelope`
9
+ * prop. Decoding a file into an envelope is the host's job, done once per file
10
+ * before the document is built. Where the recording sits on the audio lane is
11
+ * the author's timing too, which is why `FullWaveform.follow` is opt-in.
12
+ *
13
+ * ### The JSON form
14
+ *
15
+ * A document holds the envelope as plain JSON, because a prop value in a
16
+ * document is JSON. The typed arrays in {@link AudioEnvelope} are one spelling of
17
+ * it; `ArrayLike<number>` also accepts the plain arrays a document stores:
18
+ *
19
+ * ```json
20
+ * {
21
+ * "magnitude": [0, 0.25, 0.5, 1, 0.5, 0],
22
+ * "duration": 6,
23
+ * "speaker": [0, 0, 0, 1, 1, -1],
24
+ * "speakers": 2
25
+ * }
26
+ * ```
27
+ *
28
+ * `magnitude` is the peak loudness, `0`…`1`, of buckets that divide `duration`
29
+ * seconds evenly. `speaker` is `null` when nobody was identified; otherwise it is parallel to `magnitude`, one voice
30
+ * index per bucket, `-1` for "nobody". `speakers` is the voice count, `0` when
31
+ * `speaker` is `null`. A `Float32Array` or `Int16Array` is not JSON-serialisable
32
+ * (`JSON.stringify` writes an object of indices), so a host that holds the typed
33
+ * form converts with `Array.from` before storing it in a document.
34
+ *
35
+ * ## Why the data is baked rather than listened to
36
+ *
37
+ * A scene has to render identically in the preview and in a headless export,
38
+ * and an export has no audio device, no `AudioContext` and no playback to
39
+ * analyse. So a "live" visualiser cannot read a Web Audio analyser: what it
40
+ * reads is a *pre-computed envelope*, indexed by the scene clock. The picture is
41
+ * then a pure function of time, which is what makes scrubbing backwards, jumping
42
+ * to frame 900, and rendering out of order all produce the same frame.
43
+ *
44
+ * The decode happens in the host, once per file, and arrives here through the
45
+ * build — the same arrangement a chart's rows and a protein's atoms already use,
46
+ * and for the same reason: the build is synchronous and cannot await a fetch.
47
+ *
48
+ * ## Why magnitude rather than min/max
49
+ *
50
+ * An editor's waveform is drawn from per-bucket minima *and* maxima, because an
51
+ * editor is a measuring instrument. These nodes are neither — they are a bar
52
+ * chart of loudness that happens to be shaped like a recording — and audio is
53
+ * near enough symmetric that a mirrored magnitude is indistinguishable at the
54
+ * size a node draws. Half the numbers, and one array to reason about.
55
+ */
56
+
57
+ /**
58
+ * A decoded recording, reduced to a uniform grid of loudness — plus, when the
59
+ * host knows it, who is talking in each bucket.
60
+ *
61
+ * The speaker track is **not** something a decoder can produce; it comes from a
62
+ * diarized transcript and is folded in by the host before the build. It lives
63
+ * here rather than in a parallel structure because every reader of it is also a
64
+ * reader of the magnitudes at the same index, and two arrays that must stay the
65
+ * same length are better as one object than as two arguments.
66
+ */
67
+ export interface AudioEnvelope {
68
+ /**
69
+ * Peak magnitude per bucket, 0…1. Buckets span {@link duration} evenly. A
70
+ * `Float32Array`, or the plain `number[]` a document stores.
71
+ */
72
+ magnitude: ArrayLike<number>
73
+ /** The decoded length in seconds. */
74
+ duration: number
75
+ /**
76
+ * Which voice is speaking in each bucket, as an index into the recording's
77
+ * own numbering, or `-1` for "nobody identified". Parallel to
78
+ * {@link magnitude}, or `null` when the track was never diarized.
79
+ */
80
+ speaker: ArrayLike<number> | null
81
+ /** How many distinct voices the diarizer found. Zero when it did not run. */
82
+ speakers: number
83
+ }
84
+
85
+ /** The envelope of a track that hasn't loaded — or isn't there. */
86
+ export const EMPTY_ENVELOPE: AudioEnvelope = {
87
+ magnitude: new Float32Array(0),
88
+ duration: 0,
89
+ speaker: null,
90
+ speakers: 0,
91
+ }
92
+
93
+ /** One drawn bar: how loud, and whose. */
94
+ export interface EnvelopeBar {
95
+ /** 0…1. */
96
+ magnitude: number
97
+ /** The voice index, or -1. */
98
+ speaker: number
99
+ }
100
+
101
+ /**
102
+ * Resamples `[from, to)` seconds of an envelope down to `bars` columns.
103
+ *
104
+ * Peak-preserving rather than averaging, which is the whole difference between
105
+ * a waveform and a blur: averaging a hundred buckets into one column flattens
106
+ * every transient, and transients are what makes a drawn recording read as
107
+ * speech rather than as noise. The speaker of a column is the speaker of its
108
+ * *loudest* bucket, on the same reasoning — a column straddling a turn belongs
109
+ * to whoever is actually audible in it.
110
+ *
111
+ * A window past either end of the recording yields silent, unattributed
112
+ * columns rather than clamping onto the nearest real one. That matters for the
113
+ * live visualiser, which is handed a window centred on the playhead and would
114
+ * otherwise smear the first bucket across the whole run-up to a track's start.
115
+ */
116
+ export function sampleEnvelope(
117
+ envelope: AudioEnvelope,
118
+ from: number,
119
+ to: number,
120
+ bars: number
121
+ ): EnvelopeBar[] {
122
+ const count = Math.max(0, Math.floor(bars))
123
+ const out: EnvelopeBar[] = new Array(count)
124
+ for (let i = 0; i < count; i++) out[i] = { magnitude: 0, speaker: -1 }
125
+
126
+ const buckets = envelope.magnitude.length
127
+ if (count === 0 || buckets === 0 || envelope.duration <= 0) return out
128
+
129
+ const perSecond = buckets / envelope.duration
130
+ const span = (to - from) / count
131
+
132
+ for (let i = 0; i < count; i++) {
133
+ const start = (from + span * i) * perSecond
134
+ const end = (from + span * (i + 1)) * perSecond
135
+
136
+ // At least one bucket per column, so a window zoomed in past the grid draws
137
+ // the sample it is standing on rather than an empty band.
138
+ const first = Math.floor(start)
139
+ const last = Math.max(first, Math.ceil(end) - 1)
140
+
141
+ let loudest = 0
142
+ let speaker = -1
143
+ for (let b = first; b <= last; b++) {
144
+ if (b < 0 || b >= buckets) continue
145
+ const value = envelope.magnitude[b]
146
+ if (value < loudest) continue
147
+ loudest = value
148
+ speaker = envelope.speaker ? envelope.speaker[b] : -1
149
+ }
150
+
151
+ out[i] = { magnitude: loudest, speaker }
152
+ }
153
+
154
+ return out
155
+ }
156
+
157
+ /**
158
+ * The same window, with everything that isn't `voice` silenced.
159
+ *
160
+ * The point of the speaker filter, and the reason it silences rather than
161
+ * *drops*: a podcast visualiser filtered to one host should go quiet while the
162
+ * other one talks, not compress their turn out of existence. Keeping the bars
163
+ * and zeroing them is what makes the picture read as "this person is not
164
+ * speaking right now" instead of as a jump cut.
165
+ *
166
+ * `voice` of `null` returns the bars untouched, which is the unfiltered node.
167
+ */
168
+ export function forSpeaker(
169
+ bars: EnvelopeBar[],
170
+ voice: number | null
171
+ ): EnvelopeBar[] {
172
+ if (voice === null) return bars
173
+ return bars.map((bar) =>
174
+ bar.speaker === voice ? bar : { magnitude: 0, speaker: bar.speaker }
175
+ )
176
+ }