diff --git a/.gitignore b/.gitignore index 4165f67..3aeb1ac 100644 --- a/.gitignore +++ b/.gitignore @@ -3,4 +3,6 @@ # 系统杂项 Thumbs.db -.DS_Store \ No newline at end of file +.DS_Store +# Isolated local build validation cache +.gradle-validation/ diff --git a/AGENTS.md b/AGENTS.md index 7fed0cc..139af75 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -6,7 +6,7 @@ TtsSpeaker 是老人平板(A0808 类定制机型)的语音合成引擎项目 - 设备端:自研系统 TTS 引擎(实现 `TextToSpeechService`),预置进 ROM。定制 ROM 不自带任何 TTS 引擎和中文语音包,本项目必须补上。 - 服务端:CPU 在线合成服务,与设备端共用同一引擎、同一模型、同一音色。 -- 客户端(ElderlyDialer 等)只依赖标准 `android.speech.tts.TextToSpeech` API,不直接依赖本项目代码。 +- 客户端离线能力依赖标准 `android.speech.tts.TextToSpeech` API;未安装引擎时,可依赖 `android-sdk/` 的轻量在线 SDK 直接访问服务。SDK 不打包模型和原生推理库。 ## 二、硬性需求(不可妥协) @@ -103,13 +103,13 @@ TtsSpeaker/ ### 语音包导入与更换(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 秒,哈希校验在同一后台线程完成。 +- 设置页「导入语音包」走 SAF 目录选择(`ACTION_OPEN_DOCUMENT_TREE`),把所选目录整树复制到隐藏 staging 目录,校验后原子重命名为 `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`)。 +- targetSdk 37 在 Android 15+ 使用系统栏与 displayCutout 的 WindowInsets 给设置页添加安全区;不再依赖 Android 16+ 已禁用的 `windowOptOutEdgeToEdgeEnforcement`。 ### 引擎设置入口(2026-11-23,荣耀 Android 15 实测) @@ -119,4 +119,28 @@ TtsSpeaker/ - 子页「安装语音数据」行在 `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 +- 定制平板(A0808)上尚未验证,需连接设备后复测齿轮入口。 +### sherpa JNI 音频回调约束 + +- `generateWithConfigAndCallback` 的回调必须保留具体方法 `Integer invoke(float[])`。不能用 Java lambda 替代:lambda 通常只有擦除后的 `Object invoke(Object)`,sherpa JNI 按 `invoke([F)Ljava/lang/Integer;` 查找会触发 NoSuchMethodError 并使 ART SIGABRT。合成使用 `SynthesisAudioCallback`;预热保留显式匿名类;发布前需真机合成验证。 + +### Android HTTP 在线合成 + +- 在线音色固定名称 `ttstd-online-zh-CN`,`Voice.isNetworkConnectionRequired=true`,标准 `TextToSpeech.setVoice()` 选择。默认服务器 `https://tts.ttstd.com/tts`,向服务端传递语速与音调,不再本地重复处理。 +- 引擎设置页「在线合成设置」或测试 APK「配置在线服务地址与令牌」进入 `OnlineSettingsActivity`。仅支持 HTTPS,不跟随重定向,令牌保存在引擎私有 `online_tts` SharedPreferences;不通过 Intent 接受或打印令牌。 +- 当前单次上限 300 字;不自动回退离线,避免错误被掩盖或重复播放。`stop()` 会断开正在进行的 HTTP 连接。 +- WAV 按 RIFF chunk 解析,支持额外元数据和填充,只接受 8–48kHz 单声道 PCM16,限制音频 20MiB、元数据 1MiB。按系统回调限制和 20ms 分片输出,回调仍在合成线程。 +- 测试 APK 开启「在线合成」后可使用朗读、停止、参数遍历和 301 字错误用例。adb 自动测试:`am start -n com.ttstd.tts.testclient/.MainActivity --ez online true --ez autospeak true`;将 `autospeak` 替换为 `autosweep` 可遍历参数;`--ez autospeak true --ez autocancel true` 可在 300ms 后取消。 + +- 2026-11-23 荣耀 Android 15 实测:HTTP 在线朗读返回非静音 PCM 并播放完成,错误令牌收到网络错误回调,300ms 取消收到 onStop,正确令牌已恢复。11 项 JVM 单测通过(含 RIFF 额外 chunk、截断、立体声拒绝、超大数据拒绝)。测试 APK 支持 `--ez online true --ez autoerror true` 自动运行 301 字错误用例。 + +### 私有 Maven SDK + +- 工程位于 `android-sdk/`,坐标 `com.ttstd:tts-speaker-sdk:1.0.0`,发布规范遵循 `D:/TongTongStudio/TTSTD/MavenRepository/AGENTS.md`。版本只增不覆盖,凭据仅从本地 Gradle 属性或环境变量读取。 +- test-client 通过真实 Maven 依赖使用 SDK,保留 SDK 在线(mode=0)、系统引擎离线(mode=1)、系统引擎在线(mode=2)三种模式,不使用源码替换代替 Maven 验证。接入与发布步骤见 `android-sdk/README.md`。 + +### 网页音色管理 + +- 管理页位于 `server/adminweb/`,由 Go embed 提供,线上入口 `/admin/`。管理 API 使用独立 `TTS_ADMIN_TOKEN`,必须与普通合成令牌不同,凭据只保存在 Kubernetes Secret;不得提交或输出令牌。 +- `VoiceStore` 对 ZIP 语音包做路径、文件类型、体积、资源和 SHA256 校验;先验证再发布新目录及清单,不覆盖原模型。管理操作串行,仓库指针只在更新时短暂加锁,上传不得阻塞合成或健康检查。 +- 默认音色变更持久化;新增包会更新清单版本,离线端语音包需另行同步。部署步骤和权限变更见 `docs/deploy.md` 第 10 节。 diff --git a/android-engine/app/build.gradle b/android-engine/app/build.gradle index 1dd26d4..a77fd1f 100644 --- a/android-engine/app/build.gradle +++ b/android-engine/app/build.gradle @@ -31,12 +31,13 @@ android { } lint { - abortOnError false - checkReleaseBuilds = false + abortOnError true + checkReleaseBuilds = true } } dependencies { + testImplementation 'junit:junit:4.13.2' implementation files('libs/sherpa-onnx-2.0.1.aar') - implementation 'org.jetbrains.kotlin:kotlin-stdlib:2.4.21' + implementation 'org.jetbrains.kotlin:kotlin-stdlib:2.2.21' } \ No newline at end of file diff --git a/android-engine/app/proguard-rules.pro b/android-engine/app/proguard-rules.pro index 662cfaa..45532be 100644 --- a/android-engine/app/proguard-rules.pro +++ b/android-engine/app/proguard-rules.pro @@ -1,2 +1,4 @@ -keep class com.k2fsa.sherpa.onnx.** { *; } --keepclassmembers class kotlin.jvm.functions.** { *; } \ No newline at end of file +-keepclassmembers class kotlin.jvm.functions.** { *; } +# sherpa JNI resolves this exact typed signature (not Function1.invoke(Object)). +-keep class com.ttstd.tts.engine.SynthesisAudioCallback { *; } diff --git a/android-engine/app/src/main/AndroidManifest.xml b/android-engine/app/src/main/AndroidManifest.xml index 600dfc0..b93ebc7 100644 --- a/android-engine/app/src/main/AndroidManifest.xml +++ b/android-engine/app/src/main/AndroidManifest.xml @@ -1,16 +1,19 @@ + + + + android:exported="true"> @@ -20,6 +23,8 @@ android:resource="@xml/tts_engine" /> + = 35) { + content.setOnApplyWindowInsetsListener((v,insets) -> { + android.graphics.Insets safe=insets.getInsets(android.view.WindowInsets.Type.systemBars() + | android.view.WindowInsets.Type.displayCutout() | android.view.WindowInsets.Type.ime()); + v.setPadding(padding+safe.left,padding+safe.top,padding+safe.right,padding+safe.bottom); + return insets; + }); + content.requestApplyInsets(); + } else scroll.setFitsSystemWindows(true); + TextView note=new TextView(this); + note.setText("选择在线音色后,朗读文字将发送到此服务器。配置仅保存在引擎内部。保存后返回测试应用即可使用。"); + content.addView(note); + EditText endpoint=new EditText(this); + endpoint.setHint("HTTPS 合成接口地址"); + endpoint.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_URI); + endpoint.setText(OnlineTtsConfig.prefs(this).getString("url",OnlineTtsConfig.DEFAULT_URL)); + content.addView(endpoint); + EditText token=new EditText(this); + token.setHint("访问令牌(Bearer Token)"); + token.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_PASSWORD); + token.setSaveEnabled(false); + token.setText(OnlineTtsConfig.prefs(this).getString("token","")); + content.addView(token); + Button save=new Button(this); + save.setText("保存在线配置"); + content.addView(save); + save.setOnClickListener(v -> { + try { + URL url=new URL(endpoint.getText().toString().trim()); + String secret=token.getText().toString().trim(); + if(!url.getProtocol().equals("https") || url.getHost().isEmpty() || url.getUserInfo()!=null) + throw new IllegalArgumentException(); + if(secret.contains("\r") || secret.contains("\n")) throw new IllegalArgumentException(); + OnlineTtsConfig.prefs(this).edit().putString("url",url.toString()).putString("token",secret).apply(); + Toast.makeText(this,"在线配置已保存",Toast.LENGTH_SHORT).show(); + finish(); + } catch(Exception e) { Toast.makeText(this,"请填写有效 HTTPS 地址和令牌",Toast.LENGTH_LONG).show(); } + }); + } +} diff --git a/android-engine/app/src/main/java/com/ttstd/tts/engine/OnlineSynthesizer.java b/android-engine/app/src/main/java/com/ttstd/tts/engine/OnlineSynthesizer.java new file mode 100644 index 0000000..5f30bc4 --- /dev/null +++ b/android-engine/app/src/main/java/com/ttstd/tts/engine/OnlineSynthesizer.java @@ -0,0 +1,87 @@ +package com.ttstd.tts.engine; + +import android.content.Context; +import android.content.SharedPreferences; +import android.media.AudioFormat; +import android.speech.tts.SynthesisCallback; +import android.speech.tts.TextToSpeech; +import android.util.Log; +import org.json.JSONObject; +import java.io.IOException; +import java.io.InputStream; +import java.net.HttpURLConnection; +import java.net.SocketTimeoutException; +import java.net.URL; +import java.nio.charset.StandardCharsets; + +final class OnlineSynthesizer { + private volatile HttpURLConnection active; + + void cancel() { + HttpURLConnection connection = active; + if (connection != null) connection.disconnect(); + } + void synthesize(Context context, String text, float speed, float pitch, + SynthesisCallback callback, Synthesizer.StopSignal stop) { + HttpURLConnection connection = null; + int httpStatus = 0; + try { + if (stop.stopped()) return; + if (text.trim().isEmpty() || text.codePointCount(0,text.length())>300) + throw new IllegalArgumentException("Text must contain 1..300 characters"); + SharedPreferences prefs=OnlineTtsConfig.prefs(context); + URL url = new URL(prefs.getString("url",OnlineTtsConfig.DEFAULT_URL)); + if (!url.getProtocol().equals("https") || url.getUserInfo()!=null) + throw new IOException("HTTPS endpoint required"); + String token=prefs.getString("token",""); + if (token.isEmpty()) throw new IOException("Online access token is not configured"); + byte[] body=new JSONObject().put("text",text).put("speed",speed).put("pitch",pitch) + .toString().getBytes(StandardCharsets.UTF_8); + connection=(HttpURLConnection)url.openConnection(); + connection.setInstanceFollowRedirects(false); + connection.setConnectTimeout(8000); + connection.setReadTimeout(30000); + connection.setRequestMethod("POST"); + connection.setDoOutput(true); + connection.setRequestProperty("Content-Type","application/json; charset=utf-8"); + connection.setRequestProperty("Authorization","Bearer "+token); + connection.setFixedLengthStreamingMode(body.length); + active=connection; + if (stop.stopped()) return; + try(java.io.OutputStream output=connection.getOutputStream()) { output.write(body); } + int status=connection.getResponseCode(); + httpStatus=status; + if (status!=200) throw new IOException("TTS HTTP status "+status); + try(InputStream input=connection.getInputStream()) { + WavPcmReader wav=new WavPcmReader(input); + if (stop.stopped()) return; + if(callback.start(wav.sampleRate,AudioFormat.ENCODING_PCM_16BIT,1)!=TextToSpeech.SUCCESS) return; + int bytes=Math.min(callback.getMaxBufferSize(),Math.max(2,wav.sampleRate/50*2)) & ~1; + if(bytes<2) throw new IOException("Invalid audio callback buffer"); + byte[] pcm=new byte[bytes]; + while(!stop.stopped()) { + int n=wav.readPcm(pcm); + if(n<0) break; + if(stop.stopped()) return; + if(callback.audioAvailable(pcm,0,n)!=TextToSpeech.SUCCESS) return; + } + if(!stop.stopped()) { + Log.i("OnlineTts","HTTP synthesis completed; cache="+connection.getHeaderField("X-Tts-Cache") + +" sampleRate="+wav.sampleRate); + callback.done(); + } + } + } catch(Exception e) { + if(!stop.stopped()) { + // Do not log credentials, request text or the configured URL. + Log.w("OnlineTts","Online synthesis failed: "+e.getClass().getSimpleName()+" HTTP="+httpStatus); + callback.error(e instanceof IllegalArgumentException ? TextToSpeech.ERROR_INVALID_REQUEST + : e instanceof SocketTimeoutException ? TextToSpeech.ERROR_NETWORK_TIMEOUT : TextToSpeech.ERROR_NETWORK); + callback.done(); + } + } finally { + active=null; + if(connection!=null) connection.disconnect(); + } + } +} diff --git a/android-engine/app/src/main/java/com/ttstd/tts/engine/OnlineTtsConfig.java b/android-engine/app/src/main/java/com/ttstd/tts/engine/OnlineTtsConfig.java new file mode 100644 index 0000000..ca5135e --- /dev/null +++ b/android-engine/app/src/main/java/com/ttstd/tts/engine/OnlineTtsConfig.java @@ -0,0 +1,19 @@ +package com.ttstd.tts.engine; + +import android.content.Context; +import android.content.SharedPreferences; +import android.speech.tts.Voice; +import java.util.Collections; +import java.util.Locale; + +final class OnlineTtsConfig { + static final String VOICE = "ttstd-online-zh-CN"; + static final String DEFAULT_URL = "https://tts.ttstd.com/tts"; + static SharedPreferences prefs(Context context) { + return context.getSharedPreferences("online_tts", Context.MODE_PRIVATE); + } + static Voice voice() { + return new Voice(VOICE, Locale.SIMPLIFIED_CHINESE, Voice.QUALITY_NORMAL, + Voice.LATENCY_NORMAL, true, Collections.emptySet()); + } +} 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 index 009072f..021cc01 100644 --- 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 @@ -6,11 +6,13 @@ final class PcmWriter { private PcmWriter() { } - static boolean write(SynthesisCallback callback, float[] samples, int sampleRate) { - int maxSamples = Math.max(1, sampleRate / 50); + static boolean write(SynthesisCallback callback, float[] samples, int sampleRate, Synthesizer.StopSignal stop) { + int maxSamples = Math.min(Math.max(1, sampleRate / 50), callback.getMaxBufferSize() / 2); + if (maxSamples < 1) return false; + byte[] pcm = new byte[maxSamples * 2]; for (int from = 0; from < samples.length; from += maxSamples) { int len = Math.min(maxSamples, samples.length - from); - byte[] pcm = new byte[len * 2]; + if (stop.stopped()) return false; for (int i = 0; i < len; i++) { float v = samples[from + i]; if (v > 1f) v = 1f; @@ -19,7 +21,7 @@ final class PcmWriter { pcm[i * 2] = (byte) s; pcm[i * 2 + 1] = (byte) (s >> 8); } - if (callback.audioAvailable(pcm, 0, pcm.length) != 0) return false; + if (callback.audioAvailable(pcm, 0, len * 2) != 0) return false; } return true; } 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 index b35d5cf..1dfc428 100644 --- 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 @@ -20,10 +20,22 @@ final class PitchShifter { } private static float[] timeStretch(float[] in, float factor) { + int originalLength = in.length; + float[] padded = new float[in.length + 2 * GRAIN]; + // Reflect the boundaries, including audio shorter than a grain. + for (int i = 0; i < padded.length; i++) { + if (in.length == 1) { padded[i] = in[0]; continue; } + int period = 2 * (in.length - 1); + int at = ((i - GRAIN) % period + period) % period; + if (at >= in.length) at = period - at; + padded[i] = in[at]; + } + in = padded; 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]; + float[] weights = new float[out.length]; int inPos = 0; int outPos = 0; @@ -32,7 +44,7 @@ final class PitchShifter { if (outPos > 0) { int from = Math.max(0, inPos - SEARCH); int to = Math.min(in.length - GRAIN, inPos + SEARCH); - double bestCorr = -1; + double bestCorr = 0; for (int cand = from; cand <= to; cand += 4) { double corr = 0; for (int i = 0; i < OVERLAP; i++) { @@ -46,13 +58,20 @@ final class PitchShifter { } for (int i = 0; i < GRAIN; i++) { out[outPos + i] += in[best + i] * window[i]; + weights[outPos + i] += window[i]; } inPos += hopA; outPos += HOP_S; } - float[] result = new float[expected]; - System.arraycopy(out, 0, result, 0, Math.min(expected, out.length)); + int length = Math.max(1, Math.round(originalLength * factor)); + int offset = Math.round(GRAIN * factor); + float[] result = new float[length]; + for (int i = 0; i < length; i++) { + int at = offset + i; + if (at < out.length && weights[at] > 0.00001f) + result[i] = out[at] / weights[at]; + } return result; } 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 index 414da62..e93d36d 100644 --- 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 @@ -34,6 +34,8 @@ public class SettingsActivity extends Activity { private Button importButton; private Button deleteButton; private TextToSpeech preview; + private boolean previewReady; + private int previewGeneration; private VoiceRepository repository; private String selected = ""; @@ -42,6 +44,19 @@ public class SettingsActivity extends Activity { super.onCreate(savedInstanceState); setTitle(R.string.settings_title); setContentView(R.layout.activity_settings); + if (android.os.Build.VERSION.SDK_INT >= 35) { + View content = findViewById(R.id.settings_root); + int padding = content.getPaddingLeft(); + content.setOnApplyWindowInsetsListener((v, insets) -> { + android.graphics.Insets safe = insets.getInsets( + android.view.WindowInsets.Type.systemBars() + | android.view.WindowInsets.Type.displayCutout()); + v.setPadding(padding + safe.left, padding + safe.top, + padding + safe.right, padding + safe.bottom); + return insets; + }); + content.requestApplyInsets(); + } group = findViewById(R.id.voice_group); info = findViewById(R.id.voice_info); status = findViewById(R.id.import_status); @@ -52,6 +67,7 @@ public class SettingsActivity extends Activity { repository.reload(); rebuild(); + findViewById(R.id.btn_online_settings).setOnClickListener(v -> startActivity(new Intent(this, OnlineSettingsActivity.class))); importButton.setOnClickListener(v -> importPack()); deleteButton.setOnClickListener(v -> confirmDelete()); findViewById(R.id.btn_preview).setOnClickListener(v -> preview()); @@ -66,6 +82,7 @@ public class SettingsActivity extends Activity { selected = current != null ? current.name : ""; for (VoicePack pack : packs) { RadioButton radio = new RadioButton(this); + radio.setMinHeight((int) (48 * getResources().getDisplayMetrics().density)); radio.setText(pack.label + "(" + pack.localeTag + ")"); radio.setId(View.generateViewId()); radio.setTag(pack.name); @@ -109,13 +126,16 @@ public class SettingsActivity extends Activity { } private void doImport(Uri treeUri) { - File dest = new File(VoiceRepository.userDir(this), "import-" + System.currentTimeMillis()); + File dest = new File(VoiceRepository.userDir(this), ".staging-" + java.util.UUID.randomUUID()); String message; try { if (!dest.mkdirs() && !dest.isDirectory()) throw new IOException("mkdir " + dest); - copyDocument(treeUri, DocumentsContract.getTreeDocumentId(treeUri), dest); + copyDocument(treeUri, DocumentsContract.getTreeDocumentId(treeUri), dest, 0, new long[2]); int count = VoiceRepository.validate(dest); if (count > 0) { + File published = new File(dest.getParentFile(), "import-" + System.currentTimeMillis() + + "-" + java.util.UUID.randomUUID()); + if (!dest.renameTo(published)) throw new IOException("publish failed"); repository.reload(); message = getString(R.string.settings_import_ok, count); } else { @@ -130,6 +150,7 @@ public class SettingsActivity extends Activity { } String text = message; runOnUiThread(() -> { + if (isFinishing() || isDestroyed()) return; status.setText(text); importButton.setEnabled(true); rebuild(); @@ -137,7 +158,8 @@ public class SettingsActivity extends Activity { }); } - private void copyDocument(Uri treeUri, String documentId, File dest) throws IOException { + private void copyDocument(Uri treeUri, String documentId, File dest, int depth, long[] budget) throws IOException { + if (depth > 16) throw new IOException("Too many nested directories"); Uri children = DocumentsContract.buildChildDocumentsUriUsingTree(treeUri, documentId); String[] projection = { DocumentsContract.Document.COLUMN_DOCUMENT_ID, @@ -147,6 +169,7 @@ public class SettingsActivity extends Activity { try (Cursor cursor = getContentResolver().query(children, projection, null, null, null)) { if (cursor == null) throw new IOException("query " + children); while (cursor.moveToNext()) { + if (++budget[0] > 4096) throw new IOException("Too many files"); String childId = cursor.getString(0); String name = cursor.getString(1); String mime = cursor.getString(2); @@ -157,7 +180,7 @@ public class SettingsActivity extends Activity { 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); + copyDocument(treeUri, childId, child, depth + 1, budget); } else { Uri source = DocumentsContract.buildDocumentUriUsingTree(treeUri, childId); try (InputStream in = getContentResolver().openInputStream(source); @@ -165,7 +188,11 @@ public class SettingsActivity extends Activity { 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); + while ((n = in.read(buf)) > 0) { + budget[1] += n; + if (budget[1] > 512L * 1024 * 1024) throw new IOException("Voice pack exceeds 512 MiB"); + out.write(buf, 0, n); + } } } } @@ -182,11 +209,18 @@ public class SettingsActivity extends Activity { 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(); - } + importButton.setEnabled(false); + deleteButton.setEnabled(false); + new Thread(() -> { + boolean deleted = repository.deleteUserPack(pack); + runOnUiThread(() -> { + if (isFinishing() || isDestroyed()) return; + importButton.setEnabled(true); + if (deleted) status.setText(R.string.settings_deleted); + rebuild(); + initPreview(); + }); + }, "tts-delete").start(); }) .setNegativeButton(android.R.string.cancel, null) .show(); @@ -201,17 +235,23 @@ public class SettingsActivity extends Activity { } private void initPreview() { + previewReady = false; + int generation = ++previewGeneration; + findViewById(R.id.btn_preview).setEnabled(false); if (preview != null) { preview.shutdown(); preview = null; } preview = new TextToSpeech(this, status -> { - if (status != TextToSpeech.SUCCESS) Log.e(TAG, "preview engine init failed: " + status); + if (generation != previewGeneration || isDestroyed()) return; + previewReady = status == TextToSpeech.SUCCESS; + findViewById(R.id.btn_preview).setEnabled(previewReady); + if (!previewReady) Log.e(TAG, "preview engine init failed: " + status); }, ENGINE); } private void preview() { - if (preview == null || selected.isEmpty()) return; + if (!previewReady || preview == null || selected.isEmpty()) return; Set voices = preview.getVoices(); if (voices != null) { for (Voice voice : voices) { diff --git a/android-engine/app/src/main/java/com/ttstd/tts/engine/SynthesisAudioCallback.java b/android-engine/app/src/main/java/com/ttstd/tts/engine/SynthesisAudioCallback.java new file mode 100644 index 0000000..835f06c --- /dev/null +++ b/android-engine/app/src/main/java/com/ttstd/tts/engine/SynthesisAudioCallback.java @@ -0,0 +1,33 @@ +package com.ttstd.tts.engine; + +import android.speech.tts.SynthesisCallback; +import kotlin.jvm.functions.Function1; + +/** JNI looks up invoke([F)Ljava/lang/Integer; directly; never replace with a lambda. */ +final class SynthesisAudioCallback implements Function1 { + private final SynthesisCallback callback; + private final Synthesizer.StopSignal stop; + private final int sampleRate; + private final float pitch; + private boolean aborted; + + SynthesisAudioCallback(SynthesisCallback callback, Synthesizer.StopSignal stop, + int sampleRate, float pitch) { + this.callback = callback; + this.stop = stop; + this.sampleRate = sampleRate; + this.pitch = pitch; + } + + @Override public Integer invoke(float[] samples) { + if (stop.stopped()) { aborted = true; return 0; } + float[] output = Math.abs(pitch - 1f) >= 0.01f ? PitchShifter.shift(samples, pitch) : samples; + if (stop.stopped() || !PcmWriter.write(callback, output, sampleRate, stop)) { + aborted = true; + return 0; + } + return 1; + } + + boolean completed() { return !aborted && !stop.stopped(); } +} 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 index 2341412..35ca921 100644 --- 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 @@ -15,8 +15,6 @@ 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; @@ -28,6 +26,7 @@ final class Synthesizer { private static final String TAG = "TtsSynthesizer"; private OfflineTts tts; + private boolean closed; private String loadedModel; Synthesizer() { @@ -53,46 +52,26 @@ final class Synthesizer { } } - synchronized void synthesize(VoicePack pack, String text, float speed, float pitch, + synchronized boolean synthesize(VoicePack pack, String text, float speed, float pitch, SynthesisCallback callback, StopSignal stop) { + if (stop.stopped()) return false; 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}; - + // Keep the concrete typed invoke method required by sherpa's JNI lookup. + SynthesisAudioCallback audio = new SynthesisAudioCallback(callback, stop, sampleRate, pitch); 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); - } + engine.generateWithConfigAndCallback(text, gen, audio); + return audio.completed(); } synchronized void release() { + closed = true; releaseLocked(); } private OfflineTts obtain(VoicePack pack) { + if (closed) throw new IllegalStateException("Synthesizer destroyed"); if (tts != null && pack.modelPath.equals(loadedModel)) return tts; releaseLocked(); @@ -132,15 +111,4 @@ final class Synthesizer { 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 index 5054993..90261a7 100644 --- 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 @@ -18,9 +18,11 @@ public class TtsEngineService extends TextToSpeechService { private static final int MAX_PERCENT = 200; private final Object synthesisLock = new Object(); - private volatile boolean stopRequested; + private final java.util.concurrent.atomic.AtomicLong stopGeneration = new java.util.concurrent.atomic.AtomicLong(); + private volatile boolean destroyed; private VoiceRepository voices; private Synthesizer synthesizer; + private final OnlineSynthesizer online = new OnlineSynthesizer(); @Override public void onCreate() { @@ -32,7 +34,7 @@ public class TtsEngineService extends TextToSpeechService { if (pack != null) { new Thread(() -> { try { - synthesizer.warmUp(pack); + if (!destroyed) synthesizer.warmUp(pack); } catch (Throwable t) { Log.w(TAG, "warmup failed", t); } @@ -42,15 +44,17 @@ public class TtsEngineService extends TextToSpeechService { @Override public void onDestroy() { - stopRequested = true; - synthesizer.release(); + destroyed = true; + stopGeneration.incrementAndGet(); + online.cancel(); + new Thread(() -> synthesizer.release(), "tts-release").start(); super.onDestroy(); } @Override protected String[] onGetLanguage() { VoicePack pack = voices.getDefault(); - if (pack == null) return new String[]{"cmn", "zho", "CN"}; + if (pack == null) return new String[]{"zho", "CHN", ""}; Locale locale = pack.locale(); String language = locale.getLanguage(); String iso3; @@ -59,12 +63,17 @@ public class TtsEngineService extends TextToSpeechService { } catch (MissingResourceException e) { iso3 = language; } - return new String[]{language, iso3, locale.getCountry()}; + String country; + try { country = locale.getISO3Country(); } + catch (MissingResourceException e) { country = locale.getCountry(); } + return new String[]{iso3, country, locale.getVariant()}; } @Override protected int onIsLanguageAvailable(String lang, String country, String variant) { - return voices.hasLanguage(lang) ? TextToSpeech.LANG_AVAILABLE : TextToSpeech.LANG_NOT_SUPPORTED; + int available = voices.languageAvailability(lang, country, variant); + return available >= 0 ? available : (VoiceRepository.normalizeLanguage(lang).equals("zh") + ? TextToSpeech.LANG_AVAILABLE : available); } @Override @@ -74,7 +83,7 @@ public class TtsEngineService extends TextToSpeechService { @Override public int onIsValidVoiceName(String voiceName) { - return voices.get(voiceName) != null ? TextToSpeech.SUCCESS : TextToSpeech.ERROR; + return (OnlineTtsConfig.VOICE.equals(voiceName) || voices.get(voiceName) != null) ? TextToSpeech.SUCCESS : TextToSpeech.ERROR; } @Override @@ -84,17 +93,29 @@ public class TtsEngineService extends TextToSpeechService { @Override public String onGetDefaultVoiceNameFor(String lang, String country, String variant) { + if (!voices.hasLanguage(lang)) return VoiceRepository.normalizeLanguage(lang).equals("zh") ? OnlineTtsConfig.VOICE : null; VoicePack pack = voices.resolve(null, lang, country, variant); return pack != null ? pack.name : null; } @Override public List onGetVoices() { - return voices.toVoices(); + List result = voices.toVoices(); + result.add(OnlineTtsConfig.voice()); + return result; } @Override protected void onSynthesizeText(SynthesisRequest request, SynthesisCallback callback) { + if (OnlineTtsConfig.VOICE.equals(request.getVoiceName())) { + long generation = stopGeneration.get(); + synchronized (synthesisLock) { + online.synthesize(this, request.getText(), clampPercent(request.getSpeechRate()), + clampPercent(request.getPitch()), callback, + () -> destroyed || generation != stopGeneration.get()); + } + return; + } VoicePack pack = voices.resolve(request.getVoiceName(), request.getLanguage(), request.getCountry(), request.getVariant()); if (pack == null) { @@ -103,10 +124,12 @@ public class TtsEngineService extends TextToSpeechService { return; } - stopRequested = false; + final long generation = stopGeneration.get(); synchronized (synthesisLock) { try { + if (destroyed || generation != stopGeneration.get()) return; int sampleRate = synthesizer.sampleRate(pack); + if (destroyed || generation != stopGeneration.get()) return; int started = callback.start(sampleRate, AudioFormat.ENCODING_PCM_16BIT, 1); if (started != 0) { Log.e(TAG, "callback.start failed: " + started); @@ -115,21 +138,21 @@ public class TtsEngineService extends TextToSpeechService { } float speed = clampPercent(request.getSpeechRate()); float pitch = clampPercent(request.getPitch()); - synthesizer.synthesize(pack, request.getText(), speed, pitch, - callback, () -> stopRequested); - callback.done(); + boolean complete = synthesizer.synthesize(pack, request.getText(), speed, pitch, + callback, () -> destroyed || generation != stopGeneration.get()); + if (complete) callback.done(); + else if (!destroyed && generation == stopGeneration.get()) callback.error(); } catch (Throwable t) { Log.e(TAG, "synthesis failed", t); callback.error(); - } finally { - stopRequested = false; } } } @Override protected void onStop() { - stopRequested = true; + stopGeneration.incrementAndGet(); + online.cancel(); } private static float clampPercent(int percent) { 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 index 426d26b..8f0a054 100644 --- 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 @@ -5,6 +5,7 @@ import java.util.Locale; final class VoicePack { final String name; + final String version; final String localeTag; final String label; final int speakerId; @@ -17,10 +18,11 @@ final class VoicePack { final String modelSha256; final File root; - VoicePack(String name, String localeTag, String label, int speakerId, int quality, + VoicePack(String version, 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.version = version; this.localeTag = localeTag; this.label = label; this.speakerId = speakerId; 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 index a4f6670..99e52e6 100644 --- 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 @@ -59,7 +59,7 @@ final class VoiceRepository { return new File(context.getFilesDir(), "voices/" + USER_DIR); } - void reload() { + synchronized void reload() { LinkedHashMap merged = new LinkedHashMap<>(); String firstDefault = ""; for (File root : roots()) { @@ -87,7 +87,7 @@ final class VoiceRepository { 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); + File[] imports = userDir(context).listFiles(f -> f.isDirectory() && f.getName().startsWith("import-")); if (imports != null) { Arrays.sort(imports); roots.addAll(Arrays.asList(imports)); @@ -102,7 +102,24 @@ final class VoiceRepository { if (!manifest.isFile()) return 0; try (InputStream in = new FileInputStream(manifest)) { LinkedHashMap packs = new LinkedHashMap<>(); - parse(root, new JSONObject(readAll(in)), packs); + JSONObject manifestJson = new JSONObject(readAll(in)); + parse(root, manifestJson, packs); + if (packs.size() != manifestJson.getJSONArray("voices").length()) return 0; + JSONArray entries = manifestJson.getJSONArray("voices"); + for (int i = 0; i < entries.length(); i++) { + JSONObject entry = entries.getJSONObject(i); + File base = entry.optString("dir", "").isEmpty() ? root : contained(root, entry.getString("dir")); + JSONObject hashes = entry.optJSONObject("files"); + if (hashes != null) { + java.util.Iterator names = hashes.keys(); + while (names.hasNext()) { + String name = names.next(); + if (!hashes.getString(name).matches("(?i)[0-9a-f]{64}") + || !hashes.getString(name).equalsIgnoreCase(sha256(contained(base, name)))) + return INVALID_HASH; + } + } + } if (packs.isEmpty()) return 0; for (VoicePack pack : packs.values()) { if (!usable(pack)) return 0; @@ -135,6 +152,7 @@ final class VoiceRepository { private static boolean usable(VoicePack pack) { if (!new File(pack.modelPath).isFile()) return false; + if (!pack.dataDir.isEmpty() && !new File(pack.dataDir).isDirectory()) 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(",")) { @@ -147,18 +165,30 @@ final class VoiceRepository { ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buf = new byte[8192]; int n; - while ((n = in.read(buf)) > 0) out.write(buf, 0, n); + while ((n = in.read(buf)) > 0) { + if (out.size() + n > 1024 * 1024) throw new java.io.IOException("Manifest exceeds 1 MiB"); + out.write(buf, 0, n); + } return new String(out.toByteArray(), StandardCharsets.UTF_8); } + private static File contained(File root, String relative) throws java.io.IOException { + File file = new File(root, relative).getCanonicalFile(); + String base = root.getCanonicalPath() + File.separator; + if (relative.isEmpty() || new File(relative).isAbsolute() || !file.getPath().startsWith(base)) + throw new java.io.IOException("Path outside voice directory: " + relative); + return file; + } + private static String parse(File root, JSONObject json, LinkedHashMap into) throws Exception { + if (json.getString("version").trim().isEmpty()) throw new java.io.IOException("Missing voice version"); 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); + File base = dir.isEmpty() ? root : contained(root, dir); String lexicon = o.optString("lexicon", ""); String tokens = o.optString("tokens", "tokens.txt"); String dataDir = o.optString("dataDir", ""); @@ -168,21 +198,21 @@ final class VoiceRepository { 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()); + rules.append(contained(base, ruleFsts.getString(j)).getAbsolutePath()); } } String name = o.getString("name"); VoicePack pack = new VoicePack( - name, + json.getString("version"), 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(), + contained(base, o.getString("model")).getAbsolutePath(), + lexicon.isEmpty() ? "" : contained(base, lexicon).getAbsolutePath(), + tokens.isEmpty() ? "" : contained(base, tokens).getAbsolutePath(), + dataDir.isEmpty() ? "" : contained(base, dataDir).getAbsolutePath(), rules.toString(), o.optString("sha256", ""), root); @@ -203,7 +233,7 @@ final class VoiceRepository { return new ArrayList<>(packs.values()); } - VoicePack getDefault() { + synchronized VoicePack getDefault() { LinkedHashMap snapshot = packs; String saved = prefs.getString(KEY_DEFAULT_VOICE, ""); VoicePack pack = snapshot.get(saved); @@ -215,11 +245,15 @@ final class VoiceRepository { if (named != null) return named; String want = normalizeLanguage(language); + VoicePack preferred = getDefault(); + if (preferred != null && preferred.locale().getLanguage().equals(want) + && (country == null || country.isEmpty() || countryMatches(preferred.locale(), country))) + return preferred; 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)) { + if (country == null || country.isEmpty() || countryMatches(locale, country)) { return pack; } } @@ -230,6 +264,28 @@ final class VoiceRepository { return getDefault(); } + private static boolean countryMatches(Locale locale, String country) { + if (locale.getCountry().equalsIgnoreCase(country)) return true; + try { return locale.getISO3Country().equalsIgnoreCase(country); } + catch (java.util.MissingResourceException e) { return false; } + } + + int languageAvailability(String language, String country, String variant) { + String want = normalizeLanguage(language); + int result = android.speech.tts.TextToSpeech.LANG_NOT_SUPPORTED; + for (VoicePack pack : packs.values()) { + Locale locale = pack.locale(); + if (!locale.getLanguage().equals(want)) continue; + result = Math.max(result, android.speech.tts.TextToSpeech.LANG_AVAILABLE); + if (country != null && !country.isEmpty() && countryMatches(locale, country)) { + result = Math.max(result, android.speech.tts.TextToSpeech.LANG_COUNTRY_AVAILABLE); + if (variant != null && !variant.isEmpty() && locale.getVariant().equals(variant)) + return android.speech.tts.TextToSpeech.LANG_COUNTRY_VAR_AVAILABLE; + } + } + return result; + } + boolean hasLanguage(String language) { String want = normalizeLanguage(language); if (want.isEmpty()) return false; diff --git a/android-engine/app/src/main/java/com/ttstd/tts/engine/WavPcmReader.java b/android-engine/app/src/main/java/com/ttstd/tts/engine/WavPcmReader.java new file mode 100644 index 0000000..0058493 --- /dev/null +++ b/android-engine/app/src/main/java/com/ttstd/tts/engine/WavPcmReader.java @@ -0,0 +1,86 @@ +package com.ttstd.tts.engine; + +import java.io.EOFException; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; + +/** Bounded RIFF parser: do not assume WAV has a fixed 44-byte header. */ +final class WavPcmReader { + private static final long MAX_AUDIO = 20L * 1024 * 1024; + final InputStream input; + final int sampleRate; + long remaining; + + WavPcmReader(InputStream input) throws IOException { + this.input = input; + byte[] riff = read(input, 12); + if (!tag(riff,0).equals("RIFF") || !tag(riff,8).equals("WAVE")) + throw new IOException("Not a RIFF WAV"); + long riffRemaining = uint(riff,4)-4; + int rate = 0; + long metadata = 0; + while (riffRemaining >= 8) { + byte[] header = read(input,8); + long size = uint(header,4); + riffRemaining -= 8; + if (size > riffRemaining) throw new IOException("Invalid RIFF chunk length"); + String id = tag(header,0); + if (id.equals("data")) { + if (rate == 0 || size == 0 || size > MAX_AUDIO || (size & 1) != 0) + throw new IOException("Invalid PCM data"); + sampleRate = rate; + remaining = size; + return; + } + metadata += size; + if (metadata > 1024 * 1024) throw new IOException("WAV metadata too large"); + if (id.equals("fmt ")) { + if (size < 16) throw new IOException("Invalid WAV format"); + byte[] fmt = read(input,16); + rate = (int)uint(fmt,4); + if (ushort(fmt,0)!=1 || ushort(fmt,2)!=1 || ushort(fmt,14)!=16 + || ushort(fmt,12)!=2 || rate<8000 || rate>48000 + || uint(fmt,8)!=rate*2L) throw new IOException("Expected mono PCM16 WAV"); + skip(input,size-16); + } else skip(input,size); + skip(input,size & 1); + riffRemaining -= size + (size & 1); + } + throw new IOException("WAV has no audio data"); + } + int readPcm(byte[] buffer) throws IOException { + if (remaining == 0) return -1; + int count = (int)Math.min(buffer.length,remaining); + int at = 0; + while (at < count) { + int n=input.read(buffer,at,count-at); + if (n<0) throw new EOFException("Truncated WAV audio"); + if (n==0) continue; + at+=n; + } + remaining-=count; + return count; + } + private static byte[] read(InputStream in,int size) throws IOException { + byte[] data=new byte[size]; + int at=0; + while(at0) { + int n=in.read(scratch,0,(int)Math.min(count,scratch.length)); + if(n<0) throw new EOFException("Truncated WAV chunk"); + count-=n; + } + } + private static int ushort(byte[] b,int i) { return (b[i]&255)|((b[i+1]&255)<<8); } + private static long uint(byte[] b,int i) { return (ushort(b,i)&65535L)|((long)ushort(b,i+2)<<16); } + private static String tag(byte[] b,int i) { return new String(b,i,4,StandardCharsets.US_ASCII); } +} diff --git a/android-engine/app/src/main/res/layout/activity_settings.xml b/android-engine/app/src/main/res/layout/activity_settings.xml index 73433e0..7957dfe 100644 --- a/android-engine/app/src/main/res/layout/activity_settings.xml +++ b/android-engine/app/src/main/res/layout/activity_settings.xml @@ -1,69 +1,69 @@ - - - + + android:orientation="vertical" + android:padding="24dp"> - + - - - - - +

