@lubomirklimes/character-runtime 0.0.0-stage → 0.1.0-preview.1
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/LICENSE +21 -0
- package/README.md +89 -2
- package/dist/acs/acs15.d.ts +9 -0
- package/dist/acs/acs15.js +382 -0
- package/dist/acs/acs2-reader.d.ts +2 -0
- package/dist/acs/acs2-reader.js +277 -0
- package/dist/acs/binary.d.ts +1 -0
- package/dist/acs/binary.js +107 -0
- package/dist/acs/compound-file.d.ts +1 -0
- package/dist/acs/compound-file.js +326 -0
- package/dist/acs/document.d.ts +33 -0
- package/dist/acs/document.js +99 -0
- package/dist/acs/errors.d.ts +28 -0
- package/dist/acs/errors.js +41 -0
- package/dist/acs/image.d.ts +30 -0
- package/dist/acs/image.js +113 -0
- package/dist/acs/index.d.ts +11 -0
- package/dist/acs/index.js +10 -0
- package/dist/acs/lz.d.ts +7 -0
- package/dist/acs/lz.js +102 -0
- package/dist/acs/metadata.d.ts +14 -0
- package/dist/acs/metadata.js +126 -0
- package/dist/acs/model.d.ts +130 -0
- package/dist/acs/model.js +12 -0
- package/dist/acs/mouth.d.ts +37 -0
- package/dist/acs/mouth.js +43 -0
- package/dist/acs/wave.d.ts +53 -0
- package/dist/acs/wave.js +422 -0
- package/dist/browser/animation-frame-clock.d.ts +18 -0
- package/dist/browser/animation-frame-clock.js +42 -0
- package/dist/browser/canvas-renderer.d.ts +50 -0
- package/dist/browser/canvas-renderer.js +145 -0
- package/dist/browser/host.d.ts +84 -0
- package/dist/browser/host.js +206 -0
- package/dist/browser/index.d.ts +6 -0
- package/dist/browser/index.js +8 -0
- package/dist/browser/web-audio.d.ts +48 -0
- package/dist/browser/web-audio.js +205 -0
- package/dist/browser/web-speech.d.ts +131 -0
- package/dist/browser/web-speech.js +302 -0
- package/dist/core/activities.d.ts +10 -0
- package/dist/core/activities.js +479 -0
- package/dist/core/agent.d.ts +263 -0
- package/dist/core/agent.js +764 -0
- package/dist/core/audio.d.ts +17 -0
- package/dist/core/audio.js +174 -0
- package/dist/core/balloon.d.ts +43 -0
- package/dist/core/balloon.js +94 -0
- package/dist/core/clock.d.ts +32 -0
- package/dist/core/clock.js +51 -0
- package/dist/core/compositor.d.ts +22 -0
- package/dist/core/compositor.js +67 -0
- package/dist/core/events.d.ts +131 -0
- package/dist/core/events.js +1 -0
- package/dist/core/host.d.ts +29 -0
- package/dist/core/host.js +77 -0
- package/dist/core/index.d.ts +16 -0
- package/dist/core/index.js +13 -0
- package/dist/core/lipsync.d.ts +41 -0
- package/dist/core/lipsync.js +209 -0
- package/dist/core/random.d.ts +52 -0
- package/dist/core/random.js +105 -0
- package/dist/core/request.d.ts +68 -0
- package/dist/core/request.js +131 -0
- package/dist/core/resources.d.ts +70 -0
- package/dist/core/resources.js +243 -0
- package/dist/core/scheduler.d.ts +25 -0
- package/dist/core/scheduler.js +766 -0
- package/dist/core/source.d.ts +21 -0
- package/dist/core/source.js +54 -0
- package/dist/core/speech.d.ts +91 -0
- package/dist/core/speech.js +86 -0
- package/dist/core/text.d.ts +38 -0
- package/dist/core/text.js +97 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +4 -0
- package/package.json +68 -4
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import type { AgentOptions, CharacterAgent } from '../core/agent.js';
|
|
2
|
+
import type { Clock } from '../core/clock.js';
|
|
3
|
+
import type { AgentEvent } from '../core/events.js';
|
|
4
|
+
import { AgentHost } from '../core/host.js';
|
|
5
|
+
import { CharacterSource, type CharacterInput } from '../core/source.js';
|
|
6
|
+
import { CanvasRenderer } from './canvas-renderer.js';
|
|
7
|
+
import { WebAudioEngine } from './web-audio.js';
|
|
8
|
+
import { WebSpeechProvider } from './web-speech.js';
|
|
9
|
+
/** A pointer event on a hosted character. */
|
|
10
|
+
export interface CharacterPointerEvent {
|
|
11
|
+
readonly agent: CharacterAgent;
|
|
12
|
+
readonly type: 'pointerdown' | 'pointerup' | 'pointermove' | 'click' | 'dblclick' | 'contextmenu';
|
|
13
|
+
/** Position in character pixels (top-left of the frame is 0, 0). */
|
|
14
|
+
readonly x: number;
|
|
15
|
+
readonly y: number;
|
|
16
|
+
/** True when the character's presented frame is opaque at that point. */
|
|
17
|
+
readonly opaque: boolean;
|
|
18
|
+
readonly originalEvent: MouseEvent;
|
|
19
|
+
}
|
|
20
|
+
/** Options of a {@link BrowserCharacterHost}. */
|
|
21
|
+
export interface BrowserHostOptions {
|
|
22
|
+
/** The clock of every agent (default: an {@link AnimationFrameClock}). */
|
|
23
|
+
readonly clock?: Clock;
|
|
24
|
+
/** Sound output (default: a new {@link WebAudioEngine}; false: effects are timed but silent). */
|
|
25
|
+
readonly audio?: WebAudioEngine | false;
|
|
26
|
+
/** Speech (default: a new {@link WebSpeechProvider} when the browser has speech synthesis; false: none). */
|
|
27
|
+
readonly speech?: WebSpeechProvider | false;
|
|
28
|
+
/** Draw word balloons as HTML elements (default true). */
|
|
29
|
+
readonly balloons?: boolean;
|
|
30
|
+
/** Device pixels per CSS pixel (default `devicePixelRatio`). */
|
|
31
|
+
readonly pixelRatio?: number;
|
|
32
|
+
/** Smooth scaling (default false). */
|
|
33
|
+
readonly smoothing?: boolean;
|
|
34
|
+
/** Start the animation-frame loop at once (default true). */
|
|
35
|
+
readonly autoStart?: boolean;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Embeds animated characters in a web page: one canvas per agent inside `container` (which becomes a positioning context), Web Audio
|
|
39
|
+
* effects and speech output, Web Speech synthesis, HTML word balloons, pointer events and disposal. Logical time comes from the clock;
|
|
40
|
+
* `requestAnimationFrame` only samples it, so behavior does not depend on the display refresh rate, and unchanged frames are not redrawn.
|
|
41
|
+
*/
|
|
42
|
+
export declare class BrowserCharacterHost {
|
|
43
|
+
readonly container: HTMLElement;
|
|
44
|
+
private readonly options;
|
|
45
|
+
readonly host: AgentHost;
|
|
46
|
+
readonly audio: WebAudioEngine | null;
|
|
47
|
+
readonly speech: WebSpeechProvider | null;
|
|
48
|
+
private readonly views;
|
|
49
|
+
private readonly pointerListeners;
|
|
50
|
+
private readonly eventListeners;
|
|
51
|
+
private readonly ownsAudio;
|
|
52
|
+
private readonly ownsSpeech;
|
|
53
|
+
private readonly frames;
|
|
54
|
+
private stopFrames;
|
|
55
|
+
private disposed;
|
|
56
|
+
constructor(container: HTMLElement, options?: BrowserHostOptions);
|
|
57
|
+
get agents(): readonly CharacterAgent[];
|
|
58
|
+
/** Loads a character (URL, File/Blob, ArrayBuffer or typed array) and hosts an agent for it. */
|
|
59
|
+
load(input: CharacterInput, options?: Omit<AgentOptions, 'clock'>): Promise<CharacterAgent>;
|
|
60
|
+
/** Hosts an agent for an opened source (several agents may share one source). */
|
|
61
|
+
add(source: CharacterSource, options?: Omit<AgentOptions, 'clock'>): CharacterAgent;
|
|
62
|
+
private attach;
|
|
63
|
+
private pointer;
|
|
64
|
+
/** Subscribes to pointer events on the hosted characters. Returns the unsubscribe function. */
|
|
65
|
+
onPointer(listener: (event: CharacterPointerEvent) => void): () => void;
|
|
66
|
+
/** Subscribes to the events of every advance (all agents, in host order). Returns the unsubscribe function. */
|
|
67
|
+
onEvents(listener: (events: readonly AgentEvent[]) => void): () => void;
|
|
68
|
+
/** The canvas of an agent (for example to style it), or null. */
|
|
69
|
+
canvasOf(agent: CharacterAgent): HTMLCanvasElement | null;
|
|
70
|
+
/** The renderer of an agent (diagnostics), or null. */
|
|
71
|
+
rendererOf(agent: CharacterAgent): CanvasRenderer | null;
|
|
72
|
+
/** Starts the animation-frame loop. */
|
|
73
|
+
start(): void;
|
|
74
|
+
/** Stops the animation-frame loop (logical time continues with the clock; the next tick catches up). */
|
|
75
|
+
stop(): void;
|
|
76
|
+
/** Advances every agent to the clock's time and presents them (the loop calls this once per animation frame). */
|
|
77
|
+
tick(): readonly AgentEvent[];
|
|
78
|
+
private present;
|
|
79
|
+
private presentBalloon;
|
|
80
|
+
/** Removes and disposes one agent: its canvas, balloon, listeners and resources. */
|
|
81
|
+
remove(agent: CharacterAgent): boolean;
|
|
82
|
+
/** Stops the loop and disposes every agent, the audio engine and the speech provider the host created. */
|
|
83
|
+
dispose(): void;
|
|
84
|
+
}
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
import { AgentHost } from '../core/host.js';
|
|
2
|
+
import { CharacterSource } from '../core/source.js';
|
|
3
|
+
import { AnimationFrameClock } from './animation-frame-clock.js';
|
|
4
|
+
import { CanvasRenderer } from './canvas-renderer.js';
|
|
5
|
+
import { WebAudioEngine } from './web-audio.js';
|
|
6
|
+
import { WebSpeechProvider } from './web-speech.js';
|
|
7
|
+
const POINTER_TYPES = ['pointerdown', 'pointerup', 'pointermove', 'click', 'dblclick', 'contextmenu'];
|
|
8
|
+
const colorRef = (c) => `rgb(${c & 0xff}, ${(c >>> 8) & 0xff}, ${(c >>> 16) & 0xff})`;
|
|
9
|
+
/**
|
|
10
|
+
* Embeds animated characters in a web page: one canvas per agent inside `container` (which becomes a positioning context), Web Audio
|
|
11
|
+
* effects and speech output, Web Speech synthesis, HTML word balloons, pointer events and disposal. Logical time comes from the clock;
|
|
12
|
+
* `requestAnimationFrame` only samples it, so behavior does not depend on the display refresh rate, and unchanged frames are not redrawn.
|
|
13
|
+
*/
|
|
14
|
+
export class BrowserCharacterHost {
|
|
15
|
+
container;
|
|
16
|
+
options;
|
|
17
|
+
host;
|
|
18
|
+
audio;
|
|
19
|
+
speech;
|
|
20
|
+
views = new Map();
|
|
21
|
+
pointerListeners = new Set();
|
|
22
|
+
eventListeners = new Set();
|
|
23
|
+
ownsAudio;
|
|
24
|
+
ownsSpeech;
|
|
25
|
+
frames;
|
|
26
|
+
stopFrames = null;
|
|
27
|
+
disposed = false;
|
|
28
|
+
constructor(container, options = {}) {
|
|
29
|
+
this.container = container;
|
|
30
|
+
this.options = options;
|
|
31
|
+
this.frames = options.clock instanceof AnimationFrameClock ? options.clock : new AnimationFrameClock();
|
|
32
|
+
this.host = new AgentHost(options.clock ?? this.frames);
|
|
33
|
+
this.ownsAudio = options.audio === undefined;
|
|
34
|
+
this.audio = options.audio === false ? null : options.audio ?? (WebAudioEngine.supported ? new WebAudioEngine() : null);
|
|
35
|
+
this.ownsSpeech = options.speech === undefined;
|
|
36
|
+
this.speech = options.speech === false ? null : options.speech ?? (typeof speechSynthesis !== 'undefined' ? new WebSpeechProvider() : null);
|
|
37
|
+
if (getComputedStyle(container).position === 'static')
|
|
38
|
+
container.style.position = 'relative';
|
|
39
|
+
if (options.autoStart ?? true)
|
|
40
|
+
this.start();
|
|
41
|
+
}
|
|
42
|
+
get agents() {
|
|
43
|
+
return this.host.agents;
|
|
44
|
+
}
|
|
45
|
+
/** Loads a character (URL, File/Blob, ArrayBuffer or typed array) and hosts an agent for it. */
|
|
46
|
+
async load(input, options = {}) {
|
|
47
|
+
return this.add(await CharacterSource.load(input), options);
|
|
48
|
+
}
|
|
49
|
+
/** Hosts an agent for an opened source (several agents may share one source). */
|
|
50
|
+
add(source, options = {}) {
|
|
51
|
+
if (this.disposed)
|
|
52
|
+
throw new Error('The host has been disposed.');
|
|
53
|
+
const audio = this.audio;
|
|
54
|
+
const agent = this.host.create(source, {
|
|
55
|
+
...(audio ? { audio: () => audio.createOutput(), speechAudio: () => audio.createOutput() } : {}),
|
|
56
|
+
...(this.speech?.available ? { speech: this.speech } : {}),
|
|
57
|
+
...options,
|
|
58
|
+
});
|
|
59
|
+
this.attach(agent);
|
|
60
|
+
return agent;
|
|
61
|
+
}
|
|
62
|
+
attach(agent) {
|
|
63
|
+
const element = document.createElement('div');
|
|
64
|
+
element.style.cssText = 'position:absolute;left:0;top:0;will-change:transform;line-height:0;';
|
|
65
|
+
const canvas = document.createElement('canvas');
|
|
66
|
+
canvas.style.cssText = 'display:block;touch-action:none;';
|
|
67
|
+
element.appendChild(canvas);
|
|
68
|
+
let balloon = null;
|
|
69
|
+
if (this.options.balloons ?? true) {
|
|
70
|
+
balloon = document.createElement('div');
|
|
71
|
+
balloon.setAttribute('role', 'status');
|
|
72
|
+
balloon.style.cssText = 'position:absolute;display:none;box-sizing:border-box;padding:6px 9px;border:1px solid;border-radius:8px;white-space:pre;line-height:1.25;pointer-events:none;';
|
|
73
|
+
this.container.appendChild(balloon);
|
|
74
|
+
}
|
|
75
|
+
this.container.appendChild(element);
|
|
76
|
+
const renderer = new CanvasRenderer(agent, canvas, { ...(this.options.pixelRatio ? { pixelRatio: this.options.pixelRatio } : {}), smoothing: this.options.smoothing ?? false });
|
|
77
|
+
const listeners = POINTER_TYPES.map((type) => [type, (event) => this.pointer(agent, renderer, type, event)]);
|
|
78
|
+
for (const [type, listener] of listeners)
|
|
79
|
+
canvas.addEventListener(type, listener);
|
|
80
|
+
this.views.set(agent, { agent, element, canvas, renderer, balloon, listeners, placed: '', balloonShown: '' });
|
|
81
|
+
this.present(this.views.get(agent));
|
|
82
|
+
}
|
|
83
|
+
pointer(agent, renderer, type, event) {
|
|
84
|
+
const rect = renderer.canvas.getBoundingClientRect();
|
|
85
|
+
const scale = agent.scale;
|
|
86
|
+
const cssX = event.clientX - rect.left, cssY = event.clientY - rect.top;
|
|
87
|
+
const e = { agent, type, x: cssX / scale, y: cssY / scale, opaque: renderer.hitTest(cssX, cssY), originalEvent: event };
|
|
88
|
+
for (const listener of [...this.pointerListeners])
|
|
89
|
+
listener(e);
|
|
90
|
+
}
|
|
91
|
+
/** Subscribes to pointer events on the hosted characters. Returns the unsubscribe function. */
|
|
92
|
+
onPointer(listener) {
|
|
93
|
+
this.pointerListeners.add(listener);
|
|
94
|
+
return () => this.pointerListeners.delete(listener);
|
|
95
|
+
}
|
|
96
|
+
/** Subscribes to the events of every advance (all agents, in host order). Returns the unsubscribe function. */
|
|
97
|
+
onEvents(listener) {
|
|
98
|
+
this.eventListeners.add(listener);
|
|
99
|
+
return () => this.eventListeners.delete(listener);
|
|
100
|
+
}
|
|
101
|
+
/** The canvas of an agent (for example to style it), or null. */
|
|
102
|
+
canvasOf(agent) {
|
|
103
|
+
return this.views.get(agent)?.canvas ?? null;
|
|
104
|
+
}
|
|
105
|
+
/** The renderer of an agent (diagnostics), or null. */
|
|
106
|
+
rendererOf(agent) {
|
|
107
|
+
return this.views.get(agent)?.renderer ?? null;
|
|
108
|
+
}
|
|
109
|
+
/** Starts the animation-frame loop. */
|
|
110
|
+
start() {
|
|
111
|
+
if (this.disposed || this.stopFrames)
|
|
112
|
+
return;
|
|
113
|
+
this.stopFrames = this.frames.onFrame(() => this.tick());
|
|
114
|
+
}
|
|
115
|
+
/** Stops the animation-frame loop (logical time continues with the clock; the next tick catches up). */
|
|
116
|
+
stop() {
|
|
117
|
+
this.stopFrames?.();
|
|
118
|
+
this.stopFrames = null;
|
|
119
|
+
}
|
|
120
|
+
/** Advances every agent to the clock's time and presents them (the loop calls this once per animation frame). */
|
|
121
|
+
tick() {
|
|
122
|
+
if (this.disposed)
|
|
123
|
+
return [];
|
|
124
|
+
const events = this.host.advance();
|
|
125
|
+
if (this.speech)
|
|
126
|
+
this.speech.process(events);
|
|
127
|
+
for (const view of this.views.values())
|
|
128
|
+
this.present(view);
|
|
129
|
+
if (events.length > 0)
|
|
130
|
+
for (const listener of [...this.eventListeners])
|
|
131
|
+
listener(events);
|
|
132
|
+
return events;
|
|
133
|
+
}
|
|
134
|
+
present(view) {
|
|
135
|
+
const frame = view.agent.currentFrame;
|
|
136
|
+
view.renderer.render();
|
|
137
|
+
const placed = `${frame.position.x},${frame.position.y},${frame.visible}`;
|
|
138
|
+
if (placed !== view.placed) {
|
|
139
|
+
view.placed = placed;
|
|
140
|
+
view.element.style.transform = `translate(${frame.position.x}px, ${frame.position.y}px)`;
|
|
141
|
+
view.element.style.display = frame.visible ? 'block' : 'none';
|
|
142
|
+
}
|
|
143
|
+
if (view.balloon)
|
|
144
|
+
this.presentBalloon(view, view.agent.balloon);
|
|
145
|
+
}
|
|
146
|
+
presentBalloon(view, state) {
|
|
147
|
+
const element = view.balloon;
|
|
148
|
+
const key = state.visible ? `${state.requestId}|${state.visibleLines.join('\n')}|${state.anchor.x},${state.anchor.y}` : '';
|
|
149
|
+
if (key === view.balloonShown)
|
|
150
|
+
return;
|
|
151
|
+
view.balloonShown = key;
|
|
152
|
+
if (!state.visible) {
|
|
153
|
+
element.style.display = 'none';
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
const s = state.style;
|
|
157
|
+
element.textContent = state.visibleLines.join('\n');
|
|
158
|
+
element.style.color = colorRef(s.foreColor);
|
|
159
|
+
element.style.background = colorRef(s.backColor);
|
|
160
|
+
element.style.borderColor = colorRef(s.borderColor);
|
|
161
|
+
element.style.fontFamily = `"${s.fontName}", sans-serif`;
|
|
162
|
+
element.style.fontSize = `${Math.abs(s.fontHeight)}px`;
|
|
163
|
+
element.style.fontWeight = String(s.fontWeight);
|
|
164
|
+
element.style.borderRadius = state.kind === 'thought' ? '16px' : '8px';
|
|
165
|
+
element.style.display = 'block';
|
|
166
|
+
// Above the character, centred on the anchor, kept inside the container horizontally; below it when there is no room.
|
|
167
|
+
const width = element.offsetWidth, height = element.offsetHeight;
|
|
168
|
+
const left = Math.min(Math.max(0, state.anchor.x - width / 2), Math.max(0, this.container.clientWidth - width));
|
|
169
|
+
const above = state.anchor.y - height - 8;
|
|
170
|
+
const frame = view.agent.currentFrame;
|
|
171
|
+
const top = above >= 0 ? above : state.anchor.y + frame.height * frame.scale + 8;
|
|
172
|
+
element.style.left = `${left}px`;
|
|
173
|
+
element.style.top = `${top}px`;
|
|
174
|
+
}
|
|
175
|
+
/** Removes and disposes one agent: its canvas, balloon, listeners and resources. */
|
|
176
|
+
remove(agent) {
|
|
177
|
+
const view = this.views.get(agent);
|
|
178
|
+
if (!view)
|
|
179
|
+
return false;
|
|
180
|
+
this.views.delete(agent);
|
|
181
|
+
this.speech?.cancelAgent(agent.id);
|
|
182
|
+
for (const [type, listener] of view.listeners)
|
|
183
|
+
view.canvas.removeEventListener(type, listener);
|
|
184
|
+
view.renderer.dispose();
|
|
185
|
+
view.element.remove();
|
|
186
|
+
view.balloon?.remove();
|
|
187
|
+
this.host.unload(agent);
|
|
188
|
+
return true;
|
|
189
|
+
}
|
|
190
|
+
/** Stops the loop and disposes every agent, the audio engine and the speech provider the host created. */
|
|
191
|
+
dispose() {
|
|
192
|
+
if (this.disposed)
|
|
193
|
+
return;
|
|
194
|
+
this.stop();
|
|
195
|
+
for (const agent of [...this.views.keys()])
|
|
196
|
+
this.remove(agent);
|
|
197
|
+
this.host.dispose();
|
|
198
|
+
this.disposed = true;
|
|
199
|
+
this.pointerListeners.clear();
|
|
200
|
+
this.eventListeners.clear();
|
|
201
|
+
if (this.ownsAudio)
|
|
202
|
+
this.audio?.dispose();
|
|
203
|
+
if (this.ownsSpeech)
|
|
204
|
+
this.speech?.dispose();
|
|
205
|
+
}
|
|
206
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export * from '../index.js';
|
|
2
|
+
export { AnimationFrameClock } from './animation-frame-clock.js';
|
|
3
|
+
export { CanvasRenderer, type CanvasRendererOptions } from './canvas-renderer.js';
|
|
4
|
+
export { WebAudioEngine, type WebAudioOptions, type WebAudioState } from './web-audio.js';
|
|
5
|
+
export { WebSpeechProvider, type WebSpeechOptions, type WebSpeechOutcome, type WebSpeechStatistics, type WebSpeechTiming } from './web-speech.js';
|
|
6
|
+
export { BrowserCharacterHost, type BrowserHostOptions, type CharacterPointerEvent } from './host.js';
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// Browser adapters: Canvas 2D rendering, Web Audio output, Web Speech synthesis and page hosting. They build on the portable runtime,
|
|
2
|
+
// which is re-exported so that a page needs one import.
|
|
3
|
+
export * from '../index.js';
|
|
4
|
+
export { AnimationFrameClock } from './animation-frame-clock.js';
|
|
5
|
+
export { CanvasRenderer } from './canvas-renderer.js';
|
|
6
|
+
export { WebAudioEngine } from './web-audio.js';
|
|
7
|
+
export { WebSpeechProvider } from './web-speech.js';
|
|
8
|
+
export { BrowserCharacterHost } from './host.js';
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { AudioOutput } from '../core/audio.js';
|
|
2
|
+
/** The state of a {@link WebAudioEngine}. */
|
|
3
|
+
export type WebAudioState = 'unavailable' | 'suspended' | 'running' | 'closed';
|
|
4
|
+
/** Options of a {@link WebAudioEngine}. */
|
|
5
|
+
export interface WebAudioOptions {
|
|
6
|
+
/** An existing context (not closed by the engine). Default: a context created on first need. */
|
|
7
|
+
readonly context?: AudioContext;
|
|
8
|
+
/** Where voices connect (default: the context's destination). */
|
|
9
|
+
readonly destination?: AudioNode;
|
|
10
|
+
/**
|
|
11
|
+
* Where the engine listens for the first user gesture to resume a suspended context (autoplay policy). Default: `document`; null
|
|
12
|
+
* disables it (call {@link WebAudioEngine.unlock} from a gesture handler instead).
|
|
13
|
+
*/
|
|
14
|
+
readonly unlockTarget?: EventTarget | null;
|
|
15
|
+
/** Most decoded clips kept as audio buffers (default 128). */
|
|
16
|
+
readonly maxBuffers?: number;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Sound output through the Web Audio API. One engine serves every agent of a page; each agent gets its own effect and speech voices
|
|
20
|
+
* ({@link createOutput}), so several clips sound at once. Playback before the first user gesture is silent: browsers keep the context
|
|
21
|
+
* suspended until the page is activated, and the engine resumes it on the first gesture.
|
|
22
|
+
*/
|
|
23
|
+
export declare class WebAudioEngine {
|
|
24
|
+
private context;
|
|
25
|
+
private readonly ownsContext;
|
|
26
|
+
private readonly destination;
|
|
27
|
+
private readonly unlockTarget;
|
|
28
|
+
private readonly buffers;
|
|
29
|
+
private readonly decoding;
|
|
30
|
+
private readonly maxBuffers;
|
|
31
|
+
private readonly outputs;
|
|
32
|
+
private disposed;
|
|
33
|
+
private readonly unlock;
|
|
34
|
+
constructor(options?: WebAudioOptions);
|
|
35
|
+
/** True when the platform has the Web Audio API. */
|
|
36
|
+
static get supported(): boolean;
|
|
37
|
+
get state(): WebAudioState;
|
|
38
|
+
/** The audio context (created on first call), or null when Web Audio is unavailable. */
|
|
39
|
+
ensureContext(): AudioContext | null;
|
|
40
|
+
/** Resumes a suspended context. Browsers allow it only during or after a user gesture. */
|
|
41
|
+
resume(): Promise<WebAudioState>;
|
|
42
|
+
/** A new voice: one clip at a time, independent of other voices. */
|
|
43
|
+
createOutput(): AudioOutput;
|
|
44
|
+
private keep;
|
|
45
|
+
private removeUnlock;
|
|
46
|
+
/** Stops every voice, removes the gesture listeners, drops cached buffers and closes a context the engine created. */
|
|
47
|
+
dispose(): void;
|
|
48
|
+
}
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
const UNLOCK_EVENTS = ['pointerdown', 'keydown', 'touchend'];
|
|
2
|
+
/**
|
|
3
|
+
* Sound output through the Web Audio API. One engine serves every agent of a page; each agent gets its own effect and speech voices
|
|
4
|
+
* ({@link createOutput}), so several clips sound at once. Playback before the first user gesture is silent: browsers keep the context
|
|
5
|
+
* suspended until the page is activated, and the engine resumes it on the first gesture.
|
|
6
|
+
*/
|
|
7
|
+
export class WebAudioEngine {
|
|
8
|
+
context;
|
|
9
|
+
ownsContext;
|
|
10
|
+
destination;
|
|
11
|
+
unlockTarget;
|
|
12
|
+
buffers = new Map(); // insertion order = least recently used first
|
|
13
|
+
decoding = new Map();
|
|
14
|
+
maxBuffers;
|
|
15
|
+
outputs = new Set();
|
|
16
|
+
disposed = false;
|
|
17
|
+
unlock = () => void this.resume();
|
|
18
|
+
constructor(options = {}) {
|
|
19
|
+
this.context = options.context ?? null;
|
|
20
|
+
this.ownsContext = !options.context;
|
|
21
|
+
this.destination = options.destination ?? null;
|
|
22
|
+
this.maxBuffers = options.maxBuffers ?? 128;
|
|
23
|
+
this.unlockTarget = options.unlockTarget === undefined ? (typeof document !== 'undefined' ? document : null) : options.unlockTarget;
|
|
24
|
+
for (const type of UNLOCK_EVENTS)
|
|
25
|
+
this.unlockTarget?.addEventListener(type, this.unlock, { capture: true, passive: true });
|
|
26
|
+
}
|
|
27
|
+
/** True when the platform has the Web Audio API. */
|
|
28
|
+
static get supported() {
|
|
29
|
+
return typeof globalThis.AudioContext === 'function';
|
|
30
|
+
}
|
|
31
|
+
get state() {
|
|
32
|
+
if (this.disposed)
|
|
33
|
+
return 'closed';
|
|
34
|
+
if (!this.context)
|
|
35
|
+
return WebAudioEngine.supported ? 'suspended' : 'unavailable';
|
|
36
|
+
return this.context.state === 'running' ? 'running' : this.context.state === 'closed' ? 'closed' : 'suspended';
|
|
37
|
+
}
|
|
38
|
+
/** The audio context (created on first call), or null when Web Audio is unavailable. */
|
|
39
|
+
ensureContext() {
|
|
40
|
+
if (this.disposed)
|
|
41
|
+
return null;
|
|
42
|
+
if (!this.context && WebAudioEngine.supported)
|
|
43
|
+
this.context = new AudioContext();
|
|
44
|
+
return this.context;
|
|
45
|
+
}
|
|
46
|
+
/** Resumes a suspended context. Browsers allow it only during or after a user gesture. */
|
|
47
|
+
async resume() {
|
|
48
|
+
const context = this.ensureContext();
|
|
49
|
+
if (context && context.state === 'suspended') {
|
|
50
|
+
try {
|
|
51
|
+
await context.resume();
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
// Not allowed yet (no user activation): stays suspended.
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
if (this.state === 'running')
|
|
58
|
+
this.removeUnlock();
|
|
59
|
+
return this.state;
|
|
60
|
+
}
|
|
61
|
+
/** A new voice: one clip at a time, independent of other voices. */
|
|
62
|
+
createOutput() {
|
|
63
|
+
const output = new WebAudioOutput(this);
|
|
64
|
+
this.outputs.add(output);
|
|
65
|
+
return output;
|
|
66
|
+
}
|
|
67
|
+
/** @internal */
|
|
68
|
+
get target() {
|
|
69
|
+
return this.destination ?? this.context?.destination ?? null;
|
|
70
|
+
}
|
|
71
|
+
/** @internal The decoded buffer of a clip, decoding it if needed (PCM synchronously, MPEG asynchronously). */
|
|
72
|
+
buffer(clip) {
|
|
73
|
+
const context = this.ensureContext();
|
|
74
|
+
if (!context)
|
|
75
|
+
return null;
|
|
76
|
+
const hit = this.buffers.get(clip);
|
|
77
|
+
if (hit) {
|
|
78
|
+
this.buffers.delete(clip);
|
|
79
|
+
this.buffers.set(clip, hit);
|
|
80
|
+
return hit;
|
|
81
|
+
}
|
|
82
|
+
const samples = clip.samples();
|
|
83
|
+
if (samples) {
|
|
84
|
+
const frames = Math.floor(samples.length / clip.channels);
|
|
85
|
+
if (frames === 0)
|
|
86
|
+
return null;
|
|
87
|
+
const buffer = context.createBuffer(clip.channels, frames, clip.sampleRate);
|
|
88
|
+
for (let c = 0; c < clip.channels; c++) {
|
|
89
|
+
const data = buffer.getChannelData(c);
|
|
90
|
+
for (let i = 0; i < frames; i++)
|
|
91
|
+
data[i] = samples[i * clip.channels + c] / 32768;
|
|
92
|
+
}
|
|
93
|
+
this.keep(clip, buffer);
|
|
94
|
+
return buffer;
|
|
95
|
+
}
|
|
96
|
+
const stream = clip.mpegStream;
|
|
97
|
+
if (!stream)
|
|
98
|
+
return null;
|
|
99
|
+
let pending = this.decoding.get(clip);
|
|
100
|
+
if (!pending) {
|
|
101
|
+
pending = context.decodeAudioData(stream.slice().buffer).then((buffer) => {
|
|
102
|
+
this.decoding.delete(clip);
|
|
103
|
+
if (!this.disposed)
|
|
104
|
+
this.keep(clip, buffer);
|
|
105
|
+
return buffer;
|
|
106
|
+
}, () => {
|
|
107
|
+
this.decoding.delete(clip);
|
|
108
|
+
return null;
|
|
109
|
+
});
|
|
110
|
+
this.decoding.set(clip, pending);
|
|
111
|
+
}
|
|
112
|
+
return pending;
|
|
113
|
+
}
|
|
114
|
+
keep(clip, buffer) {
|
|
115
|
+
this.buffers.set(clip, buffer);
|
|
116
|
+
for (const key of this.buffers.keys()) {
|
|
117
|
+
if (this.buffers.size <= this.maxBuffers)
|
|
118
|
+
break;
|
|
119
|
+
this.buffers.delete(key);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
/** @internal */
|
|
123
|
+
release(output) {
|
|
124
|
+
this.outputs.delete(output);
|
|
125
|
+
}
|
|
126
|
+
removeUnlock() {
|
|
127
|
+
for (const type of UNLOCK_EVENTS)
|
|
128
|
+
this.unlockTarget?.removeEventListener(type, this.unlock, { capture: true });
|
|
129
|
+
}
|
|
130
|
+
/** Stops every voice, removes the gesture listeners, drops cached buffers and closes a context the engine created. */
|
|
131
|
+
dispose() {
|
|
132
|
+
if (this.disposed)
|
|
133
|
+
return;
|
|
134
|
+
for (const output of [...this.outputs])
|
|
135
|
+
output.dispose();
|
|
136
|
+
this.disposed = true;
|
|
137
|
+
this.removeUnlock();
|
|
138
|
+
this.buffers.clear();
|
|
139
|
+
this.decoding.clear();
|
|
140
|
+
if (this.ownsContext)
|
|
141
|
+
void this.context?.close().catch(() => undefined);
|
|
142
|
+
this.context = null;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
/** One Web Audio voice. */
|
|
146
|
+
class WebAudioOutput {
|
|
147
|
+
engine;
|
|
148
|
+
node = null;
|
|
149
|
+
generation = 0;
|
|
150
|
+
constructor(engine) {
|
|
151
|
+
this.engine = engine;
|
|
152
|
+
}
|
|
153
|
+
play(clip, offsetMs) {
|
|
154
|
+
this.stop();
|
|
155
|
+
const generation = this.generation;
|
|
156
|
+
const requested = this.engine.ensureContext()?.currentTime ?? 0;
|
|
157
|
+
const buffer = this.engine.buffer(clip);
|
|
158
|
+
if (!buffer)
|
|
159
|
+
return;
|
|
160
|
+
if (buffer instanceof Promise) {
|
|
161
|
+
// MPEG Layer-3 is decoded by the platform: start when it is ready, at the offset the elapsed time gives.
|
|
162
|
+
void buffer.then((decoded) => {
|
|
163
|
+
if (!decoded || generation !== this.generation)
|
|
164
|
+
return;
|
|
165
|
+
const context = this.engine.ensureContext();
|
|
166
|
+
this.start(decoded, offsetMs / 1000 + Math.max(0, (context?.currentTime ?? requested) - requested));
|
|
167
|
+
});
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
this.start(buffer, offsetMs / 1000);
|
|
171
|
+
}
|
|
172
|
+
start(buffer, offsetSeconds) {
|
|
173
|
+
const context = this.engine.ensureContext(), target = this.engine.target;
|
|
174
|
+
if (!context || !target || offsetSeconds >= buffer.duration)
|
|
175
|
+
return;
|
|
176
|
+
const node = context.createBufferSource();
|
|
177
|
+
node.buffer = buffer;
|
|
178
|
+
node.connect(target);
|
|
179
|
+
node.onended = () => {
|
|
180
|
+
if (this.node === node)
|
|
181
|
+
this.node = null;
|
|
182
|
+
node.disconnect();
|
|
183
|
+
};
|
|
184
|
+
node.start(0, Math.max(0, offsetSeconds));
|
|
185
|
+
this.node = node;
|
|
186
|
+
}
|
|
187
|
+
stop() {
|
|
188
|
+
this.generation++;
|
|
189
|
+
const node = this.node;
|
|
190
|
+
this.node = null;
|
|
191
|
+
if (!node)
|
|
192
|
+
return;
|
|
193
|
+
try {
|
|
194
|
+
node.stop();
|
|
195
|
+
}
|
|
196
|
+
catch {
|
|
197
|
+
// Already stopped.
|
|
198
|
+
}
|
|
199
|
+
node.disconnect();
|
|
200
|
+
}
|
|
201
|
+
dispose() {
|
|
202
|
+
this.stop();
|
|
203
|
+
this.engine.release(this);
|
|
204
|
+
}
|
|
205
|
+
}
|