klatt-lf-synth 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 KasumiKitsune & T·Grid Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,209 @@
1
- # Temporary Holding Version
1
+ # klatt-lf-synth
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **Zero-dependency physical vocal-tract speech synthesis & millisecond-accurate Ground-Truth phonetic timeline engine (Mandarin · Japanese · English)**
4
+ **零依赖物理声道语音合成与毫秒级真值音素边界引擎(普通话 · 日语 · 英语)**
5
+
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](./LICENSE)
7
+ [![ESM Only](https://img.shields.io/badge/module-ESM-brightgreen.svg)](./package.json)
8
+ [![TypeScript](https://img.shields.io/badge/types-included-blue.svg)](./tsconfig.json)
9
+
10
+ [English](#english) | [中文说明](#中文说明)
11
+
12
+ ---
13
+
14
+ ## English
15
+
16
+ `klatt-lf-synth` is a standalone, pure-JavaScript (ES Module) acoustic-articulatory formant speech synthesizer coupled with deterministic, millisecond-accurate **Ground-Truth phonetic boundary compilers** for **Mandarin Chinese (`zh`)**, **Japanese (`ja`)**, and **American English (`en`)**.
17
+
18
+ Unlike black-box neural TTS models whose internal frame alignments must be estimated post-hoc, `klatt-lf-synth` compiles every utterance into explicit biomechanical control knots and exact acoustic landmark timestamps (`0 .. duration` with zero gaps) before synthesizing audio through a physical Fant LF glottal source and normal-form complex-pole Klatt vocal tract. Every stop closure, burst/release, voice onset time (VOT), nasal/lateral coupling, tap, and devoiced vowel in the output waveform aligns deterministically with its returned `groundTruth` phone and syllable intervals.
19
+
20
+ ### Scope & Honest Positioning
21
+
22
+ - **Designed for**: acoustic phonetics education, articulatory/formant synthesis research, deterministic stimulus generation (VOT / formant / pitch accent / tone sandhi continuum manipulation), forced-aligner & VAD ground-truth benchmarking, and interactive spectrogram segmentation training.
23
+ - **Not a general-purpose neural reading TTS**:
24
+ - **English (`./frontends/english`)** is purpose-built for **phonetics experiments, minimal-pair contrasts, and direct phonetic transcription driving**. It features first-class **IPA** (`/ˈʃiːp / ˈʃɪp/`) and **ARPAbet** (`SH IY1 P / SH IH1 P`) parsers, a curated **574-word phonetics teaching lexicon**, morphophonemic inflection rules (`-s/-ed/-ing`), and a lightweight rule-based fallback G2P. For arbitrary open-vocabulary English orthography with irregular spellings, pass **IPA** or **ARPAbet** directly (or pre-convert text via an external G2P dictionary such as CMUdict) rather than relying on the lightweight orthographic fallback.
25
+ - **Mandarin (`./frontends/mandarin` + optional `./hanzi`)** natively parses tone-numbered (`ba1 pa1`) and diacritic (`bā pā`) Pinyin plus a built-in zero-dependency high-frequency Hanzi table. Installing the optional peer dependency `pinyin-pro` and importing `klatt-lf-synth/hanzi` unlocks full CJK Hanzi coverage, phrase-context polyphone disambiguation, candidate enumeration, and per-character reading overrides.
26
+ - **Japanese (`./frontends/japanese`)** natively parses Hiragana, Katakana, Hepburn/Kunrei Romaji (with `'` accent-nucleus markers and `=` accentual-phrase boundaries), and core teaching Kanji compounds. For unrestricted Japanese Kanji text, convert Kanji to Kana or accented Romaji upstream (e.g., via MeCab / Kuromoji) before compilation.
27
+
28
+ ### Physical Acoustic Architecture
29
+
30
+ 1. **4x-Oversampled Continuous-Phase Fant LF Glottal Source (`./dsp`)**
31
+ - Cached zero-net-flow bisection lookup table parameterized by $R_d$, dynamic open-phase envelope, physiological micro-jitter, shimmer, delayed micro-vibrato, phrase-final creak, and polyphase sinc decimation.
32
+ 2. **Multi-Scale Biomechanical Trajectory Smoother**
33
+ - Shape-preserving PCHIP interpolation + $O(N)$ 3-pass boxcar filtering that decouples fast aerodynamic source landmarks (stop release, glottal adduction) from slower tongue/jaw formant inertia.
34
+ 3. **Unconditionally Stable Normal-Form Complex-Pole Vocal Tract ($F_1 \dots F_7$)**
35
+ - 1 ms control-rate coefficient updates with sample-level linear interpolation, vowel-height wall-loss damping, dynamic open-phase tracheal coupling ($\Delta BW_1, \Delta BW_2$), velopharyngeal nasal damping, exact algebraic pole-zero cancellation branches (**nasal**, **lateral**, and **piriform fossa notch**), compensated in-tract aspiration ($A_H$), and occlusion-scaled neck-wall voice-bar murmur radiation.
36
+ 4. **Click-Free Front-Cavity Consonant Synthesizer**
37
+ - Pre-resonator plosive burst excitation (eliminating broadband click splatter), sub-cavity antiresonance zeros, coarticulated locus-to-vowel pole glides, aerodynamic eddy flutter, and pitch-synchronous voiced fricative modulation.
38
+ 5. **Mastering & Peak Protection**
39
+ - 6-step anti-masking spectral balance, phrase-scale prosody-preserving loudness leveling, optional studio ambient floor (`noiseFloorDb`), and an $O(N)$ monotonic-deque 5 ms lookahead peak limiter.
40
+
41
+ ### Installation
42
+
43
+ ```bash
44
+ npm install klatt-lf-synth
45
+
46
+ # Optional: install pinyin-pro only if you need full Chinese Hanzi & polyphone disambiguation via `klatt-lf-synth/hanzi`
47
+ npm install pinyin-pro
48
+ ```
49
+
50
+ ### Subpath Exports
51
+
52
+ | Subpath | Runtime Env | Dependencies | Description |
53
+ | :--- | :--- | :--- | :--- |
54
+ | `klatt-lf-synth` | Node & Browser | **0** | Zero-dependency barrel re-exporting `./dsp` and `./frontends`. |
55
+ | `klatt-lf-synth/dsp` | Node & Browser | **0** | Pure physical Fant LF + normal-form Klatt vocal-tract DSP synthesis kernel. |
56
+ | `klatt-lf-synth/frontends` | Node & Browser | **0** | Multilingual router (`zh` / `ja` / `en`) + all three phonetic trajectory & `groundTruth` compilers. |
57
+ | `klatt-lf-synth/frontends/mandarin` | Node & Browser | **0** | Standalone Mandarin Pinyin frontend (T3 foot sandhi, `一/不` sandhi, neutral tone, rhotacization). |
58
+ | `klatt-lf-synth/frontends/japanese` | Node & Browser | **0** | Standalone Japanese frontend (unrounded `[ɯᵝ]`, 4-way moraic nasal, high-vowel devoicing, Tokyo pitch accent). |
59
+ | `klatt-lf-synth/frontends/english` | Node & Browser | **0** | Standalone English frontend (IPA / ARPAbet / 574-word lexicon, VOT allophones, pre-fortis clipping, `/ɹ, l, ɫ/`). |
60
+ | `klatt-lf-synth/hanzi` | Node & Browser | `pinyin-pro` *(optional peer)* | Hanzi-to-Pinyin phrase disambiguation, polyphone candidates & manual override bridge. |
61
+ | `klatt-lf-synth/browser` | Browser & Node* | **0** | Lightweight WebAudio audition player (`playPcm`, 4 ms fade-out `stop`) & async scheduler (`synthesizeAsync`). |
62
+
63
+ *\*`synthesizeAsync` / `synthesizeMultilingualAsync` in `klatt-lf-synth/browser` work in both Node.js and browsers; `playPcm` uses `AudioContext` when available in browser environments.*
64
+
65
+ ### Quick Start
66
+
67
+ #### 1. Zero-Dependency Synthesis & Millisecond Ground-Truth Alignment
68
+
69
+ ```js
70
+ import { compileMultilingualUtterance, synthesizeFromPlan } from 'klatt-lf-synth';
71
+
72
+ // Drive English directly with IPA, ARPAbet, or lexicon minimal pairs
73
+ const { plan, groundTruth, meta } = compileMultilingualUtterance('/ˈʃiːp / ˈʃɪp/', {
74
+ lang: 'en',
75
+ voice: 'female',
76
+ speed: 1.0,
77
+ });
78
+
79
+ const { pcm, sampleRate, duration, curves } = synthesizeFromPlan(plan, {
80
+ sampleRate: 24000,
81
+ oversample: 4,
82
+ });
83
+
84
+ console.log(meta); // { lang: 'en', voice: 'female', f0Ref: 212, ... }
85
+ console.log(pcm.length, sampleRate, duration);
86
+
87
+ // Seamless 0..duration phone intervals with exact acoustic roles
88
+ for (const phone of groundTruth.phones) {
89
+ console.log(`${phone.xmin.toFixed(3)}s -> ${phone.xmax.toFixed(3)}s [${phone.role}] ${phone.text || '<sil>'}`);
90
+ }
91
+ ```
92
+
93
+ #### 2. Tree-Shaking a Single Language Frontend
94
+
95
+ ```js
96
+ import { synthesizeFromPlan } from 'klatt-lf-synth/dsp';
97
+ import { compileJapaneseUtterance } from 'klatt-lf-synth/frontends/japanese';
98
+
99
+ // Compare Japanese high-vowel devoicing (i̥ / ɯ̥) ON vs OFF with identical random seed
100
+ const devoiced = compileJapaneseUtterance('すき', { voice: 'female', devoicing: true, seed: 42 });
101
+ const voiced = compileJapaneseUtterance('すき', { voice: 'female', devoicing: false, seed: 42 });
102
+
103
+ const audioDevoiced = synthesizeFromPlan(devoiced.plan, { sampleRate: 24000 });
104
+ const audioVoiced = synthesizeFromPlan(voiced.plan, { sampleRate: 24000 });
105
+ ```
106
+
107
+ #### 3. Mandarin Hanzi & Polyphone Disambiguation (`klatt-lf-synth/hanzi`)
108
+
109
+ ```js
110
+ import { resolveUtteranceInput } from 'klatt-lf-synth/hanzi';
111
+ import { compileMandarinUtterance } from 'klatt-lf-synth/frontends/mandarin';
112
+ import { synthesizeFromPlan } from 'klatt-lf-synth/dsp';
113
+
114
+ // Phrase-context disambiguation: '银行行长' -> 'yin2 hang2 hang2 zhang3'
115
+ const res = resolveUtteranceInput('银行行长');
116
+ console.log(res.markedPinyin); // 'yín háng háng zhǎng'
117
+ console.log(res.items[1].candidates); // [{ num: 'hang2', marked: 'háng' }, { num: 'xing2', marked: 'xíng' }, ...]
118
+
119
+ // Override character index 1 if needed, then compile & synthesize
120
+ const overridden = resolveUtteranceInput('银行行长', { 1: 'xing2' });
121
+ const compiled = compileMandarinUtterance(overridden, { voice: 'male', toneSandhi: true });
122
+ const { pcm } = synthesizeFromPlan(compiled.plan, { sampleRate: 24000 });
123
+ ```
124
+
125
+ #### 4. Browser WebAudio Playback & Async Synthesis (`klatt-lf-synth/browser`)
126
+
127
+ ```js
128
+ import { synthesizeAsync, playPcm, stop, disposeAudioRuntime } from 'klatt-lf-synth/browser';
129
+
130
+ const result = await synthesizeAsync('ni3 hao3 / shi4 jie4', { lang: 'zh', voice: 'female' });
131
+ await playPcm(result.pcm, result.sampleRate, (playing) => {
132
+ console.log('Playing:', playing);
133
+ });
134
+
135
+ // Click-free 4 ms linear ramp stop & teardown when unmounting UI
136
+ stop();
137
+ disposeAudioRuntime();
138
+ ```
139
+
140
+ ---
141
+
142
+ ## 中文说明
143
+
144
+ `klatt-lf-synth` 是一个零外部运行时依赖、纯原生 ES Module 实现的**物理声道共振峰语音合成与毫秒级真值(Ground-Truth)音素边界生成引擎**,支持 **普通话(`zh`)**、**日语(`ja`)** 与 **美式英语(`en`)**,同时适用于 Node.js 与现代浏览器环境。
145
+
146
+ 与端到端神经网络黑盒 TTS 需要事后借助强制对齐器(Forced Aligner)近似反推音素边界不同,`klatt-lf-synth` 先由声学音系前端将文本或音标精确编译为生物力学控制轨迹(`SynthesisPlan`)与无缝覆盖 `0 .. duration` 的音节/音素/声学事件时间轴(`groundTruth`),再经由 4 倍过采样 Fant LF 声门源与正规形复极点 Klatt 声道模型合成浮点波形。因此,输出音频中的每一处塞音闭塞、除阻冲直条、嗓音起始时间(VOT)、鼻音/边音极零点耦合、闪音触拍及高元音清化,在物理波形上都与返回的毫秒级真值边界严格对齐。
147
+
148
+ ### 适用场景与客观边界说明
149
+
150
+ - **核心适用场景**:实验语音学与声学教学演示(VOT 连续统、共振峰偏移、声调连读变调、日语拍节与高低音调、高元音清化 A/B 对比)、强制对齐与端点检测(VAD)算法的真值基准评测、语图仪切分训练刺激合成。
151
+ - **前端能力边界(非大词表神经朗读 TTS)**:
152
+ - **英语前端(`./frontends/english`)**:专为**语音学实验、最小对立组对比与音标直通驱动**打造,支持 **标准 IPA**(如 `/ˈʃiːp / ˈʃɪp/`、`/ˈθɪŋk / ˈðɪs/`)与 **ARPAbet**(如 `SH IY1 P / SH IH1 P`)直接输入,内置 **574 词语音学教学词表**、词尾屈折形态音系规则(清浊同化 `-s/-ed`、不完全爆破等)及轻量级规则回退 G2P。**它不是面向任意生僻英语拼写文章的大词表神经网络通用朗读 TTS**——若需合成词表外复杂不规则拼写词汇,建议直接传入 IPA / ARPAbet 音标(或前置接入 CMUdict 等外部词典)。
153
+ - **普通话前端(`./frontends/mandarin` + 可选 `./hanzi`)**:零依赖支持数字标调(`ba1 pa1`)、符号标调(`bā pā`)、三声韵律词左分支/右分支变调、`一/不` 变调、儿化音与轻声词表及常用汉字零依赖回退;按需安装可选对等依赖 `pinyin-pro` 并引入 `klatt-lf-synth/hanzi` 后,即可获得全量汉字词组级多音字消歧、候选音列举与单字读音手动覆写能力。
154
+ - **日语前端(`./frontends/japanese`)**:零依赖支持平假名、片假名、Hepburn/Kunrei 罗马音(支持 `'` 声调核标记与 `=` 韵律短语边界)及常用教学日文汉字,精确建模扁唇不圆唇 `/ɯ/`(`[ɯᵝ]`)、四部位同部位拨音同化(`[m, n, ŋ, ɰ̃]`)、高元音清化(`devoicing` 开关)与东京方言高低音调下倾(Downstep);开放域任意日文汉字长句建议先转为假名或带调核罗马音后传入。
155
+
156
+ ### 物理声学模型架构
157
+
158
+ 1. **4 倍过采样连续相位 Fant LF 声门源(`./dsp`)**:基于零净流量二分查找缓存表的 $R_d$ 参数化声门脉冲,内置开相呼吸包络、生理微抖动(Jitter/Shimmer)、延迟微颤音、句末嘎裂音(Creak)与多相 Sinc 抽取滤波。
159
+ 2. **多时间尺度生物力学轨迹平滑器**:采用保形分段三次 Hermite 插值(PCHIP)与 $O(N)$ 三通均值滤波,将快速的声源空气动力学地标(塞音除阻、声带内收)与较慢的舌体/下颌共振峰惯性解耦。
160
+ 3. **无条件稳定正规形复极点级联/并联声道($F_1 \dots F_7$)**:1 ms 控制率系数更新与采样级线性插值,涵盖元音高度管壁损耗、声门开相气管耦合阻尼增量($\Delta BW_1, \Delta BW_2$)、软腭鼻化阻尼、**鼻音 / 边音 / 梨状窝(Piriform Fossa)代数极零点分支**、声道内送气噪声补偿($A_H$)与闭塞期颈壁浊声杠(Voice Bar)辐射。
161
+ 4. **无咔嗒声前腔辅音瞬态合成器**:谐振器前激励爆破瞬态(消除宽带数字咔嗒伪影)、前腔反共振零点、协同发音轨迹滑移、湍流涡旋调制与基音同步浊擦音建模。
162
+ 5. **6 步反掩蔽母带链与前瞻限幅**:保留句级韵律起伏的响度均衡、可选录音室底噪(`noiseFloorDb`)以及 $O(N)$ 单调队列 5 ms 前瞻峰值限幅器。
163
+
164
+ ### 精确打包体积(Bundle Size)
165
+
166
+ 测算环境:`terser`(`--module --compress --mangle`)+ `gzip -9`。分别列出各公开子路径**单文件自身体积**与**包含内部子模块后的完整自包含闭包体积**:
167
+
168
+ #### 各 `dist/*.js` 模块单文件体积
169
+
170
+ | 子路径入口 | 对应产物文件 | 原始体积 (Raw) | Terser 压缩 | Gzip -9 |
171
+ | :--- | :--- | ---: | ---: | ---: |
172
+ | `.` *(聚合入口文件)* | `dist/index.js` | 324 B (0.32 KiB) | 51 B (0.05 KiB) | 55 B (0.05 KiB) |
173
+ | `./dsp` | `dist/dsp.js` | 75,614 B (73.84 KiB) | 29,109 B (28.43 KiB) | 11,102 B (10.84 KiB) |
174
+ | `./frontends` *(注册表文件)* | `dist/frontends.js` | 12,952 B (12.65 KiB) | 7,504 B (7.33 KiB) | 3,008 B (2.94 KiB) |
175
+ | `./frontends/mandarin` | `dist/frontends/mandarin.js` | 137,391 B (134.17 KiB) | 74,315 B (72.57 KiB) | 24,087 B (23.52 KiB) |
176
+ | `./frontends/japanese` | `dist/frontends/japanese.js` | 116,646 B (113.91 KiB) | 61,777 B (60.33 KiB) | 20,047 B (19.58 KiB) |
177
+ | `./frontends/english` | `dist/frontends/english.js` | 144,666 B (141.28 KiB) | 71,153 B (69.49 KiB) | 24,682 B (24.10 KiB) |
178
+ | `./hanzi` *(不含外部 `pinyin-pro`)* | `dist/hanzi.js` | 20,337 B (19.86 KiB) | 8,673 B (8.47 KiB) | 3,408 B (3.33 KiB) |
179
+ | `./browser` *(运行时调度文件)* | `dist/browser.js` | 9,638 B (9.41 KiB) | 2,994 B (2.92 KiB) | 1,294 B (1.26 KiB) |
180
+
181
+ #### 按需导入内部依赖完整闭包体积(Self-Contained Closures)
182
+
183
+ | 导入组合场景 | 包含的内部模块 | 原始体积 (Raw) | Terser 压缩 | Gzip -9 |
184
+ | :--- | :--- | ---: | ---: | ---: |
185
+ | `klatt-lf-synth/dsp` | `dsp` | 75,614 B (73.84 KiB) | 29,109 B (28.43 KiB) | 11,102 B (10.84 KiB) |
186
+ | `dsp` + `frontends/mandarin` *(单语按需)* | `dsp` + `mandarin` | 213,005 B (208.01 KiB) | 103,425 B (101.00 KiB) | 35,055 B (34.23 KiB) |
187
+ | `dsp` + `frontends/japanese` *(单语按需)* | `dsp` + `japanese` | 192,260 B (187.75 KiB) | 90,887 B (88.76 KiB) | 30,997 B (30.27 KiB) |
188
+ | `dsp` + `frontends/english` *(单语按需)* | `dsp` + `english` | 220,280 B (215.12 KiB) | 100,263 B (97.91 KiB) | 35,736 B (34.90 KiB) |
189
+ | `klatt-lf-synth/frontends` *(三语全集)* | `frontends` + `zh/ja/en` | 411,655 B (402.01 KiB) | 214,752 B (209.72 KiB) | 70,954 B (69.29 KiB) |
190
+ | `klatt-lf-synth` *(主入口零依赖全集)* | `index` + `dsp` + `frontends` | 487,593 B (476.17 KiB) | 243,914 B (238.20 KiB) | 81,971 B (80.05 KiB) |
191
+ | `klatt-lf-synth/hanzi` + `mandarin` | `hanzi` + `mandarin` *(peer 外部)* | 157,728 B (154.03 KiB) | 82,989 B (81.04 KiB) | 27,334 B (26.69 KiB) |
192
+ | `klatt-lf-synth/browser` *(含三语与 DSP)* | `browser` + `dsp` + `frontends` | 496,907 B (485.26 KiB) | 246,857 B (241.07 KiB) | 83,046 B (81.10 KiB) |
193
+
194
+ ### 开发与校验命令
195
+
196
+ ```bash
197
+ # 同步构建 src/ -> dist/ 并校验全部子路径产物
198
+ npm run build
199
+
200
+ # 严格模式 TypeScript + checkJs + 消费者导入类型校验
201
+ npm run typecheck
202
+
203
+ # 运行 Node 原生测试套件
204
+ npm test
205
+ ```
206
+
207
+ ### License
208
+
209
+ [MIT](./LICENSE) © 2026 KasumiKitsune & T·Grid Contributors
@@ -0,0 +1,60 @@
1
+ import type { SynthesisCurves, SynthesisPlan, SynthesizePlanOptions } from './dsp.js';
2
+ import type {
3
+ MultilingualCompileInput,
4
+ MultilingualCompileOverrides,
5
+ MultilingualGroundTruth,
6
+ PhoneticsLanguage,
7
+ } from './frontends.js';
8
+ import type { ParsedPinyinToken, PhoneticsVoice } from './frontends/mandarin.js';
9
+ import type { ParsedJapaneseToken } from './frontends/japanese.js';
10
+ import type { ParsedEnglishToken } from './frontends/english.js';
11
+
12
+ export interface AsyncSynthesisResult {
13
+ pcm: Float32Array;
14
+ sampleRate: number;
15
+ duration: number;
16
+ curves: SynthesisCurves;
17
+ plan: SynthesisPlan;
18
+ groundTruth: MultilingualGroundTruth;
19
+ tokens: ParsedPinyinToken[] | ParsedJapaneseToken[] | ParsedEnglishToken[];
20
+ meta: {
21
+ lang: PhoneticsLanguage;
22
+ voice: PhoneticsVoice;
23
+ f0Ref: number;
24
+ vtScale: number;
25
+ speed: number;
26
+ syllableCount: number;
27
+ toneSandhi?: boolean;
28
+ devoicing?: boolean;
29
+ moraCount?: number;
30
+ };
31
+ }
32
+
33
+ export declare function isPlaying(): boolean;
34
+
35
+ export declare function getPlayGeneration(): number;
36
+
37
+ export declare function activateAudioRuntime(): void;
38
+
39
+ export declare function stop(): void;
40
+
41
+ export declare function playPcm(
42
+ pcm: Float32Array,
43
+ sampleRate?: number,
44
+ onStateChange?: ((playing: boolean) => void) | null
45
+ ): Promise<boolean>;
46
+
47
+ export declare function synthesizeAsync(
48
+ input: MultilingualCompileInput,
49
+ overrides?: MultilingualCompileOverrides,
50
+ options?: SynthesizePlanOptions
51
+ ): Promise<AsyncSynthesisResult>;
52
+
53
+ export declare function synthesizeMultilingualAsync(
54
+ lang: PhoneticsLanguage | 'auto' | string,
55
+ input: MultilingualCompileInput,
56
+ overrides?: MultilingualCompileOverrides,
57
+ options?: SynthesizePlanOptions
58
+ ): Promise<AsyncSynthesisResult>;
59
+
60
+ export declare function disposeAudioRuntime(): void;
@@ -0,0 +1,363 @@
1
+ /**
2
+ * klatt-lf-synth — Browser WebAudio Playback Runtime & Async Synthesis Scheduler
3
+ *
4
+ * Provides:
5
+ * - Lightweight WebAudio audition manager: playPcm, stop, isPlaying,
6
+ * activateAudioRuntime, disposeAudioRuntime, getPlayGeneration
7
+ * - Click-free 4 ms linear fade-out on stop and monotonic playGen / disposed guards
8
+ * - Async synthesis scheduler: synthesizeAsync(input, overrides, options)
9
+ * Supports Mandarin ('zh', default), Japanese ('ja'), and English ('en')
10
+ * via `overrides.lang` (or `'auto'` script detection).
11
+ */
12
+
13
+ import { DEFAULT_PRINCIPLES, synthesizeFromPlan } from './dsp.js';
14
+ import { compileMultilingualUtterance } from './frontends.js';
15
+
16
+ // ---------------------------------------------------------------------------
17
+ // 1. WebAudio Audition Player
18
+ // ---------------------------------------------------------------------------
19
+
20
+ const STOP_FADE_SEC = 0.004;
21
+ const STOP_HALT_SEC = 0.005;
22
+ const MIN_AUDIO_SR = 8000;
23
+ const MAX_AUDIO_SR = 96000;
24
+
25
+ let sharedAudioCtx = null;
26
+ let activeSource = null;
27
+ let activeGain = null;
28
+ let activeStateCb = null;
29
+ let activeFinish = null;
30
+ let playingFlag = false;
31
+ let playGen = 0;
32
+ let disposed = false;
33
+
34
+ function getAudioContext() {
35
+ if (disposed) return null;
36
+ if (typeof window === 'undefined' && typeof globalThis === 'undefined') return null;
37
+ const g = typeof window !== 'undefined' ? window : globalThis;
38
+ const Ctor = g.AudioContext || g.webkitAudioContext;
39
+ if (!Ctor) return null;
40
+ if (!sharedAudioCtx || sharedAudioCtx.state === 'closed') {
41
+ sharedAudioCtx = new Ctor();
42
+ }
43
+ return sharedAudioCtx;
44
+ }
45
+
46
+ function disconnectNodesSafely(src, gain) {
47
+ if (src) {
48
+ try {
49
+ src.disconnect();
50
+ } catch {
51
+ // Ignore disconnect errors
52
+ }
53
+ }
54
+ if (gain) {
55
+ try {
56
+ gain.disconnect();
57
+ } catch {
58
+ // Ignore disconnect errors
59
+ }
60
+ }
61
+ }
62
+
63
+ function cleanupCurrentNodes(notify = true, immediate = false) {
64
+ const prevSource = activeSource;
65
+ const prevGain = activeGain;
66
+ const prevCb = activeStateCb;
67
+ const prevFinish = activeFinish;
68
+ activeSource = null;
69
+ activeGain = null;
70
+ activeStateCb = null;
71
+ activeFinish = null;
72
+ const wasPlaying = playingFlag;
73
+ playingFlag = false;
74
+
75
+ if (prevSource) {
76
+ const ctx = sharedAudioCtx;
77
+ const canRamp =
78
+ !immediate &&
79
+ ctx &&
80
+ ctx.state !== 'closed' &&
81
+ typeof ctx.currentTime === 'number' &&
82
+ prevGain &&
83
+ prevGain.gain &&
84
+ typeof prevGain.gain.linearRampToValueAtTime === 'function';
85
+
86
+ if (canRamp) {
87
+ const now = ctx.currentTime;
88
+ try {
89
+ if (typeof prevGain.gain.cancelScheduledValues === 'function') {
90
+ prevGain.gain.cancelScheduledValues(now);
91
+ }
92
+ const curVal =
93
+ typeof prevGain.gain.value === 'number' && Number.isFinite(prevGain.gain.value)
94
+ ? Math.max(0.0001, prevGain.gain.value)
95
+ : 0.96;
96
+ if (typeof prevGain.gain.setValueAtTime === 'function') {
97
+ prevGain.gain.setValueAtTime(curVal, now);
98
+ }
99
+ prevGain.gain.linearRampToValueAtTime(0.0001, now + STOP_FADE_SEC);
100
+ } catch {
101
+ // Fallback to direct stop if AudioParam scheduling fails
102
+ }
103
+
104
+ let cleaned = false;
105
+ const finalizeDisconnect = () => {
106
+ if (cleaned) return;
107
+ cleaned = true;
108
+ prevSource.onended = null;
109
+ disconnectNodesSafely(prevSource, prevGain);
110
+ };
111
+ prevSource.onended = finalizeDisconnect;
112
+ try {
113
+ prevSource.stop(now + STOP_HALT_SEC);
114
+ setTimeout(finalizeDisconnect, 25);
115
+ } catch {
116
+ finalizeDisconnect();
117
+ }
118
+ } else {
119
+ try {
120
+ prevSource.onended = null;
121
+ prevSource.stop();
122
+ } catch {
123
+ // Ignore already stopped source
124
+ }
125
+ disconnectNodesSafely(prevSource, prevGain);
126
+ }
127
+ } else if (prevGain) {
128
+ disconnectNodesSafely(null, prevGain);
129
+ }
130
+
131
+ if (notify && wasPlaying && typeof prevCb === 'function') {
132
+ try {
133
+ prevCb(false);
134
+ } catch {
135
+ // Never let listener errors break cleanup
136
+ }
137
+ }
138
+ if (typeof prevFinish === 'function') {
139
+ try {
140
+ prevFinish(false);
141
+ } catch {
142
+ // Ignore settle errors
143
+ }
144
+ }
145
+ }
146
+
147
+ export function isPlaying() {
148
+ return playingFlag;
149
+ }
150
+
151
+ export function getPlayGeneration() {
152
+ return playGen;
153
+ }
154
+
155
+ export function activateAudioRuntime() {
156
+ disposed = false;
157
+ }
158
+
159
+ export function stop() {
160
+ playGen++;
161
+ cleanupCurrentNodes(true, false);
162
+ }
163
+
164
+ /**
165
+ * Play mono audio samples via WebAudio with automatic AudioContext resume.
166
+ *
167
+ * @param {Float32Array} pcm
168
+ * @param {number} sampleRate
169
+ * @param {(playing: boolean) => void} [onStateChange]
170
+ * @returns {Promise<boolean>} resolves to true when playback finishes naturally, false if interrupted/failed
171
+ */
172
+ export async function playPcm(pcm, sampleRate = 24000, onStateChange = null) {
173
+ const safeNotifyFalse = () => {
174
+ if (typeof onStateChange === 'function') {
175
+ try {
176
+ onStateChange(false);
177
+ } catch {
178
+ // Ignore callback error
179
+ }
180
+ }
181
+ };
182
+
183
+ if (disposed || !pcm || pcm.length === 0) {
184
+ safeNotifyFalse();
185
+ return false;
186
+ }
187
+
188
+ cleanupCurrentNodes(true, false);
189
+ const myGen = ++playGen;
190
+
191
+ const ctx = getAudioContext();
192
+ if (!ctx || disposed) {
193
+ safeNotifyFalse();
194
+ return false;
195
+ }
196
+
197
+ try {
198
+ if (ctx.state === 'suspended') {
199
+ await ctx.resume();
200
+ }
201
+ } catch {
202
+ safeNotifyFalse();
203
+ return false;
204
+ }
205
+
206
+ if (disposed || myGen !== playGen) {
207
+ safeNotifyFalse();
208
+ return false;
209
+ }
210
+
211
+ const rawSr = Number(sampleRate);
212
+ const sr = Math.min(
213
+ MAX_AUDIO_SR,
214
+ Math.max(MIN_AUDIO_SR, Math.round(Number.isFinite(rawSr) && rawSr > 0 ? rawSr : 24000))
215
+ );
216
+
217
+ let audioBuf;
218
+ let src;
219
+ let gain;
220
+ try {
221
+ audioBuf = ctx.createBuffer(1, pcm.length, sr);
222
+ const chan = audioBuf.getChannelData(0);
223
+ chan.set(pcm);
224
+
225
+ src = ctx.createBufferSource();
226
+ src.buffer = audioBuf;
227
+
228
+ gain = ctx.createGain();
229
+ gain.gain.value = 0.96;
230
+
231
+ src.connect(gain);
232
+ gain.connect(ctx.destination);
233
+ } catch {
234
+ disconnectNodesSafely(src, gain);
235
+ safeNotifyFalse();
236
+ return false;
237
+ }
238
+
239
+ if (disposed || myGen !== playGen) {
240
+ disconnectNodesSafely(src, gain);
241
+ safeNotifyFalse();
242
+ return false;
243
+ }
244
+
245
+ activeSource = src;
246
+ activeGain = gain;
247
+ activeStateCb = typeof onStateChange === 'function' ? onStateChange : null;
248
+ playingFlag = true;
249
+
250
+ if (activeStateCb) {
251
+ try {
252
+ activeStateCb(true);
253
+ } catch {
254
+ // Ignore callback error
255
+ }
256
+ }
257
+
258
+ return new Promise((resolve) => {
259
+ let settled = false;
260
+ const finish = (natural) => {
261
+ if (settled) return;
262
+ settled = true;
263
+ if (activeSource === src) {
264
+ cleanupCurrentNodes(true, true);
265
+ } else if (!natural) {
266
+ safeNotifyFalse();
267
+ }
268
+ resolve(natural);
269
+ };
270
+
271
+ activeFinish = finish;
272
+ src.onended = () => finish(!disposed && myGen === playGen);
273
+ try {
274
+ src.start(0);
275
+ } catch {
276
+ finish(false);
277
+ }
278
+ });
279
+ }
280
+
281
+ // ---------------------------------------------------------------------------
282
+ // 2. Main-Thread Async Synthesis Scheduler (Multilingual zh / ja / en)
283
+ // ---------------------------------------------------------------------------
284
+
285
+ function runMainThreadAsync(input, overrides, options) {
286
+ return new Promise((resolve, reject) => {
287
+ setTimeout(() => {
288
+ try {
289
+ const compiled = compileMultilingualUtterance(input, overrides);
290
+ const synth = synthesizeFromPlan(compiled.plan, {
291
+ sampleRate: options.sampleRate ?? 24000,
292
+ oversample: options.oversample ?? 4,
293
+ principles: { ...DEFAULT_PRINCIPLES, ...(options.principles || {}) },
294
+ });
295
+ resolve({
296
+ ...synth,
297
+ plan: compiled.plan,
298
+ groundTruth: compiled.groundTruth,
299
+ tokens: compiled.tokens,
300
+ meta: compiled.meta,
301
+ });
302
+ } catch (err) {
303
+ reject(err);
304
+ }
305
+ }, 0);
306
+ });
307
+ }
308
+
309
+ /**
310
+ * Compile and synthesize an utterance asynchronously (`zh` default, `ja`, `en`, or `'auto'`).
311
+ *
312
+ * @param {string | object} input
313
+ * @param {object} [overrides]
314
+ * @param {{ sampleRate?: number, oversample?: number, principles?: object }} [options]
315
+ * @returns {Promise<{
316
+ * pcm: Float32Array,
317
+ * sampleRate: number,
318
+ * duration: number,
319
+ * curves: { times: number[], f0: number[], f1: number[], f2: number[], f3: number[] },
320
+ * plan: object,
321
+ * groundTruth: object,
322
+ * tokens: Array<object>,
323
+ * meta: object
324
+ * }>}
325
+ */
326
+ export function synthesizeAsync(input, overrides = {}, options = {}) {
327
+ const safeOptions = {
328
+ sampleRate: options.sampleRate ?? 24000,
329
+ oversample: options.oversample ?? 4,
330
+ principles: { ...DEFAULT_PRINCIPLES, ...(options.principles || {}) },
331
+ };
332
+
333
+ // Schedule via macrotask yield (~15-60ms pure JS) to avoid Worker serialization
334
+ // stalls in constrained WebViews while preserving main-thread responsiveness.
335
+ return runMainThreadAsync(input, overrides, safeOptions);
336
+ }
337
+
338
+ /**
339
+ * Explicit language-first async synthesis helper.
340
+ */
341
+ export function synthesizeMultilingualAsync(lang, input, overrides = {}, options = {}) {
342
+ return synthesizeAsync(input, { ...overrides, lang }, options);
343
+ }
344
+
345
+ /**
346
+ * Release active playback nodes and close the shared AudioContext.
347
+ * Marks runtime as disposed so in-flight async calls cannot spawn a stray AudioContext.
348
+ */
349
+ export function disposeAudioRuntime() {
350
+ disposed = true;
351
+ playGen++;
352
+ cleanupCurrentNodes(true, true);
353
+ if (sharedAudioCtx) {
354
+ try {
355
+ if (sharedAudioCtx.state !== 'closed') {
356
+ void sharedAudioCtx.close();
357
+ }
358
+ } catch {
359
+ // Ignore
360
+ }
361
+ sharedAudioCtx = null;
362
+ }
363
+ }