commit 1856de97bcaab09ab7312249a225185ec652b83e Author: tongtongstudio Date: Mon Nov 23 14:59:46 2026 +0800 初始化 TTS 引擎工程:Android 系统引擎、Go 在线合成服务与测试客户端 - android-engine:TextToSpeechService 引擎,含设置页、语音包导入(SHA-256 校验)与预热 - server:Go CPU 合成服务与部署文件 - test-client:端到端验证客户端 - 模型与语音包不入库,见 models/README.md diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4165f67 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +# 测试请求与合成输出(server 手工测试用) +.download/ + +# 系统杂项 +Thumbs.db +.DS_Store \ No newline at end of file diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..7fed0cc --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,122 @@ +# AGENTS.md — TTS 引擎项目(TtsSpeaker) + +## 一、项目定位 + +TtsSpeaker 是老人平板(A0808 类定制机型)的语音合成引擎项目,为 ElderlyDialer 及后续预装应用提供朗读能力: + +- 设备端:自研系统 TTS 引擎(实现 `TextToSpeechService`),预置进 ROM。定制 ROM 不自带任何 TTS 引擎和中文语音包,本项目必须补上。 +- 服务端:CPU 在线合成服务,与设备端共用同一引擎、同一模型、同一音色。 +- 客户端(ElderlyDialer 等)只依赖标准 `android.speech.tts.TextToSpeech` API,不直接依赖本项目代码。 + +## 二、硬性需求(不可妥协) + +1. **方言支持**:除普通话外必须支持方言语音包,首批语种按业务确认(候选:粤语、四川话、河南话等)。引擎选型和语音包结构要为方言保留扩展位,不允许"只能普通话"的固化设计。 +2. **服务器资源紧张(当前最高优先级:在线合成时延与内存)**:线上服务器无 GPU,可用内存约 512MB–1GB。合成必须纯 CPU 推理,单实例内存峰值目标 ≤300MB。不做高并发设计:单实例串行或最多 2 路排队,文本哈希缓存,固定文案优先预生成。 +3. **音色不能是机械音**:使用神经声学模型(VITS/Piper/Matcha/MeloTTS 等 ONNX 模型),禁止拼接式或共振峰合成方案。语音包更新前必须内部试听验收,以老人能听懂、听清为第一标准。 +4. **离线在线音色一致**:设备端引擎与服务器必须使用同一推理引擎(sherpa-onnx / ONNX Runtime)和同一版本的语音包。设备端如需 int8 量化以压缩体积,必须与服务器版本做 AB 对比,双方输出主观一致才能上线。 +5. **设备端体积与内存**:不再设 APK 体积硬性上限(原 ≤80MB 目标已取消),只打包 arm64-v8a。引擎进程按需加载模型,空闲可被系统回收;整点报时等固定文案预生成缓存,不依赖实时合成。 +6. **系统 API 能力完整**:引擎必须支持标准 `TextToSpeech` 的语速调节(`setSpeechRate`)、音调调节(`setPitch`)和语言/音色选择(`setLanguage` / `setVoice`): + - 语速:把 `SynthesisRequest.getSpeechRate()` 映射到模型 speed,支持 0.5–2.0 范围,1.0 为正常语速;老人默认语速由客户端设置(建议 0.85–0.95)。 + - 音调:支持 `SynthesisRequest.getPitch()`,范围 0.5–2.0;sherpa VITS 无原生 pitch 参数,需在引擎侧实现(变速不变调或声码器参数),验收要求能明显听出变化且无明显失真。 + - 语言/音色:在 `onGetVoices()` 暴露全部语音包,含普通话和各方言(BCP-47 命名,如 `zh-CN`、`yue-HK`);实现 `onGetDefaultVoiceNameFor` / `onLoadVoice` / `onIsValidVoiceName`,请求指定 voice 时按 `SynthesisRequest.getVoiceName()` 选择,缺失时回退默认语音包。方言切换不得靠多套引擎。 + +## 三、技术基线 + +- 推理引擎:sherpa-onnx(Android AAR;Linux CPU 版本),ONNX 模型。版本与 ElderlyDialer 现有 2.0.1 对齐或两端统一升级,不允许设备端与服务器版本不一致。 +- 原基线:`vits-piper-zh_CN-xiao_ya-medium`(ElderlyDialer 现用),其训练集 BZNSYP 为非商用许可,**已停止使用**。当前交付包为 `zh-CN-chaowen`(Piper VITS medium,语音数据 CC0),来源与哈希见 `models/README.md`。 +- 模型族候选:VITS/Piper(成熟、体积可控)、Matcha、MeloTTS(自然度更高,需实测 CPU 实时率);方言优先选用同族已发布或可微调的模型,避免引入多套推理框架。 +- 文本前端:中文分词与数字规则沿用 ElderlyDialer 的 `number.fst` / `date.fst` / `phone.fst`,方言读音规则按语音包单独配置。 +- 参数映射:语速直接映射模型 speed;音调需单独实现(复用 sherpa 的 speed 会连带改变时长,不允许用变速冒充变调)。同一文本在相同语速/音调参数下,设备端与服务器输出必须一致。 +- 在线服务:轻量 HTTP 服务,优先 Go/C++ 原生进程(避免 JVM 堆与 GC 开销);若采用 Java/Kotlin 必须限制堆并完成 512MB 环境压测。接口输出 wav/mp3,附带采样率与语音包版本号。 + +## 四、目录规划(建议,按需创建) + +``` +TtsSpeaker/ +├── AGENTS.md +├── android-engine/ # 系统 TTS 引擎(TextToSpeechService,预置 /system/priv-app) +├── server/ # 在线合成服务 +├── models/ # 语音包清单、来源、许可、哈希(模型文件不入 git) +└── docs/ # 试听验收记录、压测数据、部署说明 +``` + +## 五、语音包管理 + +- 模型文件不入 git;记录来源、许可证(Piper 系为 MIT,社区方言模型许可需逐个核实)、SHA256 和采样率。 +- 语音包带版本号,设备端与服务器强制同版本;升级需两端同步发布。 +- 默认语音包变更必须附试听样例和验收记录。 + +## 六、行为约束 + +1. 本目录是独立工程,不改动 `ElderlyDialer/`、`youlai-boot-ttstd/` 代码;客户端接入另行安排。 +2. 遵守根目录 `AGENTS.md`:`*-origin/` 只读,不修改。 +3. 不引入 GPU/CUDA 依赖,不以"以后加 GPU"作为设计前提。 +4. 不做超出需求的抽象:先跑通"普通话 + 一种方言 + 在线/离线同音色"最小闭环,再扩展。 + +## 七、验收标准(草案) + +- 普通话、方言试听样例各 ≥10 条,老人可听懂;无机械音、无明显电音或吞字。 +- 数字读法正确:手机号 3-4-4、金额、日期、时间。 +- 服务端冷启动 ≤15s,热合成短句 ≤1.5s,内存峰值 ≤300MB。 +- 同一文本在设备端与服务器输出主观一致;采样率、声道、音量规格统一。 +- 语速、音调、语言/音色三项参数经系统 `TextToSpeech` API 实测生效:语速 0.5/1.0/2.0 听感正确,音调 0.5/1.0/2.0 可听出变化且不失真,普通话与方言可通过 `setLanguage` / `setVoice` 切换并保持默认设置。 +- 引擎预置进 ROM 后可被 `TextToSpeech` 发现,`ACTION_CHECK_TTS_DATA` 返回成功,系统设置中可设为默认引擎。 + +## 八、决策记录 + +### 2026-11-23 最终方案 + +1. **统一推理栈**:设备端与服务器都使用 sherpa-onnx(设备端 2.0.1 AAR,JNI 复用;服务器用同版本的 Go cgo 绑定 `sherpa-onnx-go/v2 v2.0.1`),语音包为同一份 ONNX 文件与同一份前端资源,保证离线/在线同音色。 +2. **设备端实现语言:Java**。继承 `TextToSpeechService` 编写引擎壳,通过 JNI 调用 sherpa-onnx,不自行实现推理;C++ 只用于后续音调 DSP 等性能敏感模块。理由:团队 Java 基础、官方 Android TTS 示例可参考、JNI 边界小。 +3. **服务器实现语言:Go**(标准库 HTTP + cgo 调 sherpa-onnx v2.0.1;单进程常驻,单实例串行、最多 2 路排队,文本哈希缓存)。实测常驻约 266MB、RTF 0.09、冷启动 1.7s,满足 512MB / 内存峰值 ≤300MB 约束,Go runtime 开销可忽略;C++ 仅作为 Go 受阻时的备选,Python 只用于模型验证。代码与部署见 `server/`。 +4. **设备端形态**:系统引擎 APK(`com.ttstd.tts.engine`)预置 `/system/priv-app`,平台签名;只打包 arm64-v8a,模型不强制 int8 量化,语音包放 `/system/tts/voices/`(manifest.json 描述),开发期回退到应用外部目录。 +5. **模型选型顺序**:MeloTTS 中文(MIT)→ Kokoro 中文音色(Apache-2.0)→ 许可明确的 Piper/VITS 中文包。**停止使用** `xiao_ya`(BZNSYP 非商用)与同源的 Matcha zh-baker 模型。许可不明的社区模型不入库、不上线。 + 2026-11-23 落地:普通话改用 Piper `chaowen`,清单版本 `dev-3`。模型取当前 `rhasspy/piper-voices` 重训权重(数据集 CC0),并注入 sherpa 所需的 9 项 ONNX 元数据;2026-04 的 sherpa 旧包是 Xiao Ya 微调,禁止使用。MeloTTS 因 int8 实测 RTF≈2.1、fp32 常驻 352MB 放弃;Kokoro 中文包 350MB(int8 147MB)、82M 参数,服务端内存与时延预计高于 Piper 包(未实测),暂不采用;`huayan` 因数据许可 Unknown 排除。 +6. **方言路线**:优先粤语(社区 Piper/VITS 模型或自训),其后四川话等;统一 Piper/VITS 模型结构,靠多语音包 + `setLanguage`/`setVoice` 切换,单引擎承载。 +7. **音调实现**:sherpa 无原生 pitch 参数,引擎侧做"变速不变调"式移调(SOLA/WSOLA 时间伸缩 + 重采样),语速仍走模型 speed。当前实现为 `PitchShifter`,后续可替换为 Signalsmith Stretch(MIT);不引入 LGPL 的 SoundTouch。 +8. **参数语义**:`SynthesisRequest.getSpeechRate()` / `getPitch()` 返回的是百分整数(100 = 正常),引擎除以 100 后 clamp 到 0.5–2.0 再映射。 +9. **固定文案预生成**:整点报时等 24 条固定文本在发布前离线合成并随语音包打包,设备端直接播放缓存,冷启动/低内存时不依赖实时推理。 +10. **版权边界**:新版 Piper 仓库(piper1-gpl)与 espeak-ng 为 GPL-3.0,不链接其代码;只使用模型权重与 sherpa-onnx 运行时(Apache-2.0)。 +11. **约束调整(2026-11-23)**:取消设备端 APK ≤80MB 目标,设备端体积不再作为选型约束;当前最高优先级是服务器在线合成的时延与内存占用。 + +### 引擎开发约定 + +- 工程目录:`android-engine/`,构建 `./gradlew :app:assembleDebug --offline`(AGP 8.13.2 / Gradle 8.13 / JDK 21,`local.properties` 指向 `F:/AndroidSDK`,不入 git)。 +- 语音包清单只描述路径与参数,模型文件不进 git;`voices.example/` 仅作开发样例。 +- 首版引擎只做普通话最小闭环:加载语音包 → 合成 → 语速/音调/语音选择生效 → `ACTION_CHECK_TTS_DATA` 通过;方言与服务端在此之后接入。 + +### 引擎运行时坑(2026-11-23 实测,Honor MagicOS 15 / Android 15) + +- TTS 服务 intent-filter 必须带 `android.intent.category.DEFAULT`:框架 `TtsEngines.getEngines()` 用 `MATCH_DEFAULT_ONLY` 查询,缺 category 的系统里看不到该引擎。 +- `TextToSpeechService.onCreate()` 内部会回调 `onLoadLanguage`,语音库与合成器必须在 `super.onCreate()` 之前初始化。 +- `OfflineTts` 加载绝对路径语音包时必须传 `assetManager = null`,否则原生层拒读。 +- `SynthesisCallback.audioAvailable()` 单次不能超过约 20ms 音频(`sampleRate/50` 个采样),超出抛 `IllegalArgumentException` 并让进程 SIGABRT 崩溃;`PcmWriter` 已按 20ms 切片。 +- sherpa 的 `GenerationConfig` 第一个参数是 silenceScale,传 0 会告警并跳过静音缩放,用 0.2。 +- 开发期语音包放内部存储 `files/voices`(根目录优先级:`/system/tts/voices` → 内部 → 外部)。adb 推到外部 `Android/data//` 时由 shell 创建的目录在此 ROM 上归 shell 所有,应用进程无法遍历;用 `tar -cf - . | adb exec-in run-as tar -C files/voices -xf -` 推入内部存储。 +- 测试客户端 `test-client/`(包名 `com.ttstd.tts.testclient`,显式绑定本引擎):`am start -n com.ttstd.tts.testclient/.MainActivity --ez autospeak true` 自动朗读,`--ez autosweep true` 自动遍历语速/音调。 + +### 首次朗读时延与预加载(2026-11-23 实测,荣耀 Android 15) + +- 时延构成:冷启动加载模型约 2.5s,预热(合成一句丢弃)约 145ms,短句实时合成按句 RTF 0.2–0.3。 +- `TextToSpeechService.onCreate()` 后异步线程 `tts-warmup` 预加载默认语音包并预热;绑定后约 2.7s 内完成,此后朗读请求到开始合成仅约 30ms。 +- 绑定后立即朗读时,`Synthesizer.synchronized` 让合成等待预热结束,不会二次加载模型;最坏时延仍为一次模型加载。 + +### 语音包导入与更换(2026-11-23 实测,荣耀 Android 15) + +- 设置页「导入语音包」走 SAF 目录选择(`ACTION_OPEN_DOCUMENT_TREE`),把所选目录整树复制到 `files/voices/user/import-<时间戳>/`;只有 manifest.json 可解析、model/tokens/lexicon/ruleFsts 全部存在、且模型文件 SHA-256 与清单 `sha256` 字段一致的语音包才生效。哈希缺失或不匹配会整目录删除并单独提示「SHA-256 校验未通过」。实测复制约 63MB 语音包约 2 秒,哈希校验在同一后台线程完成。 +- 语音包发现顺序(后者同名覆盖前者):`/system/tts/voices` → `files/voices` → 外部目录 → `files/voices/user/import-*`。文件缺失的条目在解析时直接跳过——外部目录残留的 manifest 曾因“先合并后过滤”覆盖掉内部有效包,导致 native 创建 OfflineTts 失败。 +- 切换立即生效:`Synthesizer` 以 `modelPath` 判断是否重载,同名包被导入覆盖也会换模型;默认音色仍按语音包名写入 SharedPreferences。 +- 「删除导入包」删除整个导入目录并重载,内置包不可删;若删除的是当前音色,自动回退 manifest 默认包。 +- `TextToSpeech` 客户端在 init 时缓存语音列表,导入后需重新绑定引擎(重进设置页或重选引擎)才能在系统/客户端看到新音色。 +- 导入/删除时 `SettingsActivity` 会重建试听客户端并重载仓库;引擎服务与设置页同进程共享 `VoiceRepository.get()` 单例,无需重启服务。 +- targetSdk 37 在 Android 15 强制 edge-to-edge,Activity 未退出该模式时内容会顶到状态栏下面;主题需加 `android:windowOptOutEdgeToEdgeEnforcement=true`(已加 `EngineTheme`)。 + +### 引擎设置入口(2026-11-23,荣耀 Android 15 实测) + +- Android 12+ 框架从 TTS 服务的 meta-data 取设置页:``,资源为 ``;旧框架仍用 `com.android.settings.TTS_SETTINGS` action,两种入口已在 manifest 同时声明。 +- 系统设置路径:首选引擎列表(每行行尾 ⓘ「更多详情」)→ 引擎子页(语言 / 「"XX"的设置」/ 安装语音数据)→ 点「"XX"的设置」经 `TtsEngines.getSettingsIntent()` 打开引擎的 SettingsActivity。 +- 必须提供两个无界面活动,否则系统 TTS 页异常:`android.speech.tts.engine.CHECK_TTS_DATA`(缺省时「默认语言状态」永远“正在检查…”),返回 `EXTRA_AVAILABLE_VOICES`(ISO3,如 `zho-CHN`);`android.speech.tts.engine.GET_SAMPLE_TEXT`(缺省时系统会无限拉起该 action,日志刷屏),返回 `EXTRA_SAMPLE_TEXT` 例句。 +- 子页「安装语音数据」行在 `unavailableVoices` 为空时置灰,属标准行为,无需 INSTALL_TTS_DATA 活动。 +- 设置页 `SettingsActivity` 提供默认音色选择与试听;选择写入 SharedPreferences(`tts_settings/default_voice`),`VoiceRepository.getDefault()` 每次动态读取,设置后无需重启引擎。 +- `settings put secure tts_default_synth com.ttstd.tts.engine` 可切换默认引擎且进入 TTS 设置不再被重置;此前“无法选择/被重置”的根因是服务缺 `CATEGORY_DEFAULT` 未注册成功。 +- 定制平板(A0808)上尚未验证,需连接设备后复测齿轮入口。 \ No newline at end of file diff --git a/android-engine/.gitignore b/android-engine/.gitignore new file mode 100644 index 0000000..36c9229 --- /dev/null +++ b/android-engine/.gitignore @@ -0,0 +1,6 @@ +.gradle/ +build/ +local.properties +*.apk +*.iml +.idea/ \ No newline at end of file diff --git a/android-engine/app/build.gradle b/android-engine/app/build.gradle new file mode 100644 index 0000000..1dd26d4 --- /dev/null +++ b/android-engine/app/build.gradle @@ -0,0 +1,42 @@ +plugins { + id 'com.android.application' +} + +android { + namespace 'com.ttstd.tts.engine' + compileSdk 37 + + defaultConfig { + applicationId 'com.ttstd.tts.engine' + minSdk 23 + targetSdk 37 + versionCode 1 + versionName '0.1.0' + + ndk { + abiFilters 'arm64-v8a' + } + } + + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' + } + } + + compileOptions { + sourceCompatibility JavaVersion.VERSION_17 + targetCompatibility JavaVersion.VERSION_17 + } + + lint { + abortOnError false + checkReleaseBuilds = false + } +} + +dependencies { + implementation files('libs/sherpa-onnx-2.0.1.aar') + implementation 'org.jetbrains.kotlin:kotlin-stdlib:2.4.21' +} \ No newline at end of file diff --git a/android-engine/app/libs/sherpa-onnx-2.0.1.aar b/android-engine/app/libs/sherpa-onnx-2.0.1.aar new file mode 100644 index 0000000..865563c Binary files /dev/null and b/android-engine/app/libs/sherpa-onnx-2.0.1.aar differ diff --git a/android-engine/app/proguard-rules.pro b/android-engine/app/proguard-rules.pro new file mode 100644 index 0000000..662cfaa --- /dev/null +++ b/android-engine/app/proguard-rules.pro @@ -0,0 +1,2 @@ +-keep class com.k2fsa.sherpa.onnx.** { *; } +-keepclassmembers class kotlin.jvm.functions.** { *; } \ No newline at end of file diff --git a/android-engine/app/src/main/AndroidManifest.xml b/android-engine/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..600dfc0 --- /dev/null +++ b/android-engine/app/src/main/AndroidManifest.xml @@ -0,0 +1,54 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/android-engine/app/src/main/java/com/ttstd/tts/engine/CheckVoiceDataActivity.java b/android-engine/app/src/main/java/com/ttstd/tts/engine/CheckVoiceDataActivity.java new file mode 100644 index 0000000..41f1d69 --- /dev/null +++ b/android-engine/app/src/main/java/com/ttstd/tts/engine/CheckVoiceDataActivity.java @@ -0,0 +1,47 @@ +package com.ttstd.tts.engine; + +import android.app.Activity; +import android.content.Intent; +import android.os.Bundle; +import android.speech.tts.TextToSpeech; +import android.util.Log; + +import java.util.ArrayList; +import java.util.Locale; +import java.util.MissingResourceException; + +public class CheckVoiceDataActivity extends Activity { + private static final String TAG = "TtsCheckVoiceData"; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + ArrayList available = new ArrayList<>(); + for (VoicePack pack : VoiceRepository.get(this).all()) { + available.add(iso3(pack)); + } + Log.i(TAG, "checkFor=" + getIntent().getStringExtra(TextToSpeech.Engine.EXTRA_CHECK_VOICE_DATA_FOR) + + " available=" + available); + Intent data = new Intent(); + data.putStringArrayListExtra(TextToSpeech.Engine.EXTRA_AVAILABLE_VOICES, available); + setResult(RESULT_OK, data); + finish(); + } + + private static String iso3(VoicePack pack) { + Locale locale = pack.locale(); + String language; + String country; + try { + language = locale.getISO3Language(); + } catch (MissingResourceException e) { + language = locale.getLanguage(); + } + try { + country = locale.getISO3Country(); + } catch (MissingResourceException e) { + country = locale.getCountry(); + } + return language + "-" + country; + } +} \ No newline at end of file diff --git a/android-engine/app/src/main/java/com/ttstd/tts/engine/GetSampleTextActivity.java b/android-engine/app/src/main/java/com/ttstd/tts/engine/GetSampleTextActivity.java new file mode 100644 index 0000000..ef59d57 --- /dev/null +++ b/android-engine/app/src/main/java/com/ttstd/tts/engine/GetSampleTextActivity.java @@ -0,0 +1,17 @@ +package com.ttstd.tts.engine; + +import android.app.Activity; +import android.content.Intent; +import android.os.Bundle; +import android.speech.tts.TextToSpeech; + +public class GetSampleTextActivity extends Activity { + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + Intent data = new Intent(); + data.putExtra(TextToSpeech.Engine.EXTRA_SAMPLE_TEXT, getString(R.string.settings_sample)); + setResult(RESULT_OK, data); + finish(); + } +} \ No newline at end of file diff --git a/android-engine/app/src/main/java/com/ttstd/tts/engine/PcmWriter.java b/android-engine/app/src/main/java/com/ttstd/tts/engine/PcmWriter.java new file mode 100644 index 0000000..009072f --- /dev/null +++ b/android-engine/app/src/main/java/com/ttstd/tts/engine/PcmWriter.java @@ -0,0 +1,26 @@ +package com.ttstd.tts.engine; + +import android.speech.tts.SynthesisCallback; + +final class PcmWriter { + private PcmWriter() { + } + + static boolean write(SynthesisCallback callback, float[] samples, int sampleRate) { + int maxSamples = Math.max(1, sampleRate / 50); + for (int from = 0; from < samples.length; from += maxSamples) { + int len = Math.min(maxSamples, samples.length - from); + byte[] pcm = new byte[len * 2]; + for (int i = 0; i < len; i++) { + float v = samples[from + i]; + if (v > 1f) v = 1f; + if (v < -1f) v = -1f; + int s = Math.round(v * 32767f); + pcm[i * 2] = (byte) s; + pcm[i * 2 + 1] = (byte) (s >> 8); + } + if (callback.audioAvailable(pcm, 0, pcm.length) != 0) return false; + } + return true; + } +} \ No newline at end of file diff --git a/android-engine/app/src/main/java/com/ttstd/tts/engine/PitchShifter.java b/android-engine/app/src/main/java/com/ttstd/tts/engine/PitchShifter.java new file mode 100644 index 0000000..b35d5cf --- /dev/null +++ b/android-engine/app/src/main/java/com/ttstd/tts/engine/PitchShifter.java @@ -0,0 +1,80 @@ +package com.ttstd.tts.engine; + +/** + * Pitch shift without changing duration: time-stretch by the pitch factor, then resample by it. + * The server must use the same algorithm and parameters to keep output consistent. + */ +final class PitchShifter { + private static final int GRAIN = 1024; + private static final int OVERLAP = 512; + private static final int HOP_S = GRAIN - OVERLAP; + private static final int SEARCH = 128; + + private PitchShifter() { + } + + static float[] shift(float[] samples, float factor) { + if (samples.length == 0 || Math.abs(factor - 1f) < 0.01f) return samples; + float[] stretched = timeStretch(samples, factor); + return resample(stretched, factor); + } + + private static float[] timeStretch(float[] in, float factor) { + int hopA = Math.max(1, Math.round(HOP_S / factor)); + float[] window = hann(GRAIN); + int expected = Math.max(GRAIN, Math.round(in.length * factor)); + float[] out = new float[expected + GRAIN]; + + int inPos = 0; + int outPos = 0; + while (inPos + GRAIN <= in.length) { + int best = inPos; + if (outPos > 0) { + int from = Math.max(0, inPos - SEARCH); + int to = Math.min(in.length - GRAIN, inPos + SEARCH); + double bestCorr = -1; + for (int cand = from; cand <= to; cand += 4) { + double corr = 0; + for (int i = 0; i < OVERLAP; i++) { + corr += (double) in[cand + i] * out[outPos + i]; + } + if (corr > bestCorr) { + bestCorr = corr; + best = cand; + } + } + } + for (int i = 0; i < GRAIN; i++) { + out[outPos + i] += in[best + i] * window[i]; + } + inPos += hopA; + outPos += HOP_S; + } + + float[] result = new float[expected]; + System.arraycopy(out, 0, result, 0, Math.min(expected, out.length)); + return result; + } + + private static float[] resample(float[] in, float factor) { + int outLen = Math.max(1, Math.round(in.length / factor)); + float[] out = new float[outLen]; + for (int i = 0; i < outLen; i++) { + double pos = i * (double) factor; + int i0 = (int) pos; + if (i0 >= in.length) break; + int i1 = Math.min(i0 + 1, in.length - 1); + double frac = pos - i0; + out[i] = (float) (in[i0] * (1 - frac) + in[i1] * frac); + } + return out; + } + + private static float[] hann(int size) { + float[] w = new float[size]; + for (int i = 0; i < size; i++) { + w[i] = (float) (0.5 - 0.5 * Math.cos(2 * Math.PI * i / (size - 1))); + } + return w; + } +} \ No newline at end of file diff --git a/android-engine/app/src/main/java/com/ttstd/tts/engine/SettingsActivity.java b/android-engine/app/src/main/java/com/ttstd/tts/engine/SettingsActivity.java new file mode 100644 index 0000000..414da62 --- /dev/null +++ b/android-engine/app/src/main/java/com/ttstd/tts/engine/SettingsActivity.java @@ -0,0 +1,238 @@ +package com.ttstd.tts.engine; + +import android.app.Activity; +import android.app.AlertDialog; +import android.content.Intent; +import android.database.Cursor; +import android.net.Uri; +import android.os.Bundle; +import android.provider.DocumentsContract; +import android.speech.tts.TextToSpeech; +import android.speech.tts.Voice; +import android.util.Log; +import android.view.View; +import android.widget.Button; +import android.widget.RadioButton; +import android.widget.RadioGroup; +import android.widget.TextView; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.List; +import java.util.Set; + +public class SettingsActivity extends Activity { + private static final String TAG = "TtsEngineSettings"; + private static final String ENGINE = "com.ttstd.tts.engine"; + private static final int REQUEST_IMPORT = 1001; + + private RadioGroup group; + private TextView info; + private TextView status; + private Button importButton; + private Button deleteButton; + private TextToSpeech preview; + private VoiceRepository repository; + private String selected = ""; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setTitle(R.string.settings_title); + setContentView(R.layout.activity_settings); + group = findViewById(R.id.voice_group); + info = findViewById(R.id.voice_info); + status = findViewById(R.id.import_status); + importButton = findViewById(R.id.btn_import); + deleteButton = findViewById(R.id.btn_delete); + + repository = VoiceRepository.get(this); + repository.reload(); + rebuild(); + + importButton.setOnClickListener(v -> importPack()); + deleteButton.setOnClickListener(v -> confirmDelete()); + findViewById(R.id.btn_preview).setOnClickListener(v -> preview()); + initPreview(); + } + + private void rebuild() { + group.setOnCheckedChangeListener(null); + group.removeAllViews(); + List packs = repository.all(); + VoicePack current = repository.getDefault(); + selected = current != null ? current.name : ""; + for (VoicePack pack : packs) { + RadioButton radio = new RadioButton(this); + radio.setText(pack.label + "(" + pack.localeTag + ")"); + radio.setId(View.generateViewId()); + radio.setTag(pack.name); + group.addView(radio); + if (pack.name.equals(selected)) group.check(radio.getId()); + } + info.setVisibility(packs.isEmpty() ? TextView.VISIBLE : TextView.GONE); + if (packs.isEmpty()) info.setText(R.string.settings_empty); + group.setOnCheckedChangeListener((g, checkedId) -> { + RadioButton radio = g.findViewById(checkedId); + if (radio == null) return; + selected = String.valueOf(radio.getTag()); + getSharedPreferences(VoiceRepository.PREFS, MODE_PRIVATE) + .edit().putString(VoiceRepository.KEY_DEFAULT_VOICE, selected).apply(); + updateActions(); + }); + updateActions(); + } + + private void updateActions() { + VoicePack pack = repository.get(selected); + deleteButton.setEnabled(pack != null && repository.isUserPack(pack)); + } + + private void importPack() { + Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE); + intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); + startActivityForResult(intent, REQUEST_IMPORT); + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + if (requestCode != REQUEST_IMPORT || resultCode != RESULT_OK + || data == null || data.getData() == null) return; + Uri treeUri = data.getData(); + importButton.setEnabled(false); + deleteButton.setEnabled(false); + status.setText(R.string.settings_importing); + new Thread(() -> doImport(treeUri), "tts-import").start(); + } + + private void doImport(Uri treeUri) { + File dest = new File(VoiceRepository.userDir(this), "import-" + System.currentTimeMillis()); + String message; + try { + if (!dest.mkdirs() && !dest.isDirectory()) throw new IOException("mkdir " + dest); + copyDocument(treeUri, DocumentsContract.getTreeDocumentId(treeUri), dest); + int count = VoiceRepository.validate(dest); + if (count > 0) { + repository.reload(); + message = getString(R.string.settings_import_ok, count); + } else { + deleteTree(dest); + message = getString(count == VoiceRepository.INVALID_HASH + ? R.string.settings_import_hash : R.string.settings_import_fail); + } + } catch (Exception e) { + Log.e(TAG, "import failed", e); + deleteTree(dest); + message = getString(R.string.settings_import_fail); + } + String text = message; + runOnUiThread(() -> { + status.setText(text); + importButton.setEnabled(true); + rebuild(); + initPreview(); + }); + } + + private void copyDocument(Uri treeUri, String documentId, File dest) throws IOException { + Uri children = DocumentsContract.buildChildDocumentsUriUsingTree(treeUri, documentId); + String[] projection = { + DocumentsContract.Document.COLUMN_DOCUMENT_ID, + DocumentsContract.Document.COLUMN_DISPLAY_NAME, + DocumentsContract.Document.COLUMN_MIME_TYPE, + }; + try (Cursor cursor = getContentResolver().query(children, projection, null, null, null)) { + if (cursor == null) throw new IOException("query " + children); + while (cursor.moveToNext()) { + String childId = cursor.getString(0); + String name = cursor.getString(1); + String mime = cursor.getString(2); + if (name == null || name.contains("/") || name.contains("\\") + || name.equals(".") || name.equals("..")) { + throw new IOException("bad entry name: " + name); + } + File child = new File(dest, name); + if (DocumentsContract.Document.MIME_TYPE_DIR.equals(mime)) { + if (!child.mkdirs() && !child.isDirectory()) throw new IOException("mkdir " + child); + copyDocument(treeUri, childId, child); + } else { + Uri source = DocumentsContract.buildDocumentUriUsingTree(treeUri, childId); + try (InputStream in = getContentResolver().openInputStream(source); + FileOutputStream out = new FileOutputStream(child)) { + if (in == null) throw new IOException("open " + source); + byte[] buf = new byte[64 * 1024]; + int n; + while ((n = in.read(buf)) > 0) out.write(buf, 0, n); + } + } + } + } + } + + private void confirmDelete() { + VoicePack pack = repository.get(selected); + if (pack == null) return; + if (!repository.isUserPack(pack)) { + status.setText(R.string.settings_delete_builtin); + return; + } + new AlertDialog.Builder(this) + .setMessage(getString(R.string.settings_delete_confirm, pack.label)) + .setPositiveButton(android.R.string.ok, (d, w) -> { + if (repository.deleteUserPack(pack)) { + status.setText(R.string.settings_deleted); + rebuild(); + initPreview(); + } + }) + .setNegativeButton(android.R.string.cancel, null) + .show(); + } + + private static void deleteTree(File file) { + if (file.isDirectory()) { + File[] children = file.listFiles(); + if (children != null) for (File child : children) deleteTree(child); + } + file.delete(); + } + + private void initPreview() { + if (preview != null) { + preview.shutdown(); + preview = null; + } + preview = new TextToSpeech(this, status -> { + if (status != TextToSpeech.SUCCESS) Log.e(TAG, "preview engine init failed: " + status); + }, ENGINE); + } + + private void preview() { + if (preview == null || selected.isEmpty()) return; + Set voices = preview.getVoices(); + if (voices != null) { + for (Voice voice : voices) { + if (voice.getName().equals(selected)) { + preview.setVoice(voice); + break; + } + } + } + int result = preview.speak(getString(R.string.settings_sample), + TextToSpeech.QUEUE_FLUSH, null, "preview"); + if (result != TextToSpeech.SUCCESS) Log.e(TAG, "preview speak failed: " + result); + } + + @Override + protected void onDestroy() { + if (preview != null) { + preview.stop(); + preview.shutdown(); + preview = null; + } + super.onDestroy(); + } +} \ No newline at end of file diff --git a/android-engine/app/src/main/java/com/ttstd/tts/engine/Synthesizer.java b/android-engine/app/src/main/java/com/ttstd/tts/engine/Synthesizer.java new file mode 100644 index 0000000..2341412 --- /dev/null +++ b/android-engine/app/src/main/java/com/ttstd/tts/engine/Synthesizer.java @@ -0,0 +1,146 @@ +package com.ttstd.tts.engine; + +import android.speech.tts.SynthesisCallback; +import android.util.Log; + +import com.k2fsa.sherpa.onnx.GenerationConfig; +import com.k2fsa.sherpa.onnx.OfflineTts; +import com.k2fsa.sherpa.onnx.OfflineTtsConfig; +import com.k2fsa.sherpa.onnx.OfflineTtsKittenModelConfig; +import com.k2fsa.sherpa.onnx.OfflineTtsKokoroModelConfig; +import com.k2fsa.sherpa.onnx.OfflineTtsMatchaModelConfig; +import com.k2fsa.sherpa.onnx.OfflineTtsModelConfig; +import com.k2fsa.sherpa.onnx.OfflineTtsPocketModelConfig; +import com.k2fsa.sherpa.onnx.OfflineTtsSupertonicModelConfig; +import com.k2fsa.sherpa.onnx.OfflineTtsVitsModelConfig; +import com.k2fsa.sherpa.onnx.OfflineTtsZipVoiceModelConfig; + +import java.util.ArrayList; +import java.util.List; + +import kotlin.jvm.functions.Function1; + +final class Synthesizer { + interface StopSignal { + boolean stopped(); + } + + private static final String TAG = "TtsSynthesizer"; + + private OfflineTts tts; + private String loadedModel; + + Synthesizer() { + } + + synchronized int sampleRate(VoicePack pack) { + return obtain(pack).sampleRate(); + } + + void warmUp(VoicePack pack) { + synchronized (this) { + obtain(pack); + long start = System.currentTimeMillis(); + GenerationConfig gen = new GenerationConfig(0.2f, 1f, pack.speakerId, + null, 0, null, 5, null, null, null); + tts.generateWithConfigAndCallback("你好", gen, new Function1() { + @Override + public Integer invoke(float[] samples) { + return 1; + } + }); + Log.i(TAG, "warmup done in " + (System.currentTimeMillis() - start) + " ms"); + } + } + + synchronized void synthesize(VoicePack pack, String text, float speed, float pitch, + SynthesisCallback callback, StopSignal stop) { + OfflineTts engine = obtain(pack); + final int sampleRate = engine.sampleRate(); + final boolean shift = Math.abs(pitch - 1f) >= 0.01f; + final List pending = shift ? new ArrayList<>() : null; + final boolean[] aborted = {false}; + + GenerationConfig gen = new GenerationConfig(0.2f, speed, pack.speakerId, + null, 0, null, 5, null, null, null); + engine.generateWithConfigAndCallback(text, gen, new Function1() { + @Override + public Integer invoke(float[] samples) { + if (stop.stopped()) { + aborted[0] = true; + return 0; + } + if (shift) { + pending.add(samples); + return 1; + } + if (!PcmWriter.write(callback, samples, sampleRate)) { + aborted[0] = true; + return 0; + } + return 1; + } + }); + + if (shift && !aborted[0]) { + float[] shifted = PitchShifter.shift(concat(pending), pitch); + PcmWriter.write(callback, shifted, sampleRate); + } + } + + synchronized void release() { + releaseLocked(); + } + + private OfflineTts obtain(VoicePack pack) { + if (tts != null && pack.modelPath.equals(loadedModel)) return tts; + releaseLocked(); + + OfflineTtsVitsModelConfig vits = new OfflineTtsVitsModelConfig(); + vits.setModel(pack.modelPath); + vits.setTokens(pack.tokensPath); + if (!pack.lexiconPath.isEmpty()) vits.setLexicon(pack.lexiconPath); + vits.setDataDir(pack.dataDir); + + OfflineTtsModelConfig model = new OfflineTtsModelConfig( + vits, + new OfflineTtsMatchaModelConfig(), + new OfflineTtsKokoroModelConfig(), + new OfflineTtsZipVoiceModelConfig(), + new OfflineTtsKittenModelConfig(), + new OfflineTtsPocketModelConfig(), + new OfflineTtsSupertonicModelConfig(), + 2, false, "cpu"); + OfflineTtsConfig config = new OfflineTtsConfig(model, pack.ruleFsts, "", 1, 0.2f); + + long start = System.currentTimeMillis(); + tts = new OfflineTts(null, config); + loadedModel = pack.modelPath; + Log.i(TAG, "loaded " + pack.name + " in " + (System.currentTimeMillis() - start) + " ms"); + return tts; + } + + private void releaseLocked() { + if (tts != null) { + try { + tts.release(); + } catch (Throwable t) { + Log.w(TAG, "release failed", t); + } + } + tts = null; + loadedModel = null; + } + + private static float[] concat(List chunks) { + int total = 0; + for (float[] chunk : chunks) total += chunk.length; + float[] out = new float[total]; + int offset = 0; + for (float[] chunk : chunks) { + System.arraycopy(chunk, 0, out, offset, chunk.length); + offset += chunk.length; + } + return out; + } +} \ No newline at end of file diff --git a/android-engine/app/src/main/java/com/ttstd/tts/engine/TtsEngineService.java b/android-engine/app/src/main/java/com/ttstd/tts/engine/TtsEngineService.java new file mode 100644 index 0000000..5054993 --- /dev/null +++ b/android-engine/app/src/main/java/com/ttstd/tts/engine/TtsEngineService.java @@ -0,0 +1,139 @@ +package com.ttstd.tts.engine; + +import android.media.AudioFormat; +import android.speech.tts.SynthesisCallback; +import android.speech.tts.SynthesisRequest; +import android.speech.tts.TextToSpeech; +import android.speech.tts.TextToSpeechService; +import android.speech.tts.Voice; +import android.util.Log; + +import java.util.List; +import java.util.Locale; +import java.util.MissingResourceException; + +public class TtsEngineService extends TextToSpeechService { + private static final String TAG = "TtsEngineService"; + private static final int MIN_PERCENT = 50; + private static final int MAX_PERCENT = 200; + + private final Object synthesisLock = new Object(); + private volatile boolean stopRequested; + private VoiceRepository voices; + private Synthesizer synthesizer; + + @Override + public void onCreate() { + voices = VoiceRepository.get(this); + synthesizer = new Synthesizer(); + super.onCreate(); + + VoicePack pack = voices.getDefault(); + if (pack != null) { + new Thread(() -> { + try { + synthesizer.warmUp(pack); + } catch (Throwable t) { + Log.w(TAG, "warmup failed", t); + } + }, "tts-warmup").start(); + } + } + + @Override + public void onDestroy() { + stopRequested = true; + synthesizer.release(); + super.onDestroy(); + } + + @Override + protected String[] onGetLanguage() { + VoicePack pack = voices.getDefault(); + if (pack == null) return new String[]{"cmn", "zho", "CN"}; + Locale locale = pack.locale(); + String language = locale.getLanguage(); + String iso3; + try { + iso3 = locale.getISO3Language(); + } catch (MissingResourceException e) { + iso3 = language; + } + return new String[]{language, iso3, locale.getCountry()}; + } + + @Override + protected int onIsLanguageAvailable(String lang, String country, String variant) { + return voices.hasLanguage(lang) ? TextToSpeech.LANG_AVAILABLE : TextToSpeech.LANG_NOT_SUPPORTED; + } + + @Override + protected int onLoadLanguage(String lang, String country, String variant) { + return onIsLanguageAvailable(lang, country, variant); + } + + @Override + public int onIsValidVoiceName(String voiceName) { + return voices.get(voiceName) != null ? TextToSpeech.SUCCESS : TextToSpeech.ERROR; + } + + @Override + public int onLoadVoice(String voiceName) { + return onIsValidVoiceName(voiceName); + } + + @Override + public String onGetDefaultVoiceNameFor(String lang, String country, String variant) { + VoicePack pack = voices.resolve(null, lang, country, variant); + return pack != null ? pack.name : null; + } + + @Override + public List onGetVoices() { + return voices.toVoices(); + } + + @Override + protected void onSynthesizeText(SynthesisRequest request, SynthesisCallback callback) { + VoicePack pack = voices.resolve(request.getVoiceName(), request.getLanguage(), + request.getCountry(), request.getVariant()); + if (pack == null) { + Log.e(TAG, "no voice pack available"); + callback.error(); + return; + } + + stopRequested = false; + synchronized (synthesisLock) { + try { + int sampleRate = synthesizer.sampleRate(pack); + int started = callback.start(sampleRate, AudioFormat.ENCODING_PCM_16BIT, 1); + if (started != 0) { + Log.e(TAG, "callback.start failed: " + started); + callback.error(); + return; + } + float speed = clampPercent(request.getSpeechRate()); + float pitch = clampPercent(request.getPitch()); + synthesizer.synthesize(pack, request.getText(), speed, pitch, + callback, () -> stopRequested); + callback.done(); + } catch (Throwable t) { + Log.e(TAG, "synthesis failed", t); + callback.error(); + } finally { + stopRequested = false; + } + } + } + + @Override + protected void onStop() { + stopRequested = true; + } + + private static float clampPercent(int percent) { + int value = Math.max(MIN_PERCENT, Math.min(MAX_PERCENT, percent)); + return value / 100f; + } +} \ No newline at end of file diff --git a/android-engine/app/src/main/java/com/ttstd/tts/engine/VoicePack.java b/android-engine/app/src/main/java/com/ttstd/tts/engine/VoicePack.java new file mode 100644 index 0000000..426d26b --- /dev/null +++ b/android-engine/app/src/main/java/com/ttstd/tts/engine/VoicePack.java @@ -0,0 +1,40 @@ +package com.ttstd.tts.engine; + +import java.io.File; +import java.util.Locale; + +final class VoicePack { + final String name; + final String localeTag; + final String label; + final int speakerId; + final int quality; + final String modelPath; + final String lexiconPath; + final String tokensPath; + final String dataDir; + final String ruleFsts; + final String modelSha256; + final File root; + + VoicePack(String name, String localeTag, String label, int speakerId, int quality, + String modelPath, String lexiconPath, String tokensPath, String dataDir, String ruleFsts, + String modelSha256, File root) { + this.name = name; + this.localeTag = localeTag; + this.label = label; + this.speakerId = speakerId; + this.quality = quality; + this.modelPath = modelPath; + this.lexiconPath = lexiconPath; + this.tokensPath = tokensPath; + this.dataDir = dataDir; + this.ruleFsts = ruleFsts; + this.modelSha256 = modelSha256; + this.root = root; + } + + Locale locale() { + return Locale.forLanguageTag(localeTag.replace('_', '-')); + } +} \ No newline at end of file diff --git a/android-engine/app/src/main/java/com/ttstd/tts/engine/VoiceRepository.java b/android-engine/app/src/main/java/com/ttstd/tts/engine/VoiceRepository.java new file mode 100644 index 0000000..a4f6670 --- /dev/null +++ b/android-engine/app/src/main/java/com/ttstd/tts/engine/VoiceRepository.java @@ -0,0 +1,282 @@ +package com.ttstd.tts.engine; + +import android.content.Context; +import android.content.SharedPreferences; +import android.speech.tts.Voice; +import android.util.Log; + +import org.json.JSONArray; +import org.json.JSONObject; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; + +final class VoiceRepository { + private static final String TAG = "TtsVoiceRepository"; + private static final String SYSTEM_ROOT = "/system/tts/voices"; + private static final String USER_DIR = "user"; + static final String PREFS = "tts_settings"; + static final String KEY_DEFAULT_VOICE = "default_voice"; + + private static volatile VoiceRepository current; + + private volatile LinkedHashMap packs = new LinkedHashMap<>(); + private volatile String defaultName = ""; + private final Context context; + private final SharedPreferences prefs; + + private VoiceRepository(Context context) { + this.context = context.getApplicationContext(); + this.prefs = this.context.getSharedPreferences(PREFS, Context.MODE_PRIVATE); + } + + static VoiceRepository get(Context context) { + VoiceRepository repo = current; + if (repo == null) { + synchronized (VoiceRepository.class) { + repo = current; + if (repo == null) { + repo = new VoiceRepository(context); + repo.reload(); + current = repo; + } + } + } + return repo; + } + + static File userDir(Context context) { + return new File(context.getFilesDir(), "voices/" + USER_DIR); + } + + void reload() { + LinkedHashMap merged = new LinkedHashMap<>(); + String firstDefault = ""; + for (File root : roots()) { + File manifest = new File(root, "manifest.json"); + if (!manifest.isFile()) continue; + try (InputStream in = new FileInputStream(manifest)) { + JSONObject json = new JSONObject(readAll(in)); + String rootDefault = parse(root, json, merged); + if (firstDefault.isEmpty()) firstDefault = rootDefault; + } catch (Exception e) { + Log.e(TAG, "failed to load voices from " + root, e); + } + } + if (!merged.containsKey(firstDefault)) { + firstDefault = merged.isEmpty() ? "" : merged.keySet().iterator().next(); + } + packs = merged; + defaultName = firstDefault; + Log.i(TAG, "voices " + merged.keySet()); + } + + private List roots() { + List roots = new ArrayList<>(); + roots.add(new File(SYSTEM_ROOT)); + roots.add(new File(context.getFilesDir(), "voices")); + File external = context.getExternalFilesDir(null); + if (external != null) roots.add(new File(external, "voices")); + File[] imports = userDir(context).listFiles(File::isDirectory); + if (imports != null) { + Arrays.sort(imports); + roots.addAll(Arrays.asList(imports)); + } + return roots; + } + + static final int INVALID_HASH = -1; + + static int validate(File root) { + File manifest = new File(root, "manifest.json"); + if (!manifest.isFile()) return 0; + try (InputStream in = new FileInputStream(manifest)) { + LinkedHashMap packs = new LinkedHashMap<>(); + parse(root, new JSONObject(readAll(in)), packs); + if (packs.isEmpty()) return 0; + for (VoicePack pack : packs.values()) { + if (!usable(pack)) return 0; + if (pack.modelSha256.isEmpty()) return INVALID_HASH; + if (!pack.modelSha256.equalsIgnoreCase(sha256(new File(pack.modelPath)))) { + return INVALID_HASH; + } + } + return packs.size(); + } catch (Exception e) { + Log.w(TAG, "invalid voice pack at " + root, e); + return 0; + } + } + + private static String sha256(File file) { + try (InputStream in = new FileInputStream(file)) { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + byte[] buf = new byte[64 * 1024]; + int n; + while ((n = in.read(buf)) > 0) digest.update(buf, 0, n); + StringBuilder hex = new StringBuilder(); + for (byte b : digest.digest()) hex.append(String.format(Locale.ROOT, "%02x", b)); + return hex.toString(); + } catch (Exception e) { + Log.w(TAG, "sha256 failed for " + file, e); + return ""; + } + } + + private static boolean usable(VoicePack pack) { + if (!new File(pack.modelPath).isFile()) return false; + if (!pack.tokensPath.isEmpty() && !new File(pack.tokensPath).isFile()) return false; + if (!pack.lexiconPath.isEmpty() && !new File(pack.lexiconPath).isFile()) return false; + for (String rule : pack.ruleFsts.split(",")) { + if (!rule.isEmpty() && !new File(rule).isFile()) return false; + } + return true; + } + + private static String readAll(InputStream in) throws Exception { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + byte[] buf = new byte[8192]; + int n; + while ((n = in.read(buf)) > 0) out.write(buf, 0, n); + return new String(out.toByteArray(), StandardCharsets.UTF_8); + } + + private static String parse(File root, JSONObject json, LinkedHashMap into) throws Exception { + String rootDefault = json.optString("default", ""); + JSONArray voices = json.optJSONArray("voices"); + if (voices == null) return rootDefault; + for (int i = 0; i < voices.length(); i++) { + JSONObject o = voices.getJSONObject(i); + String dir = o.optString("dir", ""); + File base = dir.isEmpty() ? root : new File(root, dir); + String lexicon = o.optString("lexicon", ""); + String tokens = o.optString("tokens", "tokens.txt"); + String dataDir = o.optString("dataDir", ""); + + StringBuilder rules = new StringBuilder(); + JSONArray ruleFsts = o.optJSONArray("ruleFsts"); + if (ruleFsts != null) { + for (int j = 0; j < ruleFsts.length(); j++) { + if (rules.length() > 0) rules.append(','); + rules.append(new File(base, ruleFsts.getString(j)).getAbsolutePath()); + } + } + + String name = o.getString("name"); + VoicePack pack = new VoicePack( + name, + o.optString("locale", "zh-CN"), + o.optString("label", name), + o.optInt("speakerId", 0), + o.optInt("quality", Voice.QUALITY_NORMAL), + new File(base, o.getString("model")).getAbsolutePath(), + lexicon.isEmpty() ? "" : new File(base, lexicon).getAbsolutePath(), + tokens.isEmpty() ? "" : new File(base, tokens).getAbsolutePath(), + dataDir.isEmpty() ? "" : new File(base, dataDir).getAbsolutePath(), + rules.toString(), + o.optString("sha256", ""), + root); + if (!usable(pack)) { + Log.w(TAG, "skip unusable voice " + name + " at " + root); + continue; + } + into.put(pack.name, pack); + } + return rootDefault; + } + + VoicePack get(String name) { + return name == null ? null : packs.get(name); + } + + List all() { + return new ArrayList<>(packs.values()); + } + + VoicePack getDefault() { + LinkedHashMap snapshot = packs; + String saved = prefs.getString(KEY_DEFAULT_VOICE, ""); + VoicePack pack = snapshot.get(saved); + return pack != null ? pack : snapshot.get(defaultName); + } + + VoicePack resolve(String voiceName, String language, String country, String variant) { + VoicePack named = get(voiceName); + if (named != null) return named; + + String want = normalizeLanguage(language); + if (!want.isEmpty()) { + for (VoicePack pack : packs.values()) { + Locale locale = pack.locale(); + if (!locale.getLanguage().equals(want)) continue; + if (country == null || country.isEmpty() || locale.getCountry().equalsIgnoreCase(country)) { + return pack; + } + } + for (VoicePack pack : packs.values()) { + if (pack.locale().getLanguage().equals(want)) return pack; + } + } + return getDefault(); + } + + boolean hasLanguage(String language) { + String want = normalizeLanguage(language); + if (want.isEmpty()) return false; + for (VoicePack pack : packs.values()) { + if (pack.locale().getLanguage().equals(want)) return true; + } + return false; + } + + boolean isUserPack(VoicePack pack) { + String base = userDir(context).getAbsolutePath() + File.separator; + return pack.root.getAbsolutePath().startsWith(base); + } + + boolean deleteUserPack(VoicePack pack) { + if (!isUserPack(pack) || !deleteTree(pack.root)) return false; + reload(); + return true; + } + + private static boolean deleteTree(File file) { + if (file.isDirectory()) { + File[] children = file.listFiles(); + if (children != null) for (File child : children) deleteTree(child); + } + return file.delete(); + } + + List toVoices() { + List list = new ArrayList<>(); + for (VoicePack pack : packs.values()) { + list.add(new Voice(pack.name, pack.locale(), pack.quality, + Voice.LATENCY_NORMAL, false, Collections.emptySet())); + } + return list; + } + + static String normalizeLanguage(String language) { + if (language == null) return ""; + String lang = language.toLowerCase(Locale.ROOT); + switch (lang) { + case "cmn": + case "zho": + case "zh": + return "zh"; + default: + return lang; + } + } +} \ No newline at end of file diff --git a/android-engine/app/src/main/res/layout/activity_settings.xml b/android-engine/app/src/main/res/layout/activity_settings.xml new file mode 100644 index 0000000..73433e0 --- /dev/null +++ b/android-engine/app/src/main/res/layout/activity_settings.xml @@ -0,0 +1,69 @@ + + + + + + + + + + + + +