@onjmin/koe 1.0.2 → 1.0.4

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/dist/index.js CHANGED
@@ -1,137 +1,480 @@
1
- // src/koe.ts
2
- var MAGIC = 1263486208;
3
- function packKoe(manifest, pcmParts) {
4
- const json = new TextEncoder().encode(JSON.stringify(manifest));
5
- const header = new ArrayBuffer(8);
6
- const view = new DataView(header);
7
- view.setUint32(0, MAGIC, false);
8
- view.setUint32(4, json.byteLength, true);
9
- return new Blob([header, json, ...pcmParts]);
1
+ // src/converter/frq.ts
2
+ function parseFrqAverageF0(buffer) {
3
+ if (buffer.byteLength < 20) return null;
4
+ const view = new DataView(buffer);
5
+ let header = "";
6
+ for (let i = 0; i < 8; i++) header += String.fromCharCode(view.getUint8(i));
7
+ if (header !== "FREQ0003") return null;
8
+ const avg = view.getFloat64(12, true);
9
+ return Number.isFinite(avg) && avg > 0 ? avg : null;
10
10
  }
11
- function parseKoeHeader(headerBytes) {
12
- const view = new DataView(headerBytes);
13
- if (view.byteLength < 8 || view.getUint32(0, false) !== MAGIC) {
14
- throw new Error("Not a .koe file (bad magic)");
15
- }
16
- return { jsonLength: view.getUint32(4, true) };
11
+ function frqFileName(wavName) {
12
+ const dot = wavName.lastIndexOf(".");
13
+ const base = dot >= 0 ? wavName.slice(0, dot) : wavName;
14
+ const ext = dot >= 0 ? wavName.slice(dot + 1) : "wav";
15
+ return `${base}_${ext}.frq`;
17
16
  }
18
- var pcmBase = (jsonLength) => 8 + jsonLength;
19
17
 
20
- // src/engine/voice-bank.ts
21
- var BlobVoiceSource = class {
22
- constructor(blob, base) {
23
- this.blob = blob;
24
- this.base = base;
25
- }
26
- blob;
27
- base;
28
- readBytes(offset, length) {
29
- const start = this.base + offset;
30
- return this.blob.slice(start, start + length).arrayBuffer();
31
- }
18
+ // src/converter/pitch.ts
19
+ var SAMPLE_RATE = 48e3;
20
+ var NAME_SEMITONE = {
21
+ c: 0,
22
+ d: 2,
23
+ e: 4,
24
+ f: 5,
25
+ g: 7,
26
+ a: 9,
27
+ b: 11
32
28
  };
33
- var RangeVoiceSource = class {
34
- constructor(url, base) {
35
- this.url = url;
36
- this.base = base;
29
+ function noteNameToHz(name) {
30
+ const m = /^([A-Ga-g])([#b]?)(-?\d+)$/.exec(name);
31
+ if (!m) return null;
32
+ let semi = NAME_SEMITONE[m[1].toLowerCase()];
33
+ if (m[2] === "#") semi++;
34
+ else if (m[2] === "b") semi--;
35
+ const midi = (parseInt(m[3], 10) + 1) * 12 + semi;
36
+ return 440 * 2 ** ((midi - 69) / 12);
37
+ }
38
+ function pitchFromAliasSuffix(alias) {
39
+ const m = /_([A-Ga-g][#b]?-?\d+)$/.exec(alias);
40
+ return m ? noteNameToHz(m[1]) : null;
41
+ }
42
+ function detectF0(pcm, start, end) {
43
+ const DECIM = 4;
44
+ const sr = SAMPLE_RATE / DECIM;
45
+ const minLag = Math.floor(sr / 700);
46
+ const maxLag = Math.floor(sr / 70);
47
+ const outLen = Math.floor((end - start) / DECIM);
48
+ if (outLen < maxLag + 2) return 0;
49
+ const win = Math.min(outLen, 1500);
50
+ const buf = new Float32Array(win);
51
+ let mean = 0;
52
+ for (let i = 0; i < win; i++) {
53
+ let s = 0;
54
+ const base = start + i * DECIM;
55
+ for (let j = 0; j < DECIM; j++) s += pcm[base + j];
56
+ buf[i] = s;
57
+ mean += s;
37
58
  }
38
- url;
39
- base;
40
- async readBytes(offset, length) {
41
- const start = this.base + offset;
42
- const res = await fetch(this.url, {
43
- headers: { Range: `bytes=${start}-${start + length - 1}` }
44
- });
45
- if (!res.ok && res.status !== 206) {
46
- throw new Error(`.koe range request failed: ${res.status}`);
59
+ mean /= win;
60
+ const sq = new Float64Array(win + 1);
61
+ for (let i = 0; i < win; i++) {
62
+ buf[i] -= mean;
63
+ sq[i + 1] = sq[i] + buf[i] * buf[i];
64
+ }
65
+ if (sq[win] < 1) return 0;
66
+ const norm = (lag) => {
67
+ const n = win - lag;
68
+ let r = 0;
69
+ for (let i = 0; i < n; i++) r += buf[i] * buf[i + lag];
70
+ const e = sq[n] + (sq[lag + n] - sq[lag]);
71
+ return e > 0 ? 2 * r / e : 0;
72
+ };
73
+ let bestLag = -1;
74
+ let best = 0;
75
+ for (let lag = minLag; lag <= maxLag; lag++) {
76
+ const v = norm(lag);
77
+ if (v > best) {
78
+ best = v;
79
+ bestLag = lag;
47
80
  }
48
- return res.arrayBuffer();
49
81
  }
50
- };
51
- async function rangeFetch(url, start, length) {
52
- const res = await fetch(url, {
53
- headers: { Range: `bytes=${start}-${start + length - 1}` }
54
- });
55
- if (!res.ok && res.status !== 206)
56
- throw new Error(`.koe fetch failed: ${res.status}`);
57
- return res.arrayBuffer();
82
+ if (bestLag < 1 || best < 0.4) return 0;
83
+ const y0 = norm(bestLag - 1);
84
+ const y1 = best;
85
+ const y2 = norm(bestLag + 1);
86
+ const denom = y0 - 2 * y1 + y2;
87
+ const shift = denom !== 0 ? 0.5 * (y0 - y2) / denom : 0;
88
+ return sr / (bestLag + shift);
58
89
  }
59
- var VoiceBank = class _VoiceBank {
60
- constructor(manifest, source) {
61
- this.manifest = manifest;
62
- this.source = source;
90
+
91
+ // src/converter/pack.ts
92
+ var TARGET_RATE = 48e3;
93
+ function msToSamples(ms) {
94
+ return Math.round(ms / 1e3 * TARGET_RATE);
95
+ }
96
+ var clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));
97
+ function trimToOto(pcm, oto, recordedPitch = 0) {
98
+ const full = pcm.length;
99
+ const start = clamp(msToSamples(oto.offset), 0, full);
100
+ const end = oto.cutoff < 0 ? clamp(start + msToSamples(-oto.cutoff), start, full) : clamp(full - msToSamples(oto.cutoff), start, full);
101
+ const slice = pcm.subarray(start, end);
102
+ const length = slice.length;
103
+ const pre = clamp(msToSamples(oto.pre), 0, length);
104
+ const overlap = clamp(msToSamples(oto.overlap), 0, length);
105
+ const consonant = clamp(msToSamples(oto.consonant), 0, length);
106
+ const pitch = recordedPitch > 0 ? recordedPitch : detectF0(
107
+ slice,
108
+ Math.min(Math.max(pre, consonant), Math.max(0, length - 1)),
109
+ length
110
+ );
111
+ return {
112
+ pcm: slice,
113
+ entry: { length, pre, overlap, consonant, pitch }
114
+ };
115
+ }
116
+ function pack(inputs, referencePitch = 220) {
117
+ const phonemes = {};
118
+ const chunks = [];
119
+ let byteOffset = 0;
120
+ for (const { oto, pcm, recordedPitch } of inputs) {
121
+ const { pcm: slice, entry } = trimToOto(pcm, oto, recordedPitch);
122
+ if (slice.length === 0) continue;
123
+ phonemes[oto.alias] = { offset: byteOffset, ...entry };
124
+ byteOffset += slice.byteLength;
125
+ chunks.push(slice);
63
126
  }
64
- manifest;
65
- source;
66
- /**
67
- * Parse a .koe archive header + manifest and bind a lazy PCM source.
68
- * @param koe a Blob/File of the .koe archive, or a URL (served with Range support)
69
- */
70
- static async load(koe) {
71
- if (typeof koe === "string") {
72
- const header2 = await rangeFetch(koe, 0, 8);
73
- const { jsonLength: jsonLength2 } = parseKoeHeader(header2);
74
- const json2 = await rangeFetch(koe, 8, jsonLength2);
75
- const manifest2 = JSON.parse(new TextDecoder().decode(json2));
76
- return new _VoiceBank(
77
- manifest2,
78
- new RangeVoiceSource(koe, pcmBase(jsonLength2))
79
- );
80
- }
81
- const header = await koe.slice(0, 8).arrayBuffer();
82
- const { jsonLength } = parseKoeHeader(header);
83
- const json = await koe.slice(8, 8 + jsonLength).arrayBuffer();
84
- const manifest = JSON.parse(new TextDecoder().decode(json));
85
- return new _VoiceBank(
86
- manifest,
87
- new BlobVoiceSource(koe, pcmBase(jsonLength))
127
+ const bin = new ArrayBuffer(byteOffset);
128
+ const view = new Uint8Array(bin);
129
+ let pos = 0;
130
+ for (const chunk of chunks) {
131
+ view.set(
132
+ new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength),
133
+ pos
88
134
  );
135
+ pos += chunk.byteLength;
89
136
  }
90
- /** True if the bank contains a phoneme under this alias. */
91
- has(phoneme) {
92
- return this.manifest.phonemes[phoneme] !== void 0;
93
- }
94
- /**
95
- * Raw Int16 PCM bytes (48 kHz / mono) for a phoneme, or null if unknown.
96
- * The returned ArrayBuffer is freshly allocated and safe to transfer to a
97
- * worker / AudioWorklet.
98
- */
99
- async readPcmBytes(phoneme) {
100
- const entry = this.manifest.phonemes[phoneme];
101
- if (!entry) return null;
102
- return this.source.readBytes(entry.offset, entry.length * 2);
103
- }
104
- /**
105
- * A phoneme's PCM as a Float64Array normalised to [-1, 1], or null if unknown.
106
- * Intended for external analysis / resynthesis such as the WORLD vocoder.
107
- */
108
- async getPcm(phoneme) {
109
- const buf = await this.readPcmBytes(phoneme);
110
- if (!buf) return null;
111
- const int16 = new Int16Array(buf);
112
- const f64 = new Float64Array(int16.length);
113
- for (let i = 0; i < int16.length; i++) f64[i] = int16[i] / 32768;
114
- return f64;
115
- }
116
- };
137
+ const manifest = {
138
+ sampleRate: 48e3,
139
+ referencePitch,
140
+ phonemes
141
+ };
142
+ return { manifest, bin };
143
+ }
117
144
 
118
- // src/engine/index.ts
119
- var KoeEngine = class {
120
- ctx;
121
- workletUrl;
122
- node = null;
123
- bank = null;
124
- delivered = /* @__PURE__ */ new Set();
125
- pending = /* @__PURE__ */ new Map();
126
- constructor(options = {}) {
127
- this.ctx = new AudioContext({ sampleRate: 48e3 });
128
- this.workletUrl = options.workletUrl ?? "./koe-worklet.js";
129
- }
130
- get audioContext() {
131
- return this.ctx;
145
+ // src/converter/parse-oto.ts
146
+ function parseOto(content) {
147
+ const entries = [];
148
+ for (const raw of content.split(/\r?\n/)) {
149
+ const line = raw.trim();
150
+ if (!line || line.startsWith("#")) continue;
151
+ const eq = line.indexOf("=");
152
+ if (eq === -1) continue;
153
+ const wav = line.slice(0, eq).trim();
154
+ const parts = line.slice(eq + 1).split(",");
155
+ if (parts.length < 6) continue;
156
+ const [alias, offsetStr, consonantStr, cutoffStr, preStr, overlapStr] = parts;
157
+ const aliasStr = alias.trim() || wav.replace(/\.[^.]+$/, "");
158
+ const entry = {
159
+ wav,
160
+ alias: aliasStr,
161
+ offset: parseFloat(offsetStr) || 0,
162
+ consonant: parseFloat(consonantStr) || 0,
163
+ cutoff: parseFloat(cutoffStr) || 0,
164
+ pre: parseFloat(preStr) || 0,
165
+ overlap: parseFloat(overlapStr) || 0
166
+ };
167
+ if (!entry.alias) continue;
168
+ entries.push(entry);
132
169
  }
133
- get manifest() {
134
- return this.bank?.manifest ?? null;
170
+ return entries;
171
+ }
172
+
173
+ // src/converter/wav.ts
174
+ function parseWav(buf) {
175
+ const view = new DataView(buf);
176
+ const riff = readFourCC(view, 0);
177
+ if (riff !== "RIFF") throw new Error(`Not a RIFF file (got "${riff}")`);
178
+ let sampleRate = 0;
179
+ let channels = 0;
180
+ let bitsPerSample = 0;
181
+ let audioFormat = 1;
182
+ let dataOffset = 0;
183
+ let dataLength = 0;
184
+ let pos = 12;
185
+ while (pos < view.byteLength - 8) {
186
+ const id = readFourCC(view, pos);
187
+ const size = view.getUint32(pos + 4, true);
188
+ pos += 8;
189
+ if (id === "fmt ") {
190
+ audioFormat = view.getUint16(pos, true);
191
+ channels = view.getUint16(pos + 2, true);
192
+ sampleRate = view.getUint32(pos + 4, true);
193
+ bitsPerSample = view.getUint16(pos + 14, true);
194
+ if (audioFormat === 65534 && size >= 40) {
195
+ audioFormat = view.getUint16(pos + 24, true);
196
+ }
197
+ } else if (id === "data") {
198
+ dataOffset = pos;
199
+ dataLength = Math.min(size, view.byteLength - pos);
200
+ break;
201
+ }
202
+ pos += size + (size & 1);
203
+ }
204
+ if (!dataOffset) throw new Error("WAV has no data chunk");
205
+ if (!channels || !sampleRate) throw new Error("WAV fmt chunk missing");
206
+ const supported = audioFormat === 3 && bitsPerSample === 32 || audioFormat === 1 && (bitsPerSample === 8 || bitsPerSample === 16 || bitsPerSample === 24);
207
+ if (!supported) {
208
+ throw new Error(
209
+ `Unsupported WAV format ${audioFormat} / ${bitsPerSample}-bit (need PCM 8/16/24-bit or IEEE float 32-bit)`
210
+ );
211
+ }
212
+ const bytesPerSample = bitsPerSample >> 3;
213
+ const totalSamples = Math.floor(dataLength / bytesPerSample);
214
+ const samples = new Float32Array(totalSamples);
215
+ for (let i = 0; i < totalSamples; i++) {
216
+ const p = dataOffset + i * bytesPerSample;
217
+ if (audioFormat === 3) {
218
+ samples[i] = view.getFloat32(p, true);
219
+ } else if (bitsPerSample === 8) {
220
+ samples[i] = (view.getUint8(p) - 128) / 128;
221
+ } else if (bitsPerSample === 16) {
222
+ samples[i] = view.getInt16(p, true) / 32768;
223
+ } else if (bitsPerSample === 24) {
224
+ const lo = view.getUint8(p) | view.getUint8(p + 1) << 8;
225
+ let hi = view.getUint8(p + 2);
226
+ if (hi & 128) hi = hi | 4294967040;
227
+ samples[i] = (hi << 16 | lo) / 8388608;
228
+ }
229
+ }
230
+ return { sampleRate, channels, samples };
231
+ }
232
+ function toMono(wav) {
233
+ if (wav.channels === 1) return wav;
234
+ const len = wav.samples.length / wav.channels;
235
+ const out = new Float32Array(len);
236
+ for (let i = 0; i < len; i++) {
237
+ let sum = 0;
238
+ for (let c = 0; c < wav.channels; c++)
239
+ sum += wav.samples[i * wav.channels + c];
240
+ out[i] = sum / wav.channels;
241
+ }
242
+ return { sampleRate: wav.sampleRate, channels: 1, samples: out };
243
+ }
244
+ function resample(wav, targetRate) {
245
+ if (wav.sampleRate === targetRate) return wav;
246
+ const ratio = wav.sampleRate / targetRate;
247
+ const outLen = Math.floor(wav.samples.length / ratio);
248
+ const out = new Float32Array(outLen);
249
+ const src = wav.samples;
250
+ for (let i = 0; i < outLen; i++) {
251
+ const x = i * ratio;
252
+ const xi = Math.floor(x);
253
+ const frac = x - xi;
254
+ out[i] = (src[xi] ?? 0) + ((src[xi + 1] ?? 0) - (src[xi] ?? 0)) * frac;
255
+ }
256
+ return { sampleRate: targetRate, channels: 1, samples: out };
257
+ }
258
+ function toInt16(samples) {
259
+ const out = new Int16Array(samples.length);
260
+ for (let i = 0; i < samples.length; i++) {
261
+ out[i] = Math.round(Math.max(-1, Math.min(1, samples[i])) * 32767);
262
+ }
263
+ return out;
264
+ }
265
+ function normalizePcm(buf) {
266
+ const wav = parseWav(buf);
267
+ const mono = toMono(wav);
268
+ const resampled = resample(mono, 48e3);
269
+ return toInt16(resampled.samples);
270
+ }
271
+ function readFourCC(view, pos) {
272
+ return String.fromCharCode(
273
+ view.getUint8(pos),
274
+ view.getUint8(pos + 1),
275
+ view.getUint8(pos + 2),
276
+ view.getUint8(pos + 3)
277
+ );
278
+ }
279
+
280
+ // src/koe.ts
281
+ var MAGIC = 1263486208;
282
+ function packKoe(manifest, pcmParts) {
283
+ const json = new TextEncoder().encode(JSON.stringify(manifest));
284
+ const header = new ArrayBuffer(8);
285
+ const view = new DataView(header);
286
+ view.setUint32(0, MAGIC, false);
287
+ view.setUint32(4, json.byteLength, true);
288
+ return new Blob([header, json, ...pcmParts]);
289
+ }
290
+ function parseKoeHeader(headerBytes) {
291
+ const view = new DataView(headerBytes);
292
+ if (view.byteLength < 8 || view.getUint32(0, false) !== MAGIC) {
293
+ throw new Error("Not a .koe file (bad magic)");
294
+ }
295
+ return { jsonLength: view.getUint32(4, true) };
296
+ }
297
+ var pcmBase = (jsonLength) => 8 + jsonLength;
298
+
299
+ // src/engine/voice-bank.ts
300
+ var MAX_PHONEME_SAMPLES = 5242880;
301
+ var MAX_JSON_LENGTH = 50 * 1024 * 1024;
302
+ var BlobVoiceSource = class {
303
+ constructor(blob, base) {
304
+ this.blob = blob;
305
+ this.base = base;
306
+ }
307
+ blob;
308
+ base;
309
+ readBytes(offset, length) {
310
+ const start = this.base + offset;
311
+ return this.blob.slice(start, start + length).arrayBuffer();
312
+ }
313
+ };
314
+ var RangeVoiceSource = class {
315
+ constructor(url, base) {
316
+ this.url = url;
317
+ this.base = base;
318
+ }
319
+ url;
320
+ base;
321
+ async readBytes(offset, length) {
322
+ const start = this.base + offset;
323
+ return rangeFetch(this.url, start, length);
324
+ }
325
+ };
326
+ async function rangeFetch(url, start, length) {
327
+ const res = await fetch(url, {
328
+ headers: { Range: `bytes=${start}-${start + length - 1}` },
329
+ credentials: "omit"
330
+ // never leak cookies / auth to a MML-supplied URL
331
+ });
332
+ if (res.status !== 206) {
333
+ throw new Error(
334
+ `.koe fetch failed: expected 206 Partial Content, got ${res.status}`
335
+ );
336
+ }
337
+ return readCapped(res, length);
338
+ }
339
+ async function readCapped(res, length) {
340
+ const reader = res.body?.getReader();
341
+ if (!reader) {
342
+ const buf = await res.arrayBuffer();
343
+ if (buf.byteLength > length) {
344
+ throw new Error(
345
+ `.koe fetch failed: response exceeds requested ${length} bytes`
346
+ );
347
+ }
348
+ return buf;
349
+ }
350
+ const out = new Uint8Array(length);
351
+ let received = 0;
352
+ for (; ; ) {
353
+ const { done, value } = await reader.read();
354
+ if (done) break;
355
+ if (received + value.byteLength > length) {
356
+ await reader.cancel();
357
+ throw new Error(
358
+ `.koe fetch failed: response exceeds requested ${length} bytes`
359
+ );
360
+ }
361
+ out.set(value, received);
362
+ received += value.byteLength;
363
+ }
364
+ return received === length ? out.buffer : out.buffer.slice(0, received);
365
+ }
366
+ function validateJsonLength(jsonLength) {
367
+ if (!Number.isInteger(jsonLength) || jsonLength < 0 || jsonLength > MAX_JSON_LENGTH) {
368
+ throw new Error(`manifest JSON length out of bounds: ${jsonLength}`);
369
+ }
370
+ }
371
+ function parseManifest(json) {
372
+ const manifest = JSON.parse(new TextDecoder().decode(json));
373
+ if (!manifest || typeof manifest !== "object" || typeof manifest.phonemes !== "object" || manifest.phonemes === null) {
374
+ throw new Error("invalid manifest: missing phonemes table");
375
+ }
376
+ return manifest;
377
+ }
378
+ var VoiceBank = class _VoiceBank {
379
+ constructor(manifest, source) {
380
+ this.manifest = manifest;
381
+ this.source = source;
382
+ }
383
+ manifest;
384
+ source;
385
+ /**
386
+ * Parse a .koe archive header + manifest and bind a lazy PCM source.
387
+ * @param koe a Blob/File of the .koe archive, or a URL (served with Range support)
388
+ */
389
+ static async load(koe) {
390
+ try {
391
+ if (typeof koe === "string") {
392
+ if (/^blob:/i.test(koe)) {
393
+ const res = await fetch(koe);
394
+ if (!res.ok) {
395
+ throw new Error(`blob: URL fetch failed: ${res.status}`);
396
+ }
397
+ return await _VoiceBank.fromBlob(await res.blob());
398
+ }
399
+ if (!/^https?:/i.test(koe)) {
400
+ throw new Error(`unsupported URL protocol: ${koe}`);
401
+ }
402
+ const header = await rangeFetch(koe, 0, 8);
403
+ const { jsonLength } = parseKoeHeader(header);
404
+ validateJsonLength(jsonLength);
405
+ const json = await rangeFetch(koe, 8, jsonLength);
406
+ const manifest = parseManifest(json);
407
+ return new _VoiceBank(
408
+ manifest,
409
+ new RangeVoiceSource(koe, pcmBase(jsonLength))
410
+ );
411
+ }
412
+ return await _VoiceBank.fromBlob(koe);
413
+ } catch (error) {
414
+ throw new Error(
415
+ `Failed to load .koe voice bank: ${error instanceof Error ? error.message : String(error)}`
416
+ );
417
+ }
418
+ }
419
+ static async fromBlob(koe) {
420
+ const header = await koe.slice(0, 8).arrayBuffer();
421
+ const { jsonLength } = parseKoeHeader(header);
422
+ validateJsonLength(jsonLength);
423
+ const json = await koe.slice(8, 8 + jsonLength).arrayBuffer();
424
+ const manifest = parseManifest(json);
425
+ return new _VoiceBank(
426
+ manifest,
427
+ new BlobVoiceSource(koe, pcmBase(jsonLength))
428
+ );
429
+ }
430
+ /** True if the bank contains a phoneme under this alias. */
431
+ has(phoneme) {
432
+ return Object.hasOwn(this.manifest.phonemes, phoneme);
433
+ }
434
+ /**
435
+ * Raw Int16 PCM bytes (48 kHz / mono) for a phoneme, or null if unknown.
436
+ * The returned ArrayBuffer is freshly allocated and safe to transfer to a
437
+ * worker / AudioWorklet.
438
+ */
439
+ async readPcmBytes(phoneme) {
440
+ if (!Object.hasOwn(this.manifest.phonemes, phoneme)) return null;
441
+ const entry = this.manifest.phonemes[phoneme];
442
+ if (!Number.isInteger(entry.offset) || !Number.isInteger(entry.length) || entry.offset < 0 || entry.length < 0 || entry.length > MAX_PHONEME_SAMPLES) {
443
+ throw new Error(`manifest entry out of bounds for phoneme: ${phoneme}`);
444
+ }
445
+ return this.source.readBytes(entry.offset, entry.length * 2);
446
+ }
447
+ /**
448
+ * A phoneme's PCM as a Float64Array normalised to [-1, 1], or null if unknown.
449
+ * Intended for external analysis / resynthesis such as the WORLD vocoder.
450
+ */
451
+ async getPcm(phoneme) {
452
+ const buf = await this.readPcmBytes(phoneme);
453
+ if (!buf) return null;
454
+ const int16 = new Int16Array(buf, 0, Math.floor(buf.byteLength / 2));
455
+ const f64 = new Float64Array(int16.length);
456
+ for (let i = 0; i < int16.length; i++) f64[i] = int16[i] / 32768;
457
+ return f64;
458
+ }
459
+ };
460
+
461
+ // src/engine/index.ts
462
+ var KoeEngine = class {
463
+ ctx;
464
+ workletUrl;
465
+ node = null;
466
+ bank = null;
467
+ delivered = /* @__PURE__ */ new Set();
468
+ pending = /* @__PURE__ */ new Map();
469
+ constructor(options = {}) {
470
+ this.ctx = new AudioContext({ sampleRate: 48e3 });
471
+ this.workletUrl = options.workletUrl ?? "./koe-worklet.js";
472
+ }
473
+ get audioContext() {
474
+ return this.ctx;
475
+ }
476
+ get manifest() {
477
+ return this.bank?.manifest ?? null;
135
478
  }
136
479
  /** The underlying voice bank (manifest + on-demand PCM), or null before load(). */
137
480
  get voiceBank() {
@@ -143,6 +486,8 @@ var KoeEngine = class {
143
486
  */
144
487
  async load(koe) {
145
488
  await this.ctx.audioWorklet.addModule(this.workletUrl);
489
+ this.node?.disconnect();
490
+ this.node = null;
146
491
  this.bank = await VoiceBank.load(koe);
147
492
  this.delivered.clear();
148
493
  this.pending.clear();
@@ -166,11 +511,12 @@ var KoeEngine = class {
166
511
  if (existing) return existing;
167
512
  if (!this.bank || !this.node) return Promise.resolve();
168
513
  const load = this.bank.readPcmBytes(name).then((buf) => {
169
- if (!buf) return;
514
+ if (!buf || !this.node) return;
170
515
  this.node.port.postMessage({ type: "phoneme", name, buffer: buf }, [
171
516
  buf
172
517
  ]);
173
518
  this.delivered.add(name);
519
+ }).finally(() => {
174
520
  this.pending.delete(name);
175
521
  });
176
522
  this.pending.set(name, load);
@@ -192,6 +538,18 @@ var KoeEngine = class {
192
538
  async resume() {
193
539
  if (this.ctx.state === "suspended") await this.ctx.resume();
194
540
  }
541
+ /**
542
+ * Tear down the worklet node and close the AudioContext, releasing the audio
543
+ * hardware. The engine cannot be reused afterwards — create a new one.
544
+ */
545
+ async dispose() {
546
+ this.node?.disconnect();
547
+ this.node = null;
548
+ this.bank = null;
549
+ this.delivered.clear();
550
+ this.pending.clear();
551
+ if (this.ctx.state !== "closed") await this.ctx.close();
552
+ }
195
553
  /**
196
554
  * Read a phoneme's raw PCM and return it as a Float64Array normalised to
197
555
  * [-1, 1]. Convenience that forwards to the underlying {@link VoiceBank}.
@@ -235,22 +593,30 @@ function injectScript(src) {
235
593
  function loadWasm(scriptUrl) {
236
594
  const cached = moduleCache.get(scriptUrl);
237
595
  if (cached) return cached;
238
- if (typeof document === "undefined") {
239
- return Promise.reject(
240
- new Error(
241
- "Worldline.load requires a DOM (browser) environment to load worldline.js"
242
- )
243
- );
244
- }
245
596
  const baseUrl = scriptUrl.slice(0, scriptUrl.lastIndexOf("/") + 1);
246
- const promise = injectScript(scriptUrl).then(() => {
597
+ const instantiate = () => {
247
598
  const factory = globalThis.WorldlineModule;
248
599
  if (!factory)
249
600
  throw new Error(
250
601
  "worldline: WorldlineModule global was not defined by the script"
251
602
  );
252
603
  return factory({ locateFile: (f) => baseUrl + f });
253
- });
604
+ };
605
+ let promise;
606
+ if (typeof document !== "undefined") {
607
+ promise = injectScript(scriptUrl).then(instantiate);
608
+ } else if (typeof globalThis.importScripts === "function") {
609
+ promise = Promise.resolve().then(() => {
610
+ globalThis.importScripts(scriptUrl);
611
+ return instantiate();
612
+ });
613
+ } else {
614
+ return Promise.reject(
615
+ new Error(
616
+ "Worldline.load requires a DOM or a classic Web Worker (importScripts) to load worldline.js"
617
+ )
618
+ );
619
+ }
254
620
  moduleCache.set(scriptUrl, promise);
255
621
  return promise;
256
622
  }
@@ -260,7 +626,13 @@ var Worldline = class _Worldline {
260
626
  }
261
627
  wasm;
262
628
  sampleRate = WORLDLINE_SAMPLE_RATE;
263
- /** Load + instantiate the worldline WASM module (deduped per scriptUrl). */
629
+ /**
630
+ * Load + instantiate the worldline WASM module (deduped per scriptUrl).
631
+ *
632
+ * Works on the main thread (loads via `<script>`) and inside a classic Web
633
+ * Worker (loads via `importScripts`), so the heavy synthesis can run
634
+ * off-thread. The matching `worldline.wasm` is fetched next to scriptUrl.
635
+ */
264
636
  static async load(options) {
265
637
  return new _Worldline(await loadWasm(options.scriptUrl));
266
638
  }
@@ -374,282 +746,13 @@ var Worldline = class _Worldline {
374
746
  }
375
747
  const outLen = WL._PhraseSynthSynth(ps, yPtrPtr, 0);
376
748
  const yPtr = WL.getValue(yPtrPtr, "*");
377
- const audio = outLen > 0 ? new Float32Array(WL.HEAPF32.buffer, yPtr, outLen).slice() : null;
749
+ const audio = outLen > 0 && yPtr ? new Float32Array(WL.HEAPF32.buffer, yPtr, outLen).slice() : null;
750
+ if (yPtr) WL._free(yPtr);
378
751
  WL._free(yPtrPtr);
379
752
  WL._PhraseSynthDelete(ps);
380
753
  return audio;
381
754
  }
382
755
  };
383
-
384
- // src/converter/parse-oto.ts
385
- function parseOto(content) {
386
- const entries = [];
387
- for (const raw of content.split(/\r?\n/)) {
388
- const line = raw.trim();
389
- if (!line || line.startsWith("#")) continue;
390
- const eq = line.indexOf("=");
391
- if (eq === -1) continue;
392
- const wav = line.slice(0, eq).trim();
393
- const parts = line.slice(eq + 1).split(",");
394
- if (parts.length < 6) continue;
395
- const [alias, offsetStr, consonantStr, cutoffStr, preStr, overlapStr] = parts;
396
- const aliasStr = alias.trim() || wav.replace(/\.[^.]+$/, "");
397
- const entry = {
398
- wav,
399
- alias: aliasStr,
400
- offset: parseFloat(offsetStr) || 0,
401
- consonant: parseFloat(consonantStr) || 0,
402
- cutoff: parseFloat(cutoffStr) || 0,
403
- pre: parseFloat(preStr) || 0,
404
- overlap: parseFloat(overlapStr) || 0
405
- };
406
- if (!entry.alias) continue;
407
- entries.push(entry);
408
- }
409
- return entries;
410
- }
411
-
412
- // src/converter/wav.ts
413
- function parseWav(buf) {
414
- const view = new DataView(buf);
415
- const riff = readFourCC(view, 0);
416
- if (riff !== "RIFF") throw new Error(`Not a RIFF file (got "${riff}")`);
417
- let sampleRate = 0;
418
- let channels = 0;
419
- let bitsPerSample = 0;
420
- let audioFormat = 1;
421
- let dataOffset = 0;
422
- let dataLength = 0;
423
- let pos = 12;
424
- while (pos < view.byteLength - 8) {
425
- const id = readFourCC(view, pos);
426
- const size = view.getUint32(pos + 4, true);
427
- pos += 8;
428
- if (id === "fmt ") {
429
- audioFormat = view.getUint16(pos, true);
430
- channels = view.getUint16(pos + 2, true);
431
- sampleRate = view.getUint32(pos + 4, true);
432
- bitsPerSample = view.getUint16(pos + 14, true);
433
- } else if (id === "data") {
434
- dataOffset = pos;
435
- dataLength = size;
436
- break;
437
- }
438
- pos += size + (size & 1);
439
- }
440
- if (!dataOffset) throw new Error("WAV has no data chunk");
441
- if (!channels || !sampleRate) throw new Error("WAV fmt chunk missing");
442
- const bytesPerSample = bitsPerSample >> 3;
443
- const totalSamples = Math.floor(dataLength / bytesPerSample);
444
- const samples = new Float32Array(totalSamples);
445
- for (let i = 0; i < totalSamples; i++) {
446
- const p = dataOffset + i * bytesPerSample;
447
- if (audioFormat === 3) {
448
- samples[i] = view.getFloat32(p, true);
449
- } else if (bitsPerSample === 8) {
450
- samples[i] = (view.getUint8(p) - 128) / 128;
451
- } else if (bitsPerSample === 16) {
452
- samples[i] = view.getInt16(p, true) / 32768;
453
- } else if (bitsPerSample === 24) {
454
- const lo = view.getUint8(p) | view.getUint8(p + 1) << 8;
455
- let hi = view.getUint8(p + 2);
456
- if (hi & 128) hi = hi | 4294967040;
457
- samples[i] = (hi << 16 | lo) / 8388608;
458
- }
459
- }
460
- return { sampleRate, channels, samples };
461
- }
462
- function toMono(wav) {
463
- if (wav.channels === 1) return wav;
464
- const len = wav.samples.length / wav.channels;
465
- const out = new Float32Array(len);
466
- for (let i = 0; i < len; i++) {
467
- let sum = 0;
468
- for (let c = 0; c < wav.channels; c++)
469
- sum += wav.samples[i * wav.channels + c];
470
- out[i] = sum / wav.channels;
471
- }
472
- return { sampleRate: wav.sampleRate, channels: 1, samples: out };
473
- }
474
- function resample(wav, targetRate) {
475
- if (wav.sampleRate === targetRate) return wav;
476
- const ratio = wav.sampleRate / targetRate;
477
- const outLen = Math.floor(wav.samples.length / ratio);
478
- const out = new Float32Array(outLen);
479
- const src = wav.samples;
480
- for (let i = 0; i < outLen; i++) {
481
- const x = i * ratio;
482
- const xi = Math.floor(x);
483
- const frac = x - xi;
484
- out[i] = (src[xi] ?? 0) + ((src[xi + 1] ?? 0) - (src[xi] ?? 0)) * frac;
485
- }
486
- return { sampleRate: targetRate, channels: 1, samples: out };
487
- }
488
- function toInt16(samples) {
489
- const out = new Int16Array(samples.length);
490
- for (let i = 0; i < samples.length; i++) {
491
- out[i] = Math.round(Math.max(-1, Math.min(1, samples[i])) * 32767);
492
- }
493
- return out;
494
- }
495
- function normalizePcm(buf) {
496
- const wav = parseWav(buf);
497
- const mono = toMono(wav);
498
- const resampled = resample(mono, 48e3);
499
- return toInt16(resampled.samples);
500
- }
501
- function readFourCC(view, pos) {
502
- return String.fromCharCode(
503
- view.getUint8(pos),
504
- view.getUint8(pos + 1),
505
- view.getUint8(pos + 2),
506
- view.getUint8(pos + 3)
507
- );
508
- }
509
-
510
- // src/converter/pitch.ts
511
- var SAMPLE_RATE = 48e3;
512
- var NAME_SEMITONE = {
513
- c: 0,
514
- d: 2,
515
- e: 4,
516
- f: 5,
517
- g: 7,
518
- a: 9,
519
- b: 11
520
- };
521
- function noteNameToHz(name) {
522
- const m = /^([A-Ga-g])([#b]?)(-?\d+)$/.exec(name);
523
- if (!m) return null;
524
- let semi = NAME_SEMITONE[m[1].toLowerCase()];
525
- if (m[2] === "#") semi++;
526
- else if (m[2] === "b") semi--;
527
- const midi = (parseInt(m[3], 10) + 1) * 12 + semi;
528
- return 440 * 2 ** ((midi - 69) / 12);
529
- }
530
- function pitchFromAliasSuffix(alias) {
531
- const m = /_([A-Ga-g][#b]?-?\d+)$/.exec(alias);
532
- return m ? noteNameToHz(m[1]) : null;
533
- }
534
- function detectF0(pcm, start, end) {
535
- const DECIM = 4;
536
- const sr = SAMPLE_RATE / DECIM;
537
- const minLag = Math.floor(sr / 700);
538
- const maxLag = Math.floor(sr / 70);
539
- const outLen = Math.floor((end - start) / DECIM);
540
- if (outLen < maxLag + 2) return 0;
541
- const win = Math.min(outLen, 1500);
542
- const buf = new Float32Array(win);
543
- let mean = 0;
544
- for (let i = 0; i < win; i++) {
545
- let s = 0;
546
- const base = start + i * DECIM;
547
- for (let j = 0; j < DECIM; j++) s += pcm[base + j];
548
- buf[i] = s;
549
- mean += s;
550
- }
551
- mean /= win;
552
- const sq = new Float64Array(win + 1);
553
- for (let i = 0; i < win; i++) {
554
- buf[i] -= mean;
555
- sq[i + 1] = sq[i] + buf[i] * buf[i];
556
- }
557
- if (sq[win] < 1) return 0;
558
- const norm = (lag) => {
559
- const n = win - lag;
560
- let r = 0;
561
- for (let i = 0; i < n; i++) r += buf[i] * buf[i + lag];
562
- const e = sq[n] + (sq[lag + n] - sq[lag]);
563
- return e > 0 ? 2 * r / e : 0;
564
- };
565
- let bestLag = -1;
566
- let best = 0;
567
- for (let lag = minLag; lag <= maxLag; lag++) {
568
- const v = norm(lag);
569
- if (v > best) {
570
- best = v;
571
- bestLag = lag;
572
- }
573
- }
574
- if (bestLag < 1 || best < 0.4) return 0;
575
- const y0 = norm(bestLag - 1);
576
- const y1 = best;
577
- const y2 = norm(bestLag + 1);
578
- const denom = y0 - 2 * y1 + y2;
579
- const shift = denom !== 0 ? 0.5 * (y0 - y2) / denom : 0;
580
- return sr / (bestLag + shift);
581
- }
582
-
583
- // src/converter/pack.ts
584
- var TARGET_RATE = 48e3;
585
- function msToSamples(ms) {
586
- return Math.round(ms / 1e3 * TARGET_RATE);
587
- }
588
- var clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));
589
- function trimToOto(pcm, oto, recordedPitch = 0) {
590
- const full = pcm.length;
591
- const start = clamp(msToSamples(oto.offset), 0, full);
592
- const end = oto.cutoff < 0 ? clamp(start + msToSamples(-oto.cutoff), start, full) : clamp(full - msToSamples(oto.cutoff), start, full);
593
- const slice = pcm.subarray(start, end);
594
- const length = slice.length;
595
- const pre = clamp(msToSamples(oto.pre), 0, length);
596
- const overlap = clamp(msToSamples(oto.overlap), 0, length);
597
- const consonant = clamp(msToSamples(oto.consonant), 0, length);
598
- const pitch = recordedPitch > 0 ? recordedPitch : detectF0(
599
- slice,
600
- Math.min(Math.max(pre, consonant), Math.max(0, length - 1)),
601
- length
602
- );
603
- return {
604
- pcm: slice,
605
- entry: { length, pre, overlap, consonant, pitch }
606
- };
607
- }
608
- function pack(inputs, referencePitch = 220) {
609
- const phonemes = {};
610
- const chunks = [];
611
- let byteOffset = 0;
612
- for (const { oto, pcm, recordedPitch } of inputs) {
613
- const { pcm: slice, entry } = trimToOto(pcm, oto, recordedPitch);
614
- if (slice.length === 0) continue;
615
- phonemes[oto.alias] = { offset: byteOffset, ...entry };
616
- byteOffset += slice.byteLength;
617
- chunks.push(slice);
618
- }
619
- const bin = new ArrayBuffer(byteOffset);
620
- const view = new Uint8Array(bin);
621
- let pos = 0;
622
- for (const chunk of chunks) {
623
- view.set(
624
- new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength),
625
- pos
626
- );
627
- pos += chunk.byteLength;
628
- }
629
- const manifest = {
630
- sampleRate: 48e3,
631
- referencePitch,
632
- phonemes
633
- };
634
- return { manifest, bin };
635
- }
636
-
637
- // src/converter/frq.ts
638
- function parseFrqAverageF0(buffer) {
639
- if (buffer.byteLength < 20) return null;
640
- const view = new DataView(buffer);
641
- let header = "";
642
- for (let i = 0; i < 8; i++) header += String.fromCharCode(view.getUint8(i));
643
- if (header !== "FREQ0003") return null;
644
- const avg = view.getFloat64(12, true);
645
- return Number.isFinite(avg) && avg > 0 ? avg : null;
646
- }
647
- function frqFileName(wavName) {
648
- const dot = wavName.lastIndexOf(".");
649
- const base = dot >= 0 ? wavName.slice(0, dot) : wavName;
650
- const ext = dot >= 0 ? wavName.slice(dot + 1) : "wav";
651
- return `${base}_${ext}.frq`;
652
- }
653
756
  export {
654
757
  KoeEngine,
655
758
  MIN_WORLDLINE_SAMPLES,