File size: 16,266 Bytes
4e1096a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 | import { FoliateView } from '@/types/view';
import { AppService } from '@/types/system';
import { filterSSMLWithLang, parseSSMLMarks } from '@/utils/ssml';
import { Overlayer } from 'foliate-js/overlayer.js';
import { TTSGranularity, TTSHighlightOptions, TTSMark, TTSVoice } from './types';
import { createRejectFilter } from '@/utils/node';
import { WebSpeechClient } from './WebSpeechClient';
import { NativeTTSClient } from './NativeTTSClient';
import { EdgeTTSClient } from './EdgeTTSClient';
import { TTSUtils } from './TTSUtils';
import { TTSClient } from './TTSClient';
type TTSState =
| 'stopped'
| 'playing'
| 'paused'
| 'stop-paused'
| 'backward-paused'
| 'forward-paused'
| 'setrate-paused'
| 'setvoice-paused';
const HIGHLIGHT_KEY = 'tts-highlight';
export class TTSController extends EventTarget {
appService: AppService | null = null;
view: FoliateView;
isAuthenticated: boolean = false;
preprocessCallback?: (ssml: string) => Promise<string>;
onSectionChange?: (sectionIndex: number) => Promise<void>;
#nossmlCnt: number = 0;
#currentSpeakAbortController: AbortController | null = null;
#currentSpeakPromise: Promise<void> | null = null;
#isPreloading: boolean = false;
#ttsSectionIndex: number = -1;
state: TTSState = 'stopped';
ttsLang: string = '';
ttsRate: number = 1.0;
ttsClient: TTSClient;
ttsWebClient: TTSClient;
ttsEdgeClient: TTSClient;
ttsNativeClient: TTSClient | null = null;
ttsWebVoices: TTSVoice[] = [];
ttsEdgeVoices: TTSVoice[] = [];
ttsNativeVoices: TTSVoice[] = [];
ttsTargetLang: string = '';
options: TTSHighlightOptions = { style: 'highlight', color: 'gray' };
constructor(
appService: AppService | null,
view: FoliateView,
isAuthenticated: boolean = false,
preprocessCallback?: (ssml: string) => Promise<string>,
onSectionChange?: (sectionIndex: number) => Promise<void>,
) {
super();
this.ttsWebClient = new WebSpeechClient(this);
this.ttsEdgeClient = new EdgeTTSClient(this, appService);
// TODO: implement native TTS client for iOS and PC
if (appService?.isAndroidApp) {
this.ttsNativeClient = new NativeTTSClient(this);
}
this.ttsClient = this.ttsWebClient;
this.appService = appService;
this.view = view;
this.isAuthenticated = isAuthenticated;
this.preprocessCallback = preprocessCallback;
this.onSectionChange = onSectionChange;
}
async init() {
const availableClients = [];
if (await this.ttsEdgeClient.init()) {
availableClients.push(this.ttsEdgeClient);
}
if (this.ttsNativeClient && (await this.ttsNativeClient.init())) {
availableClients.push(this.ttsNativeClient);
this.ttsNativeVoices = await this.ttsNativeClient.getAllVoices();
}
if (await this.ttsWebClient.init()) {
availableClients.push(this.ttsWebClient);
}
this.ttsClient = availableClients[0] || this.ttsWebClient;
const preferredClientName = TTSUtils.getPreferredClient();
if (preferredClientName) {
const preferredClient = availableClients.find(
(client) => client.name === preferredClientName,
);
if (preferredClient) {
this.ttsClient = preferredClient;
}
}
this.ttsWebVoices = await this.ttsWebClient.getAllVoices();
this.ttsEdgeVoices = await this.ttsEdgeClient.getAllVoices();
}
#getHighlighter() {
return (range: Range) => {
const { doc, index, overlayer } = this.view.renderer.getContents()[0] as {
doc: Document;
index?: number;
overlayer?: Overlayer;
};
if (!doc || index === undefined || index !== this.#ttsSectionIndex) {
return;
}
try {
const cfi = this.view.getCFI(index, range);
const visibleRange = this.view.resolveCFI(cfi).anchor(doc);
const { style, color } = this.options;
overlayer?.remove(HIGHLIGHT_KEY);
overlayer?.add(HIGHLIGHT_KEY, visibleRange, Overlayer[style], { color });
} catch {}
};
}
#clearHighlighter() {
const { overlayer } = (this.view.renderer.getContents()?.[0] || {}) as { overlayer: Overlayer };
overlayer?.remove(HIGHLIGHT_KEY);
}
async initViewTTS(options?: TTSHighlightOptions) {
if (options) {
this.options.style = options.style;
this.options.color = options.color;
}
const currentSectionIndex = this.view.renderer.getContents()[0]?.index ?? 0;
if (this.#ttsSectionIndex === -1) {
await this.#initTTSForSection(currentSectionIndex);
}
}
async #initTTSForSection(sectionIndex: number): Promise<boolean> {
const sections = this.view.book.sections;
if (!sections || sectionIndex < 0 || sectionIndex >= sections.length) {
return false;
}
const section = sections[sectionIndex];
if (!section?.createDocument) {
return false;
}
this.#ttsSectionIndex = sectionIndex;
const currentSection = this.view.renderer.getContents()[0];
if (currentSection?.index !== sectionIndex) {
await this.onSectionChange?.(sectionIndex);
}
let doc: Document;
if (currentSection?.index === sectionIndex && currentSection?.doc) {
doc = currentSection.doc;
} else {
doc = await section.createDocument();
}
if (this.view.tts && this.view.tts.doc === doc) {
return true;
}
const { TTS } = await import('foliate-js/tts.js');
const { textWalker } = await import('foliate-js/text-walker.js');
let granularity: TTSGranularity = this.view.language.isCJK ? 'sentence' : 'word';
const supportedGranularities = this.ttsClient.getGranularities();
if (!supportedGranularities.includes(granularity)) {
granularity = supportedGranularities[0]!;
}
this.view.tts = new TTS(
doc,
textWalker,
createRejectFilter({
tags: ['rt'],
contents: [{ tag: 'a', content: /^[\[\(]?[\*\d]+[\)\]]?$/ }],
}),
this.#getHighlighter(),
granularity,
);
console.log(`Initialized TTS for section ${sectionIndex}`);
return true;
}
async #initTTSForNextSection(): Promise<boolean> {
const nextIndex = this.#ttsSectionIndex + 1;
const sections = this.view.book.sections;
if (!sections || nextIndex >= sections.length) {
return false;
}
return await this.#initTTSForSection(nextIndex);
}
async #initTTSForPrevSection(): Promise<boolean> {
const prevIndex = this.#ttsSectionIndex - 1;
if (prevIndex < 0) {
return false;
}
return await this.#initTTSForSection(prevIndex);
}
async #handleNavigationWithSSML(ssml: string | undefined, isPlaying: boolean) {
if (isPlaying) this.#speak(ssml);
}
async #handleNavigationWithoutSSML(initSection: () => Promise<boolean>, isPlaying: boolean) {
if (await initSection()) {
if (isPlaying) {
this.#speak(this.view.tts?.start());
} else {
this.view.tts?.start();
}
} else {
await this.stop();
}
}
async preloadSSML(ssml: string | undefined, signal: AbortSignal) {
if (!ssml) return;
const iter = await this.ttsClient.speak(ssml, signal, true);
for await (const _ of iter);
}
async preloadNextSSML(count: number = 4) {
const tts = this.view.tts;
if (!tts) return;
this.#isPreloading = true;
const ssmls: string[] = [];
for (let i = 0; i < count; i++) {
const ssml = await this.#preprocessSSML(tts.next());
if (!ssml) break;
ssmls.push(ssml);
}
for (let i = 0; i < ssmls.length; i++) {
tts.prev();
}
this.#isPreloading = false;
await Promise.all(ssmls.map((ssml) => this.preloadSSML(ssml, new AbortController().signal)));
}
async #preprocessSSML(ssml?: string) {
if (!ssml) return;
ssml = ssml
.replace(/<emphasis[^>]*>([^<]+)<\/emphasis>/g, '$1')
.replace(/[–—]/g, ',')
.replace('<break/>', ' ')
.replace(/\.{3,}/g, ' ')
.replace(/……/g, ' ')
.replace(/\*/g, ' ')
.replace(/·/g, ' ');
if (this.ttsTargetLang) {
ssml = filterSSMLWithLang(ssml, this.ttsTargetLang);
}
if (this.preprocessCallback) {
ssml = await this.preprocessCallback(ssml);
}
return ssml;
}
async #speak(ssml: string | undefined | Promise<string>, oneTime = false) {
await this.stop();
this.#currentSpeakAbortController = new AbortController();
const { signal } = this.#currentSpeakAbortController;
this.#currentSpeakPromise = new Promise(async (resolve, reject) => {
try {
console.log('TTS speak');
this.state = 'playing';
signal.addEventListener('abort', () => {
resolve();
});
ssml = await this.#preprocessSSML(await ssml);
if (!ssml) {
this.#nossmlCnt++;
// FIXME: in case we are at the end of the book, need a better way to handle this
if (this.#nossmlCnt < 10 && this.state === 'playing' && !oneTime) {
resolve();
if (await this.#initTTSForNextSection()) {
await this.forward();
} else {
await this.stop();
}
}
console.log('no SSML, skipping for', this.#nossmlCnt);
return;
} else {
this.#nossmlCnt = 0;
}
const { plainText, marks } = parseSSMLMarks(ssml);
if (!oneTime) {
if (!plainText || marks.length === 0) {
resolve();
return await this.forward();
} else {
this.dispatchSpeakMark(marks[0]);
}
await this.preloadSSML(ssml, signal);
}
const iter = await this.ttsClient.speak(ssml, signal);
let lastCode;
for await (const { code } of iter) {
if (signal.aborted) {
resolve();
return;
}
lastCode = code;
}
if (lastCode === 'end' && this.state === 'playing' && !oneTime) {
resolve();
await this.forward();
}
resolve();
} catch (e) {
if (signal.aborted) {
resolve();
} else {
reject(e);
}
} finally {
if (this.#currentSpeakAbortController) {
this.#currentSpeakAbortController.abort();
this.#currentSpeakAbortController = null;
}
}
});
await this.#currentSpeakPromise.catch((e) => this.error(e));
}
async speak(ssml: string | Promise<string>, oneTime = false, oneTimeCallback?: () => void) {
await this.initViewTTS();
this.#speak(ssml, oneTime)
.then(() => {
if (oneTime && oneTimeCallback) {
oneTimeCallback();
}
})
.catch((e) => this.error(e));
if (!oneTime) {
this.preloadNextSSML();
this.dispatchSpeakMark();
}
}
play() {
if (this.state !== 'playing') {
this.start();
} else {
this.pause();
}
}
async start() {
await this.initViewTTS();
const ssml = this.state.includes('paused') ? this.view.tts?.resume() : this.view.tts?.start();
if (this.state.includes('paused')) {
this.resume();
}
this.#speak(ssml);
this.preloadNextSSML();
}
async pause() {
this.state = 'paused';
if (!(await this.ttsClient.pause().catch((e) => this.error(e)))) {
await this.stop();
this.state = 'stop-paused';
}
}
async resume() {
this.state = 'playing';
await this.ttsClient.resume().catch((e) => this.error(e));
}
async stop() {
if (this.#currentSpeakAbortController) {
this.#currentSpeakAbortController.abort();
}
await this.ttsClient.stop().catch((e) => this.error(e));
if (this.#currentSpeakPromise) {
const timeout = new Promise((_, reject) =>
setTimeout(() => reject(new Error('Stop operation timed out')), 3000),
);
await Promise.race([this.#currentSpeakPromise.catch((e) => this.error(e)), timeout]).catch(
(e) => this.error(e),
);
this.#currentSpeakPromise = null;
}
this.state = 'stopped';
}
// goto previous mark/paragraph
async backward(byMark = false) {
await this.initViewTTS();
const isPlaying = this.state === 'playing';
await this.stop();
if (!isPlaying) this.state = 'backward-paused';
const ssml = byMark ? this.view.tts?.prevMark(!isPlaying) : this.view.tts?.prev(!isPlaying);
if (!ssml) {
await this.#handleNavigationWithoutSSML(() => this.#initTTSForPrevSection(), isPlaying);
} else {
await this.#handleNavigationWithSSML(ssml, isPlaying);
}
}
// goto next mark/paragraph
async forward(byMark = false) {
await this.initViewTTS();
const isPlaying = this.state === 'playing';
await this.stop();
if (!isPlaying) this.state = 'forward-paused';
const ssml = byMark ? this.view.tts?.nextMark(!isPlaying) : this.view.tts?.next(!isPlaying);
if (!ssml) {
await this.#handleNavigationWithoutSSML(() => this.#initTTSForNextSection(), isPlaying);
} else {
await this.#handleNavigationWithSSML(ssml, isPlaying);
}
if (isPlaying && !byMark) this.preloadNextSSML();
}
async setLang(lang: string) {
this.ttsLang = lang;
this.setPrimaryLang(lang);
}
async setPrimaryLang(lang: string) {
if (this.ttsEdgeClient.initialized) this.ttsEdgeClient.setPrimaryLang(lang);
if (this.ttsWebClient.initialized) this.ttsWebClient.setPrimaryLang(lang);
if (this.ttsNativeClient?.initialized) this.ttsNativeClient?.setPrimaryLang(lang);
}
async setRate(rate: number) {
this.state = 'setrate-paused';
this.ttsRate = rate;
await this.ttsClient.setRate(this.ttsRate);
}
async getVoices(lang: string) {
const ttsWebVoices = await this.ttsWebClient.getVoices(lang);
const ttsEdgeVoices = await this.ttsEdgeClient.getVoices(lang);
const ttsNativeVoices = (await this.ttsNativeClient?.getVoices(lang)) ?? [];
const voicesGroups = [...ttsNativeVoices, ...ttsEdgeVoices, ...ttsWebVoices];
return voicesGroups;
}
async setVoice(voiceId: string, lang: string) {
this.state = 'setvoice-paused';
const useEdgeTTS = !!this.ttsEdgeVoices.find(
(voice) => (voiceId === '' || voice.id === voiceId) && !voice.disabled,
);
const useNativeTTS = !!this.ttsNativeVoices.find(
(voice) => (voiceId === '' || voice.id === voiceId) && !voice.disabled,
);
if (useEdgeTTS) {
this.ttsClient = this.ttsEdgeClient;
await this.ttsClient.setRate(this.ttsRate);
} else if (useNativeTTS) {
if (!this.ttsNativeClient) {
throw new Error('Native TTS client is not available');
}
this.ttsClient = this.ttsNativeClient;
await this.ttsClient.setRate(this.ttsRate);
} else {
this.ttsClient = this.ttsWebClient;
await this.ttsClient.setRate(this.ttsRate);
}
TTSUtils.setPreferredClient(this.ttsClient.name);
TTSUtils.setPreferredVoice(this.ttsClient.name, lang, voiceId);
await this.ttsClient.setVoice(voiceId);
}
getVoiceId() {
return this.ttsClient.getVoiceId();
}
getSpeakingLang() {
return this.ttsClient.getSpeakingLang();
}
setTargetLang(lang: string) {
this.ttsTargetLang = lang;
}
dispatchSpeakMark(mark?: TTSMark) {
this.dispatchEvent(new CustomEvent('tts-speak-mark', { detail: mark || { text: '' } }));
if (mark && mark.name !== '-1') {
if (this.#isPreloading) {
setTimeout(() => this.dispatchSpeakMark(mark), 500);
} else {
const range = this.view.tts?.setMark(mark.name);
try {
const cfi = this.view.getCFI(this.#ttsSectionIndex, range);
this.dispatchEvent(new CustomEvent('tts-highlight-mark', { detail: { cfi } }));
} catch {}
}
}
}
error(e: unknown) {
console.error(e);
this.state = 'stopped';
}
async shutdown() {
await this.stop();
this.#clearHighlighter();
this.#ttsSectionIndex = -1;
if (this.ttsWebClient.initialized) {
await this.ttsWebClient.shutdown();
}
if (this.ttsEdgeClient.initialized) {
await this.ttsEdgeClient.shutdown();
}
if (this.ttsNativeClient?.initialized) {
await this.ttsNativeClient.shutdown();
}
}
}
|