@met4citizen/headtts 0.2.0

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.
@@ -0,0 +1,975 @@
1
+ /**
2
+ * MIT License
3
+ *
4
+ * Copyright (c) 2025 Mika Suominen
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in all
14
+ * copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ * SOFTWARE.
23
+ */
24
+
25
+ import * as utils from "./utils.mjs";
26
+
27
+ class HeadTTS {
28
+
29
+ /**
30
+ * @constructor
31
+ * @param {Object} [settings=null] Global/default options
32
+ * @param {function} [onerror=null] Global Error event callback function
33
+ */
34
+ constructor( settings = null, onerror = null ) {
35
+ this.settings = Object.assign({
36
+ endpoints: ["webgpu", "wasm"],
37
+ audioCtx: null,
38
+
39
+ transformersModule: "https://cdn.jsdelivr.net/npm/@huggingface/transformers@3.4.2/dist/transformers.min.js",
40
+
41
+ model: "onnx-community/Kokoro-82M-v1.0-ONNX-timestamped",
42
+ dtypeWebgpu: "fp32", // "fp32" | "fp16" | "q8" | "q4" | "q4f16"
43
+ dtypeWasm: "q4", // "fp32" | "fp16" | "q8" | "q4" | "q4f16"
44
+ styleDim: 256,
45
+ frameRate: 40,
46
+ audioSampleRate: 24000,
47
+ languages: ['en-us'], // Language modules to be preloaded
48
+ dictionaryURL: "../dictionaries",
49
+ voiceURL: "https://huggingface.co/onnx-community/Kokoro-82M-v1.0-ONNX/resolve/main/voices",
50
+ voices: [], // Voices to be pre-loaded
51
+
52
+ deltaStart: -10,
53
+ deltaEnd: 10,
54
+ splitSentences: true,
55
+ splitLength: 500,
56
+
57
+ defaultVoice: "af_bella",
58
+ defaultLanguage: "en-us",
59
+ defaultSpeed: 1,
60
+ defaultAudioEncoding: "wav",
61
+
62
+ trace: 0
63
+ }, settings || {});
64
+
65
+ // Client setup
66
+ this.ttsSetup = {
67
+
68
+ // synthesize
69
+ voice: this.settings.defaultVoice,
70
+ language: this.settings.defaultLanguage,
71
+ speed: this.settings.defaultSpeed,
72
+ audioEncoding: this.settings.defaultAudioEncoding
73
+
74
+ };
75
+
76
+ // Event handlers
77
+ this.onstart = null;
78
+ this.onmessage = null;
79
+ this.onend = null;
80
+ this.onerror = onerror;
81
+
82
+ // Create a new audio context, if not set
83
+ if ( !this.settings.audioCtx ) {
84
+ this.settings.audioCtx = new (window.AudioContext || window.webkitAudioContext)();
85
+ }
86
+
87
+ // Work items
88
+ this.items = new Map();
89
+ if ( this.settings.splitSentences ) {
90
+ this.dividers = { "! ":1, ". ":1, "? ":1 };
91
+ } else {
92
+ this.dividers = {};
93
+ }
94
+ this.itemWaitingForAudio = null;
95
+
96
+ // Work queues
97
+ this.queueIn = [];
98
+ this.queueOut = [];
99
+ this.isProcessingIn = false;
100
+ this.isProcessingOut = false;
101
+ this.messageId = 0;
102
+
103
+ // Connection
104
+ this.isConnecting = false;
105
+ this.isConnected = false;
106
+ this.ws = null; // WebSocket connection
107
+ this.ww = null; // Web Worker for in-browser inference
108
+ this.rest = null; // RESTful server
109
+ }
110
+
111
+ /**
112
+ * Divide the given text into parts
113
+ *
114
+ * @param {string} text Text
115
+ * @param {number} [initialLen=0] Initial length
116
+ * @return {string[]} Array of text parts.
117
+ */
118
+ divideToParts(text, initialLen=0) {
119
+ const parts = [];
120
+ const textLen = text.length;
121
+ const letters = [...text];
122
+ let lastSpace = 0;
123
+ let part = "";
124
+ for( let i=0; i<textLen; i++ ) {
125
+ const letter = letters[i];
126
+ const isLast = i === (textLen-1);
127
+ const letterTwo = isLast ? null : (letter + letters[i+1]);
128
+ const isDivider = isLast ? false : this.dividers.hasOwnProperty(letterTwo);
129
+ if ( letter === ' ' ) lastSpace = i;
130
+ const isMax = i >= (this.settings.splitLength - initialLen);
131
+
132
+ part += letter;
133
+
134
+ let s = null;
135
+ if ( isMax ) {
136
+ if ( lastSpace === 0 ) lastSpace = i;
137
+ parts.push( part.slice(0,lastSpace) );
138
+ part = part.slice(lastSpace+1);
139
+ lastSpace = 0;
140
+ initialLen = 0;
141
+ } else if ( isLast || isDivider ) {
142
+ parts.push( part );
143
+ part = "";
144
+ lastSpace = 0;
145
+ initialLen = 0;
146
+ }
147
+
148
+ }
149
+ return parts;
150
+ }
151
+
152
+
153
+ /**
154
+ * Emit message to event handlers. If no event handler was called and
155
+ * the message was set throwable, then throw the message.
156
+ *
157
+ * @param {string} title Event title for the log
158
+ * @param {Object} message Message event
159
+ * @param {function[]} handlers Event handlers
160
+ * @param {boolean} [isThrowable=false] If true and no handler called, throw message
161
+ * @param {boolean} [firstOnly=true] If true, only the first handler is called.
162
+ */
163
+ emit( title, message, handlers, isThrowable = false, firstOnly = true ) {
164
+ const isTraceEvents = this.settings.trace & utils.traceMask.events;
165
+ if ( isTraceEvents ) {
166
+ utils.trace( "EMIT: " + title, message );
167
+ }
168
+ let isCalled = false;
169
+ for(let i=0; i<handlers.length; i++) {
170
+ const handler = handlers[i];
171
+ if ( handler && typeof handler === 'function' ) {
172
+ try {
173
+ handler(message);
174
+ isCalled = true;
175
+ } catch(error) {
176
+ console.error("Error calling event handler, error=", error);
177
+ }
178
+ if ( isCalled && firstOnly ) break;
179
+ }
180
+ }
181
+ if ( !isCalled && isThrowable ) throw message;
182
+ }
183
+
184
+
185
+ /**
186
+ * Connect to WebSocket server or start a web worker for in-browser inference.
187
+ * Tries each server/browser entry in the order they are set. If all fail,
188
+ * emits an "error" event.
189
+ *
190
+ * @param {Object} [settings=false] If true, forces disconnect and re-connects.
191
+ * @param {function} [onerror=null] Callback for Error events overriding event handler
192
+ * @param {function} [onprogress=null] Callback for ProgressEvent events
193
+ */
194
+ async connect( settings = null, onprogress = null, onerror = null ) {
195
+ const isTraceConnection = this.settings.trace & utils.traceMask.connect;
196
+ const isTraceMessages = this.settings.trace & utils.traceMask.messages;
197
+
198
+ // If new settings, force re-connect
199
+ if ( settings === null ) {
200
+ if ( this.isConnected || this.isConnecting ) return;
201
+ } else {
202
+ Object.assign(this.settings, settings);
203
+ }
204
+ this.isConnecting = true;
205
+
206
+ // Disconnect previous connections if any
207
+ this.isConnected = false;
208
+ if ( this.ws ) {
209
+ if ( isTraceConnection ) {
210
+ utils.trace( "DISCONNECT: WebSocket" );
211
+ }
212
+ this.ws.close();
213
+ this.ws = null;
214
+ }
215
+ if ( this.ww ) {
216
+ if ( isTraceConnection ) {
217
+ utils.trace( "DISCONNECT: Worker" );
218
+ }
219
+ this.ww.terminate();
220
+ this.ww = null;
221
+ }
222
+ if ( this.rest ) {
223
+ if ( isTraceConnection ) {
224
+ utils.trace( "DISCONNECT: REST" );
225
+ }
226
+ this.rest = null;
227
+ }
228
+
229
+ // Error events
230
+ const events = [onerror, this.onerror];
231
+ const connectionErrorLog = [];
232
+
233
+ for( let i=0; i<this.settings.endpoints.length && !this.isConnected; i++ ) {
234
+ const endpoint = this.settings.endpoints[i].trim();
235
+ const endpointLowerCase = endpoint.toLowerCase();
236
+
237
+ if ( endpointLowerCase === "webgpu" || endpointLowerCase === "wasm" ) {
238
+
239
+ // Check support for Module Web Workers
240
+ if ( !utils.isModuleWebWorkers() ) {
241
+ if ( isTraceConnection ) {
242
+ utils.trace( "Your browser doesn't support Module Web Workers." );
243
+ }
244
+ connectionErrorLog.push( "Your browser doesn't support Module Web Workers." );
245
+ continue;
246
+ }
247
+
248
+ // Check support for WbeGPU, if needed
249
+ if ( endpointLowerCase === "webgpu" && !utils.isWebGPU() ) {
250
+ if ( isTraceConnection ) {
251
+ utils.trace( "Your browser doesn't support WebGPU." );
252
+ }
253
+ connectionErrorLog.push( "Your browser doesn't support WebGPU." );
254
+ continue;
255
+ }
256
+
257
+ // Start Web Worker
258
+ try {
259
+
260
+ // Wait for Web Worker connection
261
+ await new Promise((resolve, reject) => {
262
+
263
+ // Start the TTS web worker
264
+ const url = new URL("./worker-tts.mjs", import.meta.url);
265
+ this.ww = new Worker(url, { type: 'module' });
266
+
267
+ // Handle progress reports and wait for ready message
268
+ const rejectedTimeout = () => reject('Connection timed out.');
269
+ let timeout = setTimeout(rejectedTimeout, 30000);
270
+
271
+ this.ww.onmessage = (ev) => {
272
+ if ( ev.data?.type === 'progress' ) {
273
+ if (timeout) {
274
+ clearTimeout(timeout);
275
+ timeout = setTimeout(rejectedTimeout, 10000);
276
+ }
277
+ if ( typeof onprogress === 'function' ) {
278
+ onprogress( new ProgressEvent('progress', ev.data.data ));
279
+ }
280
+ } else if ( ev.data?.type === 'ready' ) {
281
+ if (timeout) {
282
+ clearTimeout(timeout);
283
+ timeout = null;
284
+ }
285
+ resolve();
286
+ }
287
+ }
288
+
289
+ this.ww.onerror = (ev) => {
290
+ if (timeout) {
291
+ clearTimeout(timeout);
292
+ timeout = null;
293
+ }
294
+ reject(ev);
295
+ }
296
+
297
+ // Setup
298
+ const endpointSetup = {};
299
+ [ "transformersModule", "model", "styleDim", "frameRate",
300
+ "languages", "dictionaryURL", "voiceURL", , "voices",
301
+ "audioSampleRate", "deltaStart", "deltaEnd", "trace" ].forEach( x => {
302
+ if ( this.settings[x] !== undefined ) {
303
+ endpointSetup[x] = this.settings[x];
304
+ }
305
+ });
306
+ endpointSetup.device = endpointLowerCase;
307
+ endpointSetup.dtype = (endpointLowerCase === "webgpu") ? this.settings.dtypeWebgpu : this.settings.dtypeWasm;
308
+ const message = { type: "connect", data: endpointSetup };
309
+ if ( isTraceMessages ) {
310
+ utils.trace( "OUT: HeadTTS -> worker, message=", message );
311
+ }
312
+ this.ww.postMessage( message );
313
+
314
+ });
315
+
316
+ this.ww.onmessage = (ev) => {
317
+ if ( isTraceMessages ) {
318
+ utils.trace( "IN: worker -> HeadTTS, message=", ev.data);
319
+ }
320
+ this.processData(ev.data);
321
+ }
322
+
323
+ this.ww.onerror = (error) => {
324
+ error.preventDefault();
325
+ console.error("HeadTTS: Worker error, error=", error);
326
+
327
+ this.emit("error", error, events);
328
+
329
+ this.ww.terminate();
330
+ this.ww = null;
331
+ this.isConnected = false;
332
+
333
+ this.processIn();
334
+ }
335
+
336
+ // Connected
337
+ this.isConnected = true;
338
+
339
+ } catch(error) {
340
+ if ( this.ww ) {
341
+ this.ww.terminate();
342
+ this.ww = null;
343
+ }
344
+ if ( isTraceConnection ) {
345
+ utils.trace( "Failed to start Module Web Worker." );
346
+ }
347
+ connectionErrorLog.push( "Failed to start Module Web Worker." );
348
+ }
349
+
350
+ } else {
351
+
352
+ // Get URL
353
+ let url;
354
+ try {
355
+ url = new URL(endpoint, window.location.href);
356
+ } catch(error) {
357
+ connectionErrorLog.push( "Invalid URL '" + endpoint + "'." );
358
+ }
359
+
360
+ if ( url && (url.protocol === 'ws:' || url.protocol === 'wss:' ) ) {
361
+
362
+ // Make a connection
363
+ try {
364
+
365
+ // Wait for WebSocket connection
366
+ await new Promise((resolve, reject) => {
367
+
368
+ // Handle progress reports and wait for ready message
369
+ const rejectedTimeout = () => reject('Connection timed out.');
370
+ let timeout = setTimeout(rejectedTimeout, 5000);
371
+
372
+ this.ws = new WebSocket(endpoint);
373
+ this.ws.onopen = () => {
374
+ if ( timeout ) {
375
+ clearTimeout(timeout);
376
+ }
377
+ resolve();
378
+ }
379
+ this.ws.onerror = (ev) => {
380
+ if ( timeout ) {
381
+ clearTimeout(timeout);
382
+ }
383
+ reject(ev);
384
+ }
385
+ });
386
+
387
+ // Set binary type
388
+ this.ws.binaryType = "arraybuffer";
389
+
390
+ // Message handler
391
+ this.ws.onmessage = async (ev) => {
392
+ if ( isTraceMessages ) {
393
+ utils.trace( "IN: WebSocket -> HeadTTS, message=", ev.data);
394
+ }
395
+ this.processData(ev.data);
396
+ }
397
+
398
+ // Error handler
399
+ this.ws.onerror = (error) => {
400
+ error.preventDefault();
401
+ console.error("HeadTTS: WebSocket error, error=", error);
402
+ }
403
+
404
+ // Connection closed
405
+ this.ws.onclose = (ev) => {
406
+
407
+ // Update status
408
+ this.isConnected = false;
409
+ this.ws = null;
410
+
411
+ if ( ev.wasClean) {
412
+ if ( isTraceConnection ) {
413
+ utils.trace( "WebSocket connection closed cleanly, event=", ev);
414
+ }
415
+ } else {
416
+ console.error("HeadTTS: WebSocket connection was closed, event=", ev);
417
+ }
418
+
419
+ }
420
+
421
+ // Connected
422
+ this.isConnected = true;
423
+
424
+ } catch(error) {
425
+ if ( this.ws ) {
426
+ this.ws.close();
427
+ this.ws = null;
428
+ }
429
+ if ( isTraceConnection ) {
430
+ utils.trace('Failed to connect to "' + endpoint + "'." );
431
+ }
432
+ connectionErrorLog.push( 'Failed to connect to "' + endpoint + "'." );
433
+ }
434
+
435
+ } else if ( url && (url.protocol === 'http:' || url.protocol === 'https:' ) ) {
436
+
437
+ // Check connect with `hello` request
438
+ try {
439
+ const urlHello = new URL(url);
440
+ urlHello.pathname += (urlHello.pathname.endsWith("/") ? "" : "/") + "hello";
441
+ const request = {
442
+ method: "POST",
443
+ headers: {
444
+ "Content-Type": "application/json"
445
+ }
446
+ };
447
+ const response = await fetch(urlHello, request);
448
+ const text = await response.text();
449
+
450
+ if ( !text.startsWith("HeadTTS") ) {
451
+ throw new Error("Invalid response.");
452
+ }
453
+
454
+ // Connected
455
+ this.rest = endpoint;
456
+ this.isConnected = true;
457
+
458
+ } catch(error) {
459
+ console.log(error);
460
+ if ( isTraceMessages ) {
461
+ utils.trace( 'The request hello failed on "' + endpoint + '".' );
462
+ }
463
+ connectionErrorLog.push( 'The request hello failed on "' + endpoint + '".' );
464
+ }
465
+ }
466
+ }
467
+
468
+ }
469
+
470
+ this.isConnecting = false;
471
+
472
+ if ( this.isConnected ) {
473
+
474
+ // Process queue
475
+ this.processIn(onerror);
476
+
477
+ } else {
478
+
479
+ // Report error
480
+ let msg = "HeadTTS connection failed: " + connectionErrorLog.join("\n");
481
+ this.emit("error", new Error(msg), events, true );
482
+
483
+ }
484
+ }
485
+
486
+ /**
487
+ * Clear IN and OUT work queues.
488
+ */
489
+ clear() {
490
+
491
+ // Clear item
492
+ const clearItem = (x) => {
493
+ const message = {
494
+ type: "error",
495
+ ref: x.message?.ref || x.message?.id,
496
+ data: {
497
+ error: "Cancelled, clear method called."
498
+ }
499
+ };
500
+ this.emit("message", message, [x.onmessage, this.onmessage]);
501
+ x.deferred.resolve(message);
502
+ }
503
+
504
+ // Clear IN queue
505
+ while( this.queueIn.length ) {
506
+ const item = this.queueIn[0];
507
+ this.queueIn.shift();
508
+ clearItem(item);
509
+ }
510
+
511
+ // Clear OUT queue
512
+ while( this.queueOut.length ) {
513
+ const item = this.queueOut[0];
514
+ this.queueOut.shift();
515
+ this.items.delete( item.message.id );
516
+ clearItem(item);
517
+ }
518
+
519
+ }
520
+
521
+
522
+ /**
523
+ * Processes a single "setup" request and adds a new item to the IN work queue.
524
+ *
525
+ * @param {Object} data Setup request message
526
+ * @param {function} [onerror=null] Callback for Error events overriding event handler
527
+ */
528
+ async setup( data, onerror=null ) {
529
+ const isTraceMessages = this.settings.trace & utils.traceMask.messages;
530
+ if ( isTraceMessages ) {
531
+ utils.trace( "SETUP: APP -> HeadTTS, data=",data);
532
+ }
533
+
534
+ // Check data item
535
+ const events = [onerror, this.onerror];
536
+ if ( !data ) this.emit("error", new Error("Data not set."), events, true );
537
+ if ( data.hasOwnProperty("voice") ) {
538
+ if ( typeof data.voice !== 'string' ) {
539
+ this.emit("error", new Error("Voice is not a string."), events, true );
540
+ return;
541
+ }
542
+ }
543
+ if ( data.hasOwnProperty("language") ) {
544
+ if ( typeof data.language !== 'string' ) {
545
+ this.emit("error", new Error("Language is not a string."), events, true );
546
+ return;
547
+ }
548
+ }
549
+ if ( data.hasOwnProperty("speed") ) {
550
+ if ( data.speed < 0.25 || data.speed > 4 ) {
551
+ this.emit("error", new Error("Invalid speed, must be between [0.25,4]."), events, true );
552
+ return;
553
+ }
554
+ }
555
+ if ( data.hasOwnProperty("audioEncoding") ) {
556
+ if ( data.audioEncoding !== 'wav' && data.audioEncoding !== 'pcm' ) {
557
+ this.emit("error", new Error("Unsupported audioEncoding, must be 'wav' or 'pcm'."), events, true );
558
+ return;
559
+ }
560
+ }
561
+
562
+ // New setup item
563
+ const item = {
564
+ message: {
565
+ type: "setup",
566
+ id: this.messageId++,
567
+ data: data
568
+ },
569
+ status: 0,
570
+ onmessage: null,
571
+ onerror: onerror,
572
+ started: performance.now(),
573
+ deferred: new utils.Deferred()
574
+ };
575
+ this.queueIn.push(item);
576
+
577
+ // Process
578
+ this.processIn(onerror);
579
+
580
+ // Return the promise of the setup request
581
+ return item.deferred.promise;
582
+ }
583
+
584
+ /**
585
+ * Processes a single "synthesize" request, breaks it up into one
586
+ * or more messages/items, and adds each items to the IN work queue.
587
+ *
588
+ * @param {Object} data Synthesize request message
589
+ * @param {function} [onmessage=null] Callback for audio messages overriding event handler
590
+ * @param {function} [onerror=null] Callback for Error events overriding event handler
591
+ * @return {Promise} Promise for the synthesize request that resolves with an array or audio messages.
592
+ */
593
+ async synthesize(data, onmessage=null, onerror=null) {
594
+ if ( this.settings.traceLevel ) {
595
+ utils.trace( this.settings.traceLevel, 3, "SYNTHESIZE: APP -> HeadTTS, data=",data);
596
+ }
597
+
598
+ // Check data item
599
+ const events = [onerror, this.onerror];
600
+ if ( !data ) this.emit("error", new Error("Data not set."), events, true );
601
+ if ( !data.hasOwnProperty("input") ) {
602
+ this.emit("error", new Error("Input property not set."), events, true );
603
+ return;
604
+ }
605
+ if ( typeof data.input !== 'string' && !Array.isArray(data.input) ) {
606
+ this.emit("error", new Error("Invalid input type."), events, true );
607
+ return;
608
+ }
609
+
610
+ // Setup input items
611
+ let inputItems;
612
+ if ( typeof data.input === 'string' ) {
613
+ inputItems = [ { type: "text", value: data.input } ];
614
+ } else {
615
+ inputItems = data.input.map( x => (typeof x === 'string' ? { type: "text", value: x } : x) );
616
+ }
617
+
618
+ // Generated messages
619
+ const messages = [];
620
+ const addMessage = (input) => {
621
+ const message = {
622
+ type: "synthesize",
623
+ id: this.messageId++,
624
+ data: { input }
625
+ };
626
+ if ( data.voice || this.rest ) {
627
+ message.data.voice = data.voice || this.ttsSetup.voice;
628
+ }
629
+ if ( data.language || this.rest ) {
630
+ message.data.language = data.language || this.ttsSetup.language;
631
+ }
632
+ if ( data.speed || this.rest ) {
633
+ message.data.speed = data.speed || this.ttsSetup.speed;
634
+ }
635
+ if ( data.audioEncoding || this.rest ) {
636
+ message.data.audioEncoding = data.audioEncoding || this.ttsSetup.audioEncoding;
637
+ }
638
+ messages.push(message);
639
+ }
640
+
641
+ // Process input items
642
+ const len = inputItems.length;
643
+ let outputItems = [];
644
+ let outputTextLen = 0;
645
+ for( let i=0; i<len; i++ ) {
646
+ const item = inputItems[i];
647
+
648
+ // Chech input item
649
+ if ( !item.hasOwnProperty("type") ) {
650
+ this.emit("error", new Error("Input item has no type."), events, true );
651
+ return;
652
+ }
653
+ if ( !item.hasOwnProperty("value") ) {
654
+ this.emit("error", new Error("Input item has no value."), events, true );
655
+ return;
656
+ }
657
+ if ( item.hasOwnProperty("subtitles") && typeof item.subtitles !== "string" ) {
658
+ this.emit("error", new Error("Subtitles must be a string, if set for an input item."), events, true );
659
+ return;
660
+ }
661
+
662
+ switch( item.type ) {
663
+
664
+ case "text":
665
+ const parts = this.divideToParts( item.value, outputTextLen );
666
+ const partsLen = parts.length;
667
+ for( let j=0; j<partsLen-1; j++ ) {
668
+ const part = parts[j];
669
+ outputItems.push(part);
670
+ addMessage(outputItems);
671
+ outputItems = [];
672
+ }
673
+ outputItems.push(parts[ partsLen-1 ]);
674
+ outputTextLen = parts[ partsLen-1 ];
675
+ break;
676
+
677
+ case "speech":
678
+ case "phonetic":
679
+ case "characters":
680
+ case "number":
681
+ if ( typeof item.value !== 'string' ) {
682
+ this.emit("error", new Error('Input item of type "' + item.type + '" must have a non-empty string value.'), events, true );
683
+ return;
684
+ }
685
+
686
+ if ( (outputTextLen + item.value.length) >= this.settings.splitLength ) {
687
+ addMessage(outputItems);
688
+ outputItems = [ item ];
689
+ outputTextLen = item.value.length;
690
+ } else {
691
+ outputItems.push(item);
692
+ outputTextLen += item.value.length;
693
+ }
694
+ break;
695
+
696
+ case "date":
697
+ case "time":
698
+ case "break":
699
+ if ( Number.isNaN(item.value) || item.value < 0 ) {
700
+ this.emit("error", new Error('Input item of type "' + item.type + '" must have a valid number value.'), events, true );
701
+ return;
702
+ }
703
+ outputItems.push(item);
704
+ outputTextLen += 10;
705
+ break;
706
+
707
+ default:
708
+ this.emit("error", new Error('Unknown item type: "' + item.type + '".'), events, true );
709
+ return;
710
+ }
711
+
712
+
713
+ }
714
+
715
+ // Add the remaining part
716
+ if ( outputItems.length ) {
717
+ addMessage(outputItems);
718
+ }
719
+
720
+ // Add items to queue in order
721
+ const deferredPromises = [];
722
+ for( let i=0; i<messages.length; i++ ) {
723
+ const message = messages[i];
724
+ const item = {
725
+ message: message,
726
+ status: 0,
727
+ onmessage: onmessage,
728
+ onerror: onerror,
729
+ started: performance.now(),
730
+ deferred: new utils.Deferred(),
731
+ metadata: {
732
+ part: i,
733
+ partsTotal: messages.length
734
+ }
735
+ };
736
+ deferredPromises.push( item.deferred.promise );
737
+ this.queueIn.push(item);
738
+ }
739
+
740
+ // Process
741
+ this.processIn(onerror);
742
+
743
+ // Return the promises of all synthesize messages
744
+ return Promise.all(deferredPromises);
745
+ }
746
+
747
+ /**
748
+ * Processes the IN work queue (fifo), sends the requests, and adds
749
+ * the items to the OUT work queue to wait for responses.
750
+ *
751
+ * @param {function} [onerror=null] Callback for Error events overriding event handler.
752
+ */
753
+ async processIn( onerror=null ) {
754
+ const isTraceMessages = this.settings.trace & utils.traceMask.messages;
755
+ if ( this.isProcessingIn ) return; // Already processing
756
+ if ( this.isConnecting ) return; // Still connecting
757
+ if ( !this.isConnected ) { // Not connected
758
+ this.connect(onerror);
759
+ return;
760
+ }
761
+
762
+ this.isProcessingIn = true;
763
+ while( this.queueIn.length ) {
764
+ const item = this.queueIn[0];
765
+ this.queueIn.shift();
766
+
767
+ if ( item.message.type === "setup" ) {
768
+
769
+ // Setup
770
+ Object.assign( this.ttsSetup, item.message.data );
771
+ if ( this.ws ) {
772
+ if ( isTraceMessages ) {
773
+ utils.trace( "OUT: HeadTTS -> WebSocket, message=", item.message);
774
+ }
775
+ this.ws.send( JSON.stringify( item.message) );
776
+ }
777
+ item.deferred.resolve();
778
+
779
+ } else {
780
+
781
+ // Add to output queue to wait for response
782
+ this.items.set( item.message.id, item );
783
+ this.queueOut.push(item);
784
+
785
+
786
+ // Emit event, if out queue was empty
787
+ if ( this.queueOut.length === 1 ) {
788
+ this.emit("start", null, [this.onstart]);
789
+ }
790
+
791
+ // Send item
792
+ if ( this.ws ) {
793
+ if ( isTraceMessages ) {
794
+ utils.trace( "OUT: HeadTTS -> WebSocket, message=", item.message);
795
+ }
796
+ this.ws.send( JSON.stringify( item.message) );
797
+ } else if ( this.ww ) {
798
+ if ( isTraceMessages ) {
799
+ utils.trace( "OUT: HeadTTS -> worker, message=", item.message);
800
+ }
801
+
802
+ // Set default values
803
+ if ( item.message.type === "synthesize" ) {
804
+ item.message.data.voice = this.ttsSetup.voice.slice();
805
+ item.message.data.language = this.ttsSetup.language.slice();
806
+ item.message.data.speed = this.ttsSetup.speed;
807
+ item.message.data.audioEncoding = this.ttsSetup.audioEncoding.slice();
808
+ }
809
+
810
+ this.ww.postMessage( item.message );
811
+ } else if ( this.rest ) {
812
+
813
+ if ( item.message.type === "synthesize" ) {
814
+
815
+ const url = new URL(this.rest);
816
+ url.pathname += (url.pathname.endsWith("/") ? "" : "/") + "synthesize";
817
+
818
+ const request = {
819
+ method: "POST",
820
+ headers: {
821
+ "Content-Type": "application/json"
822
+ },
823
+ body: JSON.stringify(item.message.data)
824
+ };
825
+
826
+ if ( isTraceMessages ) {
827
+ utils.trace( "OUT: HeadTTS -> REST, message=", item.message.data);
828
+ }
829
+
830
+ fetch(url, request)
831
+ .then(response => {
832
+ if (!response.ok) {
833
+ throw new Error('Network response was not ok');
834
+ }
835
+ return response.json();
836
+ })
837
+ .then(data => {
838
+ this.processData({
839
+ type: "audio",
840
+ ref: item.message.id,
841
+ data: data
842
+ });
843
+ })
844
+ .catch(error => {
845
+ console.error("HeadTTS: REST error, error=", error);
846
+ this.processData({
847
+ type: "error",
848
+ ref: item.id,
849
+ data: {
850
+ error: "HeadTTS: REST error, message=" + error.message
851
+ }
852
+ });
853
+ });
854
+ }
855
+
856
+ }
857
+ }
858
+ }
859
+ this.isProcessingIn = false;
860
+ }
861
+
862
+ /**
863
+ * Processes a single incoming response and updates the status and values
864
+ * of the corresponding item on the OUT work queue.
865
+ *
866
+ * @param {Object|string|ArrayBuffer} data Response message.
867
+ */
868
+ async processData(data) {
869
+ if ( data instanceof ArrayBuffer) {
870
+ if ( this.itemWaitingForAudio ) {
871
+ const item = this.itemWaitingForAudio;
872
+ const itemdata = item.message?.data;
873
+ if ( itemdata ) {
874
+ if ( itemdata.audioEncoding === "wav" ) {
875
+ itemdata.audio = await this.settings.audioCtx.decodeAudioData( data );
876
+ }
877
+ }
878
+ item.status = 2;
879
+ }
880
+ } else {
881
+ let o;
882
+ if ( typeof data === 'string') {
883
+ try {
884
+ o = JSON.parse(data);
885
+ } catch(error) {
886
+ console.log("HeadTTS: Data was not a JSON string.");
887
+ }
888
+ } else {
889
+ o = data;
890
+ }
891
+ if ( typeof o === 'object' ) {
892
+ if ( o.type === "error" ) {
893
+ const item = this.items.get( o.ref );
894
+ if ( item ) {
895
+ item.message = o;
896
+ item.status = 2;
897
+ } else {
898
+ console.log("HeadTTS: Item not found, ref=", o.ref);
899
+ }
900
+ } else if ( o.type === 'audio' ) {
901
+ const item = this.items.get( o.ref );
902
+ if ( item ) {
903
+ item.message = o;
904
+ if ( item.message.data ) {
905
+ const itemdata = item.message.data;
906
+ if ( itemdata.audio ) {
907
+ if ( typeof itemdata.audio === "string" ) {
908
+ itemdata.audio = utils.b64ToArrayBuffer(itemdata.audio);
909
+ }
910
+ if ( itemdata.audioEncoding === "wav" ) {
911
+ itemdata.audio = await this.settings.audioCtx.decodeAudioData( itemdata.audio );
912
+ }
913
+ item.status = 2;
914
+ } else {
915
+ this.itemWaitingForAudio = item;
916
+ item.status = 1;
917
+ }
918
+ } else {
919
+ item.status = 2;
920
+ }
921
+ } else {
922
+ console.log("HeadTTS: Item not found, ref=", o.ref);
923
+ }
924
+ } else if ( o.type === "progress" ) {
925
+ console.log("HeadTTS: Progress message.");
926
+ } else if ( o.type === "ready" ) {
927
+ console.log("HeadTTS: Ready message.");
928
+ } else {
929
+ console.error("HeadTTS: Unknown data type.");
930
+ }
931
+ } else {
932
+ console.log("HeadTTS: Unknown data format.");
933
+ }
934
+ }
935
+ this.processOut();
936
+ }
937
+
938
+ /**
939
+ * Processes the OUT work queue (fifo), sends the responses to the app by
940
+ * emitting onmessage events.
941
+ */
942
+ async processOut() {
943
+ if ( this.isProcessingOut ) return; // Already processing
944
+
945
+ this.isProcessingOut = true;
946
+ while( this.queueOut.length ) {
947
+ const item = this.queueOut[0];
948
+ if ( item.status < 2 ) break; // First item not yet ready
949
+ this.queueOut.shift();
950
+ this.items.delete( item.message.id );
951
+
952
+ const message = item.message;
953
+ Object.assign(message.data, item.metadata || {});
954
+ const type = message.type;
955
+
956
+ if ( type === "audio" ) {
957
+ this.emit("message", message, [item.onmessage, this.onmessage] );
958
+ item.deferred.resolve(message);
959
+ } else if ( type === "error" ) {
960
+ console.error("HeadTTS: Error, item=",item);
961
+ this.emit("error", message, [item.onmessage, this.onmessage] );
962
+ item.deferred.resolve(message);
963
+ }
964
+
965
+ // Emit event
966
+ if ( this.queueOut.length === 0 && this.queueIn.length === 0 ) {
967
+ this.emit("end",null,[this.onend]);
968
+ }
969
+ }
970
+ this.isProcessingOut = false;
971
+ }
972
+
973
+ }
974
+
975
+ export { HeadTTS };