初始化 TTS 引擎工程:Android 系统引擎、Go 在线合成服务与测试客户端

- android-engine:TextToSpeechService 引擎,含设置页、语音包导入(SHA-256 校验)与预热
- server:Go CPU 合成服务与部署文件
- test-client:端到端验证客户端
- 模型与语音包不入库,见 models/README.md
This commit is contained in:
tongtong committed 2026-11-23 14:59:46 +08:00
commit 1856de97bc
62 files changed
+3787

No files matched your search

+4
View File
@@ -0,0 +1,4 @@
bin/
.cache/
*.wav
*.exe
+6
View File
@@ -0,0 +1,6 @@
bin/
build/
dist/
.cache/
*.exe
*.wav
+35
View File
@@ -0,0 +1,35 @@
# syntax=docker/dockerfile:1
FROM golang:1.26-bookworm AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=1 go build -trimpath -buildvcs=false -ldflags='-s -w' -o /out/tts-server .
# cgo links against the shared libs shipped inside the Go module.
RUN set -eux; \
case "$(go env GOARCH)" in \
amd64) lib=x86_64-unknown-linux-gnu ;; \
arm64) lib=aarch64-unknown-linux-gnu ;; \
*) echo "unsupported arch $(go env GOARCH)"; exit 1 ;; \
esac; \
mkdir -p /out/lib; \
cp /go/pkg/mod/github.com/k2-fsa/sherpa-onnx-go-linux/v2@v2.0.1/lib/$lib/*.so /out/lib/
FROM debian:bookworm-slim
RUN apt-get update \
&& apt-get install -y --no-install-recommends libstdc++6 libgomp1 \
&& rm -rf /var/lib/apt/lists/* \
&& mkdir -p /cache && chown 65534:65534 /cache
WORKDIR /app
COPY --from=build /out/tts-server /app/tts-server
COPY --from=build /out/lib/ /app/lib/
ENV LD_LIBRARY_PATH=/app/lib \
TTS_LISTEN=:8080 \
TTS_VOICES=/voices \
TTS_CACHE=/cache
EXPOSE 8080
USER 65534:65534
ENTRYPOINT ["/app/tts-server"]
+13
View File
@@ -0,0 +1,13 @@
# 节点构建用:只打包预编译产物,不装 Go、不走 Docker Hub。
# 构建上下文为 dist/(tts-server + lib/*.so,由 README 的交叉编译步骤生成):
# docker build -f Dockerfile.runtime -t docker.io/library/tts-server:<tag> dist
FROM debian:bookworm-slim
RUN mkdir -p /cache && chown 65534:65534 /cache
WORKDIR /app
COPY tts-server /app/tts-server
COPY lib/ /app/lib/
RUN chmod 755 /app/tts-server
ENV LD_LIBRARY_PATH=/app/lib TTS_LISTEN=:8080 TTS_VOICES=/voices TTS_CACHE=/cache
EXPOSE 8080
USER 65534:65534
ENTRYPOINT ["/app/tts-server"]
+168
View File
@@ -0,0 +1,168 @@
# TtsSpeaker 在线合成服务
Go + cgo + sherpa-onnx **2.0.1**,与 `android-engine`(`libs/sherpa-onnx-2.0.1.aar`)同版本、同语音包、同变调算法。纯 CPU 推理,单语音包常驻,WAV 输出。
## 接口
| 方法 | 路径 | 说明 |
| --- | --- | --- |
| GET | `/healthz` | 就绪与版本信息(含 sherpa-onnx 版本) |
| GET | `/voices` | 清单版本、默认语音包、全部语音包 |
| POST | `/tts` | 合成,返回 `audio/wav` |
`POST /tts` 请求体:
```json
{"text": "您好,现在时间是上午九点整。", "voice": "zh-CN-chaowen", "speed": 0.9, "pitch": 1.0}
```
- `text` 必填,按字符数限制(`TTS_MAX_TEXT`,默认 300)。
- `voice` 可填语音包名或 BCP-47 语言(如 `yue-HK`);省略或未命中时回退默认语音包,实际使用的包见响应头。
- `speed` / `pitch` 取 0.5–2.0,越界截断,省略为 1.0。与设备端一致:`speed` 直接映射模型 speed;`pitch` 由和 `PitchShifter.java` 相同的算法实现(时长基本不变)。
响应头:`X-Tts-Voice`、`X-Tts-Voice-Version`、`X-Tts-Sample-Rate`、`X-Tts-Cache`(`hit`/`miss`)。音频为 16-bit 单声道 PCM WAV。错误返回 JSON:400(参数)、429(排队已满)、500(合成失败)。
缓存键包含文本、语音包名、语速、音调与清单版本,升级语音包后旧缓存自动失效。
## 环境变量
| 变量 | 默认 | 说明 |
| --- | --- | --- |
| `TTS_LISTEN` | `:8080` | HTTP 监听地址 |
| `TTS_VOICES` | `/opt/tts/voices` | 语音包根目录,`manifest.json` 与 `android-engine` 共用 |
| `TTS_CACHE` | `/var/cache/tts` | 合成缓存目录(WAV 文件) |
| `TTS_THREADS` | `2` | ONNX Runtime 线程数 |
| `TTS_QUEUE` | `2` | 除正在合成外允许排队的请求数,超出返回 429 |
| `TTS_MAX_TEXT` | `300` | 单次文本字符上限 |
| `TTS_PRELOAD` | `1` | 启动时加载默认语音包(健康检查通过即热) |
## 本地运行(Windows 开发机)
```bash
cd TtsSpeaker/server
go build -o bin/tts-server.exe .
# 把 sherpa 的三个 DLL 放到 exe 旁边
M=$(go env GOMODCACHE | tr '\\' '/')/github.com/k2-fsa/sherpa-onnx-go-windows/v2@v2.0.1
cp "$M"/lib/x86_64-pc-windows-gnu/*.dll bin/
TTS_LISTEN=127.0.0.1:18080 TTS_VOICES=../models/voices TTS_CACHE=.cache ./bin/tts-server.exe
```
```bash
curl http://127.0.0.1:18080/healthz
curl -o hello.wav -H 'Content-Type: application/json' \
-d '{"text":"您好,现在时间是上午九点整。","speed":0.9}' http://127.0.0.1:18080/tts
```
Linux 原生运行同理(`go build` + `LD_LIBRARY_PATH` 指向 linux 模块的 `lib/x86_64-unknown-linux-gnu`)。
单元测试(不需要模型与 cgo):`go test ./internal/...`。
## 交叉编译 Linux 二进制(Windows + zig)
生产节点没有 Go 工具链,二进制在开发机交叉编译。需 `zig` 在 PATH 中(`zig cc` 提供 glibc 2.28 交叉工具链,产物可跑在 Debian 12 / Ubuntu 22.04 及以上):
```bash
cd TtsSpeaker/server
rm -rf dist && mkdir -p dist/lib
CGO_ENABLED=1 GOOS=linux GOARCH=amd64 CC="zig cc -target x86_64-linux-gnu.2.28" \
go build -trimpath -buildvcs=false -ldflags='-s -w' -o dist/tts-server .
L=$(go env GOMODCACHE | tr '\\' '/')/github.com/k2-fsa/sherpa-onnx-go-linux/v2@v2.0.1/lib/x86_64-unknown-linux-gnu
cp "$L"/libonnxruntime.so "$L"/libsherpa-onnx-c-api.so "$L"/libsherpa-onnx-cxx-api.so dist/lib/
tar -czf dist/tts-server-linux-amd64.tgz -C dist tts-server lib
```
产物 `dist/tts-server` 的 glibc 依赖上限为 2.2.5,`dist/lib/` 即 sherpa-onnx 2.0.1 的 Linux 运行库。
## Docker 镜像与 k3s 部署
服务器无法访问 Docker Hub 且未装 Go(同 `youlai-boot-ttstd` 的约束),镜像在节点上用预编译产物构建(`Dockerfile.runtime`,基础镜像 `debian:bookworm-slim`):
```bash
cd TtsSpeaker/server
# 1. 上传产物、Dockerfile 与语音包
pscp -P 22 dist/tts-server-linux-amd64.tgz Dockerfile.runtime \
root@175.178.213.60:/opt/tts-server/
# 2. 节点解包并构建镜像(tag 与 deploy.yaml 保持一致)
plink -ssh root@175.178.213.60 "cd /opt/tts-server && rm -rf dist && mkdir dist && \
tar xzf tts-server-linux-amd64.tgz -C dist && chmod 755 dist/tts-server && \
docker build -q -f Dockerfile.runtime -t docker.io/library/tts-server:<tag> dist"
# 3. 导入 k3s containerd
plink -ssh root@175.178.213.60 \
"docker save docker.io/library/tts-server:<tag> | k3s ctr -n k8s.io images import -"
```
若构建机有 Docker 且能访问镜像源,也可以用仓库根目录的多阶段 `Dockerfile` 直接构建(`docker buildx build --platform linux/amd64`)。
上传语音包并核对哈希(哈希记录见 `models/README.md`,模型文件不入 git):
```bash
plink -ssh root@175.178.213.60 "mkdir -p /opt/tts/voices"
pscp -P 22 -r ../models/voices/* root@175.178.213.60:/opt/tts/voices/
plink -ssh root@175.178.213.60 \
"sha256sum /opt/tts/voices/vits-piper-zh_CN-chaowen-medium/zh_CN-chaowen-medium.onnx"
```
部署(改镜像 tag 后先 `kubectl apply` 清单,再滚动重启):
```bash
pscp -P 22 deploy.yaml root@175.178.213.60:/opt/tts-server/deploy.yaml
plink -ssh root@175.178.213.60 "kubectl apply -f /opt/tts-server/deploy.yaml && \
kubectl -n youlai set image deploy/tts-server tts-server=docker.io/library/tts-server:<tag> && \
kubectl -n youlai rollout restart deploy/tts-server && \
kubectl -n youlai rollout status deploy/tts-server --timeout=180s"
curl -s https://tts.ttstd.com/healthz
```
NodePort 为 **30810**(`youlai-boot` 占用 30800),冲突时改 `deploy.yaml`。公网经 nginx `tts.ttstd.com` 反代到 `127.0.0.1:30810`:把 `nginx-tts.ttstd.conf` 放到 `/etc/nginx/sites-available/zz-tts-ttstd.conf` 并软链到 `sites-enabled/`。证书已于 2026-11-23 用 `certbot certonly --webroot -w /var/www/certbot -d tts.ttstd.com` 签发(自动续期),配置直接指向 `/etc/letsencrypt/live/tts.ttstd.com/`;新节点按同样命令签发。腾讯云安全组不放行 30810,公网只走 443 反代。服务本身无鉴权,对外开放前需自行加访问控制。
## 固定文案预生成
```bash
while IFS= read -r line; do
jq -Rn --arg t "$line" '{text:$t,speed:0.9}' \
| curl -s -o /dev/null -H 'Content-Type: application/json' --data-binary @- \
https://tts.ttstd.com/tts
done < phrases.txt
```
生成后相同请求直接命中缓存(`X-Tts-Cache: hit`)。
## 与设备端一致性
- 同一 sherpa-onnx 2.0.1、同一语音包版本(`manifest.json` 的 `version` 强制两端一致)。
- 同一推理配置:VITS + `ruleFsts`(phone/date/number)、`maxNumSentences=1`、`silenceScale=0.2`、generation `silenceScale=0`、`numSteps=5`、`numThreads=2`。
- 同一变调算法(`internal/tts/pitch.go` 逐行移植 `PitchShifter.java`,常数 1024/512/512/128 不变)。
- 同一 PCM 转换规则(clamp 到 [-1,1]、乘 32767、四舍五入)。
- 设备端若使用 int8 量化模型,需与服务器模型做 AB 试听,主观一致后才能上线。
## 本地验证数据(Windows 开发机,chaowen medium)
| 项 | 实测 |
| --- | --- |
| 冷启动(加载默认包) | 1.2–1.7s |
| 热合成(17 字,speed 0.9) | 327ms,RTF 0.08,音频 3.88s |
| 热合成(36 字含金额/日期,speed 0.9) | 617ms,RTF 0.07,音频 8.83s |
| 内存占用(常驻单包) | ≈205–290MB |
| 采样率 / 声道 | 22050Hz / 单声道 16-bit |
| 语速 0.5 / 1.0 / 2.0 | 6.81s / 3.83s / 2.44s(同句) |
| 音调 1.2 | 时长 3.84s(与 1.0 基本一致),未出现 NaN/静音 |
| 文本前端 | 上述文本 OOV 0 条,静音占比约 10–12% |
## 生产 k3s 节点实测(2026-11-23,chaowen medium)
| 项 | 实测 |
| --- | --- |
| 冷启动(预加载默认包) | 1.8–3.2s |
| 热合成(14 字,speed 0.9) | 683ms,RTF 0.22,音频 3.07s |
| 热合成(53 字含手机号/金额/日期,speed 0.9) | 1.88s,RTF 0.17,音频 11.24s |
| 缓存命中 | 2.8ms |
| 容器内存(cgroup memory.current) | ≈226MB |
| NodePort 30810 内网访问 | `/healthz` 200;公网 30810 被安全组拦截,需加规则或走 nginx 反代 |
## 已知限制
- 仅 WAV;MP3 待后续需要时再加编码依赖。
- 无鉴权,按内网服务使用。
- 缓存不做淘汰,随固定文案数量增长;可定期清理 `/cache`。
- 同时只常驻一个语音包,切换语音需重新加载模型(秒级)。
- 请求排队上限由 `TTS_QUEUE` 控制;默认 1 路合成 + 2 路排队。
+90
View File
@@ -0,0 +1,90 @@
apiVersion: apps/v1
kind: Deployment
metadata:
name: tts-server
namespace: youlai
spec:
replicas: 1
strategy:
type: Recreate
selector:
matchLabels:
app: tts-server
template:
metadata:
labels:
app: tts-server
spec:
securityContext:
runAsNonRoot: true
runAsUser: 65534
fsGroup: 65534
containers:
- name: tts-server
image: docker.io/library/tts-server:dev-1
imagePullPolicy: IfNotPresent
ports:
- containerPort: 8080
env:
- name: TTS_VOICES
value: /voices
- name: TTS_CACHE
value: /cache
- name: TTS_THREADS
value: "2"
- name: TTS_QUEUE
value: "2"
- name: TTS_MAX_TEXT
value: "300"
- name: GOMEMLIMIT
value: 256MiB
resources:
requests:
cpu: 200m
memory: 256Mi
limits:
cpu: 1500m
memory: 768Mi
readinessProbe:
httpGet:
path: /healthz
port: 8080
initialDelaySeconds: 5
periodSeconds: 5
failureThreshold: 12
livenessProbe:
httpGet:
path: /healthz
port: 8080
initialDelaySeconds: 30
periodSeconds: 10
failureThreshold: 3
volumeMounts:
- name: voices
mountPath: /voices
readOnly: true
- name: cache
mountPath: /cache
volumes:
- name: voices
hostPath:
path: /opt/tts/voices
type: Directory
- name: cache
emptyDir:
sizeLimit: 1Gi
---
apiVersion: v1
kind: Service
metadata:
name: tts-server
namespace: youlai
spec:
type: NodePort
selector:
app: tts-server
ports:
- name: http
port: 8080
targetPort: 8080
nodePort: 30810
+107
View File
@@ -0,0 +1,107 @@
package main
import (
"errors"
"fmt"
"log"
"sync"
"time"
sherpa "github.com/k2-fsa/sherpa-onnx-go/v2/sherpa_onnx"
"tts-server/internal/tts"
)
// engine keeps at most one voice model loaded (the 512MB server cannot hold
// two), serializes synthesis and reloads only when the requested voice changes.
type engine struct {
mu sync.Mutex
threads int
tts *sherpa.OfflineTts
loaded string
}
func newEngine(threads int) *engine {
return &engine{threads: threads}
}
func (e *engine) preload(pack *tts.VoicePack) error {
e.mu.Lock()
defer e.mu.Unlock()
_, err := e.obtain(pack)
return err
}
func (e *engine) synthesize(pack *tts.VoicePack, text string, speed, pitch float32) ([]float32, int, error) {
e.mu.Lock()
defer e.mu.Unlock()
model, err := e.obtain(pack)
if err != nil {
return nil, 0, err
}
// Same generation config as Synthesizer.java: silenceScale 0, sid, speed,
// numSteps 5.
cfg := &sherpa.GenerationConfig{SilenceScale: 0, Speed: speed, Sid: pack.SpeakerID, NumSteps: 5}
audio := model.GenerateWithConfig(text, cfg, nil)
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)
}
return samples, audio.SampleRate, nil
}
func (e *engine) close() {
e.mu.Lock()
defer e.mu.Unlock()
e.release()
}
func (e *engine) obtain(pack *tts.VoicePack) (*sherpa.OfflineTts, error) {
if e.tts != nil && e.loaded == pack.Name {
return e.tts, nil
}
e.release()
cfg := &sherpa.OfflineTtsConfig{
Model: sherpa.OfflineTtsModelConfig{
Vits: sherpa.OfflineTtsVitsModelConfig{
Model: pack.ModelPath,
Lexicon: pack.LexiconPath,
Tokens: pack.TokensPath,
DataDir: pack.DataDir,
},
NumThreads: e.threads,
Debug: 0,
Provider: "cpu",
},
RuleFsts: pack.RuleFsts,
RuleFars: "",
MaxNumSentences: 1,
SilenceScale: 0.2,
}
start := time.Now()
model := sherpa.NewOfflineTts(cfg)
if model == nil {
return nil, fmt.Errorf("load voice %q failed", pack.Name)
}
e.tts = model
e.loaded = pack.Name
log.Printf("voice %s loaded: sample rate %d, took %s",
pack.Name, model.SampleRate(), time.Since(start).Round(time.Millisecond))
return model, nil
}
func (e *engine) release() {
if e.tts != nil {
sherpa.DeleteOfflineTts(e.tts)
e.tts = nil
e.loaded = ""
}
}
+11
View File
@@ -0,0 +1,11 @@
module tts-server
go 1.24
require github.com/k2-fsa/sherpa-onnx-go/v2 v2.0.1
require (
github.com/k2-fsa/sherpa-onnx-go-linux/v2 v2.0.1 // indirect
github.com/k2-fsa/sherpa-onnx-go-macos/v2 v2.0.1 // indirect
github.com/k2-fsa/sherpa-onnx-go-windows/v2 v2.0.1 // indirect
)
+8
View File
@@ -0,0 +1,8 @@
github.com/k2-fsa/sherpa-onnx-go-linux/v2 v2.0.1 h1:lK8mB5JfJ9HnjXb8W05GfIC/7C3twvRfQzxQOobRxic=
github.com/k2-fsa/sherpa-onnx-go-linux/v2 v2.0.1/go.mod h1:zfoI5ANNAiKCZFyWC9NfZATijClmbT1UqZ+ycvcMKCY=
github.com/k2-fsa/sherpa-onnx-go-macos/v2 v2.0.1 h1:9lFAW58pLnK60K2eKlW1u8ERDYw3wbT9FoJX77XTX3s=
github.com/k2-fsa/sherpa-onnx-go-macos/v2 v2.0.1/go.mod h1:RnFSuUrQNs+AlqEV7WiO0UIBZ1L4Ka2X5QxW8A0wCbY=
github.com/k2-fsa/sherpa-onnx-go-windows/v2 v2.0.1 h1:eGSMUAEedupoBuAIOi75tJ3/25fwEQarbRS75qWHNEs=
github.com/k2-fsa/sherpa-onnx-go-windows/v2 v2.0.1/go.mod h1:4T8q8/N4uaTxf7acMYaJrafG69HJRdlDRDstAODHz2Q=
github.com/k2-fsa/sherpa-onnx-go/v2 v2.0.1 h1:mnVi3YOMc49PfZ7nJ7I/1WGevmseMjAQdtD/7MsRwb4=
github.com/k2-fsa/sherpa-onnx-go/v2 v2.0.1/go.mod h1:MDprYfx0mHgBp2rAdLIfafqdDD+ugPWbR1lYsOKxBfs=
+55
View File
@@ -0,0 +1,55 @@
package tts
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"math"
"os"
"path/filepath"
)
type Cache struct {
dir string
}
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
}
// 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",
version, voice, math.Float32bits(speed), math.Float32bits(pitch), text)))
return hex.EncodeToString(sum[:])
}
func (c *Cache) Get(key string) ([]byte, bool) {
data, err := os.ReadFile(filepath.Join(c.dir, key+".wav"))
if err != nil {
return nil, false
}
return data, true
}
func (c *Cache) Put(key string, data []byte) error {
tmp, err := os.CreateTemp(c.dir, key[:8]+"-*.tmp")
if err != nil {
return err
}
name := tmp.Name()
if _, err := tmp.Write(data); err != nil {
tmp.Close()
os.Remove(name)
return err
}
if err := tmp.Close(); err != nil {
os.Remove(name)
return err
}
return os.Rename(name, filepath.Join(c.dir, key+".wav"))
}
+27
View File
@@ -0,0 +1,27 @@
package tts
import "testing"
func TestCacheRoundTrip(t *testing.T) {
c, err := NewCache(t.TempDir())
if err != nil {
t.Fatal(err)
}
key := c.Key("dev-1", "a", 1, 1.2, "你好")
if other := c.Key("dev-1", "a", 1, 1.2, "你好 "); other == key {
t.Fatal("different text produced the same key")
}
if other := c.Key("dev-2", "a", 1, 1.2, "你好"); other == key {
t.Fatal("version must be part of the key")
}
if _, ok := c.Get(key); ok {
t.Fatal("unexpected cache hit")
}
if err := c.Put(key, []byte("wav")); err != nil {
t.Fatal(err)
}
got, ok := c.Get(key)
if !ok || string(got) != "wav" {
t.Fatalf("cache get: %q %v", got, ok)
}
}
+109
View File
@@ -0,0 +1,109 @@
package tts
import "math"
// Pitch shifting without changing duration: time-stretch by the pitch factor,
// then resample by it. This is a line-for-line port of PitchShifter.java in
// android-engine; both ends must keep the same algorithm and parameters so the
// same text produces subjectively identical audio.
const (
grain = 1024
overlap = 512
hops = grain - overlap
search = 128
)
func PitchShiftNeeded(pitch float32) bool {
return math.Abs(float64(pitch-1)) >= 0.01
}
func ShiftPitch(samples []float32, factor float32) []float32 {
if len(samples) == 0 || !PitchShiftNeeded(factor) {
return samples
}
stretched := timeStretch(samples, factor)
return resample(stretched, factor)
}
func timeStretch(in []float32, factor float32) []float32 {
hopA := roundInt(float32(hops) / factor)
if hopA < 1 {
hopA = 1
}
window := hann(grain)
expected := roundInt(float32(len(in)) * factor)
if expected < grain {
expected = grain
}
out := make([]float32, expected+grain)
inPos, outPos := 0, 0
for inPos+grain <= len(in) {
best := inPos
if outPos > 0 {
from := inPos - search
if from < 0 {
from = 0
}
to := inPos + search
if to > len(in)-grain {
to = len(in) - grain
}
bestCorr := -1.0
for cand := from; cand <= to; cand += 4 {
var corr float64
for i := 0; i < overlap; i++ {
corr += float64(in[cand+i]) * float64(out[outPos+i])
}
if corr > bestCorr {
bestCorr = corr
best = cand
}
}
}
for i := 0; i < grain; i++ {
out[outPos+i] += in[best+i] * window[i]
}
inPos += hopA
outPos += hops
}
result := make([]float32, expected)
copy(result, out[:min(expected, len(out))])
return result
}
func resample(in []float32, factor float32) []float32 {
outLen := roundInt(float32(len(in)) / factor)
if outLen < 1 {
outLen = 1
}
out := make([]float32, outLen)
for i := 0; i < outLen; i++ {
pos := float64(i) * float64(factor)
i0 := int(pos)
if i0 >= len(in) {
break
}
i1 := i0 + 1
if i1 > len(in)-1 {
i1 = len(in) - 1
}
frac := pos - float64(i0)
out[i] = float32(float64(in[i0])*(1-frac) + float64(in[i1])*frac)
}
return out
}
func hann(size int) []float32 {
w := make([]float32, size)
for i := 0; i < size; i++ {
w[i] = float32(0.5 - 0.5*math.Cos(2*math.Pi*float64(i)/float64(size-1)))
}
return w
}
// roundInt matches Java Math.round(float): floor(x + 0.5).
func roundInt(x float32) int {
return int(math.Floor(float64(x) + 0.5))
}
+56
View File
@@ -0,0 +1,56 @@
package tts
import (
"math"
"testing"
)
func TestShiftPitchIdentity(t *testing.T) {
in := []float32{0.1, -0.2, 0.3}
out := ShiftPitch(in, 1.0)
if &out[0] != &in[0] {
t.Fatal("factor 1.0 should return the input slice unchanged")
}
}
func TestShiftPitchKeepsDuration(t *testing.T) {
const rate = 22050
in := make([]float32, rate)
for i := range in {
in[i] = float32(0.5 * math.Sin(2*math.Pi*220*float64(i)/rate))
}
for _, factor := range []float32{0.5, 1.2, 2.0} {
out := ShiftPitch(in, factor)
if len(out) == 0 {
t.Fatalf("factor %v: empty output", factor)
}
if diff := math.Abs(float64(len(out))/float64(len(in)) - 1); diff > 0.05 {
t.Fatalf("factor %v: duration changed by %.1f%% (%d vs %d samples)",
factor, diff*100, len(out), len(in))
}
var peak float32
for _, v := range out {
if math.IsNaN(float64(v)) || math.IsInf(float64(v), 0) {
t.Fatalf("factor %v: non-finite sample", factor)
}
if v < 0 {
v = -v
}
if v > peak {
peak = v
}
}
if peak < 0.2 {
t.Fatalf("factor %v: signal collapsed (peak %.3f)", factor, peak)
}
}
}
func TestShiftPitchSilence(t *testing.T) {
out := ShiftPitch(make([]float32, 5000), 1.5)
for i, v := range out {
if v != 0 {
t.Fatalf("sample %d: got %v, want 0", i, v)
}
}
}
+181
View File
@@ -0,0 +1,181 @@
package tts
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
)
// Manifest mirrors android-engine voices.example/manifest.json so a single
// file configures both the Android engine and this server.
type Manifest struct {
Version string `json:"version"`
Default string `json:"default"`
Voices []VoiceEntry `json:"voices"`
}
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"`
}
type VoicePack struct {
Name string
Locale string
Label string
SpeakerID int
Quality int
ModelPath string
LexiconPath string
TokensPath string
DataDir string
RuleFsts string
}
type Repo struct {
Version string
Default string
Packs []*VoicePack
byName map[string]*VoicePack
}
func LoadRepo(root string) (*Repo, error) {
raw, err := os.ReadFile(filepath.Join(root, "manifest.json"))
if err != nil {
return nil, fmt.Errorf("read manifest: %w", err)
}
var m Manifest
if err := json.Unmarshal(raw, &m); err != nil {
return nil, fmt.Errorf("parse manifest: %w", err)
}
if len(m.Voices) == 0 {
return nil, fmt.Errorf("manifest has no voices")
}
repo := &Repo{Version: m.Version, Default: m.Default, byName: make(map[string]*VoicePack, len(m.Voices))}
for _, e := range m.Voices {
if e.Name == "" {
return nil, fmt.Errorf("voice entry without name")
}
if _, dup := repo.byName[e.Name]; dup {
return nil, fmt.Errorf("duplicate voice %q", e.Name)
}
base := root
if e.Dir != "" {
base = filepath.Join(root, e.Dir)
}
tokens := e.Tokens
if tokens == "" {
tokens = "tokens.txt"
}
rules := make([]string, 0, len(e.RuleFsts))
for _, f := range e.RuleFsts {
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, ","),
}
if e.Lexicon != "" {
pack.LexiconPath = filepath.Join(base, e.Lexicon)
}
if e.DataDir != "" {
pack.DataDir = filepath.Join(base, e.DataDir)
}
if pack.Label == "" {
pack.Label = pack.Name
}
if err := pack.validate(); err != nil {
return nil, err
}
repo.Packs = append(repo.Packs, pack)
repo.byName[pack.Name] = pack
}
if _, ok := repo.byName[repo.Default]; !ok {
repo.Default = repo.Packs[0].Name
}
return repo, nil
}
func (p *VoicePack) validate() error {
required := []string{p.ModelPath, p.TokensPath}
if p.LexiconPath != "" {
required = append(required, p.LexiconPath)
}
if p.DataDir != "" {
required = append(required, p.DataDir)
}
if p.RuleFsts != "" {
required = append(required, strings.Split(p.RuleFsts, ",")...)
}
for _, path := range required {
if _, err := os.Stat(path); err != nil {
return fmt.Errorf("voice %q: %w", p.Name, err)
}
}
return nil
}
func (r *Repo) DefaultPack() *VoicePack {
return r.byName[r.Default]
}
// Resolve accepts a voice name or a BCP-47 language tag and falls back to the
// default pack, matching VoiceRepository.resolve on the Android side.
func (r *Repo) Resolve(requested string) *VoicePack {
requested = strings.TrimSpace(requested)
if requested == "" {
return r.DefaultPack()
}
if p, ok := r.byName[requested]; ok {
return p
}
want := normalizeLanguage(requested)
if want != "" {
for _, p := range r.Packs {
if languageOf(p.Locale) == want {
return p
}
}
}
return r.DefaultPack()
}
func languageOf(locale string) string {
tag := strings.ToLower(strings.ReplaceAll(locale, "_", "-"))
if i := strings.IndexByte(tag, '-'); i >= 0 {
tag = tag[:i]
}
return normalizeLanguage(tag)
}
func normalizeLanguage(tag string) string {
tag = strings.ToLower(strings.ReplaceAll(strings.TrimSpace(tag), "_", "-"))
if i := strings.IndexByte(tag, '-'); i >= 0 {
tag = tag[:i]
}
switch tag {
case "cmn", "zho", "zh":
return "zh"
default:
return tag
}
}
+117
View File
@@ -0,0 +1,117 @@
package tts
import (
"os"
"path/filepath"
"testing"
)
func writeVoiceFiles(t *testing.T, root, dir string) {
t.Helper()
files := map[string]string{
"model.onnx": "model",
"tokens.txt": "tokens",
"lexicon.txt": "lexicon",
"phone.fst": "fst",
}
for name, content := range files {
path := filepath.Join(root, dir, name)
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
t.Fatal(err)
}
}
}
func writeManifest(t *testing.T, root, content string) {
t.Helper()
if err := os.WriteFile(filepath.Join(root, "manifest.json"), []byte(content), 0o644); err != nil {
t.Fatal(err)
}
}
const testManifest = `{
"version": "test-1",
"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"]},
{"name": "b", "locale": "yue-HK", "label": "乙", "speakerId": 1, "quality": 300,
"dir": "pack-b", "model": "model.onnx", "lexicon": "lexicon.txt", "ruleFsts": ["phone.fst"]}
]
}`
func TestLoadRepoAndResolve(t *testing.T) {
root := t.TempDir()
writeVoiceFiles(t, root, "pack-a")
writeVoiceFiles(t, root, "pack-b")
writeManifest(t, root, testManifest)
repo, err := LoadRepo(root)
if err != nil {
t.Fatal(err)
}
if repo.Version != "test-1" || repo.Default != "a" || len(repo.Packs) != 2 {
t.Fatalf("unexpected repo: %+v", repo)
}
cases := map[string]string{
"": "a",
"a": "a",
"b": "b",
"zh-CN": "a",
"cmn": "a",
"yue-HK": "b",
"yue": "b",
"nope": "a",
}
for requested, want := range cases {
if got := repo.Resolve(requested).Name; got != want {
t.Fatalf("Resolve(%q) = %q, want %q", requested, got, want)
}
}
if repo.Packs[0].RuleFsts != filepath.Join(root, "pack-a", "phone.fst") {
t.Fatalf("rule fst path %q", repo.Packs[0].RuleFsts)
}
}
func TestLoadRepoMissingModel(t *testing.T) {
root := t.TempDir()
writeVoiceFiles(t, root, "pack-a")
writeManifest(t, root, testManifest)
if _, err := LoadRepo(root); err == nil {
t.Fatal("expected error for missing pack-b files")
}
}
func TestLoadRepoDuplicateName(t *testing.T) {
root := t.TempDir()
writeVoiceFiles(t, root, "pack-a")
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"}
]
}`)
if _, err := LoadRepo(root); err == nil {
t.Fatal("expected duplicate name error")
}
}
func TestLoadRepoDefaultFallsBackToFirst(t *testing.T) {
root := t.TempDir()
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"}]
}`)
repo, err := LoadRepo(root)
if err != nil {
t.Fatal(err)
}
if repo.Default != "a" {
t.Fatalf("default %q, want a", repo.Default)
}
}
+47
View File
@@ -0,0 +1,47 @@
package tts
import (
"encoding/binary"
"math"
)
const wavHeaderSize = 44
// EncodeWAV writes signed 16-bit little-endian mono PCM. Sample conversion
// matches PcmWriter.java: clamp to [-1, 1], scale by 32767, round half up.
func EncodeWAV(samples []float32, sampleRate int) []byte {
dataSize := len(samples) * 2
buf := make([]byte, wavHeaderSize+dataSize)
copy(buf[0:], "RIFF")
binary.LittleEndian.PutUint32(buf[4:], uint32(36+dataSize))
copy(buf[8:], "WAVE")
copy(buf[12:], "fmt ")
binary.LittleEndian.PutUint32(buf[16:], 16)
binary.LittleEndian.PutUint16(buf[20:], 1)
binary.LittleEndian.PutUint16(buf[22:], 1)
binary.LittleEndian.PutUint32(buf[24:], uint32(sampleRate))
binary.LittleEndian.PutUint32(buf[28:], uint32(sampleRate*2))
binary.LittleEndian.PutUint16(buf[32:], 2)
binary.LittleEndian.PutUint16(buf[34:], 16)
copy(buf[36:], "data")
binary.LittleEndian.PutUint32(buf[40:], uint32(dataSize))
for i, v := range samples {
if v > 1 {
v = 1
} else if v < -1 {
v = -1
}
s := int32(math.Floor(float64(v*32767) + 0.5))
binary.LittleEndian.PutUint16(buf[wavHeaderSize+i*2:], uint16(s))
}
return buf
}
func WAVSampleRate(wav []byte) int {
if len(wav) < wavHeaderSize {
return 0
}
return int(binary.LittleEndian.Uint32(wav[24:28]))
}
+36
View File
@@ -0,0 +1,36 @@
package tts
import (
"encoding/binary"
"testing"
)
func TestEncodeWAV(t *testing.T) {
wav := EncodeWAV([]float32{0, 1, -1, 2, -2, 0.5}, 22050)
if len(wav) != wavHeaderSize+12 {
t.Fatalf("length %d, want %d", len(wav), wavHeaderSize+12)
}
if string(wav[0:4]) != "RIFF" || string(wav[8:12]) != "WAVE" ||
string(wav[12:16]) != "fmt " || string(wav[36:40]) != "data" {
t.Fatalf("bad chunk tags: %q %q %q %q", wav[0:4], wav[8:12], wav[12:16], wav[36:40])
}
if rate := WAVSampleRate(wav); rate != 22050 {
t.Fatalf("sample rate %d, want 22050", rate)
}
if bits := binary.LittleEndian.Uint16(wav[34:36]); bits != 16 {
t.Fatalf("bits per sample %d, want 16", bits)
}
want := []int16{0, 32767, -32767, 32767, -32767, 16384}
for i, w := range want {
got := int16(binary.LittleEndian.Uint16(wav[wavHeaderSize+i*2:]))
if got != w {
t.Fatalf("sample %d: got %d, want %d", i, got, w)
}
}
}
func TestWAVSampleRateShortInput(t *testing.T) {
if got := WAVSampleRate([]byte{1, 2, 3}); got != 0 {
t.Fatalf("got %d, want 0", got)
}
}
+287
View File
@@ -0,0 +1,287 @@
package main
import (
"context"
"encoding/json"
"errors"
"log"
"net/http"
"os"
"os/signal"
"strconv"
"strings"
"syscall"
"time"
"unicode/utf8"
sherpa "github.com/k2-fsa/sherpa-onnx-go/v2/sherpa_onnx"
"tts-server/internal/tts"
)
const (
minRate = 0.5
maxRate = 2.0
bodyLimit = 64 << 10
maxQueue = 8
maxThreads = 8
)
type settings struct {
listen string
voicesDir string
cacheDir string
threads int
queue int
maxRunes int
preload bool
}
func main() {
log.SetFlags(log.LstdFlags | log.Lmicroseconds)
cfg := loadSettings()
repo, err := tts.LoadRepo(cfg.voicesDir)
if err != nil {
log.Fatalf("voices: %v", err)
}
log.Printf("manifest %q: %d voice(s), default %q", repo.Version, len(repo.Packs), repo.Default)
cache, err := tts.NewCache(cfg.cacheDir)
if err != nil {
log.Fatalf("cache: %v", err)
}
eng := newEngine(cfg.threads)
if cfg.preload {
start := time.Now()
if err := eng.preload(repo.DefaultPack()); err != nil {
log.Fatalf("preload %q: %v", repo.Default, err)
}
log.Printf("preloaded %q in %s", repo.Default, time.Since(start).Round(time.Millisecond))
}
s := &server{
cfg: cfg,
repo: repo,
cache: cache,
eng: eng,
queue: make(chan struct{}, cfg.queue+1),
}
srv := &http.Server{
Addr: cfg.listen,
Handler: s.routes(),
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 15 * time.Second,
WriteTimeout: 120 * time.Second,
IdleTimeout: 60 * time.Second,
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
go func() {
log.Printf("listening on %s", cfg.listen)
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatalf("http: %v", err)
}
}()
<-ctx.Done()
stopCtx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
_ = srv.Shutdown(stopCtx)
eng.close()
log.Printf("stopped")
}
type server struct {
cfg settings
repo *tts.Repo
cache *tts.Cache
eng *engine
queue chan struct{}
}
func (s *server) routes() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /healthz", s.handleHealth)
mux.HandleFunc("GET /voices", s.handleVoices)
mux.HandleFunc("POST /tts", s.handleTTS)
return mux
}
func (s *server) handleHealth(w http.ResponseWriter, r *http.Request) {
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),
})
}
func (s *server) handleVoices(w http.ResponseWriter, r *http.Request) {
type voiceInfo struct {
Name string `json:"name"`
Locale string `json:"locale"`
Label string `json:"label"`
SpeakerID int `json:"speakerId"`
Quality int `json:"quality"`
}
voices := make([]voiceInfo, 0, len(s.repo.Packs))
for _, p := range s.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,
"voices": voices,
})
}
func (s *server) handleTTS(w http.ResponseWriter, r *http.Request) {
var req struct {
Text string `json:"text"`
Voice string `json:"voice"`
Speed *float64 `json:"speed"`
Pitch *float64 `json:"pitch"`
}
r.Body = http.MaxBytesReader(w, r.Body, bodyLimit)
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON body")
return
}
text := strings.TrimSpace(req.Text)
if text == "" {
writeError(w, http.StatusBadRequest, "text is required")
return
}
if n := utf8.RuneCountInString(text); n > s.cfg.maxRunes {
writeError(w, http.StatusBadRequest, "text exceeds "+strconv.Itoa(s.cfg.maxRunes)+" characters")
return
}
speed := 1.0
if req.Speed != nil {
speed = clamp(*req.Speed)
}
pitch := 1.0
if req.Pitch != nil {
pitch = clamp(*req.Pitch)
}
fSpeed, fPitch := float32(speed), float32(pitch)
pack := s.repo.Resolve(req.Voice)
key := s.cache.Key(s.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))
return
}
select {
case s.queue <- struct{}{}:
defer func() { <-s.queue }()
default:
w.Header().Set("Retry-After", "1")
writeError(w, http.StatusTooManyRequests, "busy, retry later")
return
}
start := time.Now()
samples, rate, err := s.eng.synthesize(pack, text, fSpeed, fPitch)
if err != nil {
log.Printf("tts failed voice=%s: %v", pack.Name, err)
writeError(w, http.StatusInternalServerError, "synthesis failed")
return
}
elapsed := time.Since(start)
data := tts.EncodeWAV(samples, rate)
if err := s.cache.Put(key, data); err != nil {
log.Printf("cache write: %v", err)
}
setAudioHeaders(w, pack, s.repo.Version, rate)
w.Header().Set("X-Tts-Cache", "miss")
w.Write(data)
audioSeconds := float64(len(samples)) / float64(rate)
log.Printf("tts miss voice=%s runes=%d speed=%.2f pitch=%.2f audio=%.2fs synth=%s rtf=%.2f",
pack.Name, utf8.RuneCountInString(text), speed, pitch, audioSeconds,
elapsed.Round(time.Millisecond), elapsed.Seconds()/audioSeconds)
}
func setAudioHeaders(w http.ResponseWriter, pack *tts.VoicePack, version string, sampleRate int) {
w.Header().Set("Content-Type", "audio/wav")
w.Header().Set("X-Tts-Voice", pack.Name)
w.Header().Set("X-Tts-Voice-Version", version)
w.Header().Set("X-Tts-Sample-Rate", strconv.Itoa(sampleRate))
}
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",
}
if cfg.threads < 1 || cfg.threads > maxThreads {
log.Fatalf("TTS_THREADS must be 1..%d", maxThreads)
}
if cfg.queue < 0 || cfg.queue > maxQueue {
log.Fatalf("TTS_QUEUE must be 0..%d", maxQueue)
}
if cfg.maxRunes < 1 || cfg.maxRunes > 2000 {
log.Fatalf("TTS_MAX_TEXT must be 1..2000")
}
return cfg
}
func env(key, def string) string {
if v := os.Getenv(key); v != "" {
return v
}
return def
}
func envInt(key string, def int) int {
v := os.Getenv(key)
if v == "" {
return def
}
n, err := strconv.Atoi(v)
if err != nil {
log.Fatalf("%s must be an integer: %v", key, err)
}
return n
}
func clamp(v float64) float64 {
if v < minRate {
return minRate
}
if v > maxRate {
return maxRate
}
return v
}
func writeJSON(w http.ResponseWriter, status int, body any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(body)
}
func writeError(w http.ResponseWriter, status int, msg string) {
writeJSON(w, status, map[string]string{"error": msg})
}
+44
View File
@@ -0,0 +1,44 @@
# TTS 在线合成(k3s NodePort 30810)反向代理
# 证书由 certbot 签发(自动续期):
# certbot certonly --webroot -w /var/www/certbot -d tts.ttstd.com
server {
listen 80;
listen [::]:80;
server_name tts.ttstd.com;
location /.well-known/acme-challenge/ {
root /var/www/certbot;
}
location / {
return 301 https://$host$request_uri;
}
}
server {
listen 443 ssl;
server_name tts.ttstd.com;
ssl_certificate /etc/letsencrypt/live/tts.ttstd.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/tts.ttstd.com/privkey.pem;
ssl_session_timeout 5m;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
client_max_body_size 1m;
# 服务本身无鉴权,对外开放前需自行加访问控制
location / {
proxy_pass http://127.0.0.1:30810;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_connect_timeout 10s;
proxy_read_timeout 30s;
proxy_send_timeout 30s;
proxy_buffering off;
}
}