feat: 增加在线语音 SDK 和音色管理后台,完善引擎适配

This commit is contained in:
tongtong committed 2026-11-23 19:02:44 +08:00
1 parent 1856de97bc
commit a532ba4e0f
71 files changed
+3189 -472

No files matched your search

+4 -3
View File
@@ -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'
}
+3 -1
View File
@@ -1,2 +1,4 @@
-keep class com.k2fsa.sherpa.onnx.** { *; }
-keepclassmembers class kotlin.jvm.functions.** { *; }
-keepclassmembers class kotlin.jvm.functions.** { *; }
# sherpa JNI resolves this exact typed signature (not Function1.invoke(Object)).
-keep class com.ttstd.tts.engine.SynthesisAudioCallback { *; }
@@ -1,16 +1,19 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="false"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/EngineTheme">
<!-- Standard TTS clients must be able to bind directly on older ROMs.
BIND_TTS_SERVICE is not an Android platform permission. -->
<service
android:name=".TtsEngineService"
android:exported="true"
android:permission="android.permission.BIND_TTS_SERVICE">
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.TTS_SERVICE" />
<category android:name="android.intent.category.DEFAULT" />
@@ -20,6 +23,8 @@
android:resource="@xml/tts_engine" />
</service>
<activity android:name=".OnlineSettingsActivity" android:exported="true"
android:label="在线语音合成" android:windowSoftInputMode="adjustResize" />
<activity
android:name=".SettingsActivity"
android:exported="true"
@@ -20,11 +20,15 @@ public class CheckVoiceDataActivity extends Activity {
for (VoicePack pack : VoiceRepository.get(this).all()) {
available.add(iso3(pack));
}
Log.i(TAG, "checkFor=" + getIntent().getStringExtra(TextToSpeech.Engine.EXTRA_CHECK_VOICE_DATA_FOR)
// The online Mandarin voice is available even without installed local model data.
if (!available.contains("zho-CHN")) available.add("zho-CHN");
Log.i(TAG, "checkFor=" + getIntent().getStringArrayListExtra(TextToSpeech.Engine.EXTRA_CHECK_VOICE_DATA_FOR)
+ " available=" + available);
Intent data = new Intent();
data.putStringArrayListExtra(TextToSpeech.Engine.EXTRA_AVAILABLE_VOICES, available);
setResult(RESULT_OK, data);
data.putStringArrayListExtra(TextToSpeech.Engine.EXTRA_UNAVAILABLE_VOICES, new ArrayList<>());
setResult(available.isEmpty() ? TextToSpeech.Engine.CHECK_VOICE_DATA_FAIL
: TextToSpeech.Engine.CHECK_VOICE_DATA_PASS, data);
finish();
}
@@ -0,0 +1,60 @@
package com.ttstd.tts.engine;
import android.app.Activity;
import android.os.Bundle;
import android.text.InputType;
import android.widget.*;
import java.net.URL;
/** Interactive settings only: never accept tokens via exported Intent extras. */
public class OnlineSettingsActivity extends Activity {
@Override public void onCreate(Bundle state) {
super.onCreate(state);
setTitle("在线语音合成");
ScrollView scroll=new ScrollView(this);
LinearLayout content=new LinearLayout(this);
content.setOrientation(LinearLayout.VERTICAL);
int padding=(int)(20*getResources().getDisplayMetrics().density);
content.setPadding(padding,padding,padding,padding);
scroll.addView(content);
setContentView(scroll);
if (android.os.Build.VERSION.SDK_INT >= 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(); }
});
}
}
@@ -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();
}
}
}
@@ -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());
}
}
@@ -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;
}
@@ -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;
}
@@ -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<Voice> voices = preview.getVoices();
if (voices != null) {
for (Voice voice : voices) {
@@ -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<float[], Integer> {
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(); }
}
@@ -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<float[]> 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<float[], Integer>() {
@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<float[]> 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;
}
}
}
@@ -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<Voice> onGetVoices() {
return voices.toVoices();
List<Voice> 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) {
@@ -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;
@@ -59,7 +59,7 @@ final class VoiceRepository {
return new File(context.getFilesDir(), "voices/" + USER_DIR);
}
void reload() {
synchronized void reload() {
LinkedHashMap<String, VoicePack> 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<String, VoicePack> 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<String> 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<String, VoicePack> 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<String, VoicePack> 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;
@@ -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(at<size) {
int n=in.read(data,at,size-at);
if(n<0) throw new EOFException("Truncated WAV header");
at+=n;
}
return data;
}
private static void skip(InputStream in,long count) throws IOException {
byte[] scratch=new byte[4096];
while(count>0) {
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); }
}
@@ -1,69 +1,69 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:fillViewport="true"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="24dp">
<TextView
android:layout_height="match_parent">
<LinearLayout android:id="@+id/settings_root"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/settings_voice"
android:textSize="18sp"
android:textStyle="bold" />
android:orientation="vertical"
android:padding="24dp">
<ScrollView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:layout_marginTop="12dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/settings_voice"
android:textSize="18sp"
android:textStyle="bold" />
<RadioGroup
android:id="@+id/voice_group"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</ScrollView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:orientation="horizontal">
<Button
android:id="@+id/btn_import"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/settings_import" />
android:layout_marginTop="12dp" />
<Button
android:id="@+id/btn_delete"
android:layout_width="wrap_content"
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:enabled="false"
android:text="@string/settings_delete" />
android:layout_marginTop="16dp"
android:orientation="vertical">
<Button
android:id="@+id/btn_preview"
android:layout_width="wrap_content"
<Button
android:id="@+id/btn_import"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/settings_import" />
<Button
android:id="@+id/btn_delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:enabled="false"
android:text="@string/settings_delete" />
<Button
android:id="@+id/btn_preview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text="@string/settings_preview" />
</LinearLayout>
<Button android:id="@+id/btn_online_settings" android:layout_width="match_parent"
android:layout_height="wrap_content" android:text="在线合成设置" />
<TextView
android:id="@+id/import_status"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:text="@string/settings_preview" />
</LinearLayout>
android:layout_marginTop="12dp"
android:textSize="14sp" />
<TextView
android:id="@+id/import_status"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:textSize="14sp" />
<TextView
android:id="@+id/voice_info"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:textSize="14sp" />
<TextView
android:id="@+id/voice_info"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:textSize="14sp" />
</LinearLayout>
</LinearLayout></ScrollView>
@@ -1,6 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="EngineTheme" parent="@android:style/Theme.DeviceDefault">
<item name="android:windowOptOutEdgeToEdgeEnforcement">true</item>
</style>
</resources>
@@ -0,0 +1,39 @@
package com.ttstd.tts.engine;
import android.speech.tts.SynthesisCallback;
import org.junit.Test;
import static org.junit.Assert.*;
public class PcmWriterTest {
static final class Sink implements SynthesisCallback {
int calls, bytes;
final int limit;
Sink(int limit) { this.limit = limit; }
public int audioAvailable(byte[] pcm, int offset, int length) {
assertTrue(length <= limit);
assertEquals(0, length % 2);
calls++;
bytes += length;
return 0;
}
public int getMaxBufferSize() { return limit; }
public int done() { return 0; }
public void error() {}
public void error(int code) {}
public boolean hasStarted() { return true; }
public boolean hasFinished() { return false; }
public int start(int rate, int format, int channels) { return 0; }
}
@Test public void respectsBufferCapAndCancellation() {
Sink sink = new Sink(64);
assertTrue(PcmWriter.write(sink, new float[1000], 22050, () -> false));
assertEquals(2000, sink.bytes);
assertTrue(sink.calls > 1);
Sink cancelled = new Sink(64);
assertFalse(PcmWriter.write(cancelled, new float[1000], 22050, () -> cancelled.calls > 0));
assertEquals(1, cancelled.calls);
}
@Test public void rejectsUnusableBuffer() {
assertFalse(PcmWriter.write(new Sink(1),new float[1],22050,() -> false));
}
}
@@ -0,0 +1,29 @@
package com.ttstd.tts.engine;
import org.junit.Test;
import static org.junit.Assert.*;
public class PitchShifterTest {
@Test public void preservesShortSoundsAndTail() {
for (int length : new int[]{1, 100, 511, 1023, 1025, 2601}) {
float[] input = new float[length];
java.util.Arrays.fill(input, 0.5f);
for (float pitch : new float[]{0.5f, 1.2f, 2f}) {
float[] output = PitchShifter.shift(input, pitch);
assertTrue(Math.abs(output.length - length) <= 1);
double energy = 0, tail = 0;
for (int i=0; i<output.length; i++) {
assertFalse(Float.isNaN(output[i]) || Float.isInfinite(output[i]));
energy += output[i]*output[i];
if (i >= output.length-100) tail += output[i]*output[i];
}
assertTrue("short sound lost", energy > 0.01*length);
assertTrue("tail lost", tail > 0.01);
}
}
}
@Test public void normalPitchDoesNotCopyAudio() {
float[] input = {0.1f, -0.2f, 0.3f};
assertSame(input, PitchShifter.shift(input, 1f));
}
}
@@ -0,0 +1,23 @@
package com.ttstd.tts.engine;
import org.junit.Test;
import static org.junit.Assert.*;
public class SynthesisAudioCallbackTest {
@Test public void exposesExactJniSignatureAndWritesAudio() throws Exception {
PcmWriterTest.Sink sink = new PcmWriterTest.Sink(64);
SynthesisAudioCallback callback = new SynthesisAudioCallback(sink, () -> false, 22050, 1f);
java.lang.reflect.Method invoke = callback.getClass().getMethod("invoke", float[].class);
assertEquals(Integer.class, invoke.getReturnType());
assertEquals(Integer.valueOf(1), invoke.invoke(callback, (Object) new float[1000]));
assertEquals(2000, sink.bytes);
assertTrue(callback.completed());
}
@Test public void cancellationStopsNativeGeneration() {
PcmWriterTest.Sink sink = new PcmWriterTest.Sink(64);
SynthesisAudioCallback callback = new SynthesisAudioCallback(sink, () -> true, 22050, 1.2f);
assertEquals(Integer.valueOf(0), callback.invoke(new float[1000]));
assertEquals(0, sink.bytes);
assertFalse(callback.completed());
}
}
@@ -0,0 +1,46 @@
package com.ttstd.tts.engine;
import org.junit.Test;
import java.io.*;
import java.nio.*;
import static org.junit.Assert.*;
public class WavPcmReaderTest {
private byte[] wav(boolean extra) throws Exception {
ByteArrayOutputStream out=new ByteArrayOutputStream();
DataOutputStream d=new DataOutputStream(out);
d.writeBytes("RIFF"); le(d,40+(extra?10:0)); d.writeBytes("WAVE");
if(extra) { d.writeBytes("JUNK"); le(d,1); d.write(7); d.write(0); }
d.writeBytes("fmt "); le(d,16);
d.write(new byte[]{1,0,1,0}); le(d,22050); le(d,44100);
d.write(new byte[]{2,0,16,0}); d.writeBytes("data"); le(d,4);
d.write(new byte[]{1,2,3,4}); return out.toByteArray();
}
private void le(DataOutputStream d,int value) throws Exception { d.writeInt(Integer.reverseBytes(value)); }
@Test public void parsesExtraChunksAndStreamsPcm() throws Exception {
WavPcmReader reader=new WavPcmReader(new ByteArrayInputStream(wav(true)));
assertEquals(22050,reader.sampleRate);
byte[] pcm=new byte[2];
assertEquals(2,reader.readPcm(pcm)); assertArrayEquals(new byte[]{1,2},pcm);
assertEquals(2,reader.readPcm(pcm)); assertArrayEquals(new byte[]{3,4},pcm);
assertEquals(-1,reader.readPcm(pcm));
}
@Test(expected=IOException.class) public void rejectsTruncation() throws Exception {
byte[] data=wav(false);
WavPcmReader reader=new WavPcmReader(new ByteArrayInputStream(java.util.Arrays.copyOf(data,data.length-1)));
reader.readPcm(new byte[100]);
}
@Test(expected=IOException.class) public void rejectsWrongFormat() throws Exception {
byte[] data=wav(false); data[34]=8;
new WavPcmReader(new ByteArrayInputStream(data));
}
@Test(expected=IOException.class) public void rejectsOversizedResponseBeforeAllocation() throws Exception {
byte[] data=wav(false);
ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN).putInt(4,30*1024*1024+36).putInt(40,30*1024*1024);
new WavPcmReader(new ByteArrayInputStream(data));
}
@Test(expected=IOException.class) public void rejectsStereo() throws Exception {
byte[] data=wav(false); data[22]=2;
new WavPcmReader(new ByteArrayInputStream(data));
}
}
@@ -0,0 +1,25 @@
"""Check arm64 ELF LOAD segments in an AAR/APK for 16 KiB alignment."""
import struct
import sys
import zipfile
from pathlib import Path
path = Path(sys.argv[1]) if len(sys.argv) > 1 else Path(__file__).resolve().parents[1] / "app/libs/sherpa-onnx-2.0.1.aar"
failed = False
count = 0
with zipfile.ZipFile(path) as archive:
for name in archive.namelist():
if "arm64-v8a/" not in name or not name.endswith(".so"):
continue
count += 1
data = archive.read(name)
if data[:6] != b"\x7fELF\x02\x01":
raise SystemExit(f"Unsupported ELF: {name}")
start = struct.unpack_from("<Q", data, 32)[0]
size, number = struct.unpack_from("<HH", data, 54)
loads = [struct.unpack_from("<IIQQQQQQ", data, start+i*size) for i in range(number) if struct.unpack_from("<I",data,start+i*size)[0] == 1]
valid = bool(loads) and all(p[7] >= 16384 and p[2] % 16384 == p[3] % 16384 for p in loads)
print(f"{'PASS' if valid else 'FAIL'} {name}")
failed |= not valid
if not count:
raise SystemExit("No arm64 native libraries found")
raise SystemExit(1 if failed else 0)
+14 -3
View File
@@ -12,8 +12,19 @@
"model": "zh_CN-chaowen-medium.onnx",
"lexicon": "lexicon.txt",
"tokens": "tokens.txt",
"ruleFsts": ["phone.fst", "date.fst", "number.fst"],
"sha256": "89ba22cdbc1d6299e6f8e03643d68d69b8fe109e7b98f2aa72390d9af9eb3572"
"ruleFsts": [
"phone.fst",
"date.fst",
"number.fst"
],
"sha256": "89ba22cdbc1d6299e6f8e03643d68d69b8fe109e7b98f2aa72390d9af9eb3572",
"files": {
"tokens.txt": "e9e6d2838a2676749adbf0376c4cf3c3cd28eb27ed953dcc2adcab8db3c33ba7",
"lexicon.txt": "003e76f89fec389ec109b557f47cc315a1ac31a99091f0cc9d15949f9024416b",
"phone.fst": "1ac2b6fa56b1442320c4de7db08353bab8963a2b57f365eebcdd3a2d3562f8d7",
"date.fst": "eb8aa079ae3cb81d8f4404992f39d61a0cb990947512b5b8d1e54d1f6980e718",
"number.fst": "743f402181fcfebf76cc2f0546b71fa26476e626fbe4e460fb7b4c3a7a8bd5bd"
}
}
]
}
}