@motionscript/browser 0.1.0-alpha.3 → 0.1.0-alpha.6
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.
- package/CHANGELOG.md +108 -0
- package/LICENSE +201 -201
- package/NOTICE +48 -0
- package/README.md +118 -69
- package/dist/asset-bytes.js.map +1 -1
- package/dist/audio/bus-graph.d.ts +2 -2
- package/dist/audio/bus-graph.d.ts.map +1 -1
- package/dist/audio/bus-graph.js +6 -6
- package/dist/audio/bus-graph.js.map +1 -1
- package/dist/audio/filter-graph.d.ts +5 -5
- package/dist/audio/filter-graph.d.ts.map +1 -1
- package/dist/audio/filter-graph.js +15 -15
- package/dist/audio/filter-graph.js.map +1 -1
- package/dist/audio/index.js.map +1 -1
- package/dist/audio/loop-region.d.ts +31 -0
- package/dist/audio/loop-region.d.ts.map +1 -0
- package/dist/audio/loop-region.js +43 -0
- package/dist/audio/loop-region.js.map +1 -0
- package/dist/audio/mixer.d.ts.map +1 -1
- package/dist/audio/mixer.js +26 -10
- package/dist/audio/mixer.js.map +1 -1
- package/dist/audio/player.d.ts +4 -4
- package/dist/audio/player.d.ts.map +1 -1
- package/dist/audio/player.js +15 -14
- package/dist/audio/player.js.map +1 -1
- package/dist/browser/THIRD_PARTY_LICENSES.txt +432 -0
- package/dist/browser/audio.js +1 -1
- package/dist/browser/chunks/chunk-2MAFJWBZ.js +2 -0
- package/dist/browser/chunks/chunk-2MAFJWBZ.js.map +7 -0
- package/dist/browser/index.js +130 -276
- package/dist/browser/index.js.map +4 -4
- package/dist/browser/manifest.json +19 -2
- package/dist/concat.js.map +1 -1
- package/dist/decode/image-levels.js.map +1 -1
- package/dist/decode/levels.js.map +1 -1
- package/dist/decode/video-levels.js.map +1 -1
- package/dist/dynamic-nodes.d.ts.map +1 -1
- package/dist/dynamic-nodes.js +6 -12
- package/dist/dynamic-nodes.js.map +1 -1
- package/dist/engine.d.ts +6 -6
- package/dist/engine.d.ts.map +1 -1
- package/dist/engine.js +1 -0
- package/dist/engine.js.map +1 -1
- package/dist/exporter.d.ts +8 -2
- package/dist/exporter.d.ts.map +1 -1
- package/dist/exporter.js +8 -7
- package/dist/exporter.js.map +1 -1
- package/dist/getter.js.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/measure-context.js.map +1 -1
- package/dist/mix-timeline-audio.d.ts +2 -2
- package/dist/mix-timeline-audio.d.ts.map +1 -1
- package/dist/mix-timeline-audio.js +1 -2
- package/dist/mix-timeline-audio.js.map +1 -1
- package/dist/render-context.js.map +1 -1
- package/dist/screenshot.d.ts +3 -3
- package/dist/screenshot.d.ts.map +1 -1
- package/dist/screenshot.js +1 -2
- package/dist/screenshot.js.map +1 -1
- package/dist/still.d.ts +6 -4
- package/dist/still.d.ts.map +1 -1
- package/dist/still.js +12 -9
- package/dist/still.js.map +1 -1
- package/dist/storage-adapter.d.ts.map +1 -1
- package/dist/storage-adapter.js +5 -4
- package/dist/storage-adapter.js.map +1 -1
- package/dist/three/renderer.js.map +1 -1
- package/dist/ticker.d.ts +22 -4
- package/dist/ticker.d.ts.map +1 -1
- package/dist/ticker.js +65 -28
- package/dist/ticker.js.map +1 -1
- package/package.json +7 -6
- package/dist/browser/chunks/chunk-M7XD73ED.js +0 -2
- package/dist/browser/chunks/chunk-M7XD73ED.js.map +0 -7
- package/dist/output.d.ts +0 -7
- package/dist/output.d.ts.map +0 -1
- package/dist/output.js +0 -6
- package/dist/output.js.map +0 -1
package/dist/ticker.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Ticker } from "@motionscript/core";
|
|
2
2
|
/**
|
|
3
|
-
* Ticker backed by a Web Audio AudioContext.
|
|
3
|
+
* Ticker backed by a Web Audio AudioContext. Clip time advances in
|
|
4
4
|
* lock-step with `audioContext.currentTime`, so any AudioBufferSourceNodes
|
|
5
5
|
* scheduled on the same context play perfectly in sync.
|
|
6
6
|
*
|
|
@@ -20,6 +20,8 @@ export declare class WebTicker extends Ticker {
|
|
|
20
20
|
private speed;
|
|
21
21
|
private reverse;
|
|
22
22
|
private rafId;
|
|
23
|
+
/** Bumped by every `seek`, so the loop can tell that a listener or tick callback moved the playhead under it. */
|
|
24
|
+
private seekEpoch;
|
|
23
25
|
private silentSource;
|
|
24
26
|
constructor(opts: {
|
|
25
27
|
context?: AudioContext;
|
|
@@ -27,14 +29,30 @@ export declare class WebTicker extends Ticker {
|
|
|
27
29
|
});
|
|
28
30
|
getContext(): AudioContext;
|
|
29
31
|
seek(t: number): void;
|
|
30
|
-
/**
|
|
31
|
-
|
|
32
|
+
/**
|
|
33
|
+
* Anchors elapsed-time tracking to the current `context.currentTime`, starts the silent ticker
|
|
34
|
+
* + rAF tick loop and asks a suspended context to resume.
|
|
35
|
+
*
|
|
36
|
+
* Synchronous, as {@link Ticker.play} is: a `pause` or `seek` in the same turn must find a
|
|
37
|
+
* running clock to stop. A suspended context's `currentTime` is frozen, so the clock holds at
|
|
38
|
+
* the anchor until the resume lands — outside a user gesture that is never.
|
|
39
|
+
*/
|
|
40
|
+
play(speed?: number, reverse?: boolean): void;
|
|
32
41
|
/** Stops the tick loop and silent ticker, then suspends the context — freezing `currentTime` so elapsed-time math stays correct across the pause. */
|
|
33
42
|
pause(): void;
|
|
34
43
|
/** (Re)starts the silent buffer source covering the remaining timeline — keeps the AudioContext active and gives a stable graph for other AudioBufferSourceNodes to schedule against, per the class-level note. */
|
|
35
44
|
private startSilentTicker;
|
|
36
45
|
private stopSilentTicker;
|
|
37
|
-
/**
|
|
46
|
+
/** Where the playhead is now, from elapsed `context.currentTime` (so it stays sample-accurate), and whether that is the end of the run. */
|
|
47
|
+
private position;
|
|
48
|
+
/**
|
|
49
|
+
* Drives ticks off `requestAnimationFrame`, firing `tick()` only when a full frame interval
|
|
50
|
+
* has elapsed — and once more at the end of the run, whether or not it landed on a boundary.
|
|
51
|
+
*
|
|
52
|
+
* A listener may `seek` (a host looping wraps to 0 when it hears the end), so the end is
|
|
53
|
+
* re-read after the listeners and the tick callbacks have run: a run that was seeked out of
|
|
54
|
+
* its end carries on, and one that was not pauses itself.
|
|
55
|
+
*/
|
|
38
56
|
private startLoop;
|
|
39
57
|
private stopLoop;
|
|
40
58
|
dispose(): void;
|
package/dist/ticker.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ticker.d.ts","sourceRoot":"","sources":["../src/ticker.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAE5C;;;;;;;;;;;GAWG;AACH,qBAAa,SAAU,SAAQ,MAAM;IACjC,OAAO,CAAC,OAAO,CAAe;IAC9B,OAAO,CAAC,WAAW,CAAU;IAC7B,OAAO,CAAC,GAAG,CAAS;IAEpB,OAAO,CAAC,gBAAgB,CAAa;IACrC,OAAO,CAAC,UAAU,CAAa;IAC/B,OAAO,CAAC,KAAK,CAAa;IAC1B,OAAO,CAAC,OAAO,CAAkB;IAEjC,OAAO,CAAC,KAAK,CAAuB;IACpC,OAAO,CAAC,YAAY,CAAsC;gBAE9C,IAAI,EAAE;QAAE,OAAO,CAAC,EAAE,YAAY,CAAC;QAAC,GAAG,EAAE,MAAM,CAAA;KAAE;IAOzD,UAAU,IAAI,YAAY;IAI1B,IAAI,CAAC,CAAC,EAAE,MAAM,GAAG,IAAI;
|
|
1
|
+
{"version":3,"file":"ticker.d.ts","sourceRoot":"","sources":["../src/ticker.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAE5C;;;;;;;;;;;GAWG;AACH,qBAAa,SAAU,SAAQ,MAAM;IACjC,OAAO,CAAC,OAAO,CAAe;IAC9B,OAAO,CAAC,WAAW,CAAU;IAC7B,OAAO,CAAC,GAAG,CAAS;IAEpB,OAAO,CAAC,gBAAgB,CAAa;IACrC,OAAO,CAAC,UAAU,CAAa;IAC/B,OAAO,CAAC,KAAK,CAAa;IAC1B,OAAO,CAAC,OAAO,CAAkB;IAEjC,OAAO,CAAC,KAAK,CAAuB;IACpC,iHAAiH;IACjH,OAAO,CAAC,SAAS,CAAa;IAC9B,OAAO,CAAC,YAAY,CAAsC;gBAE9C,IAAI,EAAE;QAAE,OAAO,CAAC,EAAE,YAAY,CAAC;QAAC,GAAG,EAAE,MAAM,CAAA;KAAE;IAOzD,UAAU,IAAI,YAAY;IAI1B,IAAI,CAAC,CAAC,EAAE,MAAM,GAAG,IAAI;IAQrB;;;;;;;OAOG;IACH,IAAI,CAAC,KAAK,GAAE,MAAU,EAAE,OAAO,GAAE,OAAe,GAAG,IAAI;IAwBvD,qJAAqJ;IACrJ,KAAK,IAAI,IAAI;IAUb,mNAAmN;IACnN,OAAO,CAAC,iBAAiB;IAYzB,OAAO,CAAC,gBAAgB;IAaxB,2IAA2I;IAC3I,OAAO,CAAC,QAAQ;IAShB;;;;;;;OAOG;IACH,OAAO,CAAC,SAAS;IA+CjB,OAAO,CAAC,QAAQ;IAOhB,OAAO,IAAI,IAAI;CAQlB"}
|
package/dist/ticker.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Ticker } from "@motionscript/core";
|
|
2
2
|
/**
|
|
3
|
-
* Ticker backed by a Web Audio AudioContext.
|
|
3
|
+
* Ticker backed by a Web Audio AudioContext. Clip time advances in
|
|
4
4
|
* lock-step with `audioContext.currentTime`, so any AudioBufferSourceNodes
|
|
5
5
|
* scheduled on the same context play perfectly in sync.
|
|
6
6
|
*
|
|
@@ -20,6 +20,8 @@ export class WebTicker extends Ticker {
|
|
|
20
20
|
speed = 1;
|
|
21
21
|
reverse = false;
|
|
22
22
|
rafId = null;
|
|
23
|
+
/** Bumped by every `seek`, so the loop can tell that a listener or tick callback moved the playhead under it. */
|
|
24
|
+
seekEpoch = 0;
|
|
23
25
|
silentSource = null;
|
|
24
26
|
constructor(opts) {
|
|
25
27
|
super();
|
|
@@ -34,15 +36,30 @@ export class WebTicker extends Ticker {
|
|
|
34
36
|
const clamped = Math.max(0, Math.min(t, this.duration));
|
|
35
37
|
this.seekOffset = clamped;
|
|
36
38
|
this.playStartCtxTime = this.context.currentTime;
|
|
39
|
+
this.seekEpoch++;
|
|
37
40
|
this.setCurrentTime(clamped);
|
|
38
41
|
}
|
|
39
|
-
/**
|
|
40
|
-
|
|
42
|
+
/**
|
|
43
|
+
* Anchors elapsed-time tracking to the current `context.currentTime`, starts the silent ticker
|
|
44
|
+
* + rAF tick loop and asks a suspended context to resume.
|
|
45
|
+
*
|
|
46
|
+
* Synchronous, as {@link Ticker.play} is: a `pause` or `seek` in the same turn must find a
|
|
47
|
+
* running clock to stop. A suspended context's `currentTime` is frozen, so the clock holds at
|
|
48
|
+
* the anchor until the resume lands — outside a user gesture that is never.
|
|
49
|
+
*/
|
|
50
|
+
play(speed = 1, reverse = false) {
|
|
41
51
|
this.speed = speed;
|
|
42
52
|
this.reverse = reverse;
|
|
43
53
|
this.seekOffset = this.currentTime;
|
|
44
54
|
if (this.context.state === "suspended") {
|
|
45
|
-
|
|
55
|
+
this.context.resume().then(() => {
|
|
56
|
+
// A pause that arrived while the resume was pending could not suspend it.
|
|
57
|
+
if (!this.isPlaying && this.context.state === "running")
|
|
58
|
+
void this.context.suspend();
|
|
59
|
+
}, (error) => {
|
|
60
|
+
console.error("[WebTicker] The audio context could not resume:", error);
|
|
61
|
+
this.pause();
|
|
62
|
+
});
|
|
46
63
|
}
|
|
47
64
|
this.playStartCtxTime = this.context.currentTime;
|
|
48
65
|
this.startSilentTicker();
|
|
@@ -84,43 +101,63 @@ export class WebTicker extends Ticker {
|
|
|
84
101
|
this.silentSource = null;
|
|
85
102
|
}
|
|
86
103
|
}
|
|
87
|
-
/**
|
|
104
|
+
/** Where the playhead is now, from elapsed `context.currentTime` (so it stays sample-accurate), and whether that is the end of the run. */
|
|
105
|
+
position() {
|
|
106
|
+
const elapsed = (this.context.currentTime - this.playStartCtxTime) * this.speed;
|
|
107
|
+
const next = this.reverse
|
|
108
|
+
? this.seekOffset - elapsed
|
|
109
|
+
: this.seekOffset + elapsed;
|
|
110
|
+
const time = Math.max(0, Math.min(next, this.duration));
|
|
111
|
+
return { time, ended: this.reverse ? time <= 0 : time >= this.duration };
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Drives ticks off `requestAnimationFrame`, firing `tick()` only when a full frame interval
|
|
115
|
+
* has elapsed — and once more at the end of the run, whether or not it landed on a boundary.
|
|
116
|
+
*
|
|
117
|
+
* A listener may `seek` (a host looping wraps to 0 when it hears the end), so the end is
|
|
118
|
+
* re-read after the listeners and the tick callbacks have run: a run that was seeked out of
|
|
119
|
+
* its end carries on, and one that was not pauses itself.
|
|
120
|
+
*/
|
|
88
121
|
startLoop() {
|
|
89
122
|
if (this.rafId !== null)
|
|
90
123
|
return;
|
|
91
124
|
const frameDt = 1 / this.fps;
|
|
92
125
|
let lastTickTime = this.currentTime;
|
|
93
126
|
const loop = async () => {
|
|
94
|
-
|
|
95
|
-
const
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
//
|
|
101
|
-
//
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
127
|
+
let epoch = this.seekEpoch;
|
|
128
|
+
const position = this.position();
|
|
129
|
+
let ended = position.ended;
|
|
130
|
+
// This loop runs at the display's refresh rate, which on a 120 or 144Hz panel is two
|
|
131
|
+
// or three times the rate anything is rendered at — so the clock advances every time
|
|
132
|
+
// round (the elapsed maths in `play`/`pause` depend on it being exact) while listeners
|
|
133
|
+
// hear about it once per frame. The end of the run always reports, or the final
|
|
134
|
+
// position would never reach a host. See `Ticker.setCurrentTime`.
|
|
135
|
+
const crossed = Math.abs(position.time - lastTickTime) >= frameDt;
|
|
136
|
+
const report = crossed || ended;
|
|
137
|
+
this.setCurrentTime(position.time, report);
|
|
138
|
+
const reread = () => {
|
|
139
|
+
if (this.seekEpoch === epoch)
|
|
140
|
+
return;
|
|
141
|
+
epoch = this.seekEpoch;
|
|
142
|
+
lastTickTime = this.currentTime;
|
|
143
|
+
ended = this.position().ended;
|
|
144
|
+
};
|
|
145
|
+
reread();
|
|
146
|
+
if (report) {
|
|
147
|
+
lastTickTime = this.currentTime;
|
|
148
|
+
// Await so that a slow tick (asset load on a clip
|
|
113
149
|
// boundary) doesn't queue a second concurrent tick.
|
|
114
150
|
await this.tick();
|
|
115
|
-
|
|
116
|
-
if (ended) {
|
|
117
|
-
this.rafId = null;
|
|
118
|
-
return;
|
|
151
|
+
reread();
|
|
119
152
|
}
|
|
120
153
|
// If pause() cleared the rafId while we were awaiting tick(),
|
|
121
154
|
// do not resume the loop.
|
|
122
155
|
if (this.rafId === null)
|
|
123
156
|
return;
|
|
157
|
+
if (ended) {
|
|
158
|
+
this.pause();
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
124
161
|
this.rafId = requestAnimationFrame(loop);
|
|
125
162
|
};
|
|
126
163
|
this.rafId = requestAnimationFrame(loop);
|
package/dist/ticker.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ticker.js","sourceRoot":"","sources":["../src/ticker.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAE5C;;;;;;;;;;;GAWG;AACH,MAAM,OAAO,SAAU,SAAQ,MAAM;IACzB,OAAO,CAAe;IACtB,WAAW,CAAU;IACrB,GAAG,CAAS;IAEZ,gBAAgB,GAAW,CAAC,CAAC;IAC7B,UAAU,GAAW,CAAC,CAAC;IACvB,KAAK,GAAW,CAAC,CAAC;IAClB,OAAO,GAAY,KAAK,CAAC;IAEzB,KAAK,GAAkB,IAAI,CAAC;IAC5B,YAAY,GAAiC,IAAI,CAAC;IAE1D,YAAY,IAA6C;QACrD,KAAK,EAAE,CAAC;QACR,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,IAAI,IAAI,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I,CAAC;gBAClB,OAAO;YACX,CAAC;YACD,8DAA8D;YAC9D,0BAA0B;YAC1B,IAAI,IAAI,CAAC,KAAK,KAAK,IAAI;gBAAE,OAAO;YAChC,IAAI,CAAC,KAAK,GAAG,qBAAqB,CAAC,IAAI,CAAC,CAAC;QAC7C,CAAC,CAAC;QAEF,IAAI,CAAC,KAAK,GAAG,qBAAqB,CAAC,IAAI,CAAC,CAAC;IAC7C,CAAC;IAEO,QAAQ;QACZ,IAAI,IAAI,CAAC,KAAK,KAAK,IAAI,EAAE,CAAC;YACtB,oBAAoB,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;YACjC,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;QACtB,CAAC;IACL,CAAC;IAED,OAAO;QACH,IAAI,CAAC,QAAQ,EAAE,CAAC;QAChB,IAAI,CAAC,gBAAgB,EAAE,CAAC;QACxB,IAAI,IAAI,CAAC,WAAW,EAAE,CAAC;YACnB,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;QACzB,CAAC;QACD,KAAK,CAAC,OAAO,EAAE,CAAC;IACpB,CAAC;CACJ","sourcesContent":["import { Ticker } from \"@motionscript/core\";\n\n/**\n * Ticker backed by a Web Audio AudioContext. Scene time advances in\n * lock-step with `audioContext.currentTime`, so any AudioBufferSourceNodes\n * scheduled on the same context play perfectly in sync.\n *\n * When paused we suspend the context (audio stops, currentTime freezes);\n * when playing we resume and a rAF loop publishes ticks at the target fps.\n *\n * A single silent buffer covering the full timeline is started on play(),\n * which keeps the context active and gives the browser a stable audio\n * graph to schedule against even on scenes that contain no audio nodes.\n */\nexport class WebTicker extends Ticker {\n private context: AudioContext;\n private ownsContext: boolean;\n private fps: number;\n\n private playStartCtxTime: number = 0;\n private seekOffset: number = 0;\n private speed: number = 1;\n private reverse: boolean = false;\n\n private rafId: number | null = null;\n private silentSource: AudioBufferSourceNode | null = null;\n\n constructor(opts: { context?: AudioContext; fps: number }) {\n super();\n this.context = opts.context ?? new AudioContext();\n this.ownsContext = !opts.context;\n this.fps = opts.fps;\n }\n\n getContext(): AudioContext {\n return this.context;\n }\n\n seek(t: number): void {\n const clamped = Math.max(0, Math.min(t, this.duration));\n this.seekOffset = clamped;\n this.playStartCtxTime = this.context.currentTime;\n this.setCurrentTime(clamped);\n }\n\n /** Resumes the (possibly suspended) context, anchors elapsed-time tracking to the current `context.currentTime`, and starts the silent ticker + rAF tick loop. */\n async play(speed: number = 1, reverse: boolean = false): Promise<void> {\n this.speed = speed;\n this.reverse = reverse;\n this.seekOffset = this.currentTime;\n\n if (this.context.state === \"suspended\") {\n await this.context.resume();\n }\n\n this.playStartCtxTime = this.context.currentTime;\n this.startSilentTicker();\n super.play(speed, reverse);\n this.startLoop();\n }\n\n /** Stops the tick loop and silent ticker, then suspends the context — freezing `currentTime` so elapsed-time math stays correct across the pause. */\n pause(): void {\n this.seekOffset = this.currentTime;\n this.stopLoop();\n this.stopSilentTicker();\n if (this.context.state === \"running\") {\n this.context.suspend();\n }\n super.pause();\n }\n\n /** (Re)starts the silent buffer source covering the remaining timeline — keeps the AudioContext active and gives a stable graph for other AudioBufferSourceNodes to schedule against, per the class-level note. */\n private startSilentTicker(): void {\n this.stopSilentTicker();\n const remaining = Math.max(0.001, this.duration - this.seekOffset);\n const sampleRate = this.context.sampleRate;\n const buffer = this.context.createBuffer(1, Math.ceil(remaining * sampleRate), sampleRate);\n const source = this.context.createBufferSource();\n source.buffer = buffer;\n source.connect(this.context.destination);\n source.start();\n this.silentSource = source;\n }\n\n private stopSilentTicker(): void {\n if (this.silentSource) {\n try {\n this.silentSource.onended = null;\n this.silentSource.stop();\n this.silentSource.disconnect();\n } catch {\n // already stopped\n }\n this.silentSource = null;\n }\n }\n\n /** Drives ticks off `requestAnimationFrame`, deriving scene time from elapsed `context.currentTime` (so it stays sample-accurate) and only firing `tick()` when a full frame interval has elapsed. */\n private startLoop(): void {\n if (this.rafId !== null) return;\n const frameDt = 1 / this.fps;\n let lastTickTime = this.currentTime;\n\n const loop = async () => {\n const elapsed = (this.context.currentTime - this.playStartCtxTime) * this.speed;\n const next = this.reverse\n ? this.seekOffset - elapsed\n : this.seekOffset + elapsed;\n const clamped = Math.max(0, Math.min(next, this.duration));\n const ended = this.reverse ? clamped <= 0 : clamped >= this.duration;\n // Whether this animation frame has carried the playhead onto a new\n // *scene* frame. This loop runs at the display's refresh rate, which\n // on a 120 or 144Hz panel is two or three times the rate anything is\n // rendered at — so the clock advances every time round (the elapsed\n // maths in `play`/`pause` depend on it being exact) while listeners\n // hear about it once per frame. The end of the run always reports,\n // whether or not it landed on a boundary, or the final position would\n // never reach a host. See `Ticker.setCurrentTime`.\n const crossed = Math.abs(clamped - lastTickTime) >= frameDt;\n this.setCurrentTime(clamped, crossed || ended);\n\n if (crossed) {\n lastTickTime = clamped;\n // Await so that a slow tick (asset load on a scene\n // boundary) doesn't queue a second concurrent tick.\n await this.tick();\n }\n\n if (ended) {\n this.rafId = null;\n return;\n }\n // If pause() cleared the rafId while we were awaiting tick(),\n // do not resume the loop.\n if (this.rafId === null) return;\n this.rafId = requestAnimationFrame(loop);\n };\n\n this.rafId = requestAnimationFrame(loop);\n }\n\n private stopLoop(): void {\n if (this.rafId !== null) {\n cancelAnimationFrame(this.rafId);\n this.rafId = null;\n }\n }\n\n dispose(): void {\n this.stopLoop();\n this.stopSilentTicker();\n if (this.ownsContext) {\n this.context.close();\n }\n super.dispose();\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"ticker.js","sourceRoot":"","sources":["../src/ticker.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAE5C;;;;;;;;;;;GAWG;AACH,MAAM,OAAO,SAAU,SAAQ,MAAM;IACzB,OAAO,CAAe;IACtB,WAAW,CAAU;IACrB,GAAG,CAAS;IAEZ,gBAAgB,GAAW,CAAC,CAAC;IAC7B,UAAU,GAAW,CAAC,CAAC;IACvB,KAAK,GAAW,CAAC,CAAC;IAClB,OAAO,GA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CAAC;gBACb,OAAO;YACX,CAAC;YACD,IAAI,CAAC,KAAK,GAAG,qBAAqB,CAAC,IAAI,CAAC,CAAC;QAC7C,CAAC,CAAC;QAEF,IAAI,CAAC,KAAK,GAAG,qBAAqB,CAAC,IAAI,CAAC,CAAC;IAC7C,CAAC;IAEO,QAAQ;QACZ,IAAI,IAAI,CAAC,KAAK,KAAK,IAAI,EAAE,CAAC;YACtB,oBAAoB,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;YACjC,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;QACtB,CAAC;IACL,CAAC;IAED,OAAO;QACH,IAAI,CAAC,QAAQ,EAAE,CAAC;QAChB,IAAI,CAAC,gBAAgB,EAAE,CAAC;QACxB,IAAI,IAAI,CAAC,WAAW,EAAE,CAAC;YACnB,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;QACzB,CAAC;QACD,KAAK,CAAC,OAAO,EAAE,CAAC;IACpB,CAAC;CACJ","sourcesContent":["import { Ticker } from \"@motionscript/core\";\r\n\r\n/**\r\n * Ticker backed by a Web Audio AudioContext. Clip time advances in\r\n * lock-step with `audioContext.currentTime`, so any AudioBufferSourceNodes\r\n * scheduled on the same context play perfectly in sync.\r\n *\r\n * When paused we suspend the context (audio stops, currentTime freezes);\r\n * when playing we resume and a rAF loop publishes ticks at the target fps.\r\n *\r\n * A single silent buffer covering the full timeline is started on play(),\r\n * which keeps the context active and gives the browser a stable audio\r\n * graph to schedule against even on scenes that contain no audio nodes.\r\n */\r\nexport class WebTicker extends Ticker {\r\n private context: AudioContext;\r\n private ownsContext: boolean;\r\n private fps: number;\r\n\r\n private playStartCtxTime: number = 0;\r\n private seekOffset: number = 0;\r\n private speed: number = 1;\r\n private reverse: boolean = false;\r\n\r\n private rafId: number | null = null;\r\n /** Bumped by every `seek`, so the loop can tell that a listener or tick callback moved the playhead under it. */\r\n private seekEpoch: number = 0;\r\n private silentSource: AudioBufferSourceNode | null = null;\r\n\r\n constructor(opts: { context?: AudioContext; fps: number }) {\r\n super();\r\n this.context = opts.context ?? new AudioContext();\r\n this.ownsContext = !opts.context;\r\n this.fps = opts.fps;\r\n }\r\n\r\n getContext(): AudioContext {\r\n return this.context;\r\n }\r\n\r\n seek(t: number): void {\r\n const clamped = Math.max(0, Math.min(t, this.duration));\r\n this.seekOffset = clamped;\r\n this.playStartCtxTime = this.context.currentTime;\r\n this.seekEpoch++;\r\n this.setCurrentTime(clamped);\r\n }\r\n\r\n /**\r\n * Anchors elapsed-time tracking to the current `context.currentTime`, starts the silent ticker\r\n * + rAF tick loop and asks a suspended context to resume.\r\n *\r\n * Synchronous, as {@link Ticker.play} is: a `pause` or `seek` in the same turn must find a\r\n * running clock to stop. A suspended context's `currentTime` is frozen, so the clock holds at\r\n * the anchor until the resume lands — outside a user gesture that is never.\r\n */\r\n play(speed: number = 1, reverse: boolean = false): void {\r\n this.speed = speed;\r\n this.reverse = reverse;\r\n this.seekOffset = this.currentTime;\r\n\r\n if (this.context.state === \"suspended\") {\r\n this.context.resume().then(\r\n () => {\r\n // A pause that arrived while the resume was pending could not suspend it.\r\n if (!this.isPlaying && this.context.state === \"running\") void this.context.suspend();\r\n },\r\n (error) => {\r\n console.error(\"[WebTicker] The audio context could not resume:\", error);\r\n this.pause();\r\n },\r\n );\r\n }\r\n\r\n this.playStartCtxTime = this.context.currentTime;\r\n this.startSilentTicker();\r\n super.play(speed, reverse);\r\n this.startLoop();\r\n }\r\n\r\n /** Stops the tick loop and silent ticker, then suspends the context — freezing `currentTime` so elapsed-time math stays correct across the pause. */\r\n pause(): void {\r\n this.seekOffset = this.currentTime;\r\n this.stopLoop();\r\n this.stopSilentTicker();\r\n if (this.context.state === \"running\") {\r\n this.context.suspend();\r\n }\r\n super.pause();\r\n }\r\n\r\n /** (Re)starts the silent buffer source covering the remaining timeline — keeps the AudioContext active and gives a stable graph for other AudioBufferSourceNodes to schedule against, per the class-level note. */\r\n private startSilentTicker(): void {\r\n this.stopSilentTicker();\r\n const remaining = Math.max(0.001, this.duration - this.seekOffset);\r\n const sampleRate = this.context.sampleRate;\r\n const buffer = this.context.createBuffer(1, Math.ceil(remaining * sampleRate), sampleRate);\r\n const source = this.context.createBufferSource();\r\n source.buffer = buffer;\r\n source.connect(this.context.destination);\r\n source.start();\r\n this.silentSource = source;\r\n }\r\n\r\n private stopSilentTicker(): void {\r\n if (this.silentSource) {\r\n try {\r\n this.silentSource.onended = null;\r\n this.silentSource.stop();\r\n this.silentSource.disconnect();\r\n } catch {\r\n // already stopped\r\n }\r\n this.silentSource = null;\r\n }\r\n }\r\n\r\n /** Where the playhead is now, from elapsed `context.currentTime` (so it stays sample-accurate), and whether that is the end of the run. */\r\n private position(): { time: number; ended: boolean } {\r\n const elapsed = (this.context.currentTime - this.playStartCtxTime) * this.speed;\r\n const next = this.reverse\r\n ? this.seekOffset - elapsed\r\n : this.seekOffset + elapsed;\r\n const time = Math.max(0, Math.min(next, this.duration));\r\n return { time, ended: this.reverse ? time <= 0 : time >= this.duration };\r\n }\r\n\r\n /**\r\n * Drives ticks off `requestAnimationFrame`, firing `tick()` only when a full frame interval\r\n * has elapsed — and once more at the end of the run, whether or not it landed on a boundary.\r\n *\r\n * A listener may `seek` (a host looping wraps to 0 when it hears the end), so the end is\r\n * re-read after the listeners and the tick callbacks have run: a run that was seeked out of\r\n * its end carries on, and one that was not pauses itself.\r\n */\r\n private startLoop(): void {\r\n if (this.rafId !== null) return;\r\n const frameDt = 1 / this.fps;\r\n let lastTickTime = this.currentTime;\r\n\r\n const loop = async () => {\r\n let epoch = this.seekEpoch;\r\n const position = this.position();\r\n let ended = position.ended;\r\n // This loop runs at the display's refresh rate, which on a 120 or 144Hz panel is two\r\n // or three times the rate anything is rendered at — so the clock advances every time\r\n // round (the elapsed maths in `play`/`pause` depend on it being exact) while listeners\r\n // hear about it once per frame. The end of the run always reports, or the final\r\n // position would never reach a host. See `Ticker.setCurrentTime`.\r\n const crossed = Math.abs(position.time - lastTickTime) >= frameDt;\r\n const report = crossed || ended;\r\n this.setCurrentTime(position.time, report);\r\n\r\n const reread = () => {\r\n if (this.seekEpoch === epoch) return;\r\n epoch = this.seekEpoch;\r\n lastTickTime = this.currentTime;\r\n ended = this.position().ended;\r\n };\r\n reread();\r\n\r\n if (report) {\r\n lastTickTime = this.currentTime;\r\n // Await so that a slow tick (asset load on a clip\r\n // boundary) doesn't queue a second concurrent tick.\r\n await this.tick();\r\n reread();\r\n }\r\n\r\n // If pause() cleared the rafId while we were awaiting tick(),\r\n // do not resume the loop.\r\n if (this.rafId === null) return;\r\n if (ended) {\r\n this.pause();\r\n return;\r\n }\r\n this.rafId = requestAnimationFrame(loop);\r\n };\r\n\r\n this.rafId = requestAnimationFrame(loop);\r\n }\r\n\r\n private stopLoop(): void {\r\n if (this.rafId !== null) {\r\n cancelAnimationFrame(this.rafId);\r\n this.rafId = null;\r\n }\r\n }\r\n\r\n dispose(): void {\r\n this.stopLoop();\r\n this.stopSilentTicker();\r\n if (this.ownsContext) {\r\n this.context.close();\r\n }\r\n super.dispose();\r\n }\r\n}\r\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@motionscript/browser",
|
|
3
|
-
"version": "0.1.0-alpha.
|
|
3
|
+
"version": "0.1.0-alpha.6",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Browser rendering backend for Motion Script, powered by Skia/CanvasKit.",
|
|
6
6
|
"repository": {
|
|
@@ -21,6 +21,7 @@
|
|
|
21
21
|
"main": "dist/index.js",
|
|
22
22
|
"types": "dist/index.d.ts",
|
|
23
23
|
"files": [
|
|
24
|
+
"NOTICE",
|
|
24
25
|
"dist",
|
|
25
26
|
"CHANGELOG.md",
|
|
26
27
|
"!dist/**/*.tsbuildinfo"
|
|
@@ -36,8 +37,8 @@
|
|
|
36
37
|
}
|
|
37
38
|
},
|
|
38
39
|
"peerDependencies": {
|
|
39
|
-
"@motionscript/canvaskit": "^0.1.0-alpha.
|
|
40
|
-
"@motionscript/core": "^0.1.0-alpha.
|
|
40
|
+
"@motionscript/canvaskit": "^0.1.0-alpha.6",
|
|
41
|
+
"@motionscript/core": "^0.1.0-alpha.6"
|
|
41
42
|
},
|
|
42
43
|
"devDependencies": {
|
|
43
44
|
"@types/three": "0.185.1",
|
|
@@ -54,13 +55,13 @@
|
|
|
54
55
|
"typescript": "^6.0.3",
|
|
55
56
|
"typescript-eslint": "^8.48.0",
|
|
56
57
|
"vitest": "^4.1.5",
|
|
57
|
-
"@motionscript/
|
|
58
|
-
"@motionscript/
|
|
58
|
+
"@motionscript/canvaskit": "0.1.0-alpha.6",
|
|
59
|
+
"@motionscript/core": "0.1.0-alpha.6"
|
|
59
60
|
},
|
|
60
61
|
"dependencies": {
|
|
61
62
|
"esbuild-wasm": "^0.28.1",
|
|
62
63
|
"mediabunny": "^1.40.1",
|
|
63
|
-
"@motionscript/skia-render": "^0.1.0-alpha.
|
|
64
|
+
"@motionscript/skia-render": "^0.1.0-alpha.6"
|
|
64
65
|
},
|
|
65
66
|
"motionscriptBrowser": {
|
|
66
67
|
"assets": {
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
var T=null;function P(n){T=n}async function X(n){if(!T)return null;try{return await T(n)}catch{return null}}async function E(n){let t=await fetch(n);if(!t.ok){let e=t.statusText?`${t.status} ${t.statusText}`:`${t.status}`;throw new Error(`Fetching "${n}" failed: HTTP ${e}`)}return t.blob()}import{busStopKey as j}from"@motionscript/core";import{isCurve as C,sourceTimeAtSceneElapsed as V}from"@motionscript/core";var N=200;function $(n,t,e,o,u,f,h=c=>c){let c=s=>{let a=h(s);return Number.isFinite(a)?a:t.value};if(!C(e)){t.value=c(e);return}if(!Number.isFinite(u)||u<=0){t.value=c(e.staticValue(t.value));return}let l=o-f,d=e.resolve(u,t.value);if(d.length===0)return;let i=e.sampleAt(Math.max(0,f),u,t.value);t.setValueAtTime(c(i),o);for(let s of d){let a=l+s.startTime,r=l+s.endTime;if(r<=o||!Number.isFinite(a)||!Number.isFinite(r))continue;let p=s.endTime-s.startTime;if(p<=0){t.setValueAtTime(c(s.to),Math.max(a,o));continue}let y=Math.max(0,(o-a)/p),m=Math.max(a,o);if(s.isLinear)y===0&&t.setValueAtTime(c(s.from),m),t.linearRampToValueAtTime(c(s.to),r);else{let A=r-m;if(A<=0)continue;let g=Math.max(2,Math.ceil(A*N)),x=new Float32Array(g);for(let v=0;v<g;v++){let w=y+(1-y)*(v/(g-1));x[v]=c(s.from+(s.to-s.from)*s.ease(w))}t.setValueCurveAtTime(x,m,A)}}}function b(n,t,e,o=n.currentTime,u=0,f=0){let h=[],c=[],l=t,d=s=>{l.connect(s),h.push(s),l=s},i=(s,a,r)=>$(n,s,a,o,u,f,r);for(let s of e)switch(s.type){case"gain":{let a=n.createGain();i(a.gain,s.value),d(a);break}case"highpass":case"lowpass":{let a=n.createBiquadFilter();a.type=s.type==="highpass"?"highpass":"lowpass",i(a.frequency,s.frequency),s.q!==void 0&&i(a.Q,s.q),d(a);break}case"tremolo":{let a=n.createGain(),r=n.createOscillator(),p=n.createGain();i(a.gain,s.depth,y=>1-M(y)/2),i(p.gain,s.depth,y=>M(y)/2),i(r.frequency,s.rate),r.connect(p),p.connect(a.gain),h.push(p),c.push(r),d(a);break}case"echo":{let a=l,r=n.createGain(),p=n.createGain();i(p.gain,s.mix??.5,x=>1-M(x)),a.connect(p),p.connect(r);let y=L(s.delay),m=n.createDelay(Math.max(1,y+1));i(m.delayTime,s.delay);let A=n.createGain();i(A.gain,s.feedback,x=>Math.max(0,Math.min(.99,x)));let g=n.createGain();i(g.gain,s.mix??.5,x=>M(x)),a.connect(m),m.connect(A),A.connect(m),m.connect(g),g.connect(r),h.push(p,m,A,g,r),l=r;break}case"speed":break}return{output:l,nodes:h,oscillators:c}}function M(n){return Math.max(0,Math.min(1,n))}function L(n){return C(n)?n.staticValue(0):n}function F(n){if(!n)return 1;let t=1;for(let e of n)e.type==="speed"&&!C(e.value)&&e.value>0&&(t*=e.value);return t}function G(n){if(n){for(let t of n)if(t.type==="speed"&&C(t.value))return t.value}}function R(n,t,e,o,u,f,h){if(!t)return;let c=1/N,l=Math.max(0,h),d=V(t,e,l);n.setValueAtTime(Math.max(1e-4,t.sampleAt(d,e,1)*u),f);for(let i=l+c;i<=o+c;i+=c){let s=Math.min(i,o),a=V(t,e,s),r=Math.max(1e-4,t.sampleAt(a,e,1)*u),p=f+(s-l);if(n.linearRampToValueAtTime(r,p),s>=o)break}}var S=class{ctx;destination;constructor(t,e){this.ctx=t,this.destination=e}inputFor(t,e,o){return!t||t.length===0?this.destination:this.chainFrom(t,0,e,o)}dispose(){for(let t of this.nodes)try{t.disconnect()}catch{}for(let t of this.oscillators)try{t.stop()}catch{}this.nodes.length=0,this.oscillators.length=0,this.inputs.clear()}inputs=new Map;nodes=[];oscillators=[];chainFrom(t,e,o,u){if(e>=t.length)return this.destination;let f=t[e],h=t.slice(e).map(j).join(">"),c=this.inputs.get(h);if(c)return c;let l=this.chainFrom(t,e+1,o,u),d=this.ctx.createGain();d.gain.value=1;let i={type:"gain",value:f.mute?0:f.volume},s=b(this.ctx,d,[...f.filters??[],i],o,f.endAt-f.startAt,u-f.startAt);s.output.connect(l),this.nodes.push(d,...s.nodes),this.oscillators.push(...s.oscillators);for(let a of s.oscillators)a.start(o);return this.inputs.set(h,d),d}};import{sourceTimeAtSceneElapsed as W}from"@motionscript/core";var O=44100;function H(n,t){if(!t)return n;try{return t.getAudioMeta(n).src||n}catch{try{return t.getVideoMeta(n).src||n}catch{return n}}}async function K(n,t){let e=await(await E(n)).arrayBuffer();return t.decodeAudioData(e)}async function Q(n,t,e={}){if(n.length===0)return null;let o=e.sampleRate??O,u=Math.ceil(t*o);if(u<=0)return null;let f=[...new Set(n.map(i=>i.request.src))],h=new OfflineAudioContext(2,u,o),c=new Map;await Promise.all(f.map(async i=>{c.set(i,await K(H(i,e.catalog),h))}));let l=new OfflineAudioContext(2,u,o),d=new S(l,l.destination);for(let{request:i,globalOffset:s}of n){let a=c.get(i.src);if(!a)continue;let r=s+i.startAt,y=Math.min(s+i.endAt,t)-r;if(y<=0)continue;let m=l.createBufferSource();m.buffer=a,m.loop=i.loop;let A=F(i.filters),g=Number.isFinite(A)&&A>0?A:1,x=G(i.filters);g!==1&&!x&&(m.playbackRate.value=g);let v=l.createGain();v.gain.value=Number.isFinite(i.volume)?i.volume:1;let w=Math.max(0,a.duration-i.trimStart),k=Number.isFinite(i.endAt)?Math.max(0,i.endAt-i.startAt):w/g,B=b(l,m,i.filters??[],r,k,0);B.output.connect(v),v.connect(d.inputFor(i.bus,0,-s)),x&&R(m.playbackRate,x,w,k,g,r,0);let _=x?W(x,w,y):y*g;m.start(r,i.trimStart,_);for(let I of B.oscillators)I.start(r)}return l.startRendering()}var U=class{sampleRate;catalog;constructor(t=O,e){this.sampleRate=t,this.catalog=e}mix(t,e){return Q(t,e,{sampleRate:this.sampleRate,catalog:this.catalog})}};function ct(n){let t=n.numberOfChannels,e=n.length,o=2,u=t*o,f=e*u,h=new ArrayBuffer(44+f),c=new DataView(h),l=(s,a)=>{for(let r=0;r<a.length;r++)c.setUint8(s+r,a.charCodeAt(r))};l(0,"RIFF"),c.setUint32(4,36+f,!0),l(8,"WAVE"),l(12,"fmt "),c.setUint32(16,16,!0),c.setUint16(20,1,!0),c.setUint16(22,t,!0),c.setUint32(24,n.sampleRate,!0),c.setUint32(28,n.sampleRate*u,!0),c.setUint16(32,u,!0),c.setUint16(34,8*o,!0),l(36,"data"),c.setUint32(40,f,!0);let d=[];for(let s=0;s<t;s++)d.push(n.getChannelData(s));let i=44;for(let s=0;s<e;s++)for(let a=0;a<t;a++){let r=Math.max(-1,Math.min(1,d[a][s]));c.setInt16(i,r<0?r*32768:r*32767,!0),i+=o}return new Uint8Array(h)}import{AudioSink as z,sourceTimeAtSceneElapsed as J}from"@motionscript/core";var D=class extends z{context;ownsContext;bufferCache=new Map;decoding=new Map;active=new Map;scheduled=[];disposed=!1;masterGain;buses;muted=!1;volume=1;constructor(t){super(),this.context=t??new AudioContext,this.ownsContext=!t,this.masterGain=this.context.createGain(),this.masterGain.connect(this.context.destination),this.buses=new S(this.context,this.masterGain)}getContext(){return this.context}unlock(){this.context.state==="suspended"&&this.context.resume()}has(t){return this.bufferCache.has(t)}async append(t,e){if(this.bufferCache.has(t))return;let o=this.decoding.get(t);if(o)return o;let u=this.context.decodeAudioData(e).then(f=>{this.bufferCache.set(t,f)}).finally(()=>{this.decoding.delete(t)});this.decoding.set(t,u),await u}retain(t){for(let e of[...this.bufferCache.keys()])t.has(e)||this.bufferCache.delete(e);for(let[e,o]of this.active)t.has(o.request.src)||this.stopSource(e,o)}schedule(t){let e=new Set(t.map(o=>o.id));for(let[o,u]of this.active)e.has(o)||this.stopSource(o,u);this.scheduled=t.slice()}syncTo(t){let e=new Set;for(let o of this.scheduled)if(t>=o.startAt&&t<o.endAt&&(e.add(o.id),!this.active.has(o.id))){let f=this.bufferCache.get(o.src);f&&this.playBuffer(f,o,t)}for(let[o,u]of this.active)e.has(o)||this.stopSource(o,u)}async play(t,e,o){this.context.state==="suspended"&&await this.context.resume(),this.syncTo(t)}stop(){for(let[t,e]of this.active)this.stopSource(t,e);this.buses.dispose()}setMuted(t){this.muted=t,this.applyMasterGain()}setVolume(t){this.volume=Math.max(0,t),this.applyMasterGain()}applyMasterGain(){this.masterGain.gain.value=this.muted?0:this.volume}playBuffer(t,e,o){let u=this.context.currentTime,f=this.context.createGain();f.gain.value=Number.isFinite(e.volume)?e.volume:1,f.connect(this.buses.inputFor(e.bus,u,o));let h=this.context.createBufferSource();h.buffer=t,h.loop=e.loop;let c=F(e.filters),l=Number.isFinite(c)&&c>0?c:1,d=G(e.filters);l!==1&&!d&&(h.playbackRate.value=l);let i=Math.max(0,o-e.startAt),s=Math.max(0,t.duration-e.trimStart),a=isFinite(e.endAt)?Math.max(0,e.endAt-e.startAt):s/(l||1),r=b(this.context,h,e.filters??[],u,a,i);r.output.connect(f);let p;d?(p=e.trimStart+J(d,s,i),R(h.playbackRate,d,s,a,l,u,i)):p=e.trimStart+i*l,h.start(u,p);for(let y of r.oscillators)y.start(u);h.onended=()=>{this.active.get(e.id)?.source===h&&this.active.delete(e.id)},this.active.set(e.id,{source:h,gainNode:f,request:e,filterNodes:r.nodes,oscillators:r.oscillators})}stopSource(t,e){try{e.source.onended=null,e.source.stop();for(let o of e.oscillators)o.stop();e.source.disconnect();for(let o of e.filterNodes)o.disconnect();e.gainNode.disconnect()}catch{}this.active.delete(t)}dispose(){if(!this.disposed){this.disposed=!0,super.dispose(),this.bufferCache.clear(),this.decoding.clear(),this.scheduled.length=0,this.buses.dispose();try{this.masterGain.disconnect()}catch{}this.ownsContext&&this.context.state!=="closed"&&this.context.close()}}};export{P as a,X as b,E as c,S as d,O as e,Q as f,U as g,ct as h,D as i};
|
|
2
|
-
//# sourceMappingURL=chunk-M7XD73ED.js.map
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../../../src/asset-bytes.ts", "../../../src/audio/bus-graph.ts", "../../../src/audio/filter-graph.ts", "../../../src/audio/mixer.ts", "../../../src/audio/player.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Where a source URL's bytes come from: a host's local store, then the network.\n *\n * ## Why the web adapter needs this at all\n *\n * `WebStorageAdapter` addresses every asset by URL and fetches it. That is\n * right for an asset that lives somewhere, and wrong for one whose bytes the\n * host already has in hand — a file the user has just chosen, a render a local\n * model has just produced, a picture whose upload has not finished or cannot\n * start because there is no network. In all three the adapter downloads bytes\n * that never needed to travel.\n *\n * `NodeStorageAdapter` has had the answer since it was written: an injected\n * `AssetLoader`, with an `inline` map consulted ahead of the disk. This is the\n * same seam for the browser.\n *\n * ## Why it is module-level\n *\n * `WebStorageAdapter` is constructed at five sites *inside* these packages —\n * the React player backend, the exporter, the audio mixer, and both still\n * renderers — none of which a host can reach. A constructor argument would\n * therefore cover the preview and leave export and stills on the network,\n * which is the worst of both: the picture a user sees would come from local\n * bytes and the one they render would not.\n *\n * So this is an *injection point*, not a cache. The adapter still owns every\n * decode, every cache, every size ceiling and every eviction rule; all this\n * changes is where the compressed bytes came from. A source that answers `null`\n * — which is what an unregistered URL, an evicted entry or a host with no local\n * store does — leaves the adapter exactly as it was.\n */\n\n/** Local bytes for a source URL, or `null` to go to the network. */\nexport type AssetByteSource = (src: string) => Promise<Blob | null>;\n\nlet source: AssetByteSource | null = null;\n\n/**\n * Installs the byte source for this browsing context, or clears it with `null`.\n *\n * Called once per window that renders. Later calls replace the previous source\n * rather than stacking, because two sources disagreeing about one URL has no\n * sensible answer.\n */\nexport function setAssetByteSource(next: AssetByteSource | null): void {\n source = next;\n}\n\n/**\n * The bytes for `src`, or `null`.\n *\n * Swallows a throwing source on purpose. A host's local store failing is a\n * cache miss, not a render failure — the caller falls through to `fetch`, which\n * is what it would have done had the source never been installed.\n */\nexport async function localAssetBytes(src: string): Promise<Blob | null> {\n if (!source) return null;\n try {\n return await source(src);\n } catch {\n return null;\n }\n}\n\n/**\n * The network's bytes for `url`. A response that is not OK is a failed load,\n * never bytes: a 404 page handed to the font manager marked a family loaded\n * with no face in it.\n */\nexport async function fetchAssetBytes(url: string): Promise<Blob> {\n const response = await fetch(url);\n if (!response.ok) {\n const status = response.statusText ? `${response.status} ${response.statusText}` : `${response.status}`;\n throw new Error(`Fetching \"${url}\" failed: HTTP ${status}`);\n }\n return response.blob();\n}\n", "import { busStopKey, type AudioBusStop, type AudioFilterItem } from \"@motionscript/core\";\nimport { buildAudioFilterGraph } from \"./filter-graph\";\n\n/**\n * The live chains for one audio context's buses.\n *\n * Held per context rather than per clip, because that is the whole difference\n * between a bus and per-clip processing: every clip naming a bus connects into\n * the *same* nodes, so a reverb on a bus is one tail the group shares rather\n * than one tail each. Flattening the levels into per-clip gain would sound\n * right; flattening the effects would not.\n */\nexport class AudioBusGraph {\n constructor(\n private readonly ctx: BaseAudioContext,\n /** Where the last bus in a chain connects — the master, or the destination. */\n private readonly destination: AudioNode,\n ) { }\n\n /**\n * The input node a clip on `bus` should connect to, building the chain the\n * first time it is asked for.\n *\n * `bus` is source-adjacent first, so `bus[0]` is the one the clip feeds and\n * each stop after it is that bus's own parent. An empty or absent chain\n * returns the destination, which is what every clip did before buses\n * existed.\n *\n * `startTime` is the context time a new chain's schedule starts from, and\n * `sceneTime` the same instant in the stops' own seconds. A curve on a stop\n * runs over its `startAt`–`endAt`, so the two are what place it.\n */\n inputFor(bus: readonly AudioBusStop[] | undefined, startTime: number, sceneTime: number): AudioNode {\n if (!bus || bus.length === 0) return this.destination;\n return this.chainFrom(bus, 0, startTime, sceneTime);\n }\n\n /** Disconnect every live bus node, so the next {@link inputFor} builds afresh. Safe to call more than once. */\n dispose(): void {\n for (const node of this.nodes) {\n try { node.disconnect(); } catch { /* already torn down */ }\n }\n for (const osc of this.oscillators) {\n try { osc.stop(); } catch { /* never started, or already stopped */ }\n }\n this.nodes.length = 0;\n this.oscillators.length = 0;\n this.inputs.clear();\n }\n\n private readonly inputs = new Map<string, AudioNode>();\n private readonly nodes: AudioNode[] = [];\n private readonly oscillators: OscillatorNode[] = [];\n\n /**\n * Build (or reuse) the chain for `bus[index]`, connected to whatever\n * `bus[index + 1]` resolves to.\n *\n * Recursive rather than iterative because a bus's *output* has to exist\n * before its own nodes can connect to it, and the outermost bus is the last\n * entry.\n *\n * Reused by everything that changes what it sounds like, down to the master,\n * not by id alone: a bus edited under a playing device, or one id on two\n * tracks, is a different chain, and one built for the first would play the\n * second through stale levels and a curve anchored to the wrong span.\n */\n private chainFrom(bus: readonly AudioBusStop[], index: number, startTime: number, sceneTime: number): AudioNode {\n if (index >= bus.length) return this.destination;\n\n const stop = bus[index];\n const key = bus.slice(index).map(busStopKey).join(\">\");\n const existing = this.inputs.get(key);\n if (existing) return existing;\n\n const output = this.chainFrom(bus, index + 1, startTime, sceneTime);\n\n // A pass-through head every clip connects to, so the bus has one input\n // whatever its filters turn out to be.\n const input = this.ctx.createGain();\n input.gain.value = 1;\n\n // The level is a gain after the filters, as a sound's own level is, so a\n // curve on it is scheduled exactly as one in `filters` is.\n const level: AudioFilterItem = { type: \"gain\", value: stop.mute ? 0 : stop.volume };\n const graph = buildAudioFilterGraph(\n this.ctx, input, [...(stop.filters ?? []), level],\n startTime, stop.endAt - stop.startAt, sceneTime - stop.startAt,\n );\n graph.output.connect(output);\n\n this.nodes.push(input, ...graph.nodes);\n this.oscillators.push(...graph.oscillators);\n for (const osc of graph.oscillators) osc.start(startTime);\n\n this.inputs.set(key, input);\n return input;\n }\n}\n", "import { AudioFilterItem, Param, isCurve, sourceTimeAtSceneElapsed } from \"@motionscript/core\";\n\n/**\n * Result of building an audio-filter graph for one source.\n *\n * - `output` is the last node in the chain; connect it downstream (e.g. to the\n * per-request gain node).\n * - `nodes` are every intermediate node, so callers can `disconnect()` them on\n * teardown.\n * - `oscillators` are LFOs (from `tremolo`) the caller must `start()` — and may\n * `stop()` — alongside the source, since oscillators need an explicit start.\n */\nexport interface AudioFilterGraph {\n output: AudioNode;\n nodes: AudioNode[];\n oscillators: OscillatorNode[];\n}\n\n/**\n * How many sample points per second to bake an eased curve segment into for\n * `setValueCurveAtTime`. 200/s (≈ every 5ms) is smooth to the ear and cheap.\n */\nconst CURVE_SAMPLES_PER_SECOND = 200;\n\n/**\n * Apply a (possibly time-varying) {@link Param} to a Web Audio {@link AudioParam}.\n *\n * - **number** → set once (today's behavior; zero scheduling overhead).\n * - **Curve** → resolve against `clipDuration` and schedule each segment:\n * - linear segments via `setValueAtTime` + `linearRampToValueAtTime`,\n * - eased segments baked into a `Float32Array` via `setValueCurveAtTime`.\n *\n * `elapsed` (scene-seconds already played when a mid-clip seek starts the source)\n * shifts the schedule back by `elapsed` so \"now\" reads the curve's value at the\n * clip's *current* position, not its start. A `clamp(v)` hook lets a param keep a\n * valid range (e.g. echo mix 0–1) at every sampled point.\n */\nfunction applyParam(\n ctx: BaseAudioContext,\n audioParam: AudioParam,\n param: Param,\n startTime: number,\n clipDuration: number,\n elapsed: number,\n clamp: (v: number) => number = (v) => v,\n): void {\n // Coerce to a finite value before touching an AudioParam — the platform throws\n // on NaN/Infinity. Falls back to the current param value (never undefined here).\n const finite = (v: number): number => {\n const c = clamp(v);\n return Number.isFinite(c) ? c : audioParam.value;\n };\n\n if (!isCurve(param)) {\n audioParam.value = finite(param);\n return;\n }\n\n // A non-finite clip length yields no usable schedule; hold the curve's start value.\n if (!Number.isFinite(clipDuration) || clipDuration <= 0) {\n audioParam.value = finite(param.staticValue(audioParam.value));\n return;\n }\n\n const base = startTime - elapsed; // map curve t=0 to here so seeks line up\n const resolved = param.resolve(clipDuration, audioParam.value);\n if (resolved.length === 0) return;\n\n // Anchor the starting value at `startTime` (the seek point) so there is no\n // jump from the param's default before the first scheduled segment runs.\n const startValue = param.sampleAt(Math.max(0, elapsed), clipDuration, audioParam.value);\n audioParam.setValueAtTime(finite(startValue), startTime);\n\n for (const seg of resolved) {\n const segStart = base + seg.startTime;\n const segEnd = base + seg.endTime;\n // Skip segments wholly in the past relative to the seek point, or any with a\n // non-finite boundary (degenerate resolve) that would throw on schedule.\n if (segEnd <= startTime || !Number.isFinite(segStart) || !Number.isFinite(segEnd)) continue;\n\n const span = seg.endTime - seg.startTime;\n\n if (span <= 0) {\n audioParam.setValueAtTime(finite(seg.to), Math.max(segStart, startTime));\n continue;\n }\n\n // How far through this segment the seek lands. A segment already under way\n // carries on from the anchor rather than starting over from its `from` —\n // the case a bus hits whenever its first clip enters partway through it.\n const done = Math.max(0, (startTime - segStart) / span);\n const curveStart = Math.max(segStart, startTime);\n\n if (seg.isLinear) {\n if (done === 0) audioParam.setValueAtTime(finite(seg.from), curveStart);\n audioParam.linearRampToValueAtTime(finite(seg.to), segEnd);\n } else {\n const curveDur = segEnd - curveStart;\n if (curveDur <= 0) continue;\n const count = Math.max(2, Math.ceil(curveDur * CURVE_SAMPLES_PER_SECOND));\n const samples = new Float32Array(count);\n for (let i = 0; i < count; i++) {\n const local = done + (1 - done) * (i / (count - 1));\n samples[i] = finite(seg.from + (seg.to - seg.from) * seg.ease(local));\n }\n audioParam.setValueCurveAtTime(samples, curveStart, curveDur);\n }\n }\n}\n\n/**\n * Builds the Web Audio graph for a clip's filter chain, returning the node to\n * connect downstream. Shared by live playback ({@link WebAudioSink}) and\n * offline export (`mixAudio`) so both paths sound identical.\n *\n * Filters apply in array order (index 0 closest to the source). `speed` filters\n * are intentionally ignored here — they're realized via `source.playbackRate`\n * by the caller (and affect timeline scheduling), not as a graph node.\n *\n * `startTime` is the AudioContext time the source starts; `clipDuration` is the\n * scene-time length the curves run over (a clip's, or a bus's span); `elapsed` is\n * scene-seconds already played at a mid-clip seek (0 for a clean start, negative\n * before the span begins). These let curve-valued params schedule and align.\n *\n * Pass the already-created `source` so its `playbackRate` can be set by the\n * caller; this function only wires nodes *after* the source.\n */\nexport function buildAudioFilterGraph(\n ctx: BaseAudioContext,\n source: AudioNode,\n filters: readonly AudioFilterItem[],\n startTime: number = ctx.currentTime,\n clipDuration: number = 0,\n elapsed: number = 0,\n): AudioFilterGraph {\n const nodes: AudioNode[] = [];\n const oscillators: OscillatorNode[] = [];\n let cursor: AudioNode = source;\n\n const series = (node: AudioNode): void => {\n cursor.connect(node);\n nodes.push(node);\n cursor = node;\n };\n\n const apply = (p: AudioParam, v: Param, clamp?: (n: number) => number): void =>\n applyParam(ctx, p, v, startTime, clipDuration, elapsed, clamp);\n\n for (const filter of filters) {\n switch (filter.type) {\n case \"gain\": {\n const gain = ctx.createGain();\n apply(gain.gain, filter.value);\n series(gain);\n break;\n }\n case \"highpass\":\n case \"lowpass\": {\n const biquad = ctx.createBiquadFilter();\n biquad.type = filter.type === \"highpass\" ? \"highpass\" : \"lowpass\";\n apply(biquad.frequency, filter.frequency);\n if (filter.q !== undefined) apply(biquad.Q, filter.q);\n series(biquad);\n break;\n }\n case \"tremolo\": {\n // Carrier gain whose value is modulated by an LFO. With depth d the\n // carrier base = (1 - d/2) and the LFO swing gain = d/2. The clamp\n // hook applies these transforms whether depth is scalar or a curve.\n const carrier = ctx.createGain();\n const lfo = ctx.createOscillator();\n const lfoDepth = ctx.createGain();\n\n apply(carrier.gain, filter.depth, (d) => 1 - clamp01(d) / 2);\n apply(lfoDepth.gain, filter.depth, (d) => clamp01(d) / 2);\n apply(lfo.frequency, filter.rate);\n\n lfo.connect(lfoDepth);\n lfoDepth.connect(carrier.gain);\n\n nodes.push(lfoDepth);\n oscillators.push(lfo);\n series(carrier);\n break;\n }\n case \"echo\": {\n // Dry + wet split. The wet path is a delay with feedback; both sum\n // into a merge node that becomes the new cursor.\n const split = cursor;\n const merge = ctx.createGain();\n\n const dry = ctx.createGain();\n apply(dry.gain, filter.mix ?? 0.5, (m) => 1 - clamp01(m));\n split.connect(dry);\n dry.connect(merge);\n\n // Delay buffer must accommodate the max delay; size from the static value.\n const maxDelay = staticOf(filter.delay);\n const delay = ctx.createDelay(Math.max(1, maxDelay + 1));\n apply(delay.delayTime, filter.delay);\n const feedbackGain = ctx.createGain();\n apply(feedbackGain.gain, filter.feedback, (f) => Math.max(0, Math.min(0.99, f)));\n const wet = ctx.createGain();\n apply(wet.gain, filter.mix ?? 0.5, (m) => clamp01(m));\n\n split.connect(delay);\n delay.connect(feedbackGain);\n feedbackGain.connect(delay); // feedback loop\n delay.connect(wet);\n wet.connect(merge);\n\n nodes.push(dry, delay, feedbackGain, wet, merge);\n cursor = merge;\n break;\n }\n case \"speed\":\n // Realized via source.playbackRate by the caller; no graph node.\n break;\n }\n }\n\n return { output: cursor, nodes, oscillators };\n}\n\n/** Clamp to [0, 1]. */\nfunction clamp01(v: number): number {\n return Math.max(0, Math.min(1, v));\n}\n\n/** The static/representative number of a param (number itself, or curve's t=0 value). */\nfunction staticOf(p: Param): number {\n return isCurve(p) ? p.staticValue(0) : p;\n}\n\n/**\n * Net *constant* playback-rate multiplier from any scalar `speed` filters in the\n * chain (product of all), defaulting to 1. Curve-valued speeds contribute 1 here\n * and are scheduled separately by {@link applySpeedToPlaybackRate}. Mirrors\n * `Sound.effectiveSpeed()` so the renderer applies the same rate the core timeline\n * reserved time for.\n */\nexport function effectiveSpeed(filters: readonly AudioFilterItem[] | undefined): number {\n if (!filters) return 1;\n let speed = 1;\n for (const f of filters) {\n if (f.type === \"speed\" && !isCurve(f.value) && f.value > 0) speed *= f.value;\n }\n return speed;\n}\n\n/** The first curve-valued `speed` filter in the chain, if any. */\nexport function speedCurveOf(filters: readonly AudioFilterItem[] | undefined) {\n if (!filters) return undefined;\n for (const f of filters) {\n if (f.type === \"speed\" && isCurve(f.value)) return f.value;\n }\n return undefined;\n}\n\n/**\n * Schedule a time-varying speed curve onto an `AudioBufferSourceNode.playbackRate`.\n *\n * The curve is authored over **source time** (rate as a function of how far through\n * the source we've played). `setValueAtTime`/`linearRampToValueAtTime` schedule in\n * **context time**, so we walk scene-time forward in small steps, convert each to a\n * source-time offset via the integral inverse, read the curve there, and lay down a\n * value point at the matching context time. `scalar` folds in any constant speed\n * filters (they scale the whole rate uniformly).\n *\n * `elapsed` is scene-seconds already played at a mid-clip seek, so the schedule\n * starts at the seek point and aligns the playbackRate to the clip's true position.\n */\nexport function applySpeedToPlaybackRate(\n rate: AudioParam,\n curve: ReturnType<typeof speedCurveOf>,\n sourceLength: number,\n sceneDuration: number,\n scalar: number,\n startTime: number,\n elapsed: number,\n): void {\n if (!curve) return;\n const step = 1 / CURVE_SAMPLES_PER_SECOND; // scene-time sampling step\n let scene = Math.max(0, elapsed);\n // Seed the value exactly at the seek point.\n const seedSrc = sourceTimeAtSceneElapsed(curve, sourceLength, scene);\n rate.setValueAtTime(Math.max(1e-4, curve.sampleAt(seedSrc, sourceLength, 1) * scalar), startTime);\n\n for (let s = scene + step; s <= sceneDuration + step; s += step) {\n const clampedScene = Math.min(s, sceneDuration);\n const srcT = sourceTimeAtSceneElapsed(curve, sourceLength, clampedScene);\n const value = Math.max(1e-4, curve.sampleAt(srcT, sourceLength, 1) * scalar);\n const ctxTime = startTime + (clampedScene - scene);\n rate.linearRampToValueAtTime(value, ctxTime);\n if (clampedScene >= sceneDuration) break;\n }\n}\n", "import { sourceTimeAtSceneElapsed, type AssetCatalog } from \"@motionscript/core\";\nimport type { AudioMixer, ScheduledAudioRequest } from \"@motionscript/skia-render/export\";\nimport { fetchAssetBytes } from \"../asset-bytes\";\nimport { AudioBusGraph } from \"./bus-graph\";\nimport {\n applySpeedToPlaybackRate,\n buildAudioFilterGraph,\n effectiveSpeed,\n speedCurveOf,\n} from \"./filter-graph\";\n\n/** Sample rate used when the caller doesn't pick one. */\nexport const DEFAULT_SAMPLE_RATE = 44100;\n\nexport interface MixAudioOptions {\n /** Defaults to {@link DEFAULT_SAMPLE_RATE}. */\n sampleRate?: number;\n /**\n * Resolves a request's `src` to the address its bytes live at, the same job\n * `WebStorageAdapter.assetUrl` does for the live paths. Omitted, a `src` is\n * fetched as written — right only while the host keys its manifest by URL.\n */\n catalog?: AssetCatalog;\n}\n\n/** Audio first, then video: a clip's own soundtrack is requested under the video's key. */\nfunction audioUrl(src: string, catalog: AssetCatalog | undefined): string {\n if (!catalog) return src;\n try {\n return catalog.getAudioMeta(src).src || src;\n } catch {\n try {\n return catalog.getVideoMeta(src).src || src;\n } catch {\n return src;\n }\n }\n}\n\n/** Fetches and decodes an audio source against a scratch `OfflineAudioContext` (decoding requires a context but doesn't render through it). */\nasync function fetchAudioBuffer(src: string, ctx: OfflineAudioContext): Promise<AudioBuffer> {\n const arrayBuffer = await (await fetchAssetBytes(src)).arrayBuffer();\n return ctx.decodeAudioData(arrayBuffer);\n}\n\n/**\n * Render every scheduled request into one timeline-length buffer.\n *\n * An `OfflineAudioContext` graph — gain per request, looping/trimming, and the\n * same filter chain the live {@link WebAudioSink} builds — rendered in one\n * pass rather than scheduled per frame.\n *\n * Shared by the video exporter and by `mixTimelineAudio`, deliberately: a split\n * export and a whole one have to be the same mix, and two implementations of\n * \"stack these clips\" would eventually disagree.\n *\n * Curve-valued filter params and `speed` curves schedule here exactly as they do\n * in {@link WebAudioSink.playBuffer}, which is the reference implementation —\n * the two must be read side by side when either changes.\n *\n * One deliberate difference: this schedules at absolute context times, so clip\n * starts are sample-accurate here and quantized to `1/fps` in live playback,\n * which starts sources at `currentTime` on a clock tick.\n */\nexport async function mixAudio(\n requests: readonly ScheduledAudioRequest[],\n totalDuration: number,\n options: MixAudioOptions = {},\n): Promise<AudioBuffer | null> {\n if (requests.length === 0) return null;\n const sampleRate = options.sampleRate ?? DEFAULT_SAMPLE_RATE;\n const frames = Math.ceil(totalDuration * sampleRate);\n if (frames <= 0) return null;\n\n const uniqueSrcs = [...new Set(requests.map(r => r.request.src))];\n const scratchCtx = new OfflineAudioContext(2, frames, sampleRate);\n\n const decoded = new Map<string, AudioBuffer>();\n await Promise.all(uniqueSrcs.map(async (src) => {\n decoded.set(src, await fetchAudioBuffer(audioUrl(src, options.catalog), scratchCtx));\n }));\n\n const mixCtx = new OfflineAudioContext(2, frames, sampleRate);\n // The same shared-chain rule the live device uses, for the same reason: an\n // export that flattened buses into per-clip processing would not match what\n // the preview sounded like.\n const buses = new AudioBusGraph(mixCtx, mixCtx.destination);\n\n for (const { request: req, globalOffset } of requests) {\n const srcBuffer = decoded.get(req.src);\n if (!srcBuffer) continue;\n\n const globalStart = globalOffset + req.startAt;\n // `endAt` is `Infinity` for an open clip; either way the timeline bounds it.\n const globalEnd = Math.min(globalOffset + req.endAt, totalDuration);\n const playDuration = globalEnd - globalStart;\n if (playDuration <= 0) continue;\n\n const source = mixCtx.createBufferSource();\n source.buffer = srcBuffer;\n source.loop = req.loop;\n\n const scalarSpeed = effectiveSpeed(req.filters);\n const rate = Number.isFinite(scalarSpeed) && scalarSpeed > 0 ? scalarSpeed : 1;\n const speedCurve = speedCurveOf(req.filters);\n // With a curve the scalar is folded into the scheduled ramp below, so\n // setting it here as well would apply it twice.\n if (rate !== 1 && !speedCurve) source.playbackRate.value = rate;\n\n const gain = mixCtx.createGain();\n gain.gain.value = Number.isFinite(req.volume) ? req.volume : 1;\n\n // The trimmed source length the filter and speed curves are authored over.\n const sourceLength = Math.max(0, srcBuffer.duration - req.trimStart);\n // The clip's own scene-time length — what a curve resolves against.\n // Deliberately *not* `playDuration`, which is that length truncated by the\n // timeline end: resolving against the truncated value would squeeze the\n // whole curve into the surviving part instead of cutting it off.\n const clipDuration = Number.isFinite(req.endAt)\n ? Math.max(0, req.endAt - req.startAt)\n : sourceLength / rate;\n\n // Filter chain sits between the source and the per-request gain, matching\n // the live WebAudioSink graph so exports sound identical to preview.\n // Passing the start time and clip duration is what lets curve-valued params\n // schedule — with the defaults they collapse to a single static value.\n // `elapsed` is 0: unlike a live seek, the mix always starts a clip at its\n // own beginning.\n const graph = buildAudioFilterGraph(\n mixCtx, source, req.filters ?? [], globalStart, clipDuration, 0,\n );\n graph.output.connect(gain);\n // From the mix's start, whichever clip asks first: a bus's chain is shared,\n // so its schedule cannot begin at one clip's start. Context time 0 is\n // `-globalOffset` in this request's seconds, which are its stops' too.\n gain.connect(buses.inputFor(req.bus, 0, -globalOffset));\n\n if (speedCurve) {\n applySpeedToPlaybackRate(\n source.playbackRate, speedCurve, sourceLength, clipDuration, rate, globalStart, 0,\n );\n }\n\n // start()'s 3rd arg is a source-buffer duration. A constant rate scales it\n // linearly, but under a speed curve the buffer consumed over a span of\n // scene time is the integral of the rate, not a multiple of it.\n const consumed = speedCurve\n ? sourceTimeAtSceneElapsed(speedCurve, sourceLength, playDuration)\n : playDuration * rate;\n\n source.start(globalStart, req.trimStart, consumed);\n for (const osc of graph.oscillators) osc.start(globalStart);\n }\n\n return mixCtx.startRendering();\n}\n\n/**\n * Adapter presenting {@link mixAudio} as the exporter's injected mixer seam.\n *\n * The sample rate is a constructor argument rather than a third `mix` parameter\n * because {@link AudioMixer} — the seam `renderTimeline` calls through — takes\n * exactly two, so anything passed as a third would be silently dropped. Fixing\n * it here rather than widening the interface keeps the rate a property of *this*\n * mixer, which is whose business it is.\n */\nexport class WebAudioMixer implements AudioMixer<AudioBuffer> {\n constructor(\n private readonly sampleRate: number = DEFAULT_SAMPLE_RATE,\n private readonly catalog?: AssetCatalog,\n ) { }\n\n mix(\n requests: readonly ScheduledAudioRequest[],\n totalDuration: number,\n ): Promise<AudioBuffer | null> {\n return mixAudio(requests, totalDuration, {\n sampleRate: this.sampleRate,\n catalog: this.catalog,\n });\n }\n}\n\n/**\n * Encode an `AudioBuffer` as a 16-bit PCM WAV.\n *\n * The only other encoder in this package is the AAC track inside the mp4 muxer,\n * which is reachable solely by exporting a video — so without this a mixdown has\n * no file representation at all. WAV because it needs no codec support and is\n * lossless; a host wanting mp3/aac can re-encode from here.\n */\nexport function encodeWav(buffer: AudioBuffer): Uint8Array<ArrayBuffer> {\n const channelCount = buffer.numberOfChannels;\n const frameCount = buffer.length;\n const bytesPerSample = 2;\n const blockAlign = channelCount * bytesPerSample;\n const dataBytes = frameCount * blockAlign;\n\n const out = new ArrayBuffer(44 + dataBytes);\n const view = new DataView(out);\n\n const ascii = (offset: number, text: string) => {\n for (let i = 0; i < text.length; i++) view.setUint8(offset + i, text.charCodeAt(i));\n };\n\n ascii(0, \"RIFF\");\n view.setUint32(4, 36 + dataBytes, true);\n ascii(8, \"WAVE\");\n ascii(12, \"fmt \");\n view.setUint32(16, 16, true); // PCM header length\n view.setUint16(20, 1, true); // format: PCM\n view.setUint16(22, channelCount, true);\n view.setUint32(24, buffer.sampleRate, true);\n view.setUint32(28, buffer.sampleRate * blockAlign, true);\n view.setUint16(32, blockAlign, true);\n view.setUint16(34, 8 * bytesPerSample, true);\n ascii(36, \"data\");\n view.setUint32(40, dataBytes, true);\n\n // Pull each channel out once — getChannelData is a live view, but calling it\n // per sample inside the interleave loop is measurably slower.\n const channels: Float32Array[] = [];\n for (let c = 0; c < channelCount; c++) channels.push(buffer.getChannelData(c));\n\n let offset = 44;\n for (let frame = 0; frame < frameCount; frame++) {\n for (let c = 0; c < channelCount; c++) {\n // Clamp before scaling: the mix bus can exceed [-1,1] where clips\n // overlap, and letting that wrap turns a loud passage into noise.\n const sample = Math.max(-1, Math.min(1, channels[c][frame]));\n view.setInt16(offset, sample < 0 ? sample * 0x8000 : sample * 0x7fff, true);\n offset += bytesPerSample;\n }\n }\n\n return new Uint8Array(out);\n}\n", "import { AudioSink, AudioRequest, sourceTimeAtSceneElapsed } from \"@motionscript/core\";\nimport { AudioBusGraph } from \"./bus-graph\";\nimport { buildAudioFilterGraph, effectiveSpeed, speedCurveOf, applySpeedToPlaybackRate } from \"./filter-graph\";\n\ntype ActiveSource = {\n source: AudioBufferSourceNode;\n gainNode: GainNode;\n request: AudioRequest;\n /** Filter-graph nodes to disconnect on teardown. */\n filterNodes: AudioNode[];\n /** Tremolo LFOs to stop on teardown. */\n oscillators: OscillatorNode[];\n};\n\n/**\n * Web Audio implementation of {@link AudioSink} — decodes and caches source\n * buffers, then schedules/plays {@link AudioRequest}s as `AudioBufferSourceNode`s\n * through a shared master gain (global mute and volume). `schedule` registers the\n * active set of requests for the current frame; `syncTo` then starts/stops\n * sources to match `sceneTime`, so playback follows scrubbing and seeks.\n */\nexport class WebAudioSink extends AudioSink {\n private context: AudioContext;\n private ownsContext: boolean;\n private bufferCache = new Map<string, AudioBuffer>();\n private decoding = new Map<string, Promise<void>>();\n private active = new Map<string, ActiveSource>();\n private scheduled: AudioRequest[] = [];\n private disposed: boolean = false;\n private masterGain: GainNode;\n /** The live bus chains, shared across every clip that names one. */\n private buses: AudioBusGraph;\n private muted = false;\n private volume = 1;\n\n constructor(context?: AudioContext) {\n super();\n this.context = context ?? new AudioContext();\n this.ownsContext = !context;\n this.masterGain = this.context.createGain();\n this.masterGain.connect(this.context.destination);\n this.buses = new AudioBusGraph(this.context, this.masterGain);\n }\n\n getContext(): AudioContext {\n return this.context;\n }\n\n /**\n * Resume the AudioContext. Must be called from within a user gesture\n * (e.g. a click handler) the first time, or browsers keep the context\n * suspended and no audio is heard.\n */\n unlock(): void {\n if (this.context.state === \"suspended\") {\n this.context.resume();\n }\n }\n\n has(src: string): boolean {\n return this.bufferCache.has(src);\n }\n\n async append(src: string, data: ArrayBuffer): Promise<void> {\n if (this.bufferCache.has(src)) return;\n const existing = this.decoding.get(src);\n if (existing) return existing;\n\n // decodeAudioData detaches `data` — that's fine, the caller in\n // AssetManager.fetchAudio discards its reference immediately after\n // awaiting append. Skipping the defensive .slice(0) saves a multi-MB\n // allocation per audio source.\n const job = this.context.decodeAudioData(data).then((buffer) => {\n this.bufferCache.set(src, buffer);\n }).finally(() => {\n this.decoding.delete(src);\n });\n this.decoding.set(src, job);\n await job;\n }\n\n /** Drops cached buffers and stops active sources for srcs/requests no longer referenced — called when the asset set changes (e.g. seeking across scene boundaries). */\n retain(keep: ReadonlySet<string>): void {\n for (const src of [...this.bufferCache.keys()]) {\n if (!keep.has(src)) this.bufferCache.delete(src);\n }\n for (const [id, active] of this.active) {\n if (!keep.has(active.request.src)) this.stopSource(id, active);\n }\n }\n\n /** Replaces the active request set; stops any currently-playing source whose request is no longer scheduled. Actual start/stop-to-match-time happens in `syncTo`. */\n schedule(requests: readonly AudioRequest[]): void {\n const next = new Set(requests.map(r => r.id));\n for (const [id, active] of this.active) {\n if (!next.has(id)) this.stopSource(id, active);\n }\n this.scheduled = requests.slice();\n }\n\n /** Starts sources whose `[startAt, endAt)` window now contains `sceneTime` (computing the correct buffer offset for the seek point) and stops any that have fallen outside it. */\n syncTo(sceneTime: number): void {\n const liveIds = new Set<string>();\n\n for (const req of this.scheduled) {\n // `endAt` is `Infinity` for an open clip, so the comparison needs no\n // nullish fallback — see AudioRequest.endAt.\n const isInWindow = sceneTime >= req.startAt && sceneTime < req.endAt;\n if (!isInWindow) continue;\n\n liveIds.add(req.id);\n if (!this.active.has(req.id)) {\n const buffer = this.bufferCache.get(req.src);\n if (buffer) this.playBuffer(buffer, req, sceneTime);\n }\n }\n\n for (const [id, active] of this.active) {\n if (!liveIds.has(id)) this.stopSource(id, active);\n }\n }\n\n async play(time: number, _speed: number, _reverse: boolean): Promise<void> {\n if (this.context.state === \"suspended\") {\n await this.context.resume();\n }\n this.syncTo(time);\n }\n\n stop(): void {\n for (const [id, active] of this.active) {\n this.stopSource(id, active);\n }\n // A bus's curves are scheduled against the clock of the run that built\n // it, so the next play, from wherever it lands, builds them again.\n this.buses.dispose();\n }\n\n setMuted(muted: boolean): void {\n this.muted = muted;\n this.applyMasterGain();\n }\n\n setVolume(volume: number): void {\n this.volume = Math.max(0, volume);\n this.applyMasterGain();\n }\n\n /** Mute and volume are held separately so unmuting restores the set level. */\n private applyMasterGain(): void {\n this.masterGain.gain.value = this.muted ? 0 : this.volume;\n }\n\n /** Starts a buffer source mid-clip if `sceneTime` lands after the request's start — `audioOffset` accounts for the request's trim, the elapsed time since `startAt`, and any speed (playbackRate) change. */\n private playBuffer(buffer: AudioBuffer, req: AudioRequest, sceneTime: number): void {\n const startTime = this.context.currentTime;\n const gainNode = this.context.createGain();\n // Guard against a missing/NaN volume — a non-finite AudioParam value throws.\n gainNode.gain.value = Number.isFinite(req.volume) ? req.volume : 1;\n // Into this clip's bus chain, or straight to the master when it has none.\n // The chain is shared: two clips on one bus reach the same nodes, which is\n // what makes a bus effect one tail rather than one per clip.\n gainNode.connect(this.buses.inputFor(req.bus, startTime, sceneTime));\n\n const source = this.context.createBufferSource();\n source.buffer = buffer;\n source.loop = req.loop;\n\n const scalarSpeed = effectiveSpeed(req.filters);\n const rate = Number.isFinite(scalarSpeed) && scalarSpeed > 0 ? scalarSpeed : 1;\n const speedCurve = speedCurveOf(req.filters);\n if (rate !== 1 && !speedCurve) source.playbackRate.value = rate;\n\n const elapsed = Math.max(0, sceneTime - req.startAt);\n // Trimmed source length the filter curves / speed curve are authored over.\n const sourceLength = Math.max(0, buffer.duration - req.trimStart);\n // Scene-time length of the clip. Prefer the bounded [startAt, endAt) span; if\n // endAt is unbounded (an open/looping clip reaching the device unresolved),\n // fall back to the source length scaled by speed so curve params still resolve\n // (a clipDuration of 0 would otherwise silently drop every fade/sweep).\n const clipDuration = isFinite(req.endAt)\n ? Math.max(0, req.endAt - req.startAt)\n : sourceLength / (rate || 1);\n\n // Insert the filter chain between the source and the per-request gain. Pass\n // the start time, clip duration, and elapsed so curve-valued params schedule\n // and align to a mid-clip seek.\n const graph = buildAudioFilterGraph(\n this.context, source, req.filters ?? [], startTime, clipDuration, elapsed,\n );\n graph.output.connect(gainNode);\n\n // Source-time offset for a mid-clip seek. Scalar speed scales linearly; a\n // speed curve uses the integral inverse to find the true source position.\n let audioOffset: number;\n if (speedCurve) {\n audioOffset = req.trimStart + sourceTimeAtSceneElapsed(speedCurve, sourceLength, elapsed);\n // Schedule the time-varying playbackRate (folds in any scalar speed too).\n applySpeedToPlaybackRate(\n source.playbackRate, speedCurve, sourceLength, clipDuration, rate, startTime, elapsed,\n );\n } else {\n audioOffset = req.trimStart + elapsed * rate;\n }\n\n source.start(startTime, audioOffset);\n for (const osc of graph.oscillators) osc.start(startTime);\n\n source.onended = () => {\n if (this.active.get(req.id)?.source === source) {\n this.active.delete(req.id);\n }\n };\n\n this.active.set(req.id, {\n source,\n gainNode,\n request: req,\n filterNodes: graph.nodes,\n oscillators: graph.oscillators,\n });\n }\n\n private stopSource(id: string, active: ActiveSource): void {\n try {\n active.source.onended = null;\n active.source.stop();\n for (const osc of active.oscillators) osc.stop();\n active.source.disconnect();\n for (const node of active.filterNodes) node.disconnect();\n active.gainNode.disconnect();\n } catch {\n // already stopped\n }\n this.active.delete(id);\n }\n\n dispose(): void {\n if (this.disposed) return;\n this.disposed = true;\n super.dispose();\n this.bufferCache.clear();\n this.decoding.clear();\n this.scheduled.length = 0;\n this.buses.dispose();\n try {\n this.masterGain.disconnect();\n } catch {\n // already disconnected\n }\n if (this.ownsContext && this.context.state !== \"closed\") {\n this.context.close();\n }\n }\n}\n"],
|
|
5
|
-
"mappings": "AAmCA,IAAIA,EAAiC,KAS/B,SAAUC,EAAmBC,EAA4B,CAC3DF,EAASE,CACb,CASA,eAAsBC,EAAgBC,EAAW,CAC7C,GAAI,CAACJ,EAAQ,OAAO,KACpB,GAAI,CACA,OAAO,MAAMA,EAAOI,CAAG,CAC3B,MAA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ACT,MAAK,SAAW,GAChB,MAAM,QAAO,EACb,KAAK,YAAY,MAAK,EACtB,KAAK,SAAS,MAAK,EACnB,KAAK,UAAU,OAAS,EACxB,KAAK,MAAM,QAAO,EAClB,GAAI,CACA,KAAK,WAAW,WAAU,CAC9B,MAAQ,CAER,CACI,KAAK,aAAe,KAAK,QAAQ,QAAU,UAC3C,KAAK,QAAQ,MAAK,EAE1B",
|
|
6
|
-
"names": ["source", "setAssetByteSource", "next", "localAssetBytes", "src", "fetchAssetBytes", "url", "response", "status", "busStopKey", "isCurve", "sourceTimeAtSceneElapsed", "CURVE_SAMPLES_PER_SECOND", "applyParam", "ctx", "audioParam", "param", "startTime", "clipDuration", "elapsed", "clamp", "v", "finite", "c", "base", "resolved", "startValue", "seg", "segStart", "segEnd", "span", "done", "curveStart", "curveDur", "count", "samples", "i", "local", "buildAudioFilterGraph", "source", "filters", "nodes", "oscillators", "cursor", "series", "node", "apply", "p", "filter", "gain", "biquad", "carrier", "lfo", "lfoDepth", "d", "clamp01", "split", "merge", "dry", "m", "maxDelay", "staticOf", "delay", "feedbackGain", "f", "wet", "effectiveSpeed", "speed", "speedCurveOf", "applySpeedToPlaybackRate", "rate", "curve", "sourceLength", "sceneDuration", "scalar", "step", "scene", "seedSrc", "s", "clampedScene", "srcT", "value", "ctxTime", "AudioBusGraph", "ctx", "destination", "bus", "startTime", "sceneTime", "node", "osc", "index", "stop", "key", "busStopKey", "existing", "output", "input", "level", "graph", "buildAudioFilterGraph", "sourceTimeAtSceneElapsed", "DEFAULT_SAMPLE_RATE", "audioUrl", "src", "catalog", "fetchAudioBuffer", "ctx", "arrayBuffer", "fetchAssetBytes", "mixAudio", "requests", "totalDuration", "options", "sampleRate", "frames", "uniqueSrcs", "r", "scratchCtx", "decoded", "mixCtx", "buses", "AudioBusGraph", "req", "globalOffset", "srcBuffer", "globalStart", "playDuration", "source", "scalarSpeed", "effectiveSpeed", "rate", "speedCurve", "speedCurveOf", "gain", "sourceLength", "clipDuration", "graph", "buildAudioFilterGraph", "applySpeedToPlaybackRate", "consumed", "sourceTimeAtSceneElapsed", "osc", "WebAudioMixer", "encodeWav", "buffer", "channelCount", "frameCount", "bytesPerSample", "blockAlign", "dataBytes", "out", "view", "ascii", "offset", "text", "i", "channels", "c", "frame", "sample", "AudioSink", "sourceTimeAtSceneElapsed", "WebAudioSink", "AudioSink", "context", "AudioBusGraph", "src", "data", "existing", "job", "buffer", "keep", "id", "active", "requests", "next", "r", "sceneTime", "liveIds", "req", "time", "_speed", "_reverse", "muted", "volume", "startTime", "gainNode", "source", "scalarSpeed", "effectiveSpeed", "rate", "speedCurve", "speedCurveOf", "elapsed", "sourceLength", "clipDuration", "graph", "buildAudioFilterGraph", "audioOffset", "sourceTimeAtSceneElapsed", "applySpeedToPlaybackRate", "osc", "node"]
|
|
7
|
-
}
|
package/dist/output.d.ts
DELETED
package/dist/output.d.ts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"output.d.ts","sourceRoot":"","sources":["../src/output.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAEjD,gFAAgF;AAChF,eAAO,MAAM,cAAc,EAAE;IAAE,QAAQ,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAG3D,CAAC"}
|
package/dist/output.js
DELETED
package/dist/output.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"output.js","sourceRoot":"","sources":["../src/output.ts"],"names":[],"mappings":"AAEA,gFAAgF;AAChF,MAAM,CAAC,MAAM,cAAc,GAAsC;IAC7D,QAAQ,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE;IACvC,GAAG,EAAE,EAAE;CACV,CAAC","sourcesContent":["import type { Size2D } from \"@motionscript/core\";\n\n/** What a document renders at when neither the caller nor the document says. */\nexport const DEFAULT_OUTPUT: { viewport: Size2D; fps: number } = {\n viewport: { width: 1920, height: 1080 },\n fps: 60,\n};\n"]}
|