语音服务控制台

让每一句话,都有合适的声音。

查看语音包、试听音色,或设置默认声音。

+

进入音色管理

使用独立管理令牌。令牌仅保留在当前页面内存中。

+
TTStd 语音服务 · 已连接的离线设备需另行同步语音包。
\ No newline at end of file diff --git a/server/adminweb/style.css b/server/adminweb/style.css new file mode 100644 index 0000000..2b74f0f --- /dev/null +++ b/server/adminweb/style.css @@ -0,0 +1 @@ +*{box-sizing:border-box}body{margin:0;background:#f2f5f8;color:#152536;font:16px/1.6 system-ui,-apple-system,"Microsoft YaHei",sans-serif}aside{position:fixed;inset:0 auto 0 0;width:220px;background:#112534;color:white;padding:36px 24px;display:flex;flex-direction:column}.brand{font-size:29px;font-weight:750;letter-spacing:1px}.brand small{display:block;font-size:12px;letter-spacing:3px;color:#98b1c0}.nav{margin-top:52px;padding:12px 16px;border-radius:10px;background:#234657;color:#a6efdd}aside p{color:#a6bac7;font-size:14px;margin-top:auto}main{margin-left:220px;padding:42px 44px;max-width:1660px}header{margin-bottom:30px}h1{font-size:30px;line-height:1.45;letter-spacing:-.7px;margin:8px 0}h2{font-size:20px;margin:0 0 8px}.eyebrow{font-size:13px;font-weight:700;letter-spacing:2px;color:#16846b;margin:0}.muted{color:#637587;font-size:15px;margin:8px 0 18px}.card{background:white;border:1px solid #e0e7ec;border-radius:16px;padding:26px;box-shadow:0 5px 20px #203a4d04}#login{max-width:720px;margin-top:48px}.login-row{display:flex;gap:12px}.login-row input{flex:1;min-width:0}.stats{display:grid;grid-template-columns:1fr 1.5fr 1fr;gap:18px;margin-bottom:24px}.stats span{display:block;color:#66798a;font-size:14px}.stats strong{display:block;margin-top:9px;font-size:25px;overflow-wrap:anywhere}.columns{display:grid;grid-template-columns:minmax(300px,1.1fr) minmax(320px,1fr);gap:24px}.right{display:grid;gap:24px;align-content:start}.section-title{display:flex;align-items:center;justify-content:space-between;gap:12px}.voice{border:1px solid #dde5eb;border-radius:12px;padding:20px;margin-top:14px}.voice.selected{border-color:#16846b;background:#f0fbf7;box-shadow:0 0 0 1px #16846b}.voice-top{display:flex;justify-content:space-between;gap:12px}.voice h3{font-size:18px;margin:0}.voice p{margin:6px 0;color:#607586;font-size:14px;overflow-wrap:anywhere}.voice button{margin-top:10px;font-size:14px;padding:7px 12px}.tag{font-size:12px;color:#14775f;background:#dbf5eb;padding:3px 9px;border-radius:20px;white-space:nowrap;align-self:flex-start}button{background:#137f67;border:1px solid #137f67;color:white;border-radius:9px;padding:11px 18px;font:600 15px system-ui;cursor:pointer;white-space:nowrap}button:hover{filter:brightness(.95)}button:disabled{opacity:.5;cursor:wait}.secondary{color:#186b5b;background:white;border-color:#b7cfc6}label{display:block;font-size:14px;font-weight:600;margin:14px 0 7px}input,textarea{font:16px system-ui;border:1px solid #ccd8e1;border-radius:8px;padding:12px;color:#172d3c;background:white}input:focus,textarea:focus,button:focus-visible{outline:2px solid #68bfa9;outline-offset:2px}textarea{width:100%;resize:vertical;line-height:1.7}.sliders{display:grid;grid-template-columns:1fr 1fr;gap:24px;margin-bottom:18px}.sliders input{width:100%;padding:0;accent-color:#137f67}.sliders output{float:right;color:#137f67}audio{width:100%;margin-top:18px}.file-box{border:1px dashed #a9bfc9;background:#f8fbfc;text-align:center;padding:20px;border-radius:10px;cursor:pointer}.file-box small{display:block;font-size:13px;color:#697e8b;font-weight:400}.file-box input{width:100%;margin-top:12px;font-size:13px}.hint,footer{font-size:13px;color:#697e8b}#filename{overflow-wrap:anywhere}#notice:empty{display:none}#notice{padding:13px 18px;border-radius:9px;background:#e0f5ec;color:#11694f;margin-bottom:22px}#notice.error{background:#fff0ef;color:#a62d27}footer{margin-top:30px}[hidden]{display:none!important}@media(max-width:1100px){aside{width:170px;padding:30px 18px}main{margin-left:170px;padding:32px 24px}.columns{grid-template-columns:1fr}}@media(max-width:650px){aside{position:static;width:auto;padding:18px 22px;display:block}.brand{font-size:23px}.brand small{display:inline;margin-left:12px;font-size:10px}.nav,aside p{display:none}aside button{position:absolute;right:18px;top:14px}main{margin-left:0;padding:26px 16px}h1{font-size:25px}.stats{grid-template-columns:1fr}.card{padding:20px}.columns{grid-template-columns:minmax(0,1fr)}.login-row{flex-direction:column}.stats strong{font-size:22px}} \ No newline at end of file diff --git a/server/deploy.yaml b/server/deploy.yaml index bd77e69..bdb74df 100644 --- a/server/deploy.yaml +++ b/server/deploy.yaml @@ -21,11 +21,23 @@ spec: fsGroup: 65534 containers: - name: tts-server - image: docker.io/library/tts-server:dev-1 + image: docker.io/library/tts-server:admin-20261123-1 imagePullPolicy: IfNotPresent ports: - containerPort: 8080 env: + - name: TTS_ADMIN_TOKEN + valueFrom: + secretKeyRef: + name: tts-server-admin + key: token + - name: TTS_REQUIRE_AUTH + value: "1" + - name: TTS_API_TOKEN + valueFrom: + secretKeyRef: + name: tts-server-auth + key: token - name: TTS_VOICES value: /voices - name: TTS_CACHE @@ -37,14 +49,14 @@ spec: - name: TTS_MAX_TEXT value: "300" - name: GOMEMLIMIT - value: 256MiB + value: 64MiB resources: requests: cpu: 200m memory: 256Mi limits: cpu: 1500m - memory: 768Mi + memory: 512Mi readinessProbe: httpGet: path: /healthz @@ -62,7 +74,7 @@ spec: volumeMounts: - name: voices mountPath: /voices - readOnly: true + readOnly: false - name: cache mountPath: /cache volumes: @@ -72,7 +84,7 @@ spec: type: Directory - name: cache emptyDir: - sizeLimit: 1Gi + sizeLimit: 512Mi --- apiVersion: v1 kind: Service diff --git a/server/engine.go b/server/engine.go index e0a0952..e1739d7 100644 --- a/server/engine.go +++ b/server/engine.go @@ -1,6 +1,7 @@ package main import ( + "context" "errors" "fmt" "log" @@ -32,26 +33,44 @@ func (e *engine) preload(pack *tts.VoicePack) error { return err } -func (e *engine) synthesize(pack *tts.VoicePack, text string, speed, pitch float32) ([]float32, int, error) { +func (e *engine) synthesize(ctx context.Context, pack *tts.VoicePack, text string, speed, pitch float32) ([]float32, int, error) { e.mu.Lock() defer e.mu.Unlock() + if err := ctx.Err(); err != nil { + return nil, 0, err + } model, err := e.obtain(pack) if err != nil { return nil, 0, err } - // Same generation config as Synthesizer.java: silenceScale 0, sid, speed, + // Same generation config as Synthesizer.java: silenceScale 0.2, sid, speed, // numSteps 5. - cfg := &sherpa.GenerationConfig{SilenceScale: 0, Speed: speed, Sid: pack.SpeakerID, NumSteps: 5} - audio := model.GenerateWithConfig(text, cfg, nil) + cfg := &sherpa.GenerationConfig{SilenceScale: 0.2, Speed: speed, Sid: pack.SpeakerID, NumSteps: 5} + if err := ctx.Err(); err != nil { + return nil, 0, err + } + var shifted []float32 + audio := model.GenerateWithConfig(text, cfg, func(samples []float32, progress float32) bool { + if ctx.Err() != nil { + return false + } + if tts.PitchShiftNeeded(pitch) { + shifted = append(shifted, tts.ShiftPitch(samples, pitch)...) + } + return ctx.Err() == nil + }) + if err := ctx.Err(); err != nil { + return nil, 0, err + } if audio == nil || len(audio.Samples) == 0 { return nil, 0, errors.New("synthesis produced no audio") } samples := audio.Samples if tts.PitchShiftNeeded(pitch) { - samples = tts.ShiftPitch(samples, pitch) + samples = shifted } return samples, audio.SampleRate, nil } @@ -104,4 +123,4 @@ func (e *engine) release() { e.tts = nil e.loaded = "" } -} \ No newline at end of file +} diff --git a/server/internal/tts/cache.go b/server/internal/tts/cache.go index a2ad2dc..f2cba17 100644 --- a/server/internal/tts/cache.go +++ b/server/internal/tts/cache.go @@ -7,23 +7,31 @@ import ( "math" "os" "path/filepath" + "sort" + "sync" ) type Cache struct { - dir string + dir string + mu sync.Mutex + maxBytes int64 } func NewCache(dir string) (*Cache, error) { if err := os.MkdirAll(dir, 0o755); err != nil { return nil, fmt.Errorf("create cache dir: %w", err) } - return &Cache{dir: dir}, nil + c := &Cache{dir: dir, maxBytes: 256 << 20} + if err := c.prune(0); err != nil { + return nil, err + } + return c, nil } // Key covers everything that changes the rendered audio, including the voice // pack version, so upgrades invalidate old files on their own. func (c *Cache) Key(version, voice string, speed, pitch float32, text string) string { - sum := sha256.Sum256([]byte(fmt.Sprintf("%s\x00%s\x00%08x\x00%08x\x00%s", + sum := sha256.Sum256([]byte(fmt.Sprintf("dsp-v2\x00%s\x00%s\x00%08x\x00%08x\x00%s", version, voice, math.Float32bits(speed), math.Float32bits(pitch), text))) return hex.EncodeToString(sum[:]) } @@ -37,11 +45,20 @@ func (c *Cache) Get(key string) ([]byte, bool) { } func (c *Cache) Put(key string, data []byte) error { + c.mu.Lock() + defer c.mu.Unlock() + if int64(len(data)) > c.maxBytes { + return fmt.Errorf("audio exceeds cache budget") + } + if err := c.prune(int64(len(data))); err != nil { + return err + } tmp, err := os.CreateTemp(c.dir, key[:8]+"-*.tmp") if err != nil { return err } name := tmp.Name() + defer os.Remove(name) if _, err := tmp.Write(data); err != nil { tmp.Close() os.Remove(name) @@ -52,4 +69,38 @@ func (c *Cache) Put(key string, data []byte) error { return err } return os.Rename(name, filepath.Join(c.dir, key+".wav")) -} \ No newline at end of file +} +func (c *Cache) Open(key string) (*os.File, error) { + return os.Open(filepath.Join(c.dir, key+".wav")) +} + +func (c *Cache) prune(incoming int64) error { + entries, err := os.ReadDir(c.dir) + if err != nil { + return err + } + var files []os.FileInfo + var total int64 + for _, entry := range entries { + if entry.IsDir() || filepath.Ext(entry.Name()) != ".wav" { + continue + } + info, err := entry.Info() + if err != nil { + return err + } + total += info.Size() + files = append(files, info) + } + sort.Slice(files, func(i, j int) bool { return files[i].ModTime().Before(files[j].ModTime()) }) + for _, file := range files { + if total+incoming <= c.maxBytes { + break + } + if err := os.Remove(filepath.Join(c.dir, file.Name())); err != nil { + return err + } + total -= file.Size() + } + return nil +} diff --git a/server/internal/tts/cache_test.go b/server/internal/tts/cache_test.go index 03307fd..bfc0983 100644 --- a/server/internal/tts/cache_test.go +++ b/server/internal/tts/cache_test.go @@ -24,4 +24,28 @@ func TestCacheRoundTrip(t *testing.T) { if !ok || string(got) != "wav" { t.Fatalf("cache get: %q %v", got, ok) } -} \ No newline at end of file +} + +func TestCacheEvictsWithinBudget(t *testing.T) { + c, err := NewCache(t.TempDir()) + if err != nil { + t.Fatal(err) + } + c.maxBytes = 6 + first, second := c.Key("v", "a", 1, 1, "first"), c.Key("v", "a", 1, 1, "second") + if err := c.Put(first, []byte("1234")); err != nil { + t.Fatal(err) + } + if err := c.Put(second, []byte("5678")); err != nil { + t.Fatal(err) + } + if _, ok := c.Get(first); ok { + t.Fatal("old cache retained beyond budget") + } + if data, ok := c.Get(second); !ok || string(data) != "5678" { + t.Fatal("new cache missing") + } + if err := c.Put(first, make([]byte, 7)); err == nil { + t.Fatal("oversized cache accepted") + } +} diff --git a/server/internal/tts/pitch.go b/server/internal/tts/pitch.go index 255d1ba..044cb18 100644 --- a/server/internal/tts/pitch.go +++ b/server/internal/tts/pitch.go @@ -26,6 +26,23 @@ func ShiftPitch(samples []float32, factor float32) []float32 { } func timeStretch(in []float32, factor float32) []float32 { + originalLength := len(in) + padded := make([]float32, len(in)+2*grain) + // Reflect boundaries so even sub-window sounds retain their energy. + for i := range padded { + at := i - grain + if len(in) == 1 { + padded[i] = in[0] + continue + } + period := 2 * (len(in) - 1) + at = ((at % period) + period) % period + if at >= len(in) { + at = period - at + } + padded[i] = in[at] + } + in = padded hopA := roundInt(float32(hops) / factor) if hopA < 1 { hopA = 1 @@ -36,6 +53,7 @@ func timeStretch(in []float32, factor float32) []float32 { expected = grain } out := make([]float32, expected+grain) + weights := make([]float32, len(out)) inPos, outPos := 0, 0 for inPos+grain <= len(in) { @@ -49,7 +67,7 @@ func timeStretch(in []float32, factor float32) []float32 { if to > len(in)-grain { to = len(in) - grain } - bestCorr := -1.0 + bestCorr := 0.0 for cand := from; cand <= to; cand += 4 { var corr float64 for i := 0; i < overlap; i++ { @@ -63,13 +81,21 @@ func timeStretch(in []float32, factor float32) []float32 { } for i := 0; i < grain; i++ { out[outPos+i] += in[best+i] * window[i] + weights[outPos+i] += window[i] } inPos += hopA outPos += hops } - result := make([]float32, expected) - copy(result, out[:min(expected, len(out))]) + length := max(1, roundInt(float32(originalLength)*factor)) + offset := roundInt(float32(grain) * factor) + result := make([]float32, length) + for i := range result { + at := offset + i + if at < len(out) && weights[at] > 0.00001 { + result[i] = out[at] / weights[at] + } + } return result } @@ -106,4 +132,4 @@ func hann(size int) []float32 { // roundInt matches Java Math.round(float): floor(x + 0.5). func roundInt(x float32) int { return int(math.Floor(float64(x) + 0.5)) -} \ No newline at end of file +} diff --git a/server/internal/tts/pitch_test.go b/server/internal/tts/pitch_test.go index 96e441b..3166d76 100644 --- a/server/internal/tts/pitch_test.go +++ b/server/internal/tts/pitch_test.go @@ -53,4 +53,56 @@ func TestShiftPitchSilence(t *testing.T) { t.Fatalf("sample %d: got %v, want 0", i, v) } } -} \ No newline at end of file +} + +func TestPitchShortAndTail(t *testing.T) { + for _, length := range []int{100, 511, 1023, 1025, 2601} { + for _, factor := range []float32{0.5, 1.2, 2} { + in := make([]float32, length) + for i := range in { + in[i] = 0.5 + } + out := ShiftPitch(in, factor) + if math.Abs(float64(len(out)-length)) > 1 { + t.Fatalf("length %d factor %v: %d", length, factor, len(out)) + } + var energy float64 + for _, v := range out { + energy += float64(v * v) + } + if energy < float64(length)*0.01 { + t.Fatalf("short audio lost: length=%d factor=%v energy=%v", length, factor, energy) + } + var tail float64 + for _, v := range out[max(0, len(out)-100):] { + tail += float64(v * v) + } + if tail < 0.01 { + t.Fatalf("tail lost: length=%d factor=%v", length, factor) + } + } + } +} + +func TestPitchChangesFrequency(t *testing.T) { + const rate = 22050 + input := make([]float32, rate) + for i := range input { + input[i] = float32(0.5 * math.Sin(2*math.Pi*220*float64(i)/rate)) + } + for _, factor := range []float32{0.5, 1.2, 2} { + output := ShiftPitch(input, factor) + from, to := rate/5, 4*rate/5 + crossings := 0 + for i := from + 1; i < to; i++ { + if output[i-1] <= 0 && output[i] > 0 { + crossings++ + } + } + frequency := float64(crossings) * rate / float64(to-from) + want := 220 * float64(factor) + if math.Abs(frequency/want-1) > 0.15 { + t.Fatalf("pitch=%v frequency=%.1f want=%.1f", factor, frequency, want) + } + } +} diff --git a/server/internal/tts/voice.go b/server/internal/tts/voice.go index affae37..c169a49 100644 --- a/server/internal/tts/voice.go +++ b/server/internal/tts/voice.go @@ -1,8 +1,11 @@ package tts import ( + "crypto/sha256" + "encoding/hex" "encoding/json" "fmt" + "io" "os" "path/filepath" "strings" @@ -17,17 +20,19 @@ type Manifest struct { } type VoiceEntry struct { - Name string `json:"name"` - Locale string `json:"locale"` - Label string `json:"label"` - SpeakerID int `json:"speakerId"` - Quality int `json:"quality"` - Dir string `json:"dir"` - Model string `json:"model"` - Lexicon string `json:"lexicon"` - Tokens string `json:"tokens"` - DataDir string `json:"dataDir"` - RuleFsts []string `json:"ruleFsts"` + SHA256 string `json:"sha256"` + Files map[string]string `json:"files"` + Name string `json:"name"` + Locale string `json:"locale"` + Label string `json:"label"` + SpeakerID int `json:"speakerId"` + Quality int `json:"quality"` + Dir string `json:"dir"` + Model string `json:"model"` + Lexicon string `json:"lexicon"` + Tokens string `json:"tokens"` + DataDir string `json:"dataDir"` + RuleFsts []string `json:"ruleFsts"` } type VoicePack struct { @@ -55,10 +60,17 @@ func LoadRepo(root string) (*Repo, error) { if err != nil { return nil, fmt.Errorf("read manifest: %w", err) } + return LoadRepoManifest(root, raw) +} + +func LoadRepoManifest(root string, raw []byte) (*Repo, error) { var m Manifest if err := json.Unmarshal(raw, &m); err != nil { return nil, fmt.Errorf("parse manifest: %w", err) } + if strings.TrimSpace(m.Version) == "" { + return nil, fmt.Errorf("manifest version is required") + } if len(m.Voices) == 0 { return nil, fmt.Errorf("manifest has no voices") } @@ -84,14 +96,14 @@ func LoadRepo(root string) (*Repo, error) { rules = append(rules, filepath.Join(base, f)) } pack := &VoicePack{ - Name: e.Name, - Locale: e.Locale, - Label: e.Label, - SpeakerID: e.SpeakerID, - Quality: e.Quality, - ModelPath: filepath.Join(base, e.Model), - TokensPath: filepath.Join(base, tokens), - RuleFsts: strings.Join(rules, ","), + Name: e.Name, + Locale: e.Locale, + Label: e.Label, + SpeakerID: e.SpeakerID, + Quality: e.Quality, + ModelPath: filepath.Join(base, e.Model), + TokensPath: filepath.Join(base, tokens), + RuleFsts: strings.Join(rules, ","), } if e.Lexicon != "" { pack.LexiconPath = filepath.Join(base, e.Lexicon) @@ -102,6 +114,31 @@ func LoadRepo(root string) (*Repo, error) { if pack.Label == "" { pack.Label = pack.Name } + paths := []string{pack.ModelPath, pack.TokensPath} + if pack.LexiconPath != "" { + paths = append(paths, pack.LexiconPath) + } + if pack.DataDir != "" { + paths = append(paths, pack.DataDir) + } + paths = append(paths, rules...) + for _, path := range paths { + if err := contained(root, path); err != nil { + return nil, err + } + } + if err := verifyHash(pack.ModelPath, e.SHA256); err != nil { + return nil, err + } + for relative, hash := range e.Files { + path := filepath.Join(base, relative) + if err := contained(root, path); err != nil { + return nil, err + } + if err := verifyHash(path, hash); err != nil { + return nil, err + } + } if err := pack.validate(); err != nil { return nil, err } @@ -127,9 +164,17 @@ func (p *VoicePack) validate() error { required = append(required, strings.Split(p.RuleFsts, ",")...) } for _, path := range required { - if _, err := os.Stat(path); err != nil { + info, err := os.Stat(path) + if err != nil { return fmt.Errorf("voice %q: %w", p.Name, err) } + if path == p.DataDir { + if !info.IsDir() { + return fmt.Errorf("voice %q: dataDir must be a directory", p.Name) + } + } else if !info.Mode().IsRegular() { + return fmt.Errorf("voice %q: resource must be a regular file", p.Name) + } } return nil } @@ -148,6 +193,11 @@ func (r *Repo) Resolve(requested string) *VoicePack { if p, ok := r.byName[requested]; ok { return p } + for _, p := range r.Packs { + if strings.EqualFold(strings.ReplaceAll(requested, "_", "-"), p.Locale) { + return p + } + } want := normalizeLanguage(requested) if want != "" { for _, p := range r.Packs { @@ -178,4 +228,38 @@ func normalizeLanguage(tag string) string { default: return tag } -} \ No newline at end of file +} +func contained(root, path string) error { + base, err := filepath.EvalSymlinks(root) + if err != nil { + return err + } + target, err := filepath.EvalSymlinks(path) + if err != nil { + return err + } + rel, err := filepath.Rel(base, target) + if err != nil || rel == "." || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) || filepath.IsAbs(rel) { + return fmt.Errorf("voice path outside root: %s", path) + } + return nil +} +func verifyHash(path, expected string) error { + decoded, err := hex.DecodeString(expected) + if err != nil || len(decoded) != sha256.Size { + return fmt.Errorf("missing/invalid SHA256: %s", path) + } + f, err := os.Open(path) + if err != nil { + return err + } + defer f.Close() + hash := sha256.New() + if _, err := io.Copy(hash, f); err != nil { + return err + } + if !strings.EqualFold(hex.EncodeToString(hash.Sum(nil)), expected) { + return fmt.Errorf("SHA256 mismatch: %s", path) + } + return nil +} diff --git a/server/internal/tts/voice_store.go b/server/internal/tts/voice_store.go new file mode 100644 index 0000000..dbe8367 --- /dev/null +++ b/server/internal/tts/voice_store.go @@ -0,0 +1,198 @@ +package tts + +import ( + "archive/zip" + "encoding/json" + "fmt" + "io" + "os" + "path/filepath" + "strings" + "sync" +) + +// VoiceStore publishes validated immutable pack directories. Old files remain +// available for in-flight synthesis and rollback; manifests change atomically. +type VoiceStore struct { + Root string + mu sync.Mutex +} + +func (s *VoiceStore) manifest() (Manifest, error) { + var m Manifest + raw, err := os.ReadFile(filepath.Join(s.Root, "manifest.json")) + if err != nil { + return m, err + } + err = json.Unmarshal(raw, &m) + return m, err +} +func (s *VoiceStore) commit(m Manifest) (*Repo, error) { + raw, err := json.MarshalIndent(m, "", " ") + if err != nil { + return nil, err + } + // Validate against the real root before replacing the live manifest. + repo, err := LoadRepoManifest(s.Root, raw) + if err != nil { + return nil, err + } + temp, err := os.CreateTemp(s.Root, ".manifest-*.tmp") + if err != nil { + return nil, err + } + name := temp.Name() + defer os.Remove(name) + if _, err = temp.Write(raw); err != nil { + temp.Close() + return nil, err + } + if err = temp.Sync(); err != nil { + temp.Close() + return nil, err + } + if err = temp.Close(); err != nil { + return nil, err + } + if err = os.Rename(name, filepath.Join(s.Root, "manifest.json")); err != nil { + return nil, err + } + return repo, nil +} +func (s *VoiceStore) SetDefault(name string) (*Repo, error) { + s.mu.Lock() + defer s.mu.Unlock() + m, err := s.manifest() + if err != nil { + return nil, err + } + found := false + for _, v := range m.Voices { + if v.Name == name { + found = true + } + } + if !found { + return nil, fmt.Errorf("音色不存在") + } + m.Default = name + return s.commit(m) +} +func (s *VoiceStore) Import(archive string) (*Repo, error) { + s.mu.Lock() + defer s.mu.Unlock() + m, err := s.manifest() + if err != nil { + return nil, err + } + stage, err := os.MkdirTemp(s.Root, ".upload-") + if err != nil { + return nil, err + } + defer os.RemoveAll(stage) + if err = extractVoices(archive, stage); err != nil { + return nil, err + } + raw, err := os.ReadFile(filepath.Join(stage, "manifest.json")) + if err != nil { + return nil, fmt.Errorf("ZIP 根目录需要 manifest.json") + } + if len(raw) > 1024*1024 { + return nil, fmt.Errorf("清单过大") + } + var incoming Manifest + if err = json.Unmarshal(raw, &incoming); err != nil { + return nil, fmt.Errorf("语音包清单无效") + } + if len(incoming.Voices) > 32 { + return nil, fmt.Errorf("单次最多导入 32 个音色") + } + if _, err = LoadRepo(stage); err != nil { + return nil, fmt.Errorf("语音包资源或 SHA256 校验失败: %w", err) + } + existing := map[string]bool{} + for _, v := range m.Voices { + existing[v.Name] = true + } + folder := "pack-" + strings.TrimPrefix(filepath.Base(stage), ".upload-") + for _, v := range incoming.Voices { + if existing[v.Name] { + return nil, fmt.Errorf("音色 %q 已存在,请为新音色使用不同名称", v.Name) + } + if filepath.IsAbs(v.Dir) || strings.Contains(v.Dir, "..") { + return nil, fmt.Errorf("语音包目录无效") + } + v.Dir = filepath.Join(folder, v.Dir) + m.Voices = append(m.Voices, v) + } + destination := filepath.Join(s.Root, folder) + if err = os.Rename(stage, destination); err != nil { + return nil, err + } + m.Version = incoming.Version + repo, err := s.commit(m) + if err != nil { + os.RemoveAll(destination) + return nil, err + } + return repo, nil +} +func extractVoices(archive, root string) error { + z, err := zip.OpenReader(archive) + if err != nil { + return fmt.Errorf("无法读取 ZIP 语音包") + } + defer z.Close() + if len(z.File) > 2048 { + return fmt.Errorf("语音包文件数量超过 2048") + } + var total uint64 + for _, entry := range z.File { + name := entry.Name + if name == "" || strings.Contains(name, "\\") || strings.Contains(name, ":") || strings.HasPrefix(name, "/") { + return fmt.Errorf("ZIP 路径无效") + } + for _, part := range strings.Split(name, "/") { + if part == ".." { + return fmt.Errorf("ZIP 路径越界") + } + } + if entry.Mode()&os.ModeSymlink != 0 || (!entry.FileInfo().IsDir() && !entry.Mode().IsRegular()) { + return fmt.Errorf("ZIP 仅允许普通文件和目录") + } + total += entry.UncompressedSize64 + if total > 512<<20 { + return fmt.Errorf("解压后语音包超过 512 MiB") + } + target := filepath.Join(root, filepath.FromSlash(name)) + rel, err := filepath.Rel(root, target) + if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) { + return fmt.Errorf("ZIP 路径越界") + } + if entry.FileInfo().IsDir() { + if err = os.MkdirAll(target, 0755); err != nil { + return err + } + continue + } + if err = os.MkdirAll(filepath.Dir(target), 0755); err != nil { + return err + } + src, err := entry.Open() + if err != nil { + return err + } + dst, err := os.OpenFile(target, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644) + if err != nil { + src.Close() + return err + } + n, copyErr := io.Copy(dst, io.LimitReader(src, int64(entry.UncompressedSize64)+1)) + src.Close() + closeErr := dst.Close() + if copyErr != nil || closeErr != nil || uint64(n) != entry.UncompressedSize64 { + return fmt.Errorf("ZIP 文件不完整") + } + } + return nil +} diff --git a/server/internal/tts/voice_store_test.go b/server/internal/tts/voice_store_test.go new file mode 100644 index 0000000..2231bf8 --- /dev/null +++ b/server/internal/tts/voice_store_test.go @@ -0,0 +1,98 @@ +package tts + +import ( + "archive/zip" + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" +) + +func testVoiceStore(t *testing.T) *VoiceStore { + root := t.TempDir() + writeVoiceFiles(t, root, "pack-a") + writeVoiceFiles(t, root, "pack-b") + writeManifest(t, root, testManifest) + return &VoiceStore{Root: root} +} +func TestVoiceStoreDefaultPersists(t *testing.T) { + store := testVoiceStore(t) + repo, err := store.SetDefault("b") + if err != nil { + t.Fatal(err) + } + if repo.Default != "b" { + t.Fatal(repo.Default) + } + fresh, err := LoadRepo(store.Root) + if err != nil || fresh.Default != "b" { + t.Fatal("default not persisted", err) + } + if _, err = store.SetDefault("missing"); err == nil { + t.Fatal("unknown voice accepted") + } +} +func voiceZip(t *testing.T, entries map[string][]byte) string { + t.Helper() + name := filepath.Join(t.TempDir(), "pack.zip") + f, err := os.Create(name) + if err != nil { + t.Fatal(err) + } + w := zip.NewWriter(f) + for path, data := range entries { + entry, err := w.Create(path) + if err != nil { + t.Fatal(err) + } + if _, err = entry.Write(data); err != nil { + t.Fatal(err) + } + } + if err = w.Close(); err != nil { + t.Fatal(err) + } + if err = f.Close(); err != nil { + t.Fatal(err) + } + return name +} +func TestVoiceStoreImportAndDuplicate(t *testing.T) { + store := testVoiceStore(t) + var incoming Manifest + if err := json.Unmarshal([]byte(testManifest), &incoming); err != nil { + t.Fatal(err) + } + incoming.Version = "test-2" + incoming.Default = "c" + incoming.Voices = incoming.Voices[:1] + incoming.Voices[0].Name = "c" + raw, _ := json.Marshal(incoming) + archive := voiceZip(t, map[string][]byte{"manifest.json": raw, "pack-a/model.onnx": []byte("model"), "pack-a/tokens.txt": []byte("tokens"), "pack-a/lexicon.txt": []byte("lexicon"), "pack-a/phone.fst": []byte("fst")}) + repo, err := store.Import(archive) + if err != nil { + t.Fatal(err) + } + if len(repo.Packs) != 3 || repo.Default != "a" || repo.Version != "test-2" { + t.Fatal("import changed defaults or lost voices") + } + if _, err = store.Import(archive); err == nil { + t.Fatal("duplicate accepted") + } +} +func TestVoiceStoreRejectsTraversalAndBadHash(t *testing.T) { + store := testVoiceStore(t) + archive := voiceZip(t, map[string][]byte{"../escape": []byte("bad")}) + if _, err := store.Import(archive); err == nil { + t.Fatal("traversal accepted") + } + archive = voiceZip(t, map[string][]byte{"manifest.json": []byte(strings.ReplaceAll(testManifest, "9372c470", "00000000")), "pack-a/model.onnx": []byte("tampered")}) + if _, err := store.Import(archive); err == nil { + t.Fatal("invalid package accepted") + } + repo, err := LoadRepo(store.Root) + if err != nil || len(repo.Packs) != 2 { + t.Fatal("rejected upload changed live manifest") + } +} diff --git a/server/internal/tts/voice_test.go b/server/internal/tts/voice_test.go index 2064cae..46c2ce8 100644 --- a/server/internal/tts/voice_test.go +++ b/server/internal/tts/voice_test.go @@ -1,8 +1,10 @@ package tts import ( + "encoding/json" "os" "path/filepath" + "strings" "testing" ) @@ -37,9 +39,9 @@ const testManifest = `{ "default": "a", "voices": [ {"name": "a", "locale": "zh-CN", "label": "甲", "speakerId": 0, "quality": 300, - "dir": "pack-a", "model": "model.onnx", "lexicon": "lexicon.txt", "ruleFsts": ["phone.fst"]}, + "dir": "pack-a", "sha256": "9372c470eeadd5ecd9c3c74c2b3cb633f8e2f2fad799250a0f70d652b6b825e4", "model": "model.onnx", "lexicon": "lexicon.txt", "ruleFsts": ["phone.fst"]}, {"name": "b", "locale": "yue-HK", "label": "乙", "speakerId": 1, "quality": 300, - "dir": "pack-b", "model": "model.onnx", "lexicon": "lexicon.txt", "ruleFsts": ["phone.fst"]} + "dir": "pack-b", "sha256": "9372c470eeadd5ecd9c3c74c2b3cb633f8e2f2fad799250a0f70d652b6b825e4", "model": "model.onnx", "lexicon": "lexicon.txt", "ruleFsts": ["phone.fst"]} ] }` @@ -91,8 +93,8 @@ func TestLoadRepoDuplicateName(t *testing.T) { writeManifest(t, root, `{ "version": "t", "default": "a", "voices": [ - {"name": "a", "locale": "zh-CN", "dir": "pack-a", "model": "model.onnx", "lexicon": "lexicon.txt"}, - {"name": "a", "locale": "yue-HK", "dir": "pack-a", "model": "model.onnx", "lexicon": "lexicon.txt"} + {"name": "a", "locale": "zh-CN", "dir": "pack-a", "sha256": "9372c470eeadd5ecd9c3c74c2b3cb633f8e2f2fad799250a0f70d652b6b825e4", "model": "model.onnx", "lexicon": "lexicon.txt"}, + {"name": "a", "locale": "yue-HK", "dir": "pack-a", "sha256": "9372c470eeadd5ecd9c3c74c2b3cb633f8e2f2fad799250a0f70d652b6b825e4", "model": "model.onnx", "lexicon": "lexicon.txt"} ] }`) if _, err := LoadRepo(root); err == nil { @@ -105,7 +107,7 @@ func TestLoadRepoDefaultFallsBackToFirst(t *testing.T) { writeVoiceFiles(t, root, "pack-a") writeManifest(t, root, `{ "version": "t", "default": "missing", - "voices": [{"name": "a", "locale": "zh-CN", "dir": "pack-a", "model": "model.onnx", "lexicon": "lexicon.txt"}] + "voices": [{"name": "a", "locale": "zh-CN", "dir": "pack-a", "sha256": "9372c470eeadd5ecd9c3c74c2b3cb633f8e2f2fad799250a0f70d652b6b825e4", "model": "model.onnx", "lexicon": "lexicon.txt"}] }`) repo, err := LoadRepo(root) if err != nil { @@ -114,4 +116,48 @@ func TestLoadRepoDefaultFallsBackToFirst(t *testing.T) { if repo.Default != "a" { t.Fatalf("default %q, want a", repo.Default) } -} \ No newline at end of file +} + +func TestLoadRepoRejectsTampering(t *testing.T) { + root := t.TempDir() + writeVoiceFiles(t, root, "pack-a") + writeVoiceFiles(t, root, "pack-b") + writeManifest(t, root, testManifest) + if err := os.WriteFile(filepath.Join(root, "pack-a", "model.onnx"), []byte("tampered"), 0600); err != nil { + t.Fatal(err) + } + if _, err := LoadRepo(root); err == nil { + t.Fatal("tampered model accepted") + } +} +func TestLoadRepoRejectsEscape(t *testing.T) { + root := t.TempDir() + outside := t.TempDir() + writeVoiceFiles(t, outside, "pack-a") + rel, err := filepath.Rel(root, filepath.Join(outside, "pack-a")) + if err != nil { + t.Fatal(err) + } + // Marshal keeps Windows backslashes valid JSON. + raw, _ := json.Marshal(Manifest{Version: "test", Voices: []VoiceEntry{{Name: "a", Dir: rel, Model: "model.onnx", SHA256: "9372c470eeadd5ecd9c3c74c2b3cb633f8e2f2fad799250a0f70d652b6b825e4"}}}) + writeManifest(t, root, string(raw)) + if _, err := LoadRepo(root); err == nil { + t.Fatal("escaped model accepted") + } +} + +func TestLoadRepoRejectsFrontendHashMismatch(t *testing.T) { + root := t.TempDir() + writeVoiceFiles(t, root, "pack-a") + writeVoiceFiles(t, root, "pack-b") + var manifest Manifest + if err := json.Unmarshal([]byte(testManifest), &manifest); err != nil { + t.Fatal(err) + } + manifest.Voices[0].Files = map[string]string{"tokens.txt": strings.Repeat("0", 64)} + raw, _ := json.Marshal(manifest) + writeManifest(t, root, string(raw)) + if _, err := LoadRepo(root); err == nil { + t.Fatal("tampered frontend accepted") + } +} diff --git a/server/main.go b/server/main.go index 50926ce..fc1a58b 100644 --- a/server/main.go +++ b/server/main.go @@ -2,14 +2,17 @@ package main import ( "context" + "crypto/subtle" "encoding/json" "errors" + "io" "log" "net/http" "os" "os/signal" "strconv" "strings" + "sync" "syscall" "time" "unicode/utf8" @@ -23,18 +26,20 @@ const ( minRate = 0.5 maxRate = 2.0 bodyLimit = 64 << 10 - maxQueue = 8 + maxQueue = 2 maxThreads = 8 ) type settings struct { - listen string - voicesDir string - cacheDir string - threads int - queue int - maxRunes int - preload bool + listen string + voicesDir string + cacheDir string + threads int + queue int + maxRunes int + preload bool + apiToken string + adminToken string } func main() { @@ -62,11 +67,12 @@ func main() { } s := &server{ - cfg: cfg, - repo: repo, - cache: cache, - eng: eng, - queue: make(chan struct{}, cfg.queue+1), + cfg: cfg, + repo: repo, + cache: cache, + eng: eng, + queue: make(chan struct{}, cfg.queue+1), + worker: make(chan struct{}, 1), } srv := &http.Server{ @@ -74,7 +80,7 @@ func main() { Handler: s.routes(), ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 15 * time.Second, - WriteTimeout: 120 * time.Second, + WriteTimeout: 180 * time.Second, IdleTimeout: 60 * time.Second, } @@ -97,15 +103,19 @@ func main() { } type server struct { - cfg settings - repo *tts.Repo - cache *tts.Cache - eng *engine - queue chan struct{} + cfg settings + adminMu sync.Mutex + repoMu sync.RWMutex + repo *tts.Repo + cache *tts.Cache + eng *engine + queue chan struct{} + worker chan struct{} } func (s *server) routes() http.Handler { mux := http.NewServeMux() + s.adminRoutes(mux) mux.HandleFunc("GET /healthz", s.handleHealth) mux.HandleFunc("GET /voices", s.handleVoices) mux.HandleFunc("POST /tts", s.handleTTS) @@ -113,16 +123,18 @@ func (s *server) routes() http.Handler { } func (s *server) handleHealth(w http.ResponseWriter, r *http.Request) { + repo := s.repository() writeJSON(w, http.StatusOK, map[string]any{ "status": "ok", "sherpaVersion": sherpa.GetVersion(), - "manifestVersion": s.repo.Version, - "defaultVoice": s.repo.Default, - "voices": len(s.repo.Packs), + "manifestVersion": repo.Version, + "defaultVoice": repo.Default, + "voices": len(repo.Packs), }) } func (s *server) handleVoices(w http.ResponseWriter, r *http.Request) { + repo := s.repository() type voiceInfo struct { Name string `json:"name"` Locale string `json:"locale"` @@ -130,18 +142,26 @@ func (s *server) handleVoices(w http.ResponseWriter, r *http.Request) { SpeakerID int `json:"speakerId"` Quality int `json:"quality"` } - voices := make([]voiceInfo, 0, len(s.repo.Packs)) - for _, p := range s.repo.Packs { + voices := make([]voiceInfo, 0, len(repo.Packs)) + for _, p := range repo.Packs { voices = append(voices, voiceInfo{p.Name, p.Locale, p.Label, p.SpeakerID, p.Quality}) } writeJSON(w, http.StatusOK, map[string]any{ - "version": s.repo.Version, - "default": s.repo.Default, + "version": repo.Version, + "default": repo.Default, "voices": voices, }) } func (s *server) handleTTS(w http.ResponseWriter, r *http.Request) { + repo := s.repository() + if s.cfg.apiToken != "" && subtle.ConstantTimeCompare([]byte(r.Header.Get("Authorization")), []byte("Bearer "+s.cfg.apiToken)) != 1 { + writeError(w, http.StatusUnauthorized, "unauthorized") + return + } + ctx, cancel := context.WithTimeout(r.Context(), 25*time.Second) + defer cancel() + var req struct { Text string `json:"text"` Voice string `json:"voice"` @@ -149,11 +169,16 @@ func (s *server) handleTTS(w http.ResponseWriter, r *http.Request) { Pitch *float64 `json:"pitch"` } r.Body = http.MaxBytesReader(w, r.Body, bodyLimit) - if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + decoder := json.NewDecoder(r.Body) + if err := decoder.Decode(&req); err != nil { writeError(w, http.StatusBadRequest, "invalid JSON body") return } + if err := decoder.Decode(new(any)); err != io.EOF { + writeError(w, http.StatusBadRequest, "body must contain one JSON value") + return + } text := strings.TrimSpace(req.Text) if text == "" { writeError(w, http.StatusBadRequest, "text is required") @@ -174,15 +199,10 @@ func (s *server) handleTTS(w http.ResponseWriter, r *http.Request) { } fSpeed, fPitch := float32(speed), float32(pitch) - pack := s.repo.Resolve(req.Voice) - key := s.cache.Key(s.repo.Version, pack.Name, fSpeed, fPitch, text) + pack := repo.Resolve(req.Voice) + key := s.cache.Key(repo.Version, pack.Name, fSpeed, fPitch, text) - if data, ok := s.cache.Get(key); ok { - setAudioHeaders(w, pack, s.repo.Version, tts.WAVSampleRate(data)) - w.Header().Set("X-Tts-Cache", "hit") - w.Write(data) - log.Printf("tts hit voice=%s runes=%d speed=%.2f pitch=%.2f bytes=%d", - pack.Name, utf8.RuneCountInString(text), speed, pitch, len(data)) + if s.serveCached(w, r, key, pack, repo.Version) { return } @@ -195,9 +215,27 @@ func (s *server) handleTTS(w http.ResponseWriter, r *http.Request) { return } + select { + case s.worker <- struct{}{}: + defer func() { <-s.worker }() + case <-ctx.Done(): + writeError(w, http.StatusGatewayTimeout, "queue deadline exceeded") + return + } + if ctx.Err() != nil { + return + } + // An identical request may have filled the cache while we waited. + if s.serveCached(w, r, key, pack, repo.Version) { + return + } start := time.Now() - samples, rate, err := s.eng.synthesize(pack, text, fSpeed, fPitch) + samples, rate, err := s.eng.synthesize(ctx, pack, text, fSpeed, fPitch) if err != nil { + if ctx.Err() != nil { + writeError(w, http.StatusGatewayTimeout, "synthesis deadline exceeded") + return + } log.Printf("tts failed voice=%s: %v", pack.Name, err) writeError(w, http.StatusInternalServerError, "synthesis failed") return @@ -208,7 +246,7 @@ func (s *server) handleTTS(w http.ResponseWriter, r *http.Request) { log.Printf("cache write: %v", err) } - setAudioHeaders(w, pack, s.repo.Version, rate) + setAudioHeaders(w, pack, repo.Version, rate) w.Header().Set("X-Tts-Cache", "miss") w.Write(data) @@ -227,13 +265,21 @@ func setAudioHeaders(w http.ResponseWriter, pack *tts.VoicePack, version string, func loadSettings() settings { cfg := settings{ - listen: env("TTS_LISTEN", ":8080"), - voicesDir: env("TTS_VOICES", "/opt/tts/voices"), - cacheDir: env("TTS_CACHE", "/var/cache/tts"), - threads: envInt("TTS_THREADS", 2), - queue: envInt("TTS_QUEUE", 2), - maxRunes: envInt("TTS_MAX_TEXT", 300), - preload: env("TTS_PRELOAD", "1") != "0", + listen: env("TTS_LISTEN", ":8080"), + voicesDir: env("TTS_VOICES", "/opt/tts/voices"), + cacheDir: env("TTS_CACHE", "/var/cache/tts"), + threads: envInt("TTS_THREADS", 2), + queue: envInt("TTS_QUEUE", 2), + maxRunes: envInt("TTS_MAX_TEXT", 300), + preload: env("TTS_PRELOAD", "1") != "0", + apiToken: os.Getenv("TTS_API_TOKEN"), + adminToken: os.Getenv("TTS_ADMIN_TOKEN"), + } + if cfg.adminToken != "" && cfg.adminToken == cfg.apiToken { + log.Fatal("TTS_ADMIN_TOKEN must differ from TTS_API_TOKEN") + } + if env("TTS_REQUIRE_AUTH", "0") == "1" && strings.TrimSpace(cfg.apiToken) == "" { + log.Fatal("TTS_API_TOKEN is required when TTS_REQUIRE_AUTH=1") } if cfg.threads < 1 || cfg.threads > maxThreads { log.Fatalf("TTS_THREADS must be 1..%d", maxThreads) @@ -284,4 +330,32 @@ func writeJSON(w http.ResponseWriter, status int, body any) { func writeError(w http.ResponseWriter, status int, msg string) { writeJSON(w, status, map[string]string{"error": msg}) -} \ No newline at end of file +} +func (s *server) serveCached(w http.ResponseWriter, r *http.Request, key string, pack *tts.VoicePack, version string) bool { + file, err := s.cache.Open(key) + if err != nil { + return false + } + defer file.Close() + header := make([]byte, 44) + if _, err := io.ReadFull(file, header); err != nil { + return false + } + if _, err := file.Seek(0, io.SeekStart); err != nil { + return false + } + info, err := file.Stat() + if err != nil { + return false + } + setAudioHeaders(w, pack, version, tts.WAVSampleRate(header)) + w.Header().Set("X-Tts-Cache", "hit") + http.ServeContent(w, r, key+".wav", info.ModTime(), file) + return true +} + +func (s *server) repository() *tts.Repo { + s.repoMu.RLock() + defer s.repoMu.RUnlock() + return s.repo +} diff --git a/server/main_test.go b/server/main_test.go new file mode 100644 index 0000000..32acbfc --- /dev/null +++ b/server/main_test.go @@ -0,0 +1,111 @@ +package main + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + "tts-server/internal/tts" +) + +func testServer(t *testing.T) *server { + t.Helper() + root := t.TempDir() + for _, name := range []string{"model.onnx", "tokens.txt"} { + if err := os.WriteFile(filepath.Join(root, name), []byte(name), 0600); err != nil { + t.Fatal(err) + } + } + hash := sha256.Sum256([]byte("model.onnx")) + manifest, _ := json.Marshal(tts.Manifest{Version: "test", Default: "a", Voices: []tts.VoiceEntry{{Name: "a", Locale: "zh-CN", Model: "model.onnx", SHA256: hex.EncodeToString(hash[:])}}}) + if err := os.WriteFile(filepath.Join(root, "manifest.json"), manifest, 0600); err != nil { + t.Fatal(err) + } + repo, err := tts.LoadRepo(root) + if err != nil { + t.Fatal(err) + } + cache, err := tts.NewCache(t.TempDir()) + if err != nil { + t.Fatal(err) + } + return &server{cfg: settings{maxRunes: 300, voicesDir: root}, repo: repo, cache: cache, eng: newEngine(1), queue: make(chan struct{}, 3), worker: make(chan struct{}, 1)} +} +func TestRejectUnauthorizedAndTrailingJSON(t *testing.T) { + s := testServer(t) + s.cfg.apiToken = "test-token" + request := httptest.NewRequest("POST", "/tts", strings.NewReader(`{"text":"hello"}`)) + response := httptest.NewRecorder() + s.routes().ServeHTTP(response, request) + if response.Code != http.StatusUnauthorized { + t.Fatal(response.Code) + } + request = httptest.NewRequest("POST", "/tts", strings.NewReader(`{"text":"hello"} {}`)) + request.Header.Set("Authorization", "Bearer test-token") + response = httptest.NewRecorder() + s.routes().ServeHTTP(response, request) + if response.Code != http.StatusBadRequest { + t.Fatal(response.Code) + } +} +func TestCancelledQueueReleasesSlot(t *testing.T) { + s := testServer(t) + s.worker <- struct{}{} + ctx, cancel := context.WithCancel(context.Background()) + cancel() + request := httptest.NewRequest("POST", "/tts", strings.NewReader(`{"text":"hello"}`)).WithContext(ctx) + response := httptest.NewRecorder() + s.routes().ServeHTTP(response, request) + if response.Code != http.StatusGatewayTimeout { + t.Fatal(response.Code) + } + if len(s.queue) != 0 { + t.Fatal("cancelled request leaked queue slot") + } +} +func TestCacheHitDoesNotWaitForInference(t *testing.T) { + s := testServer(t) + key := s.cache.Key("test", "a", 1, 1, "hello") + data := tts.EncodeWAV([]float32{0.1, 0.2}, 22050) + if err := s.cache.Put(key, data); err != nil { + t.Fatal(err) + } + s.worker <- struct{}{} + request := httptest.NewRequest("POST", "/tts", strings.NewReader(`{"text":"hello"}`)) + response := httptest.NewRecorder() + s.routes().ServeHTTP(response, request) + if response.Code != 200 || response.Header().Get("X-Tts-Cache") != "hit" || response.Body.Len() != len(data) { + t.Fatal("cache response invalid") + } +} +func TestNativeSynthesis(t *testing.T) { + dir := os.Getenv("TTS_TEST_VOICES") + if dir == "" { + t.Skip("set TTS_TEST_VOICES to run native model smoke test") + } + repo, err := tts.LoadRepo(dir) + if err != nil { + t.Fatal(err) + } + engine := newEngine(2) + defer engine.close() + for _, pitch := range []float32{1, 0.5, 1.2, 2} { + samples, rate, err := engine.synthesize(context.Background(), repo.DefaultPack(), "您好。现在时间是九点整。", 0.9, pitch) + if err != nil || len(samples) == 0 || rate != 22050 { + t.Fatalf("pitch=%v samples=%d rate=%d err=%v", pitch, len(samples), rate, err) + } + var energy float64 + for _, v := range samples { + energy += float64(v * v) + } + if energy < 0.01 { + t.Fatalf("silent output pitch=%v", pitch) + } + } +} diff --git a/server/nginx-tts.ttstd.conf b/server/nginx-tts.ttstd.conf index 1dc8da7..1e36a5a 100644 --- a/server/nginx-tts.ttstd.conf +++ b/server/nginx-tts.ttstd.conf @@ -1,3 +1,6 @@ +limit_req_zone $binary_remote_addr zone=tts_requests:1m rate=2r/s; +limit_conn_zone $binary_remote_addr zone=tts_connections:1m; + # TTS 在线合成(k3s NodePort 30810)反向代理 # 证书由 certbot 签发(自动续期): # certbot certonly --webroot -w /var/www/certbot -d tts.ttstd.com @@ -28,8 +31,23 @@ server { client_max_body_size 1m; - # 服务本身无鉴权,对外开放前需自行加访问控制 + # Admin uploads are streamed to the service and independently authenticated. + location = /admin/api/import { + client_max_body_size 256m; + proxy_pass http://127.0.0.1:30810; + proxy_http_version 1.1; + proxy_request_buffering off; + proxy_read_timeout 180s; + proxy_send_timeout 180s; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-Proto $scheme; + } + + # POST /tts 使用 TTS_API_TOKEN Bearer 鉴权,部署前创建 Kubernetes Secret location / { + limit_req zone=tts_requests burst=4 nodelay; + limit_req_status 429; + limit_conn tts_connections 4; proxy_pass http://127.0.0.1:30810; proxy_http_version 1.1; proxy_set_header Host $host; diff --git a/test-client/app/build.gradle b/test-client/app/build.gradle index 37daf80..8132217 100644 --- a/test-client/app/build.gradle +++ b/test-client/app/build.gradle @@ -23,4 +23,5 @@ android { abortOnError false checkReleaseBuilds = false } -} \ No newline at end of file +} +dependencies { implementation 'com.ttstd:tts-speaker-sdk:1.0.0' } diff --git a/test-client/app/src/main/AndroidManifest.xml b/test-client/app/src/main/AndroidManifest.xml index b10dae1..ca7cd25 100644 --- a/test-client/app/src/main/AndroidManifest.xml +++ b/test-client/app/src/main/AndroidManifest.xml @@ -1,13 +1,12 @@ + + - - - + - listeners=new HashMap<>(); + + EngineTtsTester(Context context) { this.context=context.getApplicationContext(); } + void speak(SpeechRequest request,boolean network,OnlineTtsClient.Listener callback) { + stop(); + if(closed) return; + if(ready) { play(request,network,callback); return; } + pending=() -> play(request,network,callback); + pendingListener=callback; + if(tts!=null) return; + try { context.getPackageManager().getPackageInfo(PACKAGE,0); } + catch(Exception e) { failPending("未安装 TTStd 系统引擎"); return; } + tts=new TextToSpeech(context,status -> { + if(closed) return; + if(status!=TextToSpeech.SUCCESS) { + TextToSpeech failed=tts; tts=null; + if(failed!=null) failed.shutdown(); + failPending("系统引擎初始化失败"); return; + } + ready=true; + tts.setOnUtteranceProgressListener(new UtteranceProgressListener() { + public void onStart(String id) { main.post(() -> { OnlineTtsClient.Listener l=listeners.get(id); if(l!=null) l.onStart(); }); } + public void onDone(String id) { main.post(() -> { OnlineTtsClient.Listener l=listeners.remove(id); if(l!=null) l.onCompleted(); }); } + public void onError(String id) { onError(id,TextToSpeech.ERROR_SYNTHESIS); } + public void onError(String id,int error) { main.post(() -> { OnlineTtsClient.Listener l=listeners.remove(id); if(l!=null) l.onError(0,"系统引擎错误 "+error); }); } + public void onStop(String id,boolean interrupted) { main.post(() -> { OnlineTtsClient.Listener l=listeners.remove(id); if(l!=null) l.onCancelled(); }); } + }); + Runnable next=pending; pending=null; pendingListener=null; + if(next!=null) next.run(); + },PACKAGE); + } + private void play(SpeechRequest request,boolean network,OnlineTtsClient.Listener listener) { + Set voices=tts.getVoices(); + Voice selected=null; + if(voices!=null) for(Voice voice:voices) { + if(voice.isNetworkConnectionRequired()==network && voice.getLocale().getLanguage().equals("zh")) { + selected=voice; break; + } + } + if(selected==null || tts.setVoice(selected)!=TextToSpeech.SUCCESS) { + listener.onError(0,"所选引擎音色不可用;离线模式需要安装语音包"); return; + } + android.util.Log.i("TtsTestClient","引擎测试音色 "+selected.getName()+" network="+network); + tts.setSpeechRate(request.speed); tts.setPitch(request.pitch); + String id=UUID.randomUUID().toString(); listeners.put(id,listener); + if(tts.speak(request.text,TextToSpeech.QUEUE_FLUSH,new Bundle(),id)!=TextToSpeech.SUCCESS) { + listeners.remove(id); listener.onError(0,"系统引擎拒绝朗读请求"); + } + } + private void failPending(String message) { + OnlineTtsClient.Listener listener=pendingListener; + pending=null; pendingListener=null; + if(listener!=null) listener.onError(0,message); + } + void stop() { + pending=null; + OnlineTtsClient.Listener waiting=pendingListener; pendingListener=null; + if(tts!=null) tts.stop(); + List cancelled=new ArrayList<>(listeners.values()); listeners.clear(); + if(waiting!=null) waiting.onCancelled(); + for(OnlineTtsClient.Listener listener:cancelled) listener.onCancelled(); + } + @Override public void close() { closed=true; stop(); if(tts!=null) { tts.shutdown(); tts=null; } } +} diff --git a/test-client/app/src/main/java/com/ttstd/tts/testclient/MainActivity.java b/test-client/app/src/main/java/com/ttstd/tts/testclient/MainActivity.java index 25248e8..00543f6 100644 --- a/test-client/app/src/main/java/com/ttstd/tts/testclient/MainActivity.java +++ b/test-client/app/src/main/java/com/ttstd/tts/testclient/MainActivity.java @@ -1,221 +1,146 @@ package com.ttstd.tts.testclient; import android.app.Activity; -import android.content.Intent; -import android.content.pm.ResolveInfo; +import android.app.AlertDialog; +import android.content.SharedPreferences; import android.os.Bundle; -import android.speech.tts.TextToSpeech; -import android.speech.tts.UtteranceProgressListener; -import android.speech.tts.Voice; -import android.text.method.ScrollingMovementMethod; +import android.text.InputType; import android.util.Log; -import android.widget.Button; -import android.widget.EditText; -import android.widget.SeekBar; -import android.widget.TextView; - -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.List; +import android.widget.*; +import com.ttstd.tts.sdk.OnlineTtsClient; +import com.ttstd.tts.sdk.SpeechRequest; import java.util.Locale; -import java.util.Set; +/** Direct Maven SDK sample: no binding to an installed TextToSpeech engine. */ public class MainActivity extends Activity { - private static final String TAG = "TtsTestClient"; - private static final String ENGINE = "com.ttstd.tts.engine"; - private static final String[] SWEEP_TEXTS = {"一", "二", "三", "四", "五", "六"}; + private static final String TAG="TtsTestClient"; + private OnlineTtsClient client; + private EngineTtsTester engine; + private Spinner mode; + private int selectedMode; + private SharedPreferences prefs; + private EditText text; + private SeekBar rate,pitch; + private TextView log; + private boolean batch; + private int index; + private int sequence; + private final float[] rates={0.5f,1f,1.5f,2f,1f,1f}; + private final float[] pitches={1f,1f,1f,1f,0.5f,2f}; - private TextView logView; - private TextView rateLabel; - private TextView pitchLabel; - private EditText textInput; - private SeekBar rateBar; - private SeekBar pitchBar; - - private TextToSpeech tts; - private boolean ready; - private int utteranceSeq; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); + @Override public void onCreate(Bundle state) { + super.onCreate(state); setContentView(R.layout.activity_main); - - logView = findViewById(R.id.log_view); - logView.setMovementMethod(new ScrollingMovementMethod()); - textInput = findViewById(R.id.text_input); - rateBar = findViewById(R.id.rate_bar); - pitchBar = findViewById(R.id.pitch_bar); - rateLabel = findViewById(R.id.rate_label); - pitchLabel = findViewById(R.id.pitch_label); - - SeekBar.OnSeekBarChangeListener labels = new SeekBar.OnSeekBarChangeListener() { - public void onProgressChanged(SeekBar bar, int progress, boolean fromUser) { - updateLabels(); - } - - public void onStartTrackingTouch(SeekBar bar) { - } - - public void onStopTrackingTouch(SeekBar bar) { + text=findViewById(R.id.text_input); + rate=findViewById(R.id.rate_bar); + pitch=findViewById(R.id.pitch_bar); + log=findViewById(R.id.log_view); + log.setMovementMethod(new android.text.method.ScrollingMovementMethod()); + engine=new EngineTtsTester(this); + mode=findViewById(R.id.synthesis_mode); + mode.setAdapter(new ArrayAdapter<>(this,android.R.layout.simple_spinner_dropdown_item, + new String[]{"SDK 直接在线(无需引擎)","系统引擎离线","系统引擎在线"})); + selectedMode=getIntent().getIntExtra("mode",0); + mode.setSelection(selectedMode); + mode.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + public void onItemSelected(AdapterView parent,android.view.View view,int position,long id) { + if(position!=selectedMode) { selectedMode=position; stop(); } } + public void onNothingSelected(AdapterView parent) {} + }); + findViewById(R.id.btn_engine_config).setOnClickListener(v -> { + try { startActivity(new android.content.Intent().setComponent(new android.content.ComponentName( + EngineTtsTester.PACKAGE,EngineTtsTester.PACKAGE+".SettingsActivity"))); } + catch(Exception e) { append("未安装系统引擎,请先安装引擎 APK"); } + }); + prefs=getSharedPreferences("tts_sdk_test",MODE_PRIVATE); + SeekBar.OnSeekBarChangeListener labels=new SeekBar.OnSeekBarChangeListener() { + public void onProgressChanged(SeekBar b,int p,boolean u) { updateLabels(); } + public void onStartTrackingTouch(SeekBar b) {} + public void onStopTrackingTouch(SeekBar b) {} }; - rateBar.setOnSeekBarChangeListener(labels); - pitchBar.setOnSeekBarChangeListener(labels); - updateLabels(); - - findViewById(R.id.btn_speak).setOnClickListener(v -> speak()); + rate.setOnSeekBarChangeListener(labels); pitch.setOnSeekBarChangeListener(labels); updateLabels(); + findViewById(R.id.btn_speak).setOnClickListener(v -> { + batch=false; speak(text.getText().toString(),value(rate),value(pitch),false); + }); findViewById(R.id.btn_stop).setOnClickListener(v -> stop()); - findViewById(R.id.btn_sweep).setOnClickListener(v -> sweep()); - - initTts(); - } - - private void initTts() { - appendLog("连接引擎 " + ENGINE); - tts = new TextToSpeech(this, status -> { - appendLog("onInit status=" + status); - if (status != TextToSpeech.SUCCESS) { - appendLog("引擎初始化失败"); - return; - } - ready = true; - logEngines(); - tts.setOnUtteranceProgressListener(new UtteranceProgressListener() { - @Override - public void onStart(String utteranceId) { - appendLog("开始合成 " + utteranceId); - } - - @Override - public void onDone(String utteranceId) { - appendLog("播放完成 " + utteranceId); - } - - @Override - public void onError(String utteranceId) { - appendLog("合成/播放失败 " + utteranceId); - } - }); - appendLog("setLanguage zh-CN -> " + tts.setLanguage(Locale.SIMPLIFIED_CHINESE)); - listVoices(); - if (getIntent().getBooleanExtra("autosweep", false)) sweep(); - else if (getIntent().getBooleanExtra("autospeak", false)) { - long delay = getIntent().getLongExtra("speak_delay_ms", 0); - if (delay > 0) logView.postDelayed(this::speak, delay); - else speak(); - } - }, ENGINE); - } - - private void logEngines() { - List engines = tts.getEngines(); - appendLog("系统引擎数量 " + engines.size()); - for (TextToSpeech.EngineInfo engine : engines) { - appendLog("引擎 " + engine.name + " | " + engine.label); + findViewById(R.id.btn_sweep).setOnClickListener(v -> { stop(); batch=true; index=0; next(); }); + findViewById(R.id.btn_online_config).setOnClickListener(v -> configure()); + findViewById(R.id.btn_online_error).setOnClickListener(v -> { + char[] chars=new char[301]; java.util.Arrays.fill(chars,'一'); + speak(new String(chars),1,1,false); + }); + createClient(); + append("已加载 Maven SDK com.ttstd:tts-speaker-sdk:1.0.0;无需引擎 APK"); + if(getIntent().getBooleanExtra("autoerror",false)) findViewById(R.id.btn_online_error).performClick(); + else if(getIntent().getBooleanExtra("autosweep",false)) { batch=true; index=0; next(); } + else if(getIntent().getBooleanExtra("autospeak",false)) { + speak(text.getText().toString(),value(rate),value(pitch),false); + if(getIntent().getBooleanExtra("autocancel",false)) log.postDelayed(this::stop,300); } - List services = getPackageManager().queryIntentServices( - new Intent("android.intent.action.TTS_SERVICE"), 0); - appendLog("PM TTS 服务数量(flags=0) " + (services == null ? -1 : services.size())); - if (services != null) { - for (ResolveInfo info : services) { - if (info.serviceInfo != null) { - appendLog("PM 服务 " + info.serviceInfo.packageName + "/" + info.serviceInfo.name); - } - } - } - Intent explicit = new Intent("android.intent.action.TTS_SERVICE").setPackage(ENGINE); - List explicitServices = getPackageManager().queryIntentServices(explicit, 0); - appendLog("显式包查询数量 " + (explicitServices == null ? -1 : explicitServices.size())); + } + private boolean createClient() { try { - getPackageManager().getPackageInfo(ENGINE, 0); - appendLog("getPackageInfo(" + ENGINE + ") 可见"); - } catch (Exception e) { - appendLog("getPackageInfo(" + ENGINE + ") 不可见: " + e.getClass().getSimpleName()); - } + client=new OnlineTtsClient(this,prefs.getString("url",OnlineTtsClient.DEFAULT_ENDPOINT), + () -> prefs.getString("token","")); + return true; + } catch(IllegalArgumentException e) { append("服务地址无效,请重新配置 HTTPS 地址"); return false; } } - - private void listVoices() { - Set voices = tts.getVoices(); - if (voices == null) { - appendLog("getVoices() = null"); - return; - } - appendLog("语音数量 " + voices.size()); - for (Voice voice : voices) { - appendLog("语音 " + voice.getName() + " | " + voice.getLocale().toLanguageTag() - + " | q=" + voice.getQuality()); - } + private void speak(String content,float speed,float tone,boolean sweep) { + if(client==null && mode.getSelectedItemPosition()==0) { append("请先配置服务地址"); return; } + String id=(sweep?"sweep-":"utt-")+(++sequence); + try { + SpeechRequest request=new SpeechRequest(content,speed,tone); + append(String.format(Locale.ROOT,"模式=%s %s speed=%.2f pitch=%.2f",mode.getSelectedItem(),id,speed,tone)); + OnlineTtsClient.Listener listener=new OnlineTtsClient.Listener() { + public void onStart() { append("播放开始 "+id); } + public void onCompleted() { append("播放完成 "+id); if(sweep && batch) next(); } + public void onError(int status,String message) { batch=false; append("在线合成失败 "+id+" HTTP="+status+" "+message); } + public void onCancelled() { append("已停止 "+id); } + }; + if(mode.getSelectedItemPosition()==0) client.speak(request,listener); + else engine.speak(request,mode.getSelectedItemPosition()==2,listener); + } catch(IllegalArgumentException e) { append("参数校验失败:"+e.getMessage()); } } - - private void speak() { - if (!ready) { - appendLog("引擎未就绪"); - return; - } - String text = textInput.getText().toString().trim(); - if (text.isEmpty()) { - appendLog("文本为空"); - return; - } - float rate = rate(); - float pitch = pitch(); - tts.setSpeechRate(rate); - tts.setPitch(pitch); - String id = "utt-" + (++utteranceSeq); - int result = tts.speak(text, TextToSpeech.QUEUE_FLUSH, null, id); - appendLog(String.format(Locale.ROOT, "speak %s speed=%.2f pitch=%.2f -> %d", id, rate, pitch, result)); + private void next() { + if(index>=rates.length) { batch=false; append("六组 SDK 参数用例全部完成"); return; } + int current=index++; + speak("您好,现在测试在线语音合成。",rates[current],pitches[current],true); } - - private void sweep() { - if (!ready) { - appendLog("引擎未就绪"); - return; - } - float[] rates = {0.5f, 1.0f, 1.5f, 2.0f, 1.0f, 1.0f}; - float[] pitches = {1.0f, 1.0f, 1.0f, 1.0f, 0.5f, 2.0f}; - for (int i = 0; i < rates.length; i++) { - tts.setSpeechRate(rates[i]); - tts.setPitch(pitches[i]); - String id = "sweep-" + (++utteranceSeq); - tts.speak(SWEEP_TEXTS[i], TextToSpeech.QUEUE_ADD, null, id); - appendLog(String.format(Locale.ROOT, "%s speed=%.2f pitch=%.2f", id, rates[i], pitches[i])); - } - } - - private void stop() { - if (tts != null) { - tts.stop(); - appendLog("stop()"); - } - } - - private float rate() { - return (50 + rateBar.getProgress()) / 100f; - } - - private float pitch() { - return (50 + pitchBar.getProgress()) / 100f; - } - + private void stop() { batch=false; if(client!=null) client.stop(); if(engine!=null) engine.stop(); append("stop()"); } + private float value(SeekBar bar) { return (50+bar.getProgress())/100f; } private void updateLabels() { - rateLabel.setText(getString(R.string.rate_label, rate())); - pitchLabel.setText(getString(R.string.pitch_label, pitch())); + ((TextView)findViewById(R.id.rate_label)).setText(getString(R.string.rate_label,value(rate))); + ((TextView)findViewById(R.id.pitch_label)).setText(getString(R.string.pitch_label,value(pitch))); } - - private void appendLog(String message) { - Log.i(TAG, message); - String line = new SimpleDateFormat("HH:mm:ss", Locale.ROOT).format(new Date()) + " " + message; - logView.append(line + "\n"); + private void configure() { + LinearLayout fields=new LinearLayout(this); fields.setOrientation(LinearLayout.VERTICAL); + int padding=(int)(16*getResources().getDisplayMetrics().density); fields.setPadding(padding,padding,padding,padding); + EditText url=new EditText(this); url.setHint("HTTPS 合成接口"); + url.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_URI); + url.setText(prefs.getString("url",OnlineTtsClient.DEFAULT_ENDPOINT)); fields.addView(url); + EditText token=new EditText(this); token.setHint("访问令牌"); token.setSaveEnabled(false); + token.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_PASSWORD); + token.setText(prefs.getString("token","")); fields.addView(token); + new AlertDialog.Builder(this).setTitle("SDK 在线合成配置").setView(fields) + .setPositiveButton("保存",(d,w) -> { + String endpoint=url.getText().toString().trim(); + try { OnlineTtsClient check=new OnlineTtsClient(this,endpoint,() -> ""); check.close(); } + catch(IllegalArgumentException e) { append("HTTPS 地址无效,未保存"); return; } + batch=false; + if(client!=null) client.close(); + prefs.edit().putString("url",endpoint).putString("token",token.getText().toString().trim()).apply(); + createClient(); append("配置已保存到测试应用私有存储"); + }).setNegativeButton("取消",null).show(); } - - @Override - protected void onDestroy() { - if (tts != null) { - tts.stop(); - tts.shutdown(); - tts = null; - } + private void append(String message) { + Log.i(TAG,message); + runOnUiThread(() -> { if(!isDestroyed()) log.append(message+"\n"); }); + } + @Override public void onDestroy() { + batch=false; + if(client!=null) client.close(); + if(engine!=null) engine.close(); super.onDestroy(); } -} \ No newline at end of file +} diff --git a/test-client/app/src/main/res/layout/activity_main.xml b/test-client/app/src/main/res/layout/activity_main.xml index 760d96f..4fa38b4 100644 --- a/test-client/app/src/main/res/layout/activity_main.xml +++ b/test-client/app/src/main/res/layout/activity_main.xml @@ -1,12 +1,23 @@ - + + + +