1
0
mirror of https://github.com/ndarilek/tts-rs.git synced 2024-11-01 00:29:37 +00:00
tts-rs/src/backends/android.rs

389 lines
11 KiB
Rust
Raw Normal View History

2020-12-27 15:41:11 +00:00
#[cfg(target_os = "android")]
2022-01-10 16:51:18 +00:00
use std::{
collections::HashSet,
ffi::{CStr, CString},
os::raw::c_void,
sync::{Mutex, RwLock},
thread,
time::{Duration, Instant},
};
2020-12-27 15:41:11 +00:00
2022-01-10 16:51:18 +00:00
use jni::{
objects::{GlobalRef, JObject, JString},
sys::{jfloat, jint, JNI_VERSION_1_6},
JNIEnv, JavaVM,
};
2020-12-27 15:41:11 +00:00
use lazy_static::lazy_static;
2020-12-30 16:10:00 +00:00
use log::{error, info};
2020-12-27 15:41:11 +00:00
use crate::{Backend, BackendId, Error, Features, UtteranceId, CALLBACKS};
lazy_static! {
static ref BRIDGE: Mutex<Option<GlobalRef>> = Mutex::new(None);
2020-12-27 15:41:11 +00:00
static ref NEXT_BACKEND_ID: Mutex<u64> = Mutex::new(0);
static ref PENDING_INITIALIZATIONS: RwLock<HashSet<u64>> = RwLock::new(HashSet::new());
static ref NEXT_UTTERANCE_ID: Mutex<u64> = Mutex::new(0);
}
#[allow(non_snake_case)]
#[no_mangle]
pub extern "system" fn JNI_OnLoad(vm: JavaVM, _: *mut c_void) -> jint {
let env = vm.get_env().expect("Cannot get reference to the JNIEnv");
let b = env
.find_class("rs/tts/Bridge")
.expect("Failed to find `Bridge`");
let b = env
.new_global_ref(b)
.expect("Failed to create `Bridge` `GlobalRef`");
let mut bridge = BRIDGE.lock().unwrap();
*bridge = Some(b);
JNI_VERSION_1_6
}
#[no_mangle]
#[allow(non_snake_case)]
2020-12-30 16:10:00 +00:00
pub unsafe extern "C" fn Java_rs_tts_Bridge_onInit(env: JNIEnv, obj: JObject, status: jint) {
let id = env
.get_field(obj, "backendId", "I")
.expect("Failed to get backend ID")
.i()
.expect("Failed to cast to int") as u64;
let mut pending = PENDING_INITIALIZATIONS.write().unwrap();
(*pending).remove(&id);
2020-12-30 16:10:00 +00:00
if status != 0 {
error!("Failed to initialize TTS engine");
}
2020-12-27 15:41:11 +00:00
}
#[no_mangle]
#[allow(non_snake_case)]
pub unsafe extern "C" fn Java_rs_tts_Bridge_onStart(
env: JNIEnv,
obj: JObject,
utterance_id: JString,
) {
let backend_id = env
.get_field(obj, "backendId", "I")
.expect("Failed to get backend ID")
.i()
.expect("Failed to cast to int") as u64;
let backend_id = BackendId::Android(backend_id);
let utterance_id = CString::from(CStr::from_ptr(
env.get_string(utterance_id).unwrap().as_ptr(),
))
.into_string()
.unwrap();
let utterance_id = utterance_id.parse::<u64>().unwrap();
let utterance_id = UtteranceId::Android(utterance_id);
let mut callbacks = CALLBACKS.lock().unwrap();
2020-12-30 18:19:44 +00:00
let cb = callbacks.get_mut(&backend_id).unwrap();
if let Some(f) = cb.utterance_begin.as_mut() {
f(utterance_id);
}
}
#[no_mangle]
#[allow(non_snake_case)]
pub unsafe extern "C" fn Java_rs_tts_Bridge_onStop(
env: JNIEnv,
obj: JObject,
utterance_id: JString,
) {
2020-12-30 18:19:44 +00:00
let backend_id = env
.get_field(obj, "backendId", "I")
.expect("Failed to get backend ID")
.i()
.expect("Failed to cast to int") as u64;
2020-12-30 18:19:44 +00:00
let backend_id = BackendId::Android(backend_id);
let utterance_id = CString::from(CStr::from_ptr(
env.get_string(utterance_id).unwrap().as_ptr(),
))
.into_string()
.unwrap();
2020-12-30 18:19:44 +00:00
let utterance_id = utterance_id.parse::<u64>().unwrap();
let utterance_id = UtteranceId::Android(utterance_id);
let mut callbacks = CALLBACKS.lock().unwrap();
let cb = callbacks.get_mut(&backend_id).unwrap();
if let Some(f) = cb.utterance_end.as_mut() {
f(utterance_id);
}
}
#[no_mangle]
#[allow(non_snake_case)]
pub unsafe extern "C" fn Java_rs_tts_Bridge_onDone(
env: JNIEnv,
obj: JObject,
utterance_id: JString,
) {
2020-12-30 18:19:44 +00:00
let backend_id = env
.get_field(obj, "backendId", "I")
.expect("Failed to get backend ID")
.i()
.expect("Failed to cast to int") as u64;
2020-12-30 18:19:44 +00:00
let backend_id = BackendId::Android(backend_id);
let utterance_id = CString::from(CStr::from_ptr(
env.get_string(utterance_id).unwrap().as_ptr(),
))
.into_string()
.unwrap();
2020-12-30 18:19:44 +00:00
let utterance_id = utterance_id.parse::<u64>().unwrap();
let utterance_id = UtteranceId::Android(utterance_id);
let mut callbacks = CALLBACKS.lock().unwrap();
let cb = callbacks.get_mut(&backend_id).unwrap();
if let Some(f) = cb.utterance_stop.as_mut() {
f(utterance_id);
}
}
#[no_mangle]
#[allow(non_snake_case)]
pub unsafe extern "C" fn Java_rs_tts_Bridge_onError(
env: JNIEnv,
obj: JObject,
utterance_id: JString,
) {
2020-12-30 18:19:44 +00:00
let backend_id = env
.get_field(obj, "backendId", "I")
.expect("Failed to get backend ID")
.i()
.expect("Failed to cast to int") as u64;
2020-12-30 18:19:44 +00:00
let backend_id = BackendId::Android(backend_id);
let utterance_id = CString::from(CStr::from_ptr(
env.get_string(utterance_id).unwrap().as_ptr(),
))
.into_string()
.unwrap();
2020-12-30 18:19:44 +00:00
let utterance_id = utterance_id.parse::<u64>().unwrap();
let utterance_id = UtteranceId::Android(utterance_id);
let mut callbacks = CALLBACKS.lock().unwrap();
let cb = callbacks.get_mut(&backend_id).unwrap();
if let Some(f) = cb.utterance_end.as_mut() {
f(utterance_id);
}
}
2020-12-29 21:45:56 +00:00
#[derive(Clone)]
2020-12-29 20:10:39 +00:00
pub(crate) struct Android {
id: BackendId,
2020-12-29 21:45:56 +00:00
tts: GlobalRef,
2020-12-30 16:06:18 +00:00
rate: f32,
pitch: f32,
2020-12-29 20:10:39 +00:00
}
2020-12-27 15:41:11 +00:00
impl Android {
pub(crate) fn new() -> Result<Self, Error> {
2020-12-27 15:41:11 +00:00
info!("Initializing Android backend");
let mut backend_id = NEXT_BACKEND_ID.lock().unwrap();
let bid = *backend_id;
let id = BackendId::Android(bid);
2020-12-27 15:41:11 +00:00
*backend_id += 1;
drop(backend_id);
let native_activity = ndk_glue::native_activity();
let vm = Self::vm()?;
let env = vm.attach_current_thread_permanently()?;
let bridge = BRIDGE.lock().unwrap();
if let Some(bridge) = &*bridge {
let bridge = env.new_object(bridge, "(I)V", &[(bid as jint).into()])?;
let tts = env.new_object(
"android/speech/tts/TextToSpeech",
"(Landroid/content/Context;Landroid/speech/tts/TextToSpeech$OnInitListener;)V",
&[native_activity.activity().into(), bridge.into()],
)?;
env.call_method(
tts,
"setOnUtteranceProgressListener",
"(Landroid/speech/tts/UtteranceProgressListener;)I",
&[bridge.into()],
)?;
{
let mut pending = PENDING_INITIALIZATIONS.write().unwrap();
(*pending).insert(bid);
}
let tts = env.new_global_ref(tts)?;
// This hack makes my brain bleed.
const MAX_WAIT_TIME: Duration = Duration::from_millis(500);
let start = Instant::now();
// Wait a max of 500ms for initialization, then return an error to avoid hanging.
loop {
{
let pending = PENDING_INITIALIZATIONS.read().unwrap();
if !(*pending).contains(&bid) {
break;
}
if start.elapsed() > MAX_WAIT_TIME {
return Err(Error::OperationFailed);
}
}
thread::sleep(Duration::from_millis(5));
}
2020-12-30 16:06:18 +00:00
Ok(Self {
id,
tts,
rate: 1.,
pitch: 1.,
})
} else {
Err(Error::NoneError)
}
2020-12-27 15:41:11 +00:00
}
fn vm() -> Result<JavaVM, jni::errors::Error> {
let native_activity = ndk_glue::native_activity();
let vm_ptr = native_activity.vm();
unsafe { jni::JavaVM::from_raw(vm_ptr) }
}
2020-12-27 15:41:11 +00:00
}
impl Backend for Android {
fn id(&self) -> Option<BackendId> {
2020-12-29 20:10:39 +00:00
Some(self.id)
2020-12-27 15:41:11 +00:00
}
fn supported_features(&self) -> Features {
Features {
2020-12-30 15:49:13 +00:00
stop: true,
2020-12-30 16:06:18 +00:00
rate: true,
pitch: true,
2020-12-27 15:41:11 +00:00
volume: false,
2020-12-30 16:15:37 +00:00
is_speaking: true,
utterance_callbacks: true,
2020-12-27 15:41:11 +00:00
}
}
fn speak(&mut self, text: &str, interrupt: bool) -> Result<Option<UtteranceId>, Error> {
let vm = Self::vm()?;
let env = vm.get_env()?;
let tts = self.tts.as_obj();
let text = env.new_string(text)?;
let queue_mode = if interrupt { 0 } else { 1 };
let mut utterance_id = NEXT_UTTERANCE_ID.lock().unwrap();
let uid = *utterance_id;
*utterance_id += 1;
drop(utterance_id);
let id = UtteranceId::Android(uid);
let uid = env.new_string(uid.to_string())?;
let rv = env.call_method(
tts,
"speak",
"(Ljava/lang/CharSequence;ILandroid/os/Bundle;Ljava/lang/String;)I",
&[
text.into(),
queue_mode.into(),
JObject::null().into(),
uid.into(),
],
)?;
2020-12-30 16:06:18 +00:00
let rv = rv.i()?;
if rv == 0 {
Ok(Some(id))
} else {
Err(Error::OperationFailed)
}
2020-12-27 15:41:11 +00:00
}
fn stop(&mut self) -> Result<(), Error> {
2020-12-30 15:49:13 +00:00
let vm = Self::vm()?;
let env = vm.get_env()?;
let tts = self.tts.as_obj();
let rv = env.call_method(tts, "stop", "()I", &[])?;
2020-12-30 16:06:18 +00:00
let rv = rv.i()?;
2020-12-30 15:49:13 +00:00
if rv == 0 {
Ok(())
} else {
Err(Error::OperationFailed)
}
2020-12-27 15:41:11 +00:00
}
fn min_rate(&self) -> f32 {
0.1
2020-12-27 15:41:11 +00:00
}
fn max_rate(&self) -> f32 {
10.
2020-12-27 15:41:11 +00:00
}
fn normal_rate(&self) -> f32 {
1.
2020-12-27 15:41:11 +00:00
}
fn get_rate(&self) -> Result<f32, Error> {
2020-12-30 16:06:18 +00:00
Ok(self.rate)
2020-12-27 15:41:11 +00:00
}
fn set_rate(&mut self, rate: f32) -> Result<(), Error> {
2020-12-30 16:06:18 +00:00
let vm = Self::vm()?;
let env = vm.get_env()?;
let tts = self.tts.as_obj();
let rate = rate as jfloat;
let rv = env.call_method(tts, "setSpeechRate", "(F)I", &[rate.into()])?;
let rv = rv.i()?;
if rv == 0 {
self.rate = rate;
Ok(())
} else {
Err(Error::OperationFailed)
}
2020-12-27 15:41:11 +00:00
}
fn min_pitch(&self) -> f32 {
0.1
2020-12-27 15:41:11 +00:00
}
fn max_pitch(&self) -> f32 {
2.
2020-12-27 15:41:11 +00:00
}
fn normal_pitch(&self) -> f32 {
1.
2020-12-27 15:41:11 +00:00
}
fn get_pitch(&self) -> Result<f32, Error> {
2020-12-30 16:06:18 +00:00
Ok(self.pitch)
2020-12-27 15:41:11 +00:00
}
fn set_pitch(&mut self, pitch: f32) -> Result<(), Error> {
2020-12-30 16:06:18 +00:00
let vm = Self::vm()?;
let env = vm.get_env()?;
let tts = self.tts.as_obj();
let pitch = pitch as jfloat;
let rv = env.call_method(tts, "setPitch", "(F)I", &[pitch.into()])?;
let rv = rv.i()?;
if rv == 0 {
self.pitch = pitch;
Ok(())
} else {
Err(Error::OperationFailed)
}
2020-12-27 15:41:11 +00:00
}
fn min_volume(&self) -> f32 {
todo!()
}
fn max_volume(&self) -> f32 {
todo!()
}
fn normal_volume(&self) -> f32 {
todo!()
}
fn get_volume(&self) -> Result<f32, Error> {
todo!()
}
2020-12-30 16:07:27 +00:00
fn set_volume(&mut self, _volume: f32) -> Result<(), Error> {
2020-12-27 15:41:11 +00:00
todo!()
}
fn is_speaking(&self) -> Result<bool, Error> {
2020-12-30 16:15:37 +00:00
let vm = Self::vm()?;
let env = vm.get_env()?;
let tts = self.tts.as_obj();
let rv = env.call_method(tts, "isSpeaking", "()Z", &[])?;
let rv = rv.z()?;
Ok(rv)
2020-12-27 15:41:11 +00:00
}
}