markdown-up 5.2.1 → 5.3.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.
package/lib/voice.js ADDED
@@ -0,0 +1,813 @@
1
+ // Licensed under the MIT License
2
+ // https://github.com/craigahobbs/markdown-up/blob/main/LICENSE
3
+
4
+ // The MarkdownUp voice playback - text read aloud with PicoVox speech synthesis and Web Audio. The playback's text may
5
+ // grow as it plays (e.g., a response that's still generating): the text's last sentence is held back until the text is
6
+ // final, and if playback reaches the end of the text before it's final, it pauses. Apart from the playback, there are
7
+ // the voice lines - text said aloud in a voice and a speaking style (e.g., a film's dialogue), each over any others.
8
+
9
+ import {speechText, splitSentences} from 'picovox/lib/sentences.js';
10
+
11
+
12
+ // The voice playback sample rate (Hz) - PicoVox's own. The audio context runs at it, so the blocks join exactly.
13
+ const voiceSampleRate = 24000;
14
+
15
+
16
+ // The playback timing (s) - how far ahead of the audio context's time a block starts, and how far ahead of playback
17
+ // synthesis runs
18
+ const playbackLead = 0.05;
19
+ const playbackAhead = 4;
20
+
21
+
22
+ // The noise seed of the text's first sentence (sentence i is rendered with seed + i)
23
+ const playbackSeed = 1000;
24
+
25
+
26
+ // Skip back goes to the previous section within this many seconds of a section's start (otherwise, to the section's start)
27
+ const skipBackSeconds = 2;
28
+
29
+
30
+ // How long a voice line waits for its audio context to run (ms) - a line that can't be heard (the browser hasn't let the
31
+ // audio start) is dropped
32
+ const lineStartMs = 250;
33
+
34
+
35
+ // The voice playback speaking rates
36
+ export const voiceRates = [0.8, 1, 1.1, 1.2, 1.5];
37
+
38
+
39
+ // The default speaking style
40
+ const voiceDefaultStyle = 'neutral';
41
+
42
+
43
+ // The default male voice (the default voice) and the default female voice
44
+ const voiceDefaultMale = 'michael';
45
+ const voiceDefaultFemale = 'sarah';
46
+
47
+
48
+ // The voice label overrides - PicoVox's "male" and "female" voices are named
49
+ const voiceLabels = {'male': 'John', 'female': 'Mary'};
50
+
51
+
52
+ // The element model HTML tags that continue a paragraph's text
53
+ const inlineTags = new Set([
54
+ 'a', 'abbr', 'b', 'bdi', 'bdo', 'cite', 'code', 'del', 'dfn', 'em', 'font', 'i', 'ins', 'kbd', 'label', 'mark', 'q', 's',
55
+ 'samp', 'small', 'span', 'strong', 'sub', 'sup', 'u', 'var'
56
+ ]);
57
+
58
+
59
+ // The element model HTML tags that aren't read aloud - code blocks, images, and controls
60
+ const skipTags = new Set([
61
+ 'audio', 'button', 'canvas', 'iframe', 'img', 'input', 'object', 'option', 'pre', 'script', 'select', 'style', 'textarea',
62
+ 'video'
63
+ ]);
64
+
65
+
66
+ // The element model HTML tags whose headers don't start a section
67
+ const nestedTags = new Set(['blockquote', 'li', 'td', 'th']);
68
+
69
+
70
+ // Matches a header tag
71
+ const rHeaderTag = /^h[1-6]$/;
72
+
73
+
74
+ // Matches text with something to read aloud - PicoVox speaks English text
75
+ const rSpeakable = /[A-Za-z0-9]/;
76
+
77
+
78
+ // Matches text that ends with punctuation (closing quotes and parentheses allowed)
79
+ const rTextEnd = /[.!?:;,]["')”’]*$/;
80
+
81
+
82
+ /**
83
+ * A paragraph of text to read aloud
84
+ *
85
+ * @typedef {Object} VoiceParagraph
86
+ * @property {string} text - The paragraph's text
87
+ * @property {boolean} section - If true, the paragraph starts a section (it's a top-level header)
88
+ *
89
+ * @ignore
90
+ */
91
+
92
+
93
+ /**
94
+ * Get an element model's paragraphs to read aloud. Code blocks, images, graphics, and controls are skipped. Each table
95
+ * row is a paragraph of its cells' texts as sentences. A header that isn't within a list, a block quote, or a table
96
+ * starts a section.
97
+ *
98
+ * @param {?(Object|Array)} elements - The element model
99
+ * @param {boolean} [skipNavigation = false] - If true, skip the paragraphs above the first section whose text is all
100
+ * links (e.g., a page's navigation links)
101
+ * @returns {Object[]} The array of [paragraphs]{@link module:lib/voice~VoiceParagraph}
102
+ *
103
+ * @ignore
104
+ */
105
+ export function voiceElementsParagraphs(elements, skipNavigation = false) {
106
+ const state = {'paragraphs': [], 'parts': [], 'linkOnly': true, 'section': false};
107
+ elementsParagraphs(state, elements, false, false);
108
+ paragraphEnd(state);
109
+
110
+ // Skip the link-only paragraphs above the first section?
111
+ const {paragraphs} = state;
112
+ const ixSection = (skipNavigation ? paragraphs.findIndex((paragraph) => paragraph.section) : -1);
113
+ return paragraphs.
114
+ filter((paragraph, ixParagraph) => !(ixParagraph < ixSection && paragraph.linkOnly)).
115
+ map(({text, section}) => ({text, section}));
116
+ }
117
+
118
+
119
+ // Helper to add an element model's text to its paragraphs
120
+ function elementsParagraphs(state, elements, inLink, nested) {
121
+ // Ignore non-objects
122
+ if (elements === null || typeof elements !== 'object') {
123
+ return;
124
+ }
125
+
126
+ // Array?
127
+ if (Array.isArray(elements)) {
128
+ for (const childElements of elements) {
129
+ elementsParagraphs(state, childElements, inLink, nested);
130
+ }
131
+ return;
132
+ }
133
+
134
+ // Text?
135
+ if ('text' in elements) {
136
+ const text = String(elements.text);
137
+ state.parts.push(text);
138
+ if (!inLink && rSpeakable.test(text)) {
139
+ state.linkOnly = false;
140
+ }
141
+ return;
142
+ }
143
+
144
+ // Graphics (and anything else that isn't HTML) aren't read aloud
145
+ if (typeof elements.html !== 'string') {
146
+ return;
147
+ }
148
+ const tag = elements.html.toLowerCase();
149
+ const elem = elements.elem ?? null;
150
+ const href = (elements.attr ?? null) !== null ? (elements.attr.href ?? null) : null;
151
+
152
+ // Code blocks, images, controls, and link buttons (links without a URL) aren't read aloud
153
+ if (skipTags.has(tag) || (tag === 'a' && href === null)) {
154
+ return;
155
+ }
156
+
157
+ // A line break is a space
158
+ if (tag === 'br') {
159
+ state.parts.push(' ');
160
+ return;
161
+ }
162
+
163
+ // Inline elements continue the paragraph
164
+ if (inlineTags.has(tag)) {
165
+ elementsParagraphs(state, elem, inLink || tag === 'a', nested);
166
+ return;
167
+ }
168
+
169
+ // A table cell is a sentence of its row's paragraph
170
+ if (tag === 'td' || tag === 'th') {
171
+ const ixCell = state.parts.length;
172
+ elementsParagraphs(state, elem, inLink, true);
173
+ const cellText = state.parts.slice(ixCell).join('').trim();
174
+ if (cellText !== '') {
175
+ state.parts.push(rTextEnd.test(cellText) ? ' ' : '. ');
176
+ }
177
+ return;
178
+ }
179
+
180
+ // Any other element is a paragraph (or contains paragraphs) - a top-level header starts a section
181
+ paragraphEnd(state);
182
+ elementsParagraphs(state, elem, inLink, nested || nestedTags.has(tag));
183
+ state.section = !nested && rHeaderTag.test(tag);
184
+ paragraphEnd(state);
185
+ }
186
+
187
+
188
+ // Helper to end the paragraph being added, if any
189
+ function paragraphEnd(state) {
190
+ const text = state.parts.join('').replace(/\s+/g, ' ').trim();
191
+ if (rSpeakable.test(text)) {
192
+ state.paragraphs.push({text, 'section': state.section, 'linkOnly': state.linkOnly});
193
+ }
194
+ state.parts = [];
195
+ state.linkOnly = true;
196
+ state.section = false;
197
+ }
198
+
199
+
200
+ // Load PicoVox - its synthesis module and its models - on first use
201
+ async function loadPicovox() {
202
+ const synthesis = await import('picovox/lib/synthesis.js');
203
+ const loadModel = synthesis.modelLoader(
204
+ () => import('picovox/lib/models/g2pModel.js'),
205
+ () => import('picovox/lib/models/voiceModel.js')
206
+ );
207
+ const model = await loadModel();
208
+ return {
209
+ 'voices': synthesis.voiceTable.map(({key, label, sex}) => ({key, label, sex})),
210
+ 'styles': synthesis.styleTable.map(({key}) => key),
211
+ 'paragraphPause': synthesis.paragraphPause,
212
+ 'sentencePause': synthesis.sentencePause,
213
+ 'sentenceBlocks': (text, options) => synthesis.sentenceBlocks(model, text, options)
214
+ };
215
+ }
216
+
217
+
218
+ // Get the voices in the playback's order - male and female interleaved, the default male voice first (the default
219
+ // voice), then the default female voice
220
+ function voicesInterleaved(voices) {
221
+ // Split the voices by sex, each with its default voice first
222
+ const defaults = [voiceDefaultMale, voiceDefaultFemale];
223
+ const ordered = [
224
+ ...defaults.flatMap((voiceKey) => voices.filter(({key}) => key === voiceKey)),
225
+ ...voices.filter(({key}) => !defaults.includes(key))
226
+ ];
227
+ const females = ordered.filter(({sex}) => sex === 'female');
228
+ const males = ordered.filter(({sex}) => sex !== 'female');
229
+
230
+ // Interleave the male and female voices
231
+ const interleaved = [];
232
+ for (let ixVoice = 0; ixVoice < males.length || ixVoice < females.length; ixVoice++) {
233
+ interleaved.push(...males.slice(ixVoice, ixVoice + 1), ...females.slice(ixVoice, ixVoice + 1));
234
+ }
235
+ return interleaved;
236
+ }
237
+
238
+
239
+ // The paragraphs' sentences to speak - until the text is final, its last sentence may be incomplete, so it's held back
240
+ function playbackSentences(paragraphs, final) {
241
+ const sentences = [];
242
+ for (const paragraph of paragraphs) {
243
+ let sectionStart = paragraph.section;
244
+ for (const {text, paragraphStart} of splitSentences(paragraph.text)) {
245
+ sentences.push({text, paragraphStart, sectionStart});
246
+ sectionStart = false;
247
+ }
248
+ }
249
+ return final ? sentences : sentences.slice(0, -1);
250
+ }
251
+
252
+
253
+ // The pause before a sentence (s) - none before the first sentence played, so that speech starts at once
254
+ function sentencePause(picovox, sentence, isFirst) {
255
+ if (isFirst) {
256
+ return 0;
257
+ }
258
+ return sentence.paragraphStart ? picovox.paragraphPause : picovox.sentencePause;
259
+ }
260
+
261
+
262
+ // A sentence's words, for comparing sentences - a sentence's punctuation may change as its text grows (e.g., Markdown
263
+ // emphasis spanning sentences is literal until it's closed)
264
+ function sentenceWords(sentence) {
265
+ return sentence.text.replace(/[^\p{L}\p{N}]+/gu, '');
266
+ }
267
+
268
+
269
+ // The sentence indexes that skip back and skip forward move to - the sections' first sentences (the text's first
270
+ // sentence starts one) or, if the text isn't in sections, the paragraphs' first sentences
271
+ function skipStarts(sentences) {
272
+ const sectionStarts = sentences.flatMap(({sectionStart}, ixSentence) => (ixSentence === 0 || sectionStart ? [ixSentence] : []));
273
+ if (sectionStarts.length > 1) {
274
+ return sectionStarts;
275
+ }
276
+ return sentences.flatMap(({paragraphStart}, ixSentence) => (paragraphStart ? [ixSentence] : []));
277
+ }
278
+
279
+
280
+ // The next task - a promise resolved by a message to the page itself (a timer would be throttled in background tabs)
281
+ function nextTask() {
282
+ return new Promise((resolve) => {
283
+ const channel = new MessageChannel();
284
+ channel.port1.onmessage = () => {
285
+ channel.port1.close();
286
+ resolve();
287
+ };
288
+ channel.port2.postMessage(null);
289
+ });
290
+ }
291
+
292
+
293
+ // Wait for a run's event - a scheduled block ending, the text changing, or the run stopping
294
+ function runWait(run) {
295
+ return new Promise((resolve) => {
296
+ run.waiting.push(resolve);
297
+ });
298
+ }
299
+
300
+
301
+ // Wake a run's waiters
302
+ function runWake(run) {
303
+ for (const resolve of run.waiting.splice(0)) {
304
+ resolve();
305
+ }
306
+ }
307
+
308
+
309
+ /**
310
+ * The MarkdownUp voice playback - at most one playback at a time
311
+ *
312
+ * @property {Object} window - The web browser window object
313
+ * @property {function} onChange - The playback change callback, called when the playback's state changes
314
+ * @property {?string} voice - The preferred voice key (null is the default voice)
315
+ * @property {number} rate - The speaking rate, from 0.5 to 2 (1 is normal)
316
+ *
317
+ * @ignore
318
+ */
319
+ export class MarkdownUpVoice {
320
+ /**
321
+ * @param {Object} window - The web browser window object
322
+ * @param {function} onChange - The playback change callback, called when the playback's state changes
323
+ */
324
+ constructor(window, onChange) {
325
+ this.window = window;
326
+ this.onChange = onChange;
327
+ this.voice = null;
328
+ this.rate = 1;
329
+
330
+ // PicoVox, loaded on first use - {voices, styles, paragraphPause, sentencePause, sentenceBlocks}
331
+ this.loadFn = loadPicovox;
332
+ this.loading = null;
333
+ this.picovox = null;
334
+ this.voicesOrdered = null;
335
+
336
+ // The audio context, created on first playback (from a user gesture, so the browser lets the audio start)
337
+ this.audioContext = null;
338
+
339
+ // The playback, if any - {key, final, sentences, position (the sentence index to play from), playing,
340
+ // run (the active synthesis run, or null)}
341
+ this.playback = null;
342
+
343
+ // The voice lines that are playing - each {sources, done, stopped} - and their audio context (the playback's is
344
+ // suspended when the playback is paused), created on first use
345
+ this.lines = new Set();
346
+ this.lineAudioContext = null;
347
+ }
348
+
349
+
350
+ // Load PicoVox, once - a failed load is retried on the next call
351
+ load() {
352
+ if (this.loading === null) {
353
+ this.loading = this.loadFn().then((picovox) => {
354
+ this.picovox = picovox;
355
+ this.voicesOrdered = voicesInterleaved(picovox.voices);
356
+ this.onChange();
357
+ return picovox;
358
+ });
359
+ this.loading.catch(() => {
360
+ this.loading = null;
361
+ });
362
+ }
363
+ return this.loading;
364
+ }
365
+
366
+
367
+ // Get the playback's voice key - the preferred voice, if it's a voice (it's unknown until PicoVox loads)
368
+ voiceKey() {
369
+ const {voice, voicesOrdered} = this;
370
+ if (voicesOrdered === null) {
371
+ return voice ?? voiceDefaultMale;
372
+ }
373
+ return (voicesOrdered.find(({key}) => key === voice) ?? voicesOrdered[0]).key;
374
+ }
375
+
376
+
377
+ // Get the playback's voice label
378
+ voiceLabel() {
379
+ const voiceKey = this.voiceKey();
380
+ const voiceInfo = (this.voicesOrdered ?? []).find(({key}) => key === voiceKey) ?? null;
381
+ const voiceLabel = (voiceInfo !== null ? voiceInfo.label : `${voiceKey.slice(0, 1).toUpperCase()}${voiceKey.slice(1)}`);
382
+ return voiceLabels[voiceKey] ?? voiceLabel;
383
+ }
384
+
385
+
386
+ // Get the voice key after the playback's voice (wraps to the first voice) - null until PicoVox loads
387
+ voiceNext() {
388
+ const {voicesOrdered} = this;
389
+ if (voicesOrdered === null) {
390
+ return null;
391
+ }
392
+ const voiceKey = this.voiceKey();
393
+ const ixVoice = voicesOrdered.findIndex(({key}) => key === voiceKey);
394
+ return voicesOrdered[(ixVoice + 1) % voicesOrdered.length].key;
395
+ }
396
+
397
+
398
+ // Get the speaking rate after the playback's rate (wraps to the first rate)
399
+ rateNext() {
400
+ return voiceRates[(voiceRates.indexOf(this.rate) + 1) % voiceRates.length];
401
+ }
402
+
403
+
404
+ // Get the playback state - {key, playing} - or null if there's no playback
405
+ state() {
406
+ const {playback} = this;
407
+ return playback !== null ? {'key': playback.key, 'playing': playback.playing} : null;
408
+ }
409
+
410
+
411
+ // Start reading paragraphs aloud (from a user gesture, so the browser lets the audio start), closing any playback
412
+ speak(paragraphs, final, key) {
413
+ this.runStop();
414
+ if (this.audioContext === null) {
415
+ this.audioContext = new this.window.AudioContext({'sampleRate': voiceSampleRate});
416
+ }
417
+ this.audioContext.resume();
418
+ this.playback = {key, final, 'sentences': playbackSentences(paragraphs, final), 'position': 0, 'playing': true, 'run': null};
419
+ this.runStart();
420
+ this.onChange();
421
+ }
422
+
423
+
424
+ // Set the playback's paragraphs - its text grows as it plays (if the words that have already played change, the
425
+ // playback starts again from the beginning)
426
+ setText(paragraphs, final) {
427
+ const {playback} = this;
428
+ if (playback === null) {
429
+ return;
430
+ }
431
+
432
+ // Has the text that's already played changed? Has the text that's scheduled to play?
433
+ const {run} = playback;
434
+ const sentences = playbackSentences(paragraphs, final);
435
+ const ixSentence = this.playbackSentence();
436
+ const isChanged = (ix) => ix >= sentences.length || sentenceWords(sentences[ix]) !== sentenceWords(playback.sentences[ix]);
437
+ let playedChanged = false;
438
+ for (let ix = 0; ix < ixSentence && !playedChanged; ix++) {
439
+ playedChanged = isChanged(ix);
440
+ }
441
+ const scheduledChanged = run !== null && run.starts.some(([ixStarted]) => ixStarted >= ixSentence && isChanged(ixStarted));
442
+
443
+ // Update the text - if the text that's already played changed, start again from the beginning; if the text
444
+ // that's scheduled to play changed, continue from the sentence that's playing
445
+ playback.final = final;
446
+ playback.sentences = sentences;
447
+ if (playedChanged) {
448
+ this.playbackSeek(0);
449
+ } else if (scheduledChanged) {
450
+ this.playbackSeek(ixSentence);
451
+ } else if (run !== null) {
452
+ runWake(run);
453
+ }
454
+ }
455
+
456
+
457
+ // Close the playback, if any
458
+ close() {
459
+ if (this.playback !== null) {
460
+ this.runStop();
461
+ this.playback = null;
462
+ this.audioContext.suspend();
463
+ this.onChange();
464
+ }
465
+ }
466
+
467
+
468
+ // Play (resume) the playback
469
+ play() {
470
+ const {playback} = this;
471
+ if (playback !== null && !playback.playing) {
472
+ playback.playing = true;
473
+ this.audioContext.resume();
474
+ if (playback.run === null) {
475
+ this.runStart();
476
+ }
477
+ this.onChange();
478
+ }
479
+ }
480
+
481
+
482
+ // Pause the playback
483
+ pause() {
484
+ const {playback} = this;
485
+ if (playback !== null && playback.playing) {
486
+ playback.playing = false;
487
+ this.audioContext.suspend();
488
+ this.onChange();
489
+ }
490
+ }
491
+
492
+
493
+ // Move the playback back to the beginning
494
+ rewind() {
495
+ if (this.playback !== null) {
496
+ this.playbackSeek(0);
497
+ }
498
+ }
499
+
500
+
501
+ // Move the playback back to the start of the section - or, near the section's start, to the start of the previous
502
+ // section
503
+ skipBack() {
504
+ const {playback} = this;
505
+ if (playback === null || playback.sentences.length === 0) {
506
+ return;
507
+ }
508
+ const {sentences, run} = playback;
509
+ const starts = skipStarts(sentences);
510
+ const ixSentence = this.playbackSentence();
511
+
512
+ // Past the end of the text? Back to the start of the last section.
513
+ if (ixSentence >= sentences.length) {
514
+ this.playbackSeek(starts[starts.length - 1]);
515
+ return;
516
+ }
517
+
518
+ // Near the start of the section? Back to the start of the previous section.
519
+ const ixStart = starts.findLastIndex((start) => start <= ixSentence);
520
+ const start = starts[ixStart];
521
+ const startTime = run !== null ? (run.starts.find(([ixStarted]) => ixStarted === start) ?? [])[1] : undefined;
522
+ const isNearStart = ixSentence === start &&
523
+ (startTime === undefined || this.audioContext.currentTime - startTime < skipBackSeconds);
524
+ this.playbackSeek(isNearStart && ixStart > 0 ? starts[ixStart - 1] : start);
525
+ }
526
+
527
+
528
+ // Move the playback forward to the start of the next section, if there is one
529
+ skipForward() {
530
+ const {playback} = this;
531
+ if (playback === null) {
532
+ return;
533
+ }
534
+ const ixSentence = this.playbackSentence();
535
+ const ixNext = skipStarts(playback.sentences).find((start) => start > ixSentence);
536
+ if (ixNext !== undefined) {
537
+ this.playbackSeek(ixNext);
538
+ }
539
+ }
540
+
541
+
542
+ // Set the voice - the playback, if any, continues with it
543
+ setVoice(voice) {
544
+ if (voice !== this.voice) {
545
+ this.voice = voice;
546
+ if (this.playback !== null) {
547
+ this.playbackSeek(this.playbackSentence());
548
+ }
549
+ this.onChange();
550
+ }
551
+ }
552
+
553
+
554
+ // Set the speaking rate - the playback, if any, continues at it
555
+ setRate(rate) {
556
+ if (rate !== this.rate) {
557
+ this.rate = rate;
558
+ if (this.playback !== null) {
559
+ this.playbackSeek(this.playbackSentence());
560
+ }
561
+ this.onChange();
562
+ }
563
+ }
564
+
565
+
566
+ // Get the voice lines' audio context, creating (and starting) it on first use. A browser may not let audio start
567
+ // until the user interacts with the page, so the context is resumed when they do.
568
+ lineContext() {
569
+ if (this.lineAudioContext === null) {
570
+ const audioContext = new this.window.AudioContext({'sampleRate': voiceSampleRate});
571
+ this.lineAudioContext = audioContext;
572
+ const resume = () => {
573
+ if (audioContext.state !== 'running') {
574
+ audioContext.resume();
575
+ }
576
+ };
577
+ resume();
578
+ for (const eventType of ['pointerdown', 'pointerup', 'keydown']) {
579
+ this.window.addEventListener(eventType, resume);
580
+ }
581
+ }
582
+ return this.lineAudioContext;
583
+ }
584
+
585
+
586
+ // Prepare for voice lines (and voice playback) - load PicoVox and start the voice lines' audio context - so that
587
+ // the first line starts at once
588
+ prepare() {
589
+ this.lineContext();
590
+ this.load().catch(() => null);
591
+ }
592
+
593
+
594
+ // Test whether voice lines can be heard - the browser has let their audio start
595
+ ready() {
596
+ return this.lineContext().state === 'running';
597
+ }
598
+
599
+
600
+ // Say a line of text aloud, over any other lines - in a voice (null is the default voice), a speaking style, and
601
+ // at a speaking rate. An unknown voice is the default voice and an unknown style is the default style.
602
+ say(text, voice, style, rate) {
603
+ const line = {'sources': new Set(), 'done': false, 'stopped': false};
604
+ this.lines.add(line);
605
+ this.linePlay(line, this.lineContext(), text, voice, style, rate).catch((error) => {
606
+ this.window.console.error(`MarkdownUp: Voice line failed: ${error}`);
607
+ }).then(() => {
608
+ // The line ends when its audio does
609
+ line.done = true;
610
+ if (line.sources.size === 0) {
611
+ this.lines.delete(line);
612
+ }
613
+ });
614
+ }
615
+
616
+
617
+ // Stop the voice lines
618
+ sayStop() {
619
+ for (const line of this.lines) {
620
+ line.stopped = true;
621
+ for (const source of line.sources) {
622
+ source.onended = null;
623
+ source.stop();
624
+ }
625
+ line.sources.clear();
626
+ }
627
+ this.lines.clear();
628
+ }
629
+
630
+
631
+ // Synthesize and schedule a voice line's sentences, a block at a time (yielding to the page after each)
632
+ async linePlay(line, audioContext, text, voice, style, rate) {
633
+ // Wait for the audio context to run - a line that can't be heard is dropped
634
+ const picovox = await this.load();
635
+ await Promise.race([
636
+ audioContext.resume(),
637
+ new Promise((resolve) => {
638
+ this.window.setTimeout(resolve, lineStartMs);
639
+ })
640
+ ]);
641
+ if (line.stopped || audioContext.state !== 'running') {
642
+ return;
643
+ }
644
+
645
+ // Synthesize and schedule the sentences' blocks
646
+ const {voicesOrdered} = this;
647
+ const blockOptions = {
648
+ 'voice': (voicesOrdered.find(({key}) => key === voice) ?? voicesOrdered[0]).key,
649
+ 'style': picovox.styles.includes(style) ? style : voiceDefaultStyle,
650
+ rate,
651
+ 'sampleRate': voiceSampleRate
652
+ };
653
+ let time = 0;
654
+ for (const [ixSentence, sentence] of splitSentences(text).entries()) {
655
+ blockOptions.seed = playbackSeed + ixSentence;
656
+ blockOptions.pause = sentencePause(picovox, sentence, ixSentence === 0);
657
+ for (const block of picovox.sentenceBlocks(speechText(sentence.text), {...blockOptions})) {
658
+ if (line.stopped) {
659
+ return;
660
+ }
661
+ const buffer = audioContext.createBuffer(1, block.length, voiceSampleRate);
662
+ buffer.copyToChannel(block, 0);
663
+ const source = audioContext.createBufferSource();
664
+ source.buffer = buffer;
665
+ source.connect(audioContext.destination);
666
+ source.onended = () => {
667
+ line.sources.delete(source);
668
+ if (line.done && line.sources.size === 0) {
669
+ this.lines.delete(line);
670
+ }
671
+ };
672
+ time = Math.max(time, audioContext.currentTime + playbackLead);
673
+ line.sources.add(source);
674
+ source.start(time);
675
+ time += block.length / voiceSampleRate;
676
+ await nextTask();
677
+ }
678
+ }
679
+ }
680
+
681
+
682
+ // The index of the sentence that's playing (or that's next to play)
683
+ playbackSentence() {
684
+ const {run, position} = this.playback;
685
+ if (run === null) {
686
+ return position;
687
+ }
688
+ let sentence = run.position;
689
+ for (const [ixSentence, startTime] of run.starts) {
690
+ if (startTime <= this.audioContext.currentTime) {
691
+ sentence = ixSentence;
692
+ }
693
+ }
694
+ return sentence;
695
+ }
696
+
697
+
698
+ // Move the playback to a sentence - playing from there if it's playing, otherwise when it plays
699
+ playbackSeek(position) {
700
+ this.runStop();
701
+ this.playback.position = position;
702
+ if (this.playback.playing) {
703
+ this.runStart();
704
+ }
705
+ }
706
+
707
+
708
+ // Start a synthesis run at the playback's position
709
+ runStart() {
710
+ const {playback} = this;
711
+ const run = {'position': playback.position, 'starts': [], 'sources': new Set(), 'waiting': [], 'stopped': false};
712
+ playback.run = run;
713
+ this.runPlay(playback, run).catch((error) => {
714
+ // Synthesis failed - stop the playback
715
+ if (!run.stopped) {
716
+ this.window.console.error(`MarkdownUp: Voice playback failed: ${error}`);
717
+ this.runStop();
718
+ playback.playing = false;
719
+ this.audioContext.suspend();
720
+ this.onChange();
721
+ }
722
+ });
723
+ }
724
+
725
+
726
+ // Stop the playback's synthesis run, if any
727
+ runStop() {
728
+ const run = this.playback !== null ? this.playback.run : null;
729
+ if (run !== null) {
730
+ run.stopped = true;
731
+ for (const source of run.sources) {
732
+ source.onended = null;
733
+ source.stop();
734
+ }
735
+ run.sources.clear();
736
+ runWake(run);
737
+ this.playback.run = null;
738
+ }
739
+ }
740
+
741
+
742
+ // Synthesize and schedule the playback's sentences, a block at a time (yielding to the page after each), staying at
743
+ // most a few seconds ahead of playback
744
+ async runPlay(playback, run) {
745
+ const {audioContext} = this;
746
+ const picovox = await this.load();
747
+ let time = 0;
748
+ let ixSentence = run.position;
749
+ while (!run.stopped) {
750
+ // Wait for the sentence's text - while its earlier audio plays, or for the first sentence of the run
751
+ while (!run.stopped && ixSentence >= playback.sentences.length && !playback.final &&
752
+ (run.sources.size > 0 || run.starts.length === 0)) {
753
+ await runWait(run);
754
+ }
755
+ if (run.stopped || ixSentence >= playback.sentences.length) {
756
+ break;
757
+ }
758
+
759
+ // Synthesize and schedule the sentence's blocks
760
+ const sentence = playback.sentences[ixSentence];
761
+ const blockOptions = {
762
+ 'voice': this.voiceKey(),
763
+ 'rate': this.rate,
764
+ 'seed': playbackSeed + ixSentence,
765
+ 'pause': sentencePause(picovox, sentence, ixSentence === run.position),
766
+ 'sampleRate': voiceSampleRate
767
+ };
768
+ let isFirstBlock = true;
769
+ for (const block of picovox.sentenceBlocks(speechText(sentence.text), blockOptions)) {
770
+ if (run.stopped) {
771
+ return;
772
+ }
773
+ const buffer = audioContext.createBuffer(1, block.length, voiceSampleRate);
774
+ buffer.copyToChannel(block, 0);
775
+ const source = audioContext.createBufferSource();
776
+ source.buffer = buffer;
777
+ source.connect(audioContext.destination);
778
+ source.onended = () => {
779
+ run.sources.delete(source);
780
+ runWake(run);
781
+ };
782
+ time = Math.max(time, audioContext.currentTime + playbackLead);
783
+ if (isFirstBlock) {
784
+ run.starts.push([ixSentence, time]);
785
+ isFirstBlock = false;
786
+ }
787
+ run.sources.add(source);
788
+ source.start(time);
789
+ time += block.length / voiceSampleRate;
790
+ await nextTask();
791
+ while (!run.stopped && time - audioContext.currentTime > playbackAhead) {
792
+ await runWait(run);
793
+ }
794
+ }
795
+ ixSentence += 1;
796
+ }
797
+
798
+ // Wait for the scheduled audio to end
799
+ while (!run.stopped && run.sources.size > 0) {
800
+ await runWait(run);
801
+ }
802
+ if (run.stopped) {
803
+ return;
804
+ }
805
+
806
+ // The end of the text - if it's final, the playback ends (back at the start); otherwise, it pauses
807
+ playback.run = null;
808
+ playback.position = (playback.final ? 0 : ixSentence);
809
+ playback.playing = false;
810
+ audioContext.suspend();
811
+ this.onChange();
812
+ }
813
+ }