@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
package/dist/acs/wave.js
ADDED
|
@@ -0,0 +1,422 @@
|
|
|
1
|
+
import { equalBytes, fourCC, i16, u16, u32, writeU16, writeU32 } from './binary.js';
|
|
2
|
+
import { InvalidArgumentError, NotSupportedError } from './errors.js';
|
|
3
|
+
/** Largest sound record (16 MiB). */
|
|
4
|
+
export const MAX_SOUND_BYTES = 16 * 1024 * 1024;
|
|
5
|
+
/** Longest sound (60 s). */
|
|
6
|
+
export const MAX_SOUND_MS = 60_000;
|
|
7
|
+
/** WAVE format tags of the codecs CharacterRuntime reads (ACS.md §9). */
|
|
8
|
+
export const WaveCodec = { pcm: 1, msAdpcm: 2, ieeeFloat: 3, aLaw: 6, muLaw: 7, imaAdpcm: 0x11, mpegLayer3: 0x55 };
|
|
9
|
+
const RIFF = fourCC('RIFF'), WAVE = fourCC('WAVE'), FMT = fourCC('fmt '), DATA = fourCC('data'), FACT = fourCC('fact');
|
|
10
|
+
const PLAYABLE = new Set(Object.values(WaveCodec));
|
|
11
|
+
/**
|
|
12
|
+
* A decoded RIFF/WAVE sound. PCM is kept as stored; Microsoft ADPCM, IMA ADPCM, G.711 and IEEE float are decoded to 16-bit PCM;
|
|
13
|
+
* MPEG Layer-3 is validated by its frame headers and kept as its MPEG stream (decoding it is a platform service).
|
|
14
|
+
*/
|
|
15
|
+
export class WaveAudio {
|
|
16
|
+
sourceCodec;
|
|
17
|
+
channels;
|
|
18
|
+
sampleRate;
|
|
19
|
+
bitsPerSample;
|
|
20
|
+
durationMs;
|
|
21
|
+
playableFormat;
|
|
22
|
+
pcmData;
|
|
23
|
+
decoded;
|
|
24
|
+
mpeg;
|
|
25
|
+
byteLength;
|
|
26
|
+
constructor(
|
|
27
|
+
/** WAVE format tag of the source. */
|
|
28
|
+
sourceCodec, channels, sampleRate,
|
|
29
|
+
/** Bits per sample of the playable PCM (8 or 16); 0 for an MPEG stream. */
|
|
30
|
+
bitsPerSample, durationMs,
|
|
31
|
+
/** `pcm` (PCM samples available through {@link samples}) or `mpeg-layer3` (the MPEG stream in {@link mpegStream}). */
|
|
32
|
+
playableFormat, pcmData, decoded, mpeg,
|
|
33
|
+
/** Bytes the sound occupies in memory (cache accounting). */
|
|
34
|
+
byteLength) {
|
|
35
|
+
this.sourceCodec = sourceCodec;
|
|
36
|
+
this.channels = channels;
|
|
37
|
+
this.sampleRate = sampleRate;
|
|
38
|
+
this.bitsPerSample = bitsPerSample;
|
|
39
|
+
this.durationMs = durationMs;
|
|
40
|
+
this.playableFormat = playableFormat;
|
|
41
|
+
this.pcmData = pcmData;
|
|
42
|
+
this.decoded = decoded;
|
|
43
|
+
this.mpeg = mpeg;
|
|
44
|
+
this.byteLength = byteLength;
|
|
45
|
+
}
|
|
46
|
+
/** The playable samples as interleaved signed 16-bit PCM (8-bit PCM widened as (s − 128) × 256). Null for an MPEG stream. */
|
|
47
|
+
samples() {
|
|
48
|
+
if (this.decoded)
|
|
49
|
+
return this.decoded;
|
|
50
|
+
if (!this.pcmData)
|
|
51
|
+
return null;
|
|
52
|
+
const data = this.pcmData;
|
|
53
|
+
if (this.bitsPerSample === 16) {
|
|
54
|
+
const n = data.length >> 1, out = new Int16Array(n);
|
|
55
|
+
for (let i = 0; i < n; i++)
|
|
56
|
+
out[i] = i16(data, i * 2);
|
|
57
|
+
return out;
|
|
58
|
+
}
|
|
59
|
+
const out = new Int16Array(data.length);
|
|
60
|
+
for (let i = 0; i < data.length; i++)
|
|
61
|
+
out[i] = (data[i] - 128) * 256;
|
|
62
|
+
return out;
|
|
63
|
+
}
|
|
64
|
+
/** The MPEG Layer-3 elementary stream (source data chunk), or null for PCM. */
|
|
65
|
+
get mpegStream() {
|
|
66
|
+
return this.mpeg;
|
|
67
|
+
}
|
|
68
|
+
/** Sample frames of the playable audio. */
|
|
69
|
+
get frames() {
|
|
70
|
+
if (this.playableFormat !== 'pcm')
|
|
71
|
+
return Math.round((this.durationMs * this.sampleRate) / 1000);
|
|
72
|
+
const samples = this.decoded ? this.decoded.length : this.bitsPerSample === 16 ? this.pcmData.length >> 1 : this.pcmData.length;
|
|
73
|
+
return Math.floor(samples / this.channels);
|
|
74
|
+
}
|
|
75
|
+
/** A canonical 16-bit PCM RIFF/WAVE file of the playable samples (null for MPEG). */
|
|
76
|
+
toWav() {
|
|
77
|
+
const samples = this.samples();
|
|
78
|
+
if (!samples)
|
|
79
|
+
return null;
|
|
80
|
+
return pcm16Wave(samples, this.channels, this.sampleRate);
|
|
81
|
+
}
|
|
82
|
+
/** Reads a RIFF/WAVE record (ACS.md §9.1 check order). Throws {@link NotSupportedError} or {@link InvalidArgumentError}. */
|
|
83
|
+
static read(data) {
|
|
84
|
+
if (data.length < 12 || data.length > MAX_SOUND_BYTES || !equalBytes(data, 0, RIFF) || !equalBytes(data, 8, WAVE))
|
|
85
|
+
throw new NotSupportedError('Expected bounded RIFF/WAVE audio.');
|
|
86
|
+
const end = 8 + u32(data, 4);
|
|
87
|
+
if (end > data.length || end < 12)
|
|
88
|
+
throw new InvalidArgumentError('Truncated RIFF payload.');
|
|
89
|
+
let channels = 0, rate = 0, bits = 0, align = 0, byteRate = 0, tag = 0, dataStart = -1, length = -1, factSamples = -1;
|
|
90
|
+
let fmt = null;
|
|
91
|
+
for (let p = 12; p < end;) {
|
|
92
|
+
if (p + 8 > end)
|
|
93
|
+
throw new InvalidArgumentError('Truncated WAVE chunk header.');
|
|
94
|
+
const size = u32(data, p + 4);
|
|
95
|
+
const next = p + 8 + size + (size & 1);
|
|
96
|
+
if (next > end)
|
|
97
|
+
throw new InvalidArgumentError('Truncated WAVE chunk.');
|
|
98
|
+
const body = data.subarray(p + 8, p + 8 + size);
|
|
99
|
+
if (equalBytes(data, p, FMT)) {
|
|
100
|
+
if (fmt !== null || size < 16)
|
|
101
|
+
throw new InvalidArgumentError('Invalid WAVE format chunk.');
|
|
102
|
+
fmt = body;
|
|
103
|
+
tag = u16(body, 0);
|
|
104
|
+
if (!PLAYABLE.has(tag))
|
|
105
|
+
throw new NotSupportedError(`WAVE codec ${tag} is preserved but not decoded.`);
|
|
106
|
+
channels = u16(body, 2);
|
|
107
|
+
const rawRate = u32(body, 4), rawByteRate = u32(body, 8);
|
|
108
|
+
if (rawRate > 192000 || rawByteRate > 768000)
|
|
109
|
+
throw new InvalidArgumentError('Sample/byte rate exceeds policy.');
|
|
110
|
+
rate = rawRate;
|
|
111
|
+
byteRate = rawByteRate;
|
|
112
|
+
align = u16(body, 12);
|
|
113
|
+
bits = u16(body, 14);
|
|
114
|
+
}
|
|
115
|
+
else if (equalBytes(data, p, DATA)) {
|
|
116
|
+
if (length >= 0)
|
|
117
|
+
throw new InvalidArgumentError('Duplicate WAVE data.');
|
|
118
|
+
length = size;
|
|
119
|
+
dataStart = p + 8;
|
|
120
|
+
}
|
|
121
|
+
else if (equalBytes(data, p, FACT) && size >= 4) {
|
|
122
|
+
factSamples = u32(body, 0);
|
|
123
|
+
}
|
|
124
|
+
p = next;
|
|
125
|
+
}
|
|
126
|
+
if (fmt === null)
|
|
127
|
+
throw new InvalidArgumentError('Missing WAVE format chunk.');
|
|
128
|
+
if (tag === WaveCodec.pcm) {
|
|
129
|
+
if (channels < 1 || channels > 2 || rate < 8000 || rate > 192000 || (bits !== 8 && bits !== 16) || align !== channels * (bits / 8) ||
|
|
130
|
+
byteRate !== rate * align || length <= 0 || length % align !== 0)
|
|
131
|
+
throw new InvalidArgumentError('Unsupported or malformed PCM format/data.');
|
|
132
|
+
const duration = (length * 1000) / byteRate;
|
|
133
|
+
if (duration > MAX_SOUND_MS)
|
|
134
|
+
throw new NotSupportedError('Sound exceeds 60 second policy.');
|
|
135
|
+
return new WaveAudio(tag, channels, rate, bits, duration, 'pcm', data.subarray(dataStart, dataStart + length), null, null, end);
|
|
136
|
+
}
|
|
137
|
+
if (tag === WaveCodec.aLaw || tag === WaveCodec.muLaw || tag === WaveCodec.ieeeFloat) {
|
|
138
|
+
const g711 = tag !== WaveCodec.ieeeFloat;
|
|
139
|
+
if (channels < 1 || channels > 2 || rate < 4000 || rate > 192000 || (g711 ? bits !== 8 : bits !== 32 && bits !== 64) ||
|
|
140
|
+
align !== channels * (bits / 8) || byteRate !== rate * align || length <= 0)
|
|
141
|
+
throw new InvalidArgumentError('Unsupported or malformed sample format/data.');
|
|
142
|
+
let count = Math.floor(length / align);
|
|
143
|
+
if (count <= 0)
|
|
144
|
+
throw new InvalidArgumentError('Sound has no complete sample frame.');
|
|
145
|
+
if (factSamples > 0 && factSamples < count)
|
|
146
|
+
count = factSamples;
|
|
147
|
+
const duration = (count * 1000) / rate;
|
|
148
|
+
if (duration > MAX_SOUND_MS)
|
|
149
|
+
throw new NotSupportedError('Sound exceeds 60 second policy.');
|
|
150
|
+
const samples = decodeSampleCodec(tag, bits, data.subarray(dataStart, dataStart + count * align));
|
|
151
|
+
return new WaveAudio(tag, channels, rate, 16, duration, 'pcm', null, samples, null, 44 + samples.length * 2);
|
|
152
|
+
}
|
|
153
|
+
if (tag === WaveCodec.mpegLayer3) {
|
|
154
|
+
if (channels < 1 || channels > 2 || length <= 0)
|
|
155
|
+
throw new InvalidArgumentError('Malformed MPEG Layer-3 format/data.');
|
|
156
|
+
const stream = data.subarray(dataStart, dataStart + length);
|
|
157
|
+
const walk = readMpegFrames(stream, Math.floor((MAX_SOUND_MS * 48000) / 1000 / 576) + 1);
|
|
158
|
+
if (walk.sampleRate !== rate || walk.channels !== channels)
|
|
159
|
+
throw new InvalidArgumentError('MPEG Layer-3 frames disagree with the format chunk.');
|
|
160
|
+
const duration = (walk.samples * 1000) / walk.sampleRate;
|
|
161
|
+
if (duration > MAX_SOUND_MS)
|
|
162
|
+
throw new NotSupportedError('Sound exceeds 60 second policy.');
|
|
163
|
+
return new WaveAudio(tag, channels, rate, 0, duration, 'mpeg-layer3', null, null, stream, stream.length);
|
|
164
|
+
}
|
|
165
|
+
const format = readAdpcmFormat(tag, fmt);
|
|
166
|
+
if (length <= 0)
|
|
167
|
+
throw new InvalidArgumentError('ADPCM sound has no data chunk.');
|
|
168
|
+
let samples = decodeAdpcm(format, data.subarray(dataStart, dataStart + length), Math.trunc((format.sampleRate * MAX_SOUND_MS) / 1000));
|
|
169
|
+
let frames = Math.floor(samples.length / format.channels);
|
|
170
|
+
if (factSamples > 0 && factSamples < frames)
|
|
171
|
+
frames = factSamples;
|
|
172
|
+
if (frames <= 0)
|
|
173
|
+
throw new InvalidArgumentError('ADPCM sound decodes to no samples.');
|
|
174
|
+
samples = samples.subarray(0, frames * format.channels);
|
|
175
|
+
return new WaveAudio(tag, format.channels, format.sampleRate, 16, (frames * 1000) / format.sampleRate, 'pcm', null, samples, null, 44 + samples.length * 2);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
/** A canonical 44-byte-header 16-bit PCM RIFF/WAVE file. */
|
|
179
|
+
export function pcm16Wave(samples, channels, rate) {
|
|
180
|
+
const dataBytes = samples.length * 2;
|
|
181
|
+
const s = new Uint8Array(44 + dataBytes);
|
|
182
|
+
s.set(RIFF, 0);
|
|
183
|
+
writeU32(s, 4, 36 + dataBytes);
|
|
184
|
+
s.set([...WAVE, ...FMT], 8);
|
|
185
|
+
writeU32(s, 16, 16);
|
|
186
|
+
writeU16(s, 20, 1);
|
|
187
|
+
writeU16(s, 22, channels);
|
|
188
|
+
writeU32(s, 24, rate);
|
|
189
|
+
writeU32(s, 28, rate * channels * 2);
|
|
190
|
+
writeU16(s, 32, channels * 2);
|
|
191
|
+
writeU16(s, 34, 16);
|
|
192
|
+
s.set(DATA, 36);
|
|
193
|
+
writeU32(s, 40, dataBytes);
|
|
194
|
+
for (let i = 0; i < samples.length; i++)
|
|
195
|
+
writeU16(s, 44 + i * 2, samples[i] & 0xffff);
|
|
196
|
+
return s;
|
|
197
|
+
}
|
|
198
|
+
// ---------------------------------------------------------------- G.711 and IEEE float (ACS.md §9.4)
|
|
199
|
+
/** One µ-law code to 16-bit PCM. */
|
|
200
|
+
export function muLawToPcm(code) {
|
|
201
|
+
const u = ~code & 0xff;
|
|
202
|
+
const magnitude = (((u & 0x0f) << 3) + 0x84) << ((u & 0x70) >> 4);
|
|
203
|
+
return (u & 0x80) !== 0 ? 0x84 - magnitude : magnitude - 0x84;
|
|
204
|
+
}
|
|
205
|
+
/** One A-law code to 16-bit PCM. */
|
|
206
|
+
export function aLawToPcm(code) {
|
|
207
|
+
const a = code ^ 0x55;
|
|
208
|
+
let magnitude = (a & 0x0f) << 4;
|
|
209
|
+
const segment = (a & 0x70) >> 4;
|
|
210
|
+
magnitude = segment === 0 ? magnitude + 8 : segment === 1 ? magnitude + 0x108 : (magnitude + 0x108) << (segment - 1);
|
|
211
|
+
return (a & 0x80) !== 0 ? magnitude : -magnitude;
|
|
212
|
+
}
|
|
213
|
+
/** One float sample to 16-bit PCM: x × 32768 rounded half to even, clipped; NaN → 0. */
|
|
214
|
+
export function floatToPcm(sample) {
|
|
215
|
+
if (Number.isNaN(sample))
|
|
216
|
+
return 0;
|
|
217
|
+
const v = sample * 32768;
|
|
218
|
+
if (!Number.isFinite(v))
|
|
219
|
+
return v > 0 ? 32767 : -32768;
|
|
220
|
+
const floor = Math.floor(v), diff = v - floor;
|
|
221
|
+
const rounded = diff > 0.5 ? floor + 1 : diff < 0.5 ? floor : floor % 2 === 0 ? floor : floor + 1;
|
|
222
|
+
return Math.min(32767, Math.max(-32768, rounded));
|
|
223
|
+
}
|
|
224
|
+
function decodeSampleCodec(tag, bits, data) {
|
|
225
|
+
if (tag === WaveCodec.muLaw || tag === WaveCodec.aLaw) {
|
|
226
|
+
const out = new Int16Array(data.length), f = tag === WaveCodec.muLaw ? muLawToPcm : aLawToPcm;
|
|
227
|
+
for (let i = 0; i < data.length; i++)
|
|
228
|
+
out[i] = f(data[i]);
|
|
229
|
+
return out;
|
|
230
|
+
}
|
|
231
|
+
const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
|
|
232
|
+
const size = bits / 8, out = new Int16Array(Math.floor(data.length / size));
|
|
233
|
+
for (let i = 0; i < out.length; i++)
|
|
234
|
+
out[i] = floatToPcm(size === 4 ? view.getFloat32(i * 4, true) : view.getFloat64(i * 8, true));
|
|
235
|
+
return out;
|
|
236
|
+
}
|
|
237
|
+
// ---------------------------------------------------------------- ADPCM (ACS.md §9.2, §9.3)
|
|
238
|
+
const MS_ADAPTATION = [230, 230, 230, 230, 307, 409, 512, 614, 768, 614, 512, 409, 307, 230, 230, 230];
|
|
239
|
+
const MS_STANDARD = [[256, 0], [512, -256], [0, 0], [192, 64], [240, 0], [460, -208], [392, -232]];
|
|
240
|
+
const IMA_INDEX = [-1, -1, -1, -1, 2, 4, 6, 8, -1, -1, -1, -1, 2, 4, 6, 8];
|
|
241
|
+
const IMA_STEP = [7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, 50, 55, 60, 66, 73, 80, 88, 97, 107, 118, 130, 143,
|
|
242
|
+
157, 173, 190, 209, 230, 253, 279, 307, 337, 371, 408, 449, 494, 544, 598, 658, 724, 796, 876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878,
|
|
243
|
+
2066, 2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358, 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899, 15289,
|
|
244
|
+
16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767];
|
|
245
|
+
function readAdpcmFormat(tag, fmt) {
|
|
246
|
+
if (fmt.length < 20)
|
|
247
|
+
throw new InvalidArgumentError('ADPCM format chunk lacks the cbSize/wSamplesPerBlock extension.');
|
|
248
|
+
const channels = u16(fmt, 2), rate = u32(fmt, 4), align = u16(fmt, 12), bits = u16(fmt, 14), extra = u16(fmt, 16);
|
|
249
|
+
if (channels < 1 || channels > 2 || rate < 4000 || rate > 96000 || bits !== 4)
|
|
250
|
+
throw new InvalidArgumentError('ADPCM requires 4-bit mono/stereo at 4..96 kHz.');
|
|
251
|
+
if (18 + extra > fmt.length || extra < 2)
|
|
252
|
+
throw new InvalidArgumentError('ADPCM cbSize exceeds its format chunk.');
|
|
253
|
+
const perBlock = u16(fmt, 18);
|
|
254
|
+
if (tag === WaveCodec.msAdpcm) {
|
|
255
|
+
if (extra < 4)
|
|
256
|
+
throw new InvalidArgumentError('Microsoft ADPCM requires wNumCoef.');
|
|
257
|
+
const count = u16(fmt, 20);
|
|
258
|
+
if (count < 7 || count > 256 || extra < 4 + count * 4)
|
|
259
|
+
throw new InvalidArgumentError('Microsoft ADPCM coefficient table is missing or truncated.');
|
|
260
|
+
const coefficients = [];
|
|
261
|
+
for (let i = 0; i < count; i++)
|
|
262
|
+
coefficients.push([i16(fmt, 22 + i * 4), i16(fmt, 24 + i * 4)]);
|
|
263
|
+
for (let i = 0; i < 7; i++)
|
|
264
|
+
if (coefficients[i][0] !== MS_STANDARD[i][0] || coefficients[i][1] !== MS_STANDARD[i][1])
|
|
265
|
+
throw new NotSupportedError('Microsoft ADPCM with nonstandard predictor coefficients is preserved but not decoded.');
|
|
266
|
+
const header = 7 * channels;
|
|
267
|
+
if (align <= header || perBlock !== 2 + Math.trunc(((align - header) * 2) / channels))
|
|
268
|
+
throw new InvalidArgumentError('Microsoft ADPCM block alignment and samples-per-block disagree.');
|
|
269
|
+
return { tag, channels, sampleRate: rate, blockAlign: align, samplesPerBlock: perBlock, coefficients };
|
|
270
|
+
}
|
|
271
|
+
const header = 4 * channels;
|
|
272
|
+
if (align <= header || (align - header) % (4 * channels) !== 0 || perBlock !== 1 + Math.trunc(((align - header) * 2) / channels))
|
|
273
|
+
throw new InvalidArgumentError('IMA ADPCM block alignment and samples-per-block disagree.');
|
|
274
|
+
return { tag, channels, sampleRate: rate, blockAlign: align, samplesPerBlock: perBlock, coefficients: [] };
|
|
275
|
+
}
|
|
276
|
+
function adpcmHeaderBytes(f) {
|
|
277
|
+
return f.tag === WaveCodec.msAdpcm ? 7 * f.channels : 4 * f.channels;
|
|
278
|
+
}
|
|
279
|
+
function decodeAdpcm(format, data, maxSamplesPerChannel) {
|
|
280
|
+
const blocks = Math.floor(data.length / format.blockAlign), rest = data.length % format.blockAlign;
|
|
281
|
+
const header = adpcmHeaderBytes(format);
|
|
282
|
+
const partial = rest > 0 && rest >= header && format.tag === WaveCodec.msAdpcm ? 2 + Math.trunc(((rest - header) * 2) / format.channels) : 0;
|
|
283
|
+
const frames = blocks * format.samplesPerBlock + partial;
|
|
284
|
+
if (frames <= 0)
|
|
285
|
+
throw new InvalidArgumentError('ADPCM data chunk contains no complete block header.');
|
|
286
|
+
if (frames > maxSamplesPerChannel)
|
|
287
|
+
throw new NotSupportedError('Decoded ADPCM exceeds the sound duration policy.');
|
|
288
|
+
const output = new Int16Array(frames * format.channels);
|
|
289
|
+
let written = 0;
|
|
290
|
+
for (let offset = 0; offset < data.length; offset += format.blockAlign) {
|
|
291
|
+
const block = data.subarray(offset, offset + Math.min(format.blockAlign, data.length - offset));
|
|
292
|
+
if (block.length < header || (format.tag === WaveCodec.imaAdpcm && block.length < format.blockAlign))
|
|
293
|
+
break;
|
|
294
|
+
written += format.tag === WaveCodec.msAdpcm ? decodeMsBlock(format, block, output, written) : decodeImaBlock(format, block, output, written);
|
|
295
|
+
}
|
|
296
|
+
return written === output.length ? output : output.subarray(0, written);
|
|
297
|
+
}
|
|
298
|
+
const clamp16 = (v) => (v < -32768 ? -32768 : v > 32767 ? 32767 : v);
|
|
299
|
+
function decodeMsBlock(f, block, output, at) {
|
|
300
|
+
const ch = f.channels, predictor = [0, 0], delta = [0, 0], s1 = [0, 0], s2 = [0, 0];
|
|
301
|
+
let p = 0;
|
|
302
|
+
for (let c = 0; c < ch; c++) {
|
|
303
|
+
predictor[c] = block[p++];
|
|
304
|
+
if (predictor[c] >= f.coefficients.length)
|
|
305
|
+
throw new InvalidArgumentError('Microsoft ADPCM block predictor is outside the coefficient table.');
|
|
306
|
+
}
|
|
307
|
+
for (let c = 0; c < ch; c++) {
|
|
308
|
+
delta[c] = i16(block, p);
|
|
309
|
+
p += 2;
|
|
310
|
+
}
|
|
311
|
+
for (let c = 0; c < ch; c++) {
|
|
312
|
+
s1[c] = i16(block, p);
|
|
313
|
+
p += 2;
|
|
314
|
+
}
|
|
315
|
+
for (let c = 0; c < ch; c++) {
|
|
316
|
+
s2[c] = i16(block, p);
|
|
317
|
+
p += 2;
|
|
318
|
+
}
|
|
319
|
+
let o = at;
|
|
320
|
+
for (let c = 0; c < ch; c++)
|
|
321
|
+
output[o++] = s2[c];
|
|
322
|
+
for (let c = 0; c < ch; c++)
|
|
323
|
+
output[o++] = s1[c];
|
|
324
|
+
let channel = 0;
|
|
325
|
+
for (; p < block.length; p++) {
|
|
326
|
+
for (let half = 0; half < 2; half++) {
|
|
327
|
+
const nibble = half === 0 ? block[p] >> 4 : block[p] & 15;
|
|
328
|
+
const signed = nibble >= 8 ? nibble - 16 : nibble;
|
|
329
|
+
const [c1, c2] = f.coefficients[predictor[channel]];
|
|
330
|
+
const prediction = (s1[channel] * c1 + s2[channel] * c2) >> 8;
|
|
331
|
+
const sample = clamp16(prediction + signed * delta[channel]);
|
|
332
|
+
s2[channel] = s1[channel];
|
|
333
|
+
s1[channel] = sample;
|
|
334
|
+
delta[channel] = Math.max(16, Math.trunc((MS_ADAPTATION[nibble] * delta[channel]) / 256));
|
|
335
|
+
output[o++] = sample;
|
|
336
|
+
channel = (channel + 1) % ch;
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
return o - at;
|
|
340
|
+
}
|
|
341
|
+
function decodeImaBlock(f, block, output, at) {
|
|
342
|
+
const ch = f.channels, predictor = [0, 0], index = [0, 0];
|
|
343
|
+
for (let c = 0; c < ch; c++) {
|
|
344
|
+
predictor[c] = i16(block, c * 4);
|
|
345
|
+
index[c] = block[c * 4 + 2];
|
|
346
|
+
if (index[c] > 88 || block[c * 4 + 3] !== 0)
|
|
347
|
+
throw new InvalidArgumentError('IMA ADPCM block header has an invalid step index or reserved byte.');
|
|
348
|
+
output[at + c] = predictor[c];
|
|
349
|
+
}
|
|
350
|
+
const o = at + ch, groups = Math.floor((block.length - 4 * ch) / (4 * ch));
|
|
351
|
+
for (let g = 0; g < groups; g++) {
|
|
352
|
+
for (let c = 0; c < ch; c++) {
|
|
353
|
+
const base = 4 * ch + (g * ch + c) * 4;
|
|
354
|
+
for (let n = 0; n < 8; n++) {
|
|
355
|
+
const byte = block[base + (n >> 1)];
|
|
356
|
+
const nibble = (n & 1) === 0 ? byte & 15 : byte >> 4;
|
|
357
|
+
const step = IMA_STEP[index[c]];
|
|
358
|
+
let diff = step >> 3;
|
|
359
|
+
if ((nibble & 4) !== 0)
|
|
360
|
+
diff += step;
|
|
361
|
+
if ((nibble & 2) !== 0)
|
|
362
|
+
diff += step >> 1;
|
|
363
|
+
if ((nibble & 1) !== 0)
|
|
364
|
+
diff += step >> 2;
|
|
365
|
+
predictor[c] = clamp16((nibble & 8) !== 0 ? predictor[c] - diff : predictor[c] + diff);
|
|
366
|
+
index[c] = Math.min(88, Math.max(0, index[c] + IMA_INDEX[nibble]));
|
|
367
|
+
output[o + (g * 8 + n) * ch + c] = predictor[c];
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
return ch + groups * 8 * ch;
|
|
372
|
+
}
|
|
373
|
+
// ---------------------------------------------------------------- MPEG Layer-3 frame headers (no decoding)
|
|
374
|
+
const MPEG1_RATES = [0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 0];
|
|
375
|
+
const MPEG2_RATES = [0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, 0];
|
|
376
|
+
const MAX_JUNK_BYTES = 4096;
|
|
377
|
+
function mpegHeader(data, at) {
|
|
378
|
+
if (data.length - at < 4)
|
|
379
|
+
return null;
|
|
380
|
+
const h = ((data[at] << 24) | (data[at + 1] << 16) | (data[at + 2] << 8) | data[at + 3]) >>> 0;
|
|
381
|
+
if (((h >>> 21) & 0x7ff) !== 0x7ff)
|
|
382
|
+
return null;
|
|
383
|
+
const versionBits = (h >>> 19) & 3, layer = (h >>> 17) & 3, rateIndex = (h >>> 12) & 15, sampleIndex = (h >>> 10) & 3;
|
|
384
|
+
const padding = (h >>> 9) & 1, mode = (h >>> 6) & 3;
|
|
385
|
+
if (versionBits === 1 || layer !== 1 || rateIndex === 0 || rateIndex === 15 || sampleIndex === 3)
|
|
386
|
+
return null;
|
|
387
|
+
const version = versionBits === 3 ? 1 : versionBits === 2 ? 2 : 25;
|
|
388
|
+
const base = sampleIndex === 0 ? 44100 : sampleIndex === 1 ? 48000 : 32000;
|
|
389
|
+
const sampleRate = version === 1 ? base : version === 2 ? base / 2 : base / 4;
|
|
390
|
+
const kbps = version === 1 ? MPEG1_RATES[rateIndex] : MPEG2_RATES[rateIndex];
|
|
391
|
+
const samplesPerFrame = version === 1 ? 1152 : 576;
|
|
392
|
+
const length = Math.trunc(((samplesPerFrame / 8) * kbps * 1000) / sampleRate) + padding;
|
|
393
|
+
return { version, sampleRate, channels: mode === 3 ? 1 : 2, length, samplesPerFrame };
|
|
394
|
+
}
|
|
395
|
+
function readMpegFrames(data, maxFrames) {
|
|
396
|
+
let p = 0, junk = 0, frames = 0, first = -1, samples = 0;
|
|
397
|
+
let reference = null;
|
|
398
|
+
while (p < data.length) {
|
|
399
|
+
const h = mpegHeader(data, p);
|
|
400
|
+
if (h && (reference === null || (h.version === reference.version && h.sampleRate === reference.sampleRate && h.channels === reference.channels))) {
|
|
401
|
+
if (p + h.length > data.length)
|
|
402
|
+
break;
|
|
403
|
+
if (first < 0)
|
|
404
|
+
first = p;
|
|
405
|
+
reference ??= h;
|
|
406
|
+
frames++;
|
|
407
|
+
samples += h.samplesPerFrame;
|
|
408
|
+
if (frames > maxFrames)
|
|
409
|
+
throw new NotSupportedError('MPEG audio exceeds the sound duration policy.');
|
|
410
|
+
p += h.length;
|
|
411
|
+
continue;
|
|
412
|
+
}
|
|
413
|
+
if (data.length - p < 4 && first >= 0)
|
|
414
|
+
break;
|
|
415
|
+
if (++junk > MAX_JUNK_BYTES)
|
|
416
|
+
throw new InvalidArgumentError('No MPEG Layer III frame sequence in the data chunk.');
|
|
417
|
+
p++;
|
|
418
|
+
}
|
|
419
|
+
if (reference === null || frames === 0)
|
|
420
|
+
throw new InvalidArgumentError('MPEG Layer III data chunk contains no complete frame.');
|
|
421
|
+
return { sampleRate: reference.sampleRate, channels: reference.channels, samples };
|
|
422
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { Clock } from '../core/clock.js';
|
|
2
|
+
/**
|
|
3
|
+
* The browser clock adapter: monotonic time from `performance.now()` (milliseconds since the clock was created) and presentation
|
|
4
|
+
* callbacks on `requestAnimationFrame`. Logical time follows real time, not the display refresh: when frames are throttled (a background
|
|
5
|
+
* tab) the next frame catches up. The animation-frame loop runs only while at least one frame listener is registered.
|
|
6
|
+
*/
|
|
7
|
+
export declare class AnimationFrameClock implements Clock {
|
|
8
|
+
private readonly origin;
|
|
9
|
+
private last;
|
|
10
|
+
private readonly listeners;
|
|
11
|
+
private request;
|
|
12
|
+
private readonly frame;
|
|
13
|
+
get nowMs(): number;
|
|
14
|
+
/** True while the animation-frame loop runs. */
|
|
15
|
+
get running(): boolean;
|
|
16
|
+
/** Calls `listener` once per animation frame with the clock time. Returns the unsubscribe function. */
|
|
17
|
+
onFrame(listener: (nowMs: number) => void): () => void;
|
|
18
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The browser clock adapter: monotonic time from `performance.now()` (milliseconds since the clock was created) and presentation
|
|
3
|
+
* callbacks on `requestAnimationFrame`. Logical time follows real time, not the display refresh: when frames are throttled (a background
|
|
4
|
+
* tab) the next frame catches up. The animation-frame loop runs only while at least one frame listener is registered.
|
|
5
|
+
*/
|
|
6
|
+
export class AnimationFrameClock {
|
|
7
|
+
origin = performance.now();
|
|
8
|
+
last = 0;
|
|
9
|
+
listeners = new Set();
|
|
10
|
+
request = null;
|
|
11
|
+
frame = () => {
|
|
12
|
+
this.request = null;
|
|
13
|
+
const now = this.nowMs;
|
|
14
|
+
for (const listener of [...this.listeners])
|
|
15
|
+
listener(now);
|
|
16
|
+
if (this.listeners.size > 0)
|
|
17
|
+
this.request = requestAnimationFrame(this.frame);
|
|
18
|
+
};
|
|
19
|
+
get nowMs() {
|
|
20
|
+
const t = performance.now() - this.origin;
|
|
21
|
+
if (t > this.last)
|
|
22
|
+
this.last = t;
|
|
23
|
+
return this.last;
|
|
24
|
+
}
|
|
25
|
+
/** True while the animation-frame loop runs. */
|
|
26
|
+
get running() {
|
|
27
|
+
return this.request !== null;
|
|
28
|
+
}
|
|
29
|
+
/** Calls `listener` once per animation frame with the clock time. Returns the unsubscribe function. */
|
|
30
|
+
onFrame(listener) {
|
|
31
|
+
this.listeners.add(listener);
|
|
32
|
+
if (this.request === null)
|
|
33
|
+
this.request = requestAnimationFrame(this.frame);
|
|
34
|
+
return () => {
|
|
35
|
+
this.listeners.delete(listener);
|
|
36
|
+
if (this.listeners.size === 0 && this.request !== null) {
|
|
37
|
+
cancelAnimationFrame(this.request);
|
|
38
|
+
this.request = null;
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import type { CharacterAgent } from '../core/agent.js';
|
|
2
|
+
/** Options of a {@link CanvasRenderer}. */
|
|
3
|
+
export interface CanvasRendererOptions {
|
|
4
|
+
/** Device pixels per CSS pixel (default `devicePixelRatio`). */
|
|
5
|
+
readonly pixelRatio?: number;
|
|
6
|
+
/** Smooth scaling (default false: characters are pixel art and scale with nearest-neighbour sampling). */
|
|
7
|
+
readonly smoothing?: boolean;
|
|
8
|
+
/** Bytes of prepared frame bitmaps kept (default 32 MiB). */
|
|
9
|
+
readonly frameCacheBytes?: number;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Draws an agent's presented frame into a canvas with the Canvas 2D API. The canvas shows the character at its scale (CSS pixels) with a
|
|
13
|
+
* backing store of `pixelRatio` device pixels per CSS pixel, preserving transparency. Composed frames are prepared once per pixel content
|
|
14
|
+
* and kept in a bounded cache; the canvas is redrawn only when the frame, scale, size or pixel ratio changes. Position is the host's
|
|
15
|
+
* concern (the canvas is moved, not redrawn).
|
|
16
|
+
*/
|
|
17
|
+
export declare class CanvasRenderer {
|
|
18
|
+
readonly agent: CharacterAgent;
|
|
19
|
+
readonly canvas: HTMLCanvasElement;
|
|
20
|
+
private readonly options;
|
|
21
|
+
private readonly context;
|
|
22
|
+
private readonly cache;
|
|
23
|
+
private cacheBytes;
|
|
24
|
+
private readonly cacheBudget;
|
|
25
|
+
private shown;
|
|
26
|
+
private disposed;
|
|
27
|
+
private redraws;
|
|
28
|
+
private uploads;
|
|
29
|
+
/** The last presentation problem (a frame that cannot be composed), or null. */
|
|
30
|
+
problem: string | null;
|
|
31
|
+
constructor(agent: CharacterAgent, canvas: HTMLCanvasElement, options?: CanvasRendererOptions);
|
|
32
|
+
/** Canvas redraws and frame uploads so far (diagnostics: unchanged frames are neither redrawn nor uploaded). */
|
|
33
|
+
get statistics(): {
|
|
34
|
+
redraws: number;
|
|
35
|
+
uploads: number;
|
|
36
|
+
cachedFrames: number;
|
|
37
|
+
cachedBytes: number;
|
|
38
|
+
};
|
|
39
|
+
private get pixelRatio();
|
|
40
|
+
/** Brings the canvas up to date. Returns true when it was redrawn. */
|
|
41
|
+
render(): boolean;
|
|
42
|
+
/** The prepared bitmap of the current frame (composed through the agent's bounded resources). */
|
|
43
|
+
private surface;
|
|
44
|
+
/** True when the pixel at (x, y) in CSS pixels of the canvas is opaque in the presented frame. */
|
|
45
|
+
hitTest(x: number, y: number): boolean;
|
|
46
|
+
/** Forgets the presented state so that the next {@link render} redraws. */
|
|
47
|
+
invalidate(): void;
|
|
48
|
+
/** Releases the prepared bitmaps and clears the canvas. */
|
|
49
|
+
dispose(): void;
|
|
50
|
+
}
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
function createSurface(width, height) {
|
|
2
|
+
if (typeof OffscreenCanvas === 'function')
|
|
3
|
+
return new OffscreenCanvas(width, height);
|
|
4
|
+
const canvas = document.createElement('canvas');
|
|
5
|
+
canvas.width = width;
|
|
6
|
+
canvas.height = height;
|
|
7
|
+
return canvas;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Draws an agent's presented frame into a canvas with the Canvas 2D API. The canvas shows the character at its scale (CSS pixels) with a
|
|
11
|
+
* backing store of `pixelRatio` device pixels per CSS pixel, preserving transparency. Composed frames are prepared once per pixel content
|
|
12
|
+
* and kept in a bounded cache; the canvas is redrawn only when the frame, scale, size or pixel ratio changes. Position is the host's
|
|
13
|
+
* concern (the canvas is moved, not redrawn).
|
|
14
|
+
*/
|
|
15
|
+
export class CanvasRenderer {
|
|
16
|
+
agent;
|
|
17
|
+
canvas;
|
|
18
|
+
options;
|
|
19
|
+
context;
|
|
20
|
+
cache = new Map(); // insertion order = least recently used first
|
|
21
|
+
cacheBytes = 0;
|
|
22
|
+
cacheBudget;
|
|
23
|
+
shown = null;
|
|
24
|
+
disposed = false;
|
|
25
|
+
redraws = 0;
|
|
26
|
+
uploads = 0;
|
|
27
|
+
/** The last presentation problem (a frame that cannot be composed), or null. */
|
|
28
|
+
problem = null;
|
|
29
|
+
constructor(agent, canvas, options = {}) {
|
|
30
|
+
this.agent = agent;
|
|
31
|
+
this.canvas = canvas;
|
|
32
|
+
this.options = options;
|
|
33
|
+
const context = canvas.getContext('2d');
|
|
34
|
+
if (!context)
|
|
35
|
+
throw new Error('Canvas 2D is not available.');
|
|
36
|
+
this.context = context;
|
|
37
|
+
this.cacheBudget = options.frameCacheBytes ?? 32 * 1024 * 1024;
|
|
38
|
+
}
|
|
39
|
+
/** Canvas redraws and frame uploads so far (diagnostics: unchanged frames are neither redrawn nor uploaded). */
|
|
40
|
+
get statistics() {
|
|
41
|
+
return { redraws: this.redraws, uploads: this.uploads, cachedFrames: this.cache.size, cachedBytes: this.cacheBytes };
|
|
42
|
+
}
|
|
43
|
+
get pixelRatio() {
|
|
44
|
+
return this.options.pixelRatio ?? (typeof devicePixelRatio === 'number' && devicePixelRatio > 0 ? devicePixelRatio : 1);
|
|
45
|
+
}
|
|
46
|
+
/** Brings the canvas up to date. Returns true when it was redrawn. */
|
|
47
|
+
render() {
|
|
48
|
+
if (this.disposed)
|
|
49
|
+
return false;
|
|
50
|
+
const frame = this.agent.currentFrame;
|
|
51
|
+
const ratio = this.pixelRatio;
|
|
52
|
+
const cssWidth = frame.width * frame.scale, cssHeight = frame.height * frame.scale;
|
|
53
|
+
const width = Math.max(1, Math.round(cssWidth * ratio)), height = Math.max(1, Math.round(cssHeight * ratio));
|
|
54
|
+
const content = frame.hasImage ? this.agent.resources.frameKey(frame.animation, frame.frame, frame.mouth) : '';
|
|
55
|
+
const key = `${content}#${width}x${height}`;
|
|
56
|
+
if (key === this.shown)
|
|
57
|
+
return false;
|
|
58
|
+
if (this.canvas.width !== width || this.canvas.height !== height) {
|
|
59
|
+
this.canvas.width = width;
|
|
60
|
+
this.canvas.height = height;
|
|
61
|
+
}
|
|
62
|
+
this.canvas.style.width = `${cssWidth}px`;
|
|
63
|
+
this.canvas.style.height = `${cssHeight}px`;
|
|
64
|
+
const ctx = this.context;
|
|
65
|
+
ctx.setTransform(1, 0, 0, 1, 0, 0);
|
|
66
|
+
ctx.clearRect(0, 0, width, height);
|
|
67
|
+
this.shown = key;
|
|
68
|
+
this.redraws++;
|
|
69
|
+
if (!frame.hasImage) {
|
|
70
|
+
this.problem = null;
|
|
71
|
+
return true;
|
|
72
|
+
}
|
|
73
|
+
let surface;
|
|
74
|
+
try {
|
|
75
|
+
surface = this.surface(content);
|
|
76
|
+
this.problem = null;
|
|
77
|
+
}
|
|
78
|
+
catch (e) {
|
|
79
|
+
this.problem = e.message;
|
|
80
|
+
return true;
|
|
81
|
+
}
|
|
82
|
+
ctx.imageSmoothingEnabled = this.options.smoothing ?? false;
|
|
83
|
+
ctx.drawImage(surface, 0, 0, width, height);
|
|
84
|
+
return true;
|
|
85
|
+
}
|
|
86
|
+
/** The prepared bitmap of the current frame (composed through the agent's bounded resources). */
|
|
87
|
+
surface(content) {
|
|
88
|
+
const hit = this.cache.get(content);
|
|
89
|
+
if (hit) {
|
|
90
|
+
this.cache.delete(content);
|
|
91
|
+
this.cache.set(content, hit);
|
|
92
|
+
return hit;
|
|
93
|
+
}
|
|
94
|
+
const bitmap = this.agent.composeFrame();
|
|
95
|
+
if (!bitmap)
|
|
96
|
+
throw new Error('Nothing to compose.');
|
|
97
|
+
const surface = createSurface(bitmap.width, bitmap.height);
|
|
98
|
+
const ctx = surface.getContext('2d');
|
|
99
|
+
if (!ctx)
|
|
100
|
+
throw new Error('Canvas 2D is not available.');
|
|
101
|
+
ctx.putImageData(new ImageData(new Uint8ClampedArray(bitmap.pixels), bitmap.width, bitmap.height), 0, 0);
|
|
102
|
+
this.uploads++;
|
|
103
|
+
const cost = bitmap.width * bitmap.height * 4;
|
|
104
|
+
if (cost <= this.cacheBudget) {
|
|
105
|
+
this.cache.set(content, surface);
|
|
106
|
+
this.cacheBytes += cost;
|
|
107
|
+
for (const [k, s] of this.cache) {
|
|
108
|
+
if (this.cacheBytes <= this.cacheBudget)
|
|
109
|
+
break;
|
|
110
|
+
this.cache.delete(k);
|
|
111
|
+
this.cacheBytes -= s.width * s.height * 4;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
return surface;
|
|
115
|
+
}
|
|
116
|
+
/** True when the pixel at (x, y) in CSS pixels of the canvas is opaque in the presented frame. */
|
|
117
|
+
hitTest(x, y) {
|
|
118
|
+
const frame = this.agent.currentFrame;
|
|
119
|
+
if (!frame.hasImage)
|
|
120
|
+
return false;
|
|
121
|
+
const px = Math.floor(x / frame.scale), py = Math.floor(y / frame.scale);
|
|
122
|
+
if (px < 0 || py < 0 || px >= frame.width || py >= frame.height)
|
|
123
|
+
return false;
|
|
124
|
+
try {
|
|
125
|
+
const bitmap = this.agent.composeFrame();
|
|
126
|
+
return !!bitmap && bitmap.pixels[(py * bitmap.width + px) * 4 + 3] > 0;
|
|
127
|
+
}
|
|
128
|
+
catch {
|
|
129
|
+
return false;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
/** Forgets the presented state so that the next {@link render} redraws. */
|
|
133
|
+
invalidate() {
|
|
134
|
+
this.shown = null;
|
|
135
|
+
}
|
|
136
|
+
/** Releases the prepared bitmaps and clears the canvas. */
|
|
137
|
+
dispose() {
|
|
138
|
+
if (this.disposed)
|
|
139
|
+
return;
|
|
140
|
+
this.disposed = true;
|
|
141
|
+
this.cache.clear();
|
|
142
|
+
this.cacheBytes = 0;
|
|
143
|
+
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
|
|
144
|
+
}
|
|
145
|
+
}
|