From 0788c2ef225f0665cbe371b80ee3f3b53a869f2a Mon Sep 17 00:00:00 2001 From: Ryo Yamashita Date: Sun, 10 Dec 2023 18:53:05 +0900 Subject: [PATCH] =?UTF-8?q?C=E3=81=A8Java=E3=81=AE=E3=83=96=E3=83=AD?= =?UTF-8?q?=E3=83=83=E3=82=AD=E3=83=B3=E3=82=B0API=E3=82=92=E5=AE=9F?= =?UTF-8?q?=E8=A3=85=20(#705)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Cargo.lock | 2 - crates/voicevox_core/Cargo.toml | 2 +- crates/voicevox_core/src/synthesizer.rs | 54 +----- crates/voicevox_core_c_api/Cargo.toml | 1 - crates/voicevox_core_c_api/src/c_impls.rs | 20 +-- .../src/compatible_engine.rs | 42 ++--- crates/voicevox_core_c_api/src/lib.rs | 158 ++++++++++-------- crates/voicevox_core_java_api/Cargo.toml | 1 - .../java/jp/hiroshiba/voicevoxcore/Dll.java | 6 + crates/voicevox_core_java_api/src/common.rs | 20 ++- .../voicevox_core_java_api/src/open_jtalk.rs | 11 +- .../voicevox_core_java_api/src/synthesizer.rs | 99 +++++------ .../voicevox_core_java_api/src/user_dict.rs | 24 +-- .../voicevox_core_java_api/src/voice_model.rs | 8 +- 14 files changed, 212 insertions(+), 236 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index deba74398..7cab0379a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4414,7 +4414,6 @@ dependencies = [ "tempfile", "test_util", "thiserror", - "tokio", "toml 0.7.2", "tracing", "tracing-subscriber", @@ -4433,7 +4432,6 @@ dependencies = [ "jni", "once_cell", "serde_json", - "tokio", "tracing", "tracing-subscriber", "uuid", diff --git a/crates/voicevox_core/Cargo.toml b/crates/voicevox_core/Cargo.toml index 1b8904875..96a8bb574 100644 --- a/crates/voicevox_core/Cargo.toml +++ b/crates/voicevox_core/Cargo.toml @@ -35,7 +35,7 @@ serde = { workspace = true, features = ["derive"] } serde_json = { workspace = true, features = ["preserve_order"] } tempfile.workspace = true thiserror.workspace = true -tokio = { workspace = true, features = ["rt"] } +tokio = { workspace = true, features = ["rt"] } # FIXME: feature-gateする tracing.workspace = true uuid = { workspace = true, features = ["v4", "serde"] } voicevox_core_macros = { path = "../voicevox_core_macros" } diff --git a/crates/voicevox_core/src/synthesizer.rs b/crates/voicevox_core/src/synthesizer.rs index c178a0ddd..a728fff65 100644 --- a/crates/voicevox_core/src/synthesizer.rs +++ b/crates/voicevox_core/src/synthesizer.rs @@ -357,7 +357,8 @@ impl self::blocking::Synthesizer { self.status.is_loaded_model(voice_model_id) } - fn is_loaded_model_by_style_id(&self, style_id: StyleId) -> bool { + #[doc(hidden)] + pub fn is_loaded_model_by_style_id(&self, style_id: StyleId) -> bool { self.status.is_loaded_model_by_style_id(style_id) } @@ -1039,47 +1040,6 @@ pub trait PerformInference { ) -> Result>; } -impl PerformInference for self::tokio::Synthesizer { - fn predict_duration(&self, phoneme_vector: &[i64], style_id: StyleId) -> Result> { - self.0.predict_duration(phoneme_vector, style_id) - } - - fn predict_intonation( - &self, - length: usize, - vowel_phoneme_vector: &[i64], - consonant_phoneme_vector: &[i64], - start_accent_vector: &[i64], - end_accent_vector: &[i64], - start_accent_phrase_vector: &[i64], - end_accent_phrase_vector: &[i64], - style_id: StyleId, - ) -> Result> { - self.0.predict_intonation( - length, - vowel_phoneme_vector, - consonant_phoneme_vector, - start_accent_vector, - end_accent_vector, - start_accent_phrase_vector, - end_accent_phrase_vector, - style_id, - ) - } - - fn decode( - &self, - length: usize, - phoneme_size: usize, - f0: &[f32], - phoneme_vector: &[f32], - style_id: StyleId, - ) -> Result> { - self.0 - .decode(length, phoneme_size, f0, phoneme_vector, style_id) - } -} - impl PerformInference for self::blocking::Synthesizer { fn predict_duration(&self, phoneme_vector: &[i64], style_id: StyleId) -> Result> { // FIXME: `Status::ids_for`があるため、ここは不要なはず @@ -1516,7 +1476,9 @@ mod tests { 30, 35, 14, 23, 7, 21, 14, 43, 30, 30, 23, 30, 35, 30, 0, ]; - let result = syntesizer.predict_duration(&phoneme_vector, StyleId::new(1)); + let result = syntesizer + .0 + .predict_duration(&phoneme_vector, StyleId::new(1)); assert!(result.is_ok(), "{result:?}"); assert_eq!(result.unwrap().len(), phoneme_vector.len()); @@ -1546,7 +1508,7 @@ mod tests { let start_accent_phrase_vector = [0, 1, 0, 0, 0]; let end_accent_phrase_vector = [0, 0, 0, 1, 0]; - let result = syntesizer.predict_intonation( + let result = syntesizer.0.predict_intonation( vowel_phoneme_vector.len(), &vowel_phoneme_vector, &consonant_phoneme_vector, @@ -1599,7 +1561,9 @@ mod tests { set_one(30, 45..60); set_one(0, 60..69); - let result = syntesizer.decode(F0_LENGTH, PHONEME_SIZE, &f0, &phoneme, StyleId::new(1)); + let result = syntesizer + .0 + .decode(F0_LENGTH, PHONEME_SIZE, &f0, &phoneme, StyleId::new(1)); assert!(result.is_ok(), "{result:?}"); assert_eq!(result.unwrap().len(), F0_LENGTH * 256); diff --git a/crates/voicevox_core_c_api/Cargo.toml b/crates/voicevox_core_c_api/Cargo.toml index fe5ef243b..ee45eee79 100644 --- a/crates/voicevox_core_c_api/Cargo.toml +++ b/crates/voicevox_core_c_api/Cargo.toml @@ -29,7 +29,6 @@ once_cell.workspace = true process_path.workspace = true serde_json = { workspace = true, features = ["preserve_order"] } thiserror.workspace = true -tokio = { workspace = true, features = ["rt", "rt-multi-thread"] } tracing.workspace = true tracing-subscriber = { workspace = true, features = ["env-filter"] } uuid.workspace = true diff --git a/crates/voicevox_core_c_api/src/c_impls.rs b/crates/voicevox_core_c_api/src/c_impls.rs index 61665f48f..4a839e68b 100644 --- a/crates/voicevox_core_c_api/src/c_impls.rs +++ b/crates/voicevox_core_c_api/src/c_impls.rs @@ -5,29 +5,25 @@ use voicevox_core::{InitializeOptions, Result, VoiceModelId}; use crate::{CApiResult, OpenJtalkRc, VoicevoxSynthesizer, VoicevoxVoiceModel}; impl OpenJtalkRc { - pub(crate) async fn new(open_jtalk_dic_dir: impl AsRef) -> Result { + pub(crate) fn new(open_jtalk_dic_dir: impl AsRef) -> Result { Ok(Self { - open_jtalk: voicevox_core::tokio::OpenJtalk::new(open_jtalk_dic_dir).await?, + open_jtalk: voicevox_core::blocking::OpenJtalk::new(open_jtalk_dic_dir)?, }) } } impl VoicevoxSynthesizer { pub(crate) fn new(open_jtalk: &OpenJtalkRc, options: &InitializeOptions) -> Result { - // ロガーを起動 - // FIXME: `into_result_code_with_error`を`run`とかに改名し、`init_logger`をその中に移動 - let _ = *crate::RUNTIME; - let synthesizer = - voicevox_core::tokio::Synthesizer::new(open_jtalk.open_jtalk.clone(), options)?; + voicevox_core::blocking::Synthesizer::new(open_jtalk.open_jtalk.clone(), options)?; Ok(Self { synthesizer }) } - pub(crate) async fn load_voice_model( + pub(crate) fn load_voice_model( &self, - model: &voicevox_core::tokio::VoiceModel, + model: &voicevox_core::blocking::VoiceModel, ) -> CApiResult<()> { - self.synthesizer.load_voice_model(model).await?; + self.synthesizer.load_voice_model(model)?; Ok(()) } @@ -43,8 +39,8 @@ impl VoicevoxSynthesizer { } impl VoicevoxVoiceModel { - pub(crate) async fn from_path(path: impl AsRef) -> Result { - let model = voicevox_core::tokio::VoiceModel::from_path(path).await?; + pub(crate) fn from_path(path: impl AsRef) -> Result { + let model = voicevox_core::blocking::VoiceModel::from_path(path)?; let id = CString::new(model.id().raw_voice_model_id().as_str()).unwrap(); let metas = CString::new(serde_json::to_string(model.metas()).unwrap()).unwrap(); Ok(Self { model, id, metas }) diff --git a/crates/voicevox_core_c_api/src/compatible_engine.rs b/crates/voicevox_core_c_api/src/compatible_engine.rs index 694753827..2dcccbeb7 100644 --- a/crates/voicevox_core_c_api/src/compatible_engine.rs +++ b/crates/voicevox_core_c_api/src/compatible_engine.rs @@ -20,14 +20,14 @@ macro_rules! ensure_initialized { static ERROR_MESSAGE: Lazy> = Lazy::new(|| Mutex::new(String::new())); struct VoiceModelSet { - all_vvms: Vec, + all_vvms: Vec, all_metas_json: CString, style_model_map: BTreeMap, - model_map: BTreeMap, + model_map: BTreeMap, } static VOICE_MODEL_SET: Lazy = Lazy::new(|| { - let all_vvms = RUNTIME.block_on(get_all_models()); + let all_vvms = get_all_models(); let model_map: BTreeMap<_, _> = all_vvms .iter() .map(|vvm| (vvm.id().clone(), vvm.clone())) @@ -52,7 +52,7 @@ static VOICE_MODEL_SET: Lazy = Lazy::new(|| { /// # Panics /// /// 失敗したらパニックする - async fn get_all_models() -> Vec { + fn get_all_models() -> Vec { let root_dir = if let Some(root_dir) = env::var_os(ROOT_DIR_ENV_NAME) { root_dir.into() } else { @@ -64,17 +64,13 @@ static VOICE_MODEL_SET: Lazy = Lazy::new(|| { .join("model") }; - let vvm_paths = root_dir + root_dir .read_dir() .and_then(|entries| entries.collect::, _>>()) .unwrap_or_else(|e| panic!("{}が読めませんでした: {e}", root_dir.display())) .into_iter() .filter(|entry| entry.path().extension().map_or(false, |ext| ext == "vvm")) - .map(|entry| voicevox_core::tokio::VoiceModel::from_path(entry.path())); - - futures::future::join_all(vvm_paths) - .await - .into_iter() + .map(|entry| voicevox_core::blocking::VoiceModel::from_path(entry.path())) .collect::>() .unwrap() } @@ -88,10 +84,10 @@ fn voice_model_set() -> &'static VoiceModelSet { &VOICE_MODEL_SET } -static SYNTHESIZER: Lazy>>> = +static SYNTHESIZER: Lazy>>> = Lazy::new(|| Mutex::new(None)); -fn lock_synthesizer() -> MutexGuard<'static, Option>> { +fn lock_synthesizer() -> MutexGuard<'static, Option>> { SYNTHESIZER.lock().unwrap() } @@ -104,10 +100,9 @@ fn set_message(message: &str) { #[no_mangle] pub extern "C" fn initialize(use_gpu: bool, cpu_num_threads: c_int, load_all_models: bool) -> bool { - // FIXME: ここはもう`RUNTIME.block_on`で包む必要は無くなっているのだが、ロガーの設定を`RUNTIME` - // で行っているという構造になってしまっているので、外すとロガーの初期化が遅れてしまでう - let result = RUNTIME.block_on(async { - let synthesizer = voicevox_core::tokio::Synthesizer::new( + init_logger_once(); + let result = (|| { + let synthesizer = voicevox_core::blocking::Synthesizer::new( (), &voicevox_core::InitializeOptions { acceleration_mode: if use_gpu { @@ -121,12 +116,12 @@ pub extern "C" fn initialize(use_gpu: bool, cpu_num_threads: c_int, load_all_mod if load_all_models { for model in &voice_model_set().all_vvms { - synthesizer.load_voice_model(model).await?; + synthesizer.load_voice_model(model)?; } } Ok::<_, voicevox_core::Error>(synthesizer) - }); + })(); match result { Ok(synthesizer) => { @@ -142,12 +137,13 @@ pub extern "C" fn initialize(use_gpu: bool, cpu_num_threads: c_int, load_all_mod #[no_mangle] pub extern "C" fn load_model(style_id: i64) -> bool { + init_logger_once(); let style_id = StyleId::new(style_id as u32); let model_set = voice_model_set(); if let Some(model_id) = model_set.style_model_map.get(&style_id) { let vvm = model_set.model_map.get(model_id).unwrap(); let synthesizer = &mut *lock_synthesizer(); - let result = RUNTIME.block_on(ensure_initialized!(synthesizer).load_voice_model(vvm)); + let result = ensure_initialized!(synthesizer).load_voice_model(vvm); if let Some(err) = result.err() { set_message(&format!("{err}")); false @@ -162,28 +158,33 @@ pub extern "C" fn load_model(style_id: i64) -> bool { #[no_mangle] pub extern "C" fn is_model_loaded(speaker_id: i64) -> bool { + init_logger_once(); ensure_initialized!(&*lock_synthesizer()) .is_loaded_model_by_style_id(StyleId::new(speaker_id as u32)) } #[no_mangle] pub extern "C" fn finalize() { + init_logger_once(); *lock_synthesizer() = None; } #[no_mangle] pub extern "C" fn metas() -> *const c_char { + init_logger_once(); let model_set = voice_model_set(); model_set.all_metas_json.as_ptr() } #[no_mangle] pub extern "C" fn last_error_message() -> *const c_char { + init_logger_once(); ERROR_MESSAGE.lock().unwrap().as_ptr() as *const c_char } #[no_mangle] pub extern "C" fn supported_devices() -> *const c_char { + init_logger_once(); return SUPPORTED_DEVICES.as_ptr(); static SUPPORTED_DEVICES: Lazy = Lazy::new(|| { @@ -198,6 +199,7 @@ pub extern "C" fn yukarin_s_forward( speaker_id: *mut i64, output: *mut f32, ) -> bool { + init_logger_once(); let synthesizer = &*lock_synthesizer(); let result = ensure_initialized!(synthesizer).predict_duration( unsafe { std::slice::from_raw_parts_mut(phoneme_list, length as usize) }, @@ -228,6 +230,7 @@ pub extern "C" fn yukarin_sa_forward( speaker_id: *mut i64, output: *mut f32, ) -> bool { + init_logger_once(); let synthesizer = &*lock_synthesizer(); let result = ensure_initialized!(synthesizer).predict_intonation( length as usize, @@ -261,6 +264,7 @@ pub extern "C" fn decode_forward( speaker_id: *mut i64, output: *mut f32, ) -> bool { + init_logger_once(); let length = length as usize; let phoneme_size = phoneme_size as usize; let synthesizer = &*lock_synthesizer(); diff --git a/crates/voicevox_core_c_api/src/lib.rs b/crates/voicevox_core_c_api/src/lib.rs index 1be2cafc6..7ceb84383 100644 --- a/crates/voicevox_core_c_api/src/lib.rs +++ b/crates/voicevox_core_c_api/src/lib.rs @@ -24,18 +24,17 @@ use std::fmt; use std::io; use std::os::raw::c_char; use std::ptr::NonNull; -use std::sync::{Arc, Mutex, MutexGuard}; -use tokio::runtime::Runtime; +use std::sync::{Arc, Mutex, MutexGuard, Once}; use tracing_subscriber::fmt::format::Writer; use tracing_subscriber::EnvFilter; use uuid::Uuid; use voicevox_core::{AccentPhraseModel, AudioQueryModel, TtsOptions, UserDictWord, VoiceModelId}; use voicevox_core::{StyleId, SupportedDevices, SynthesisOptions}; -static RUNTIME: Lazy = Lazy::new(|| { - let _ = init_logger(); +fn init_logger_once() { + static ONCE: Once = Once::new(); - fn init_logger() -> std::result::Result<(), impl Sized> { + ONCE.call_once(|| { let ansi = { // anstyle系のクレートを利用して次の2つを行う。 // @@ -53,7 +52,8 @@ static RUNTIME: Lazy = Lazy::new(|| { && anstyle_query::windows::enable_ansi_colors().unwrap_or(true) }; - tracing_subscriber::fmt() + // FIXME: `try_init` → `init` (subscriberは他に存在しないはずなので) + let _ = tracing_subscriber::fmt() .with_env_filter(if env::var_os(EnvFilter::DEFAULT_ENV).is_some() { EnvFilter::from_default_env() } else { @@ -62,8 +62,8 @@ static RUNTIME: Lazy = Lazy::new(|| { .with_timer(local_time as fn(&mut Writer<'_>) -> _) .with_ansi(ansi) .with_writer(out) - .try_init() - } + .try_init(); + }); fn local_time(wtr: &mut Writer<'_>) -> fmt::Result { // ローカル時刻で表示はするが、そのフォーマットはtracing-subscriber本来のものに近いようにする。 @@ -74,9 +74,7 @@ static RUNTIME: Lazy = Lazy::new(|| { fn out() -> impl RawStream { io::stderr() } - - Runtime::new().unwrap() -}); +} /* * Cの関数として公開するための型や関数を定義するこれらの実装はvoicevox_core/publish.rsに定義してある対応する関数にある @@ -101,7 +99,7 @@ static RUNTIME: Lazy = Lazy::new(|| { /// ``` /// } pub struct OpenJtalkRc { - open_jtalk: voicevox_core::tokio::OpenJtalk, + open_jtalk: voicevox_core::blocking::OpenJtalk, } /// ::OpenJtalkRc を構築(_construct_)する。 @@ -129,11 +127,10 @@ pub unsafe extern "C" fn voicevox_open_jtalk_rc_new( open_jtalk_dic_dir: *const c_char, out_open_jtalk: NonNull>, ) -> VoicevoxResultCode { + init_logger_once(); into_result_code_with_error((|| { let open_jtalk_dic_dir = ensure_utf8(CStr::from_ptr(open_jtalk_dic_dir))?; - let open_jtalk = RUNTIME - .block_on(OpenJtalkRc::new(open_jtalk_dic_dir))? - .into(); + let open_jtalk = OpenJtalkRc::new(open_jtalk_dic_dir)?.into(); out_open_jtalk.as_ptr().write_unaligned(open_jtalk); Ok(()) })()) @@ -155,8 +152,9 @@ pub extern "C" fn voicevox_open_jtalk_rc_use_user_dict( open_jtalk: &OpenJtalkRc, user_dict: &VoicevoxUserDict, ) -> VoicevoxResultCode { + init_logger_once(); into_result_code_with_error((|| { - RUNTIME.block_on(open_jtalk.open_jtalk.use_user_dict(&user_dict.dict))?; + open_jtalk.open_jtalk.use_user_dict(&user_dict.dict)?; Ok(()) })()) } @@ -177,6 +175,7 @@ pub extern "C" fn voicevox_open_jtalk_rc_use_user_dict( /// } #[no_mangle] pub extern "C" fn voicevox_open_jtalk_rc_delete(open_jtalk: Box) { + init_logger_once(); drop(open_jtalk); } @@ -207,6 +206,7 @@ pub struct VoicevoxInitializeOptions { /// @return デフォルト値が設定された初期化オプション #[no_mangle] pub extern "C" fn voicevox_make_default_initialize_options() -> VoicevoxInitializeOptions { + init_logger_once(); VoicevoxInitializeOptions::default() } @@ -214,6 +214,7 @@ pub extern "C" fn voicevox_make_default_initialize_options() -> VoicevoxInitiali /// @return SemVerでフォーマットされたバージョン。 #[no_mangle] pub extern "C" fn voicevox_get_version() -> *const c_char { + init_logger_once(); return C_STRING_DROP_CHECKER.blacklist(VERSION).as_ptr(); const VERSION: &CStr = unsafe { @@ -228,7 +229,7 @@ pub extern "C" fn voicevox_get_version() -> *const c_char { /// 構築(_construction_)は ::voicevox_voice_model_new_from_path で行い、破棄(_destruction_)は ::voicevox_voice_model_delete で行う。 #[derive(Getters)] pub struct VoicevoxVoiceModel { - model: voicevox_core::tokio::VoiceModel, + model: voicevox_core::blocking::VoiceModel, id: CString, metas: CString, } @@ -257,11 +258,10 @@ pub unsafe extern "C" fn voicevox_voice_model_new_from_path( path: *const c_char, out_model: NonNull>, ) -> VoicevoxResultCode { + init_logger_once(); into_result_code_with_error((|| { let path = ensure_utf8(CStr::from_ptr(path))?; - let model = RUNTIME - .block_on(VoicevoxVoiceModel::from_path(path))? - .into(); + let model = VoicevoxVoiceModel::from_path(path)?.into(); out_model.as_ptr().write_unaligned(model); Ok(()) })()) @@ -278,6 +278,7 @@ pub unsafe extern "C" fn voicevox_voice_model_new_from_path( /// } #[no_mangle] pub extern "C" fn voicevox_voice_model_id(model: &VoicevoxVoiceModel) -> VoicevoxVoiceModelId { + init_logger_once(); model.id().as_ptr() } @@ -293,6 +294,7 @@ pub extern "C" fn voicevox_voice_model_id(model: &VoicevoxVoiceModel) -> Voicevo /// } #[no_mangle] pub extern "C" fn voicevox_voice_model_get_metas_json(model: &VoicevoxVoiceModel) -> *const c_char { + init_logger_once(); model.metas().as_ptr() } @@ -306,6 +308,7 @@ pub extern "C" fn voicevox_voice_model_get_metas_json(model: &VoicevoxVoiceModel /// } #[no_mangle] pub extern "C" fn voicevox_voice_model_delete(model: Box) { + init_logger_once(); drop(model); } @@ -314,7 +317,7 @@ pub extern "C" fn voicevox_voice_model_delete(model: Box) { /// 構築(_construction_)は ::voicevox_synthesizer_new で行い、破棄(_destruction_)は ::voicevox_synthesizer_delete で行う。 #[derive(Getters)] pub struct VoicevoxSynthesizer { - synthesizer: voicevox_core::tokio::Synthesizer, + synthesizer: voicevox_core::blocking::Synthesizer, } /// ::VoicevoxSynthesizer を構築(_construct_)する。 @@ -335,6 +338,7 @@ pub unsafe extern "C" fn voicevox_synthesizer_new( options: VoicevoxInitializeOptions, out_synthesizer: NonNull>, ) -> VoicevoxResultCode { + init_logger_once(); into_result_code_with_error((|| { let options = options.into(); @@ -354,6 +358,7 @@ pub unsafe extern "C" fn voicevox_synthesizer_new( /// } #[no_mangle] pub extern "C" fn voicevox_synthesizer_delete(synthesizer: Box) { + init_logger_once(); drop(synthesizer); } @@ -373,7 +378,8 @@ pub extern "C" fn voicevox_synthesizer_load_voice_model( synthesizer: &VoicevoxSynthesizer, model: &VoicevoxVoiceModel, ) -> VoicevoxResultCode { - into_result_code_with_error(RUNTIME.block_on(synthesizer.load_voice_model(model.model()))) + init_logger_once(); + into_result_code_with_error(synthesizer.load_voice_model(model.model())) } /// 音声モデルの読み込みを解除する。 @@ -392,6 +398,7 @@ pub unsafe extern "C" fn voicevox_synthesizer_unload_voice_model( synthesizer: &VoicevoxSynthesizer, model_id: VoicevoxVoiceModelId, ) -> VoicevoxResultCode { + init_logger_once(); into_result_code_with_error((|| { let raw_model_id = ensure_utf8(unsafe { CStr::from_ptr(model_id) })?; synthesizer @@ -411,6 +418,7 @@ pub unsafe extern "C" fn voicevox_synthesizer_unload_voice_model( /// } #[no_mangle] pub extern "C" fn voicevox_synthesizer_is_gpu_mode(synthesizer: &VoicevoxSynthesizer) -> bool { + init_logger_once(); synthesizer.synthesizer().is_gpu_mode() } @@ -430,6 +438,8 @@ pub unsafe extern "C" fn voicevox_synthesizer_is_loaded_voice_model( synthesizer: &VoicevoxSynthesizer, model_id: VoicevoxVoiceModelId, ) -> bool { + init_logger_once(); + // FIXME: 不正なUTF-8文字列に対し、正式なエラーとするか黙って`false`を返す let raw_model_id = ensure_utf8(unsafe { CStr::from_ptr(model_id) }).unwrap(); synthesizer .synthesizer() @@ -451,6 +461,7 @@ pub unsafe extern "C" fn voicevox_synthesizer_is_loaded_voice_model( pub extern "C" fn voicevox_synthesizer_create_metas_json( synthesizer: &VoicevoxSynthesizer, ) -> *mut c_char { + init_logger_once(); let metas = synthesizer.metas(); C_STRING_DROP_CHECKER.whitelist(metas).into_raw() } @@ -479,6 +490,7 @@ pub extern "C" fn voicevox_synthesizer_create_metas_json( pub unsafe extern "C" fn voicevox_create_supported_devices_json( output_supported_devices_json: NonNull<*mut c_char>, ) -> VoicevoxResultCode { + init_logger_once(); into_result_code_with_error((|| { let supported_devices = CString::new(SupportedDevices::create()?.to_json().to_string()).unwrap(); @@ -523,14 +535,14 @@ pub unsafe extern "C" fn voicevox_synthesizer_create_audio_query_from_kana( style_id: VoicevoxStyleId, output_audio_query_json: NonNull<*mut c_char>, ) -> VoicevoxResultCode { + init_logger_once(); into_result_code_with_error((|| { let kana = CStr::from_ptr(kana); let kana = ensure_utf8(kana)?; - let audio_query = RUNTIME.block_on( - synthesizer - .synthesizer() - .audio_query_from_kana(kana, StyleId::new(style_id)), - )?; + + let audio_query = synthesizer + .synthesizer() + .audio_query_from_kana(kana, StyleId::new(style_id))?; let audio_query = CString::new(audio_query_model_to_json(&audio_query)) .expect("should not contain '\\0'"); output_audio_query_json @@ -572,14 +584,14 @@ pub unsafe extern "C" fn voicevox_synthesizer_create_audio_query( style_id: VoicevoxStyleId, output_audio_query_json: NonNull<*mut c_char>, ) -> VoicevoxResultCode { + init_logger_once(); into_result_code_with_error((|| { let text = CStr::from_ptr(text); let text = ensure_utf8(text)?; - let audio_query = RUNTIME.block_on( - synthesizer - .synthesizer() - .audio_query(text, StyleId::new(style_id)), - )?; + + let audio_query = synthesizer + .synthesizer() + .audio_query(text, StyleId::new(style_id))?; let audio_query = CString::new(audio_query_model_to_json(&audio_query)) .expect("should not contain '\\0'"); output_audio_query_json @@ -622,13 +634,12 @@ pub unsafe extern "C" fn voicevox_synthesizer_create_accent_phrases_from_kana( style_id: VoicevoxStyleId, output_accent_phrases_json: NonNull<*mut c_char>, ) -> VoicevoxResultCode { + init_logger_once(); into_result_code_with_error((|| { let kana = ensure_utf8(CStr::from_ptr(kana))?; - let accent_phrases = RUNTIME.block_on( - synthesizer - .synthesizer() - .create_accent_phrases_from_kana(kana, StyleId::new(style_id)), - )?; + let accent_phrases = synthesizer + .synthesizer() + .create_accent_phrases_from_kana(kana, StyleId::new(style_id))?; let accent_phrases = CString::new(accent_phrases_to_json(&accent_phrases)) .expect("should not contain '\\0'"); output_accent_phrases_json @@ -670,13 +681,12 @@ pub unsafe extern "C" fn voicevox_synthesizer_create_accent_phrases( style_id: VoicevoxStyleId, output_accent_phrases_json: NonNull<*mut c_char>, ) -> VoicevoxResultCode { + init_logger_once(); into_result_code_with_error((|| { let text = ensure_utf8(CStr::from_ptr(text))?; - let accent_phrases = RUNTIME.block_on( - synthesizer - .synthesizer() - .create_accent_phrases(text, StyleId::new(style_id)), - )?; + let accent_phrases = synthesizer + .synthesizer() + .create_accent_phrases(text, StyleId::new(style_id))?; let accent_phrases = CString::new(accent_phrases_to_json(&accent_phrases)) .expect("should not contain '\\0'"); output_accent_phrases_json @@ -709,15 +719,14 @@ pub unsafe extern "C" fn voicevox_synthesizer_replace_mora_data( style_id: VoicevoxStyleId, output_accent_phrases_json: NonNull<*mut c_char>, ) -> VoicevoxResultCode { + init_logger_once(); into_result_code_with_error((|| { let accent_phrases: Vec = serde_json::from_str(ensure_utf8(CStr::from_ptr(accent_phrases_json))?) .map_err(CApiError::InvalidAccentPhrase)?; - let accent_phrases = RUNTIME.block_on( - synthesizer - .synthesizer() - .replace_mora_data(&accent_phrases, StyleId::new(style_id)), - )?; + let accent_phrases = synthesizer + .synthesizer() + .replace_mora_data(&accent_phrases, StyleId::new(style_id))?; let accent_phrases = CString::new(accent_phrases_to_json(&accent_phrases)) .expect("should not contain '\\0'"); output_accent_phrases_json @@ -750,15 +759,14 @@ pub unsafe extern "C" fn voicevox_synthesizer_replace_phoneme_length( style_id: VoicevoxStyleId, output_accent_phrases_json: NonNull<*mut c_char>, ) -> VoicevoxResultCode { + init_logger_once(); into_result_code_with_error((|| { let accent_phrases: Vec = serde_json::from_str(ensure_utf8(CStr::from_ptr(accent_phrases_json))?) .map_err(CApiError::InvalidAccentPhrase)?; - let accent_phrases = RUNTIME.block_on( - synthesizer - .synthesizer() - .replace_phoneme_length(&accent_phrases, StyleId::new(style_id)), - )?; + let accent_phrases = synthesizer + .synthesizer() + .replace_phoneme_length(&accent_phrases, StyleId::new(style_id))?; let accent_phrases = CString::new(accent_phrases_to_json(&accent_phrases)) .expect("should not contain '\\0'"); output_accent_phrases_json @@ -791,15 +799,14 @@ pub unsafe extern "C" fn voicevox_synthesizer_replace_mora_pitch( style_id: VoicevoxStyleId, output_accent_phrases_json: NonNull<*mut c_char>, ) -> VoicevoxResultCode { + init_logger_once(); into_result_code_with_error((|| { let accent_phrases: Vec = serde_json::from_str(ensure_utf8(CStr::from_ptr(accent_phrases_json))?) .map_err(CApiError::InvalidAccentPhrase)?; - let accent_phrases = RUNTIME.block_on( - synthesizer - .synthesizer() - .replace_mora_pitch(&accent_phrases, StyleId::new(style_id)), - )?; + let accent_phrases = synthesizer + .synthesizer() + .replace_mora_pitch(&accent_phrases, StyleId::new(style_id))?; let accent_phrases = CString::new(accent_phrases_to_json(&accent_phrases)) .expect("should not contain '\\0'"); output_accent_phrases_json @@ -820,6 +827,7 @@ pub struct VoicevoxSynthesisOptions { /// @return デフォルト値が設定された `voicevox_synthesizer_synthesis` のオプション #[no_mangle] pub extern "C" fn voicevox_make_default_synthesis_options() -> VoicevoxSynthesisOptions { + init_logger_once(); VoicevoxSynthesisOptions::default() } @@ -851,17 +859,18 @@ pub unsafe extern "C" fn voicevox_synthesizer_synthesis( output_wav_length: NonNull, output_wav: NonNull<*mut u8>, ) -> VoicevoxResultCode { + init_logger_once(); into_result_code_with_error((|| { let audio_query_json = CStr::from_ptr(audio_query_json) .to_str() .map_err(|_| CApiError::InvalidUtf8Input)?; let audio_query: AudioQueryModel = serde_json::from_str(audio_query_json).map_err(CApiError::InvalidAudioQuery)?; - let wav = RUNTIME.block_on(synthesizer.synthesizer().synthesis( + let wav = synthesizer.synthesizer().synthesis( &audio_query, StyleId::new(style_id), &SynthesisOptions::from(options), - ))?; + )?; U8_SLICE_OWNER.own_and_lend(wav, output_wav, output_wav_length); Ok(()) })()) @@ -878,6 +887,7 @@ pub struct VoicevoxTtsOptions { /// @return テキスト音声合成オプション #[no_mangle] pub extern "C" fn voicevox_make_default_tts_options() -> VoicevoxTtsOptions { + init_logger_once(); voicevox_core::TtsOptions::default().into() } @@ -909,13 +919,14 @@ pub unsafe extern "C" fn voicevox_synthesizer_tts_from_kana( output_wav_length: NonNull, output_wav: NonNull<*mut u8>, ) -> VoicevoxResultCode { + init_logger_once(); into_result_code_with_error((|| { let kana = ensure_utf8(CStr::from_ptr(kana))?; - let output = RUNTIME.block_on(synthesizer.synthesizer().tts_from_kana( + let output = synthesizer.synthesizer().tts_from_kana( kana, StyleId::new(style_id), &TtsOptions::from(options), - ))?; + )?; U8_SLICE_OWNER.own_and_lend(output, output_wav, output_wav_length); Ok(()) })()) @@ -949,13 +960,14 @@ pub unsafe extern "C" fn voicevox_synthesizer_tts( output_wav_length: NonNull, output_wav: NonNull<*mut u8>, ) -> VoicevoxResultCode { + init_logger_once(); into_result_code_with_error((|| { let text = ensure_utf8(CStr::from_ptr(text))?; - let output = RUNTIME.block_on(synthesizer.synthesizer().tts( + let output = synthesizer.synthesizer().tts( text, StyleId::new(style_id), &TtsOptions::from(options), - ))?; + )?; U8_SLICE_OWNER.own_and_lend(output, output_wav, output_wav_length); Ok(()) })()) @@ -981,6 +993,7 @@ pub unsafe extern "C" fn voicevox_synthesizer_tts( /// } #[no_mangle] pub unsafe extern "C" fn voicevox_json_free(json: *mut c_char) { + init_logger_once(); drop(CString::from_raw(C_STRING_DROP_CHECKER.check(json))); } @@ -997,6 +1010,7 @@ pub unsafe extern "C" fn voicevox_json_free(json: *mut c_char) { /// } #[no_mangle] pub extern "C" fn voicevox_wav_free(wav: *mut u8) { + init_logger_once(); U8_SLICE_OWNER.drop_for(wav); } @@ -1024,6 +1038,7 @@ pub extern "C" fn voicevox_wav_free(wav: *mut u8) { pub extern "C" fn voicevox_error_result_to_message( result_code: VoicevoxResultCode, ) -> *const c_char { + init_logger_once(); let message = result_code::error_result_to_message(result_code); C_STRING_DROP_CHECKER.blacklist(message).as_ptr() } @@ -1031,7 +1046,7 @@ pub extern "C" fn voicevox_error_result_to_message( /// ユーザー辞書。 #[derive(Default)] pub struct VoicevoxUserDict { - dict: Arc, + dict: Arc, } /// ユーザー辞書の単語。 @@ -1077,6 +1092,7 @@ pub extern "C" fn voicevox_user_dict_word_make( surface: *const c_char, pronunciation: *const c_char, ) -> VoicevoxUserDictWord { + init_logger_once(); VoicevoxUserDictWord { surface, pronunciation, @@ -1091,6 +1107,7 @@ pub extern "C" fn voicevox_user_dict_word_make( /// @returns ::VoicevoxUserDict #[no_mangle] pub extern "C" fn voicevox_user_dict_new() -> Box { + init_logger_once(); Default::default() } @@ -1109,9 +1126,10 @@ pub unsafe extern "C" fn voicevox_user_dict_load( user_dict: &VoicevoxUserDict, dict_path: *const c_char, ) -> VoicevoxResultCode { + init_logger_once(); into_result_code_with_error((|| { let dict_path = ensure_utf8(unsafe { CStr::from_ptr(dict_path) })?; - RUNTIME.block_on(user_dict.dict.load(dict_path))?; + user_dict.dict.load(dict_path)?; Ok(()) })()) @@ -1138,6 +1156,7 @@ pub unsafe extern "C" fn voicevox_user_dict_add_word( word: *const VoicevoxUserDictWord, output_word_uuid: NonNull<[u8; 16]>, ) -> VoicevoxResultCode { + init_logger_once(); into_result_code_with_error((|| { let word = word.read_unaligned().try_into_word()?; let uuid = user_dict.dict.add_word(word)?; @@ -1165,6 +1184,7 @@ pub unsafe extern "C" fn voicevox_user_dict_update_word( word_uuid: &[u8; 16], word: *const VoicevoxUserDictWord, ) -> VoicevoxResultCode { + init_logger_once(); into_result_code_with_error((|| { let word_uuid = Uuid::from_slice(word_uuid).map_err(CApiError::InvalidUuid)?; let word = word.read_unaligned().try_into_word()?; @@ -1189,6 +1209,7 @@ pub extern "C" fn voicevox_user_dict_remove_word( user_dict: &VoicevoxUserDict, word_uuid: &[u8; 16], ) -> VoicevoxResultCode { + init_logger_once(); into_result_code_with_error((|| { let word_uuid = Uuid::from_slice(word_uuid).map_err(CApiError::InvalidUuid)?; user_dict.dict.remove_word(word_uuid)?; @@ -1196,6 +1217,7 @@ pub extern "C" fn voicevox_user_dict_remove_word( })()) } +// FIXME: infallibleなので、`char*`を戻り値にしてもよいはず /// ユーザー辞書の単語をJSON形式で出力する。 /// /// 生成したJSON文字列を解放するには ::voicevox_json_free を使う。 @@ -1213,6 +1235,7 @@ pub unsafe extern "C" fn voicevox_user_dict_to_json( user_dict: &VoicevoxUserDict, output_json: NonNull<*mut c_char>, ) -> VoicevoxResultCode { + init_logger_once(); let json = user_dict.dict.to_json(); let json = CString::new(json).expect("\\0を含まない文字列であることが保証されている"); output_json @@ -1235,6 +1258,7 @@ pub extern "C" fn voicevox_user_dict_import( user_dict: &VoicevoxUserDict, other_dict: &VoicevoxUserDict, ) -> VoicevoxResultCode { + init_logger_once(); into_result_code_with_error((|| { user_dict.dict.import(&other_dict.dict)?; Ok(()) @@ -1255,9 +1279,10 @@ pub unsafe extern "C" fn voicevox_user_dict_save( user_dict: &VoicevoxUserDict, path: *const c_char, ) -> VoicevoxResultCode { + init_logger_once(); into_result_code_with_error((|| { let path = ensure_utf8(CStr::from_ptr(path))?; - RUNTIME.block_on(user_dict.dict.save(path))?; + user_dict.dict.save(path)?; Ok(()) })()) } @@ -1271,5 +1296,6 @@ pub unsafe extern "C" fn voicevox_user_dict_save( /// } #[no_mangle] pub unsafe extern "C" fn voicevox_user_dict_delete(user_dict: Box) { + init_logger_once(); drop(user_dict); } diff --git a/crates/voicevox_core_java_api/Cargo.toml b/crates/voicevox_core_java_api/Cargo.toml index e09ec29ad..887813685 100644 --- a/crates/voicevox_core_java_api/Cargo.toml +++ b/crates/voicevox_core_java_api/Cargo.toml @@ -17,7 +17,6 @@ derive_more.workspace = true jni.workspace = true once_cell.workspace = true serde_json = { workspace = true, features = ["preserve_order"] } -tokio = { workspace = true, features = ["rt", "rt-multi-thread"] } tracing = { workspace = true, features = ["log"] } tracing-subscriber = { workspace = true, features = ["env-filter"] } uuid.workspace = true diff --git a/crates/voicevox_core_java_api/lib/src/main/java/jp/hiroshiba/voicevoxcore/Dll.java b/crates/voicevox_core_java_api/lib/src/main/java/jp/hiroshiba/voicevoxcore/Dll.java index e4e674205..4e642bbda 100644 --- a/crates/voicevox_core_java_api/lib/src/main/java/jp/hiroshiba/voicevoxcore/Dll.java +++ b/crates/voicevox_core_java_api/lib/src/main/java/jp/hiroshiba/voicevoxcore/Dll.java @@ -64,5 +64,11 @@ abstract class Dll { throw new RuntimeException("Failed to load Voicevox Core DLL for " + target, e); } } + + new LoggerInitializer().initLogger(); + } + + static class LoggerInitializer { + native void initLogger(); } } diff --git a/crates/voicevox_core_java_api/src/common.rs b/crates/voicevox_core_java_api/src/common.rs index 138676a1d..c2987e207 100644 --- a/crates/voicevox_core_java_api/src/common.rs +++ b/crates/voicevox_core_java_api/src/common.rs @@ -1,11 +1,17 @@ use std::{error::Error as _, iter}; use derive_more::From; -use jni::{objects::JThrowable, JNIEnv}; -use once_cell::sync::Lazy; -use tokio::runtime::Runtime; - -pub static RUNTIME: Lazy = Lazy::new(|| { +use jni::{ + objects::{JObject, JThrowable}, + JNIEnv, +}; + +// FIXME: 別ファイルに分離する +#[no_mangle] +extern "system" fn Java_jp_hiroshiba_voicevoxcore_Dll_00024LoggerInitializer_initLogger( + _: JNIEnv<'_>, + _: JObject<'_>, +) { if cfg!(target_os = "android") { android_logger::init_once( android_logger::Config::default() @@ -25,6 +31,7 @@ pub static RUNTIME: Lazy = Lazy::new(|| { }; use tracing_subscriber::{fmt::format::Writer, EnvFilter}; + // FIXME: `try_init` → `init` (subscriberは他に存在しないはずなので) let _ = tracing_subscriber::fmt() .with_env_filter(if env::var_os(EnvFilter::DEFAULT_ENV).is_some() { EnvFilter::from_default_env() @@ -57,8 +64,7 @@ pub static RUNTIME: Lazy = Lazy::new(|| { ) && env::var_os("NO_COLOR").is_none() } } - Runtime::new().unwrap() -}); +} #[macro_export] macro_rules! object { diff --git a/crates/voicevox_core_java_api/src/open_jtalk.rs b/crates/voicevox_core_java_api/src/open_jtalk.rs index b2242e984..905baa2b1 100644 --- a/crates/voicevox_core_java_api/src/open_jtalk.rs +++ b/crates/voicevox_core_java_api/src/open_jtalk.rs @@ -1,6 +1,6 @@ use std::{borrow::Cow, sync::Arc}; -use crate::common::{throw_if_err, RUNTIME}; +use crate::common::throw_if_err; use jni::{ objects::{JObject, JString}, JNIEnv, @@ -16,8 +16,7 @@ unsafe extern "system" fn Java_jp_hiroshiba_voicevoxcore_OpenJtalk_rsNew<'local> let open_jtalk_dict_dir = env.get_string(&open_jtalk_dict_dir)?; let open_jtalk_dict_dir = &*Cow::from(&open_jtalk_dict_dir); - let internal = - RUNTIME.block_on(voicevox_core::tokio::OpenJtalk::new(open_jtalk_dict_dir))?; + let internal = voicevox_core::blocking::OpenJtalk::new(open_jtalk_dict_dir)?; env.set_rust_field(&this, "handle", internal)?; Ok(()) @@ -32,14 +31,14 @@ unsafe extern "system" fn Java_jp_hiroshiba_voicevoxcore_OpenJtalk_rsUseUserDict ) { throw_if_err(env, (), |env| { let internal = env - .get_rust_field::<_, _, voicevox_core::tokio::OpenJtalk>(&this, "handle")? + .get_rust_field::<_, _, voicevox_core::blocking::OpenJtalk>(&this, "handle")? .clone(); let user_dict = env - .get_rust_field::<_, _, Arc>(&user_dict, "handle")? + .get_rust_field::<_, _, Arc>(&user_dict, "handle")? .clone(); - RUNTIME.block_on(internal.use_user_dict(&user_dict))?; + internal.use_user_dict(&user_dict)?; Ok(()) }) diff --git a/crates/voicevox_core_java_api/src/synthesizer.rs b/crates/voicevox_core_java_api/src/synthesizer.rs index e36e0b9c2..fee5bc132 100644 --- a/crates/voicevox_core_java_api/src/synthesizer.rs +++ b/crates/voicevox_core_java_api/src/synthesizer.rs @@ -1,5 +1,5 @@ use crate::{ - common::{throw_if_err, JavaApiError, RUNTIME}, + common::{throw_if_err, JavaApiError}, enum_object, object, object_type, }; @@ -18,10 +18,6 @@ unsafe extern "system" fn Java_jp_hiroshiba_voicevoxcore_Synthesizer_rsNew<'loca builder: JObject<'local>, ) { throw_if_err(env, (), |env| { - // ロガーを起動 - // FIXME: `throw_if_err`を`run`とかに改名し、`init_logger`をその中に移動 - let _ = *RUNTIME; - let mut options = voicevox_core::InitializeOptions::default(); let acceleration_mode = env @@ -50,10 +46,11 @@ unsafe extern "system" fn Java_jp_hiroshiba_voicevoxcore_Synthesizer_rsNew<'loca options.cpu_num_threads = cpu_num_threads.i().expect("cpuNumThreads is not integer") as u16; let open_jtalk = env - .get_rust_field::<_, _, voicevox_core::tokio::OpenJtalk>(&open_jtalk, "handle")? + .get_rust_field::<_, _, voicevox_core::blocking::OpenJtalk>(&open_jtalk, "handle")? .clone(); - let internal = - voicevox_core::tokio::Synthesizer::new(open_jtalk, Box::leak(Box::new(options)))?; + let internal = Arc::new(voicevox_core::blocking::Synthesizer::new( + open_jtalk, &options, + )?); env.set_rust_field(&this, "handle", internal)?; Ok(()) }) @@ -65,7 +62,7 @@ unsafe extern "system" fn Java_jp_hiroshiba_voicevoxcore_Synthesizer_rsIsGpuMode ) -> jboolean { throw_if_err(env, false, |env| { let internal = env - .get_rust_field::<_, _, voicevox_core::tokio::Synthesizer>( + .get_rust_field::<_, _, Arc>>( &this, "handle", )? .clone(); @@ -81,7 +78,7 @@ unsafe extern "system" fn Java_jp_hiroshiba_voicevoxcore_Synthesizer_rsGetMetasJ ) -> jobject { throw_if_err(env, std::ptr::null_mut(), |env| { let internal = env - .get_rust_field::<_, _, voicevox_core::tokio::Synthesizer>( + .get_rust_field::<_, _, Arc>>( &this, "handle", )? .clone(); @@ -102,14 +99,14 @@ unsafe extern "system" fn Java_jp_hiroshiba_voicevoxcore_Synthesizer_rsLoadVoice ) { throw_if_err(env, (), |env| { let model = env - .get_rust_field::<_, _, Arc>(&model, "handle")? + .get_rust_field::<_, _, Arc>(&model, "handle")? .clone(); let internal = env - .get_rust_field::<_, _, voicevox_core::tokio::Synthesizer>( + .get_rust_field::<_, _, Arc>>( &this, "handle", )? .clone(); - RUNTIME.block_on(internal.load_voice_model(&model))?; + internal.load_voice_model(&model)?; Ok(()) }) } @@ -124,7 +121,7 @@ unsafe extern "system" fn Java_jp_hiroshiba_voicevoxcore_Synthesizer_rsUnloadVoi let model_id: String = env.get_string(&model_id)?.into(); let internal = env - .get_rust_field::<_, _, voicevox_core::tokio::Synthesizer>( + .get_rust_field::<_, _, Arc>>( &this, "handle", )? .clone(); @@ -147,7 +144,7 @@ unsafe extern "system" fn Java_jp_hiroshiba_voicevoxcore_Synthesizer_rsIsLoadedV let model_id: String = env.get_string(&model_id)?.into(); let internal = env - .get_rust_field::<_, _, voicevox_core::tokio::Synthesizer>( + .get_rust_field::<_, _, Arc>>( &this, "handle", )? .clone(); @@ -173,14 +170,13 @@ unsafe extern "system" fn Java_jp_hiroshiba_voicevoxcore_Synthesizer_rsAudioQuer let style_id = style_id as u32; let internal = env - .get_rust_field::<_, _, voicevox_core::tokio::Synthesizer>( + .get_rust_field::<_, _, Arc>>( &this, "handle", )? .clone(); - let audio_query = RUNTIME.block_on( - internal.audio_query_from_kana(&kana, voicevox_core::StyleId::new(style_id)), - )?; + let audio_query = + internal.audio_query_from_kana(&kana, voicevox_core::StyleId::new(style_id))?; let query_json = serde_json::to_string(&audio_query).expect("should not fail"); @@ -202,13 +198,12 @@ unsafe extern "system" fn Java_jp_hiroshiba_voicevoxcore_Synthesizer_rsAudioQuer let style_id = style_id as u32; let internal = env - .get_rust_field::<_, _, voicevox_core::tokio::Synthesizer>( + .get_rust_field::<_, _, Arc>>( &this, "handle", )? .clone(); - let audio_query = - RUNTIME.block_on(internal.audio_query(&text, voicevox_core::StyleId::new(style_id)))?; + let audio_query = internal.audio_query(&text, voicevox_core::StyleId::new(style_id))?; let query_json = serde_json::to_string(&audio_query).expect("should not fail"); @@ -232,14 +227,13 @@ unsafe extern "system" fn Java_jp_hiroshiba_voicevoxcore_Synthesizer_rsAccentPhr let style_id = style_id as u32; let internal = env - .get_rust_field::<_, _, voicevox_core::tokio::Synthesizer>( + .get_rust_field::<_, _, Arc>>( &this, "handle", )? .clone(); - let accent_phrases = RUNTIME.block_on( - internal.create_accent_phrases_from_kana(&kana, voicevox_core::StyleId::new(style_id)), - )?; + let accent_phrases = internal + .create_accent_phrases_from_kana(&kana, voicevox_core::StyleId::new(style_id))?; let query_json = serde_json::to_string(&accent_phrases).expect("should not fail"); @@ -261,14 +255,13 @@ unsafe extern "system" fn Java_jp_hiroshiba_voicevoxcore_Synthesizer_rsAccentPhr let style_id = style_id as u32; let internal = env - .get_rust_field::<_, _, voicevox_core::tokio::Synthesizer>( + .get_rust_field::<_, _, Arc>>( &this, "handle", )? .clone(); - let accent_phrases = RUNTIME.block_on( - internal.create_accent_phrases(&text, voicevox_core::StyleId::new(style_id)), - )?; + let accent_phrases = + internal.create_accent_phrases(&text, voicevox_core::StyleId::new(style_id))?; let query_json = serde_json::to_string(&accent_phrases).expect("should not fail"); @@ -292,14 +285,13 @@ unsafe extern "system" fn Java_jp_hiroshiba_voicevoxcore_Synthesizer_rsReplaceMo let style_id = style_id as u32; let internal = env - .get_rust_field::<_, _, voicevox_core::tokio::Synthesizer>( + .get_rust_field::<_, _, Arc>>( &this, "handle", )? .clone(); - let replaced_accent_phrases = RUNTIME.block_on( - internal.replace_mora_data(&accent_phrases, voicevox_core::StyleId::new(style_id)), - )?; + let replaced_accent_phrases = + internal.replace_mora_data(&accent_phrases, voicevox_core::StyleId::new(style_id))?; let replaced_accent_phrases_json = serde_json::to_string(&replaced_accent_phrases).expect("should not fail"); @@ -324,17 +316,13 @@ unsafe extern "system" fn Java_jp_hiroshiba_voicevoxcore_Synthesizer_rsReplacePh let style_id = style_id as u32; let internal = env - .get_rust_field::<_, _, voicevox_core::tokio::Synthesizer>( + .get_rust_field::<_, _, Arc>>( &this, "handle", )? .clone(); - let replaced_accent_phrases = { - RUNTIME.block_on( - internal - .replace_phoneme_length(&accent_phrases, voicevox_core::StyleId::new(style_id)), - )? - }; + let replaced_accent_phrases = internal + .replace_phoneme_length(&accent_phrases, voicevox_core::StyleId::new(style_id))?; let replaced_accent_phrases_json = serde_json::to_string(&replaced_accent_phrases).expect("should not fail"); @@ -357,14 +345,13 @@ unsafe extern "system" fn Java_jp_hiroshiba_voicevoxcore_Synthesizer_rsReplaceMo let style_id = style_id as u32; let internal = env - .get_rust_field::<_, _, voicevox_core::tokio::Synthesizer>( + .get_rust_field::<_, _, Arc>>( &this, "handle", )? .clone(); - let replaced_accent_phrases = RUNTIME.block_on( - internal.replace_mora_pitch(&accent_phrases, voicevox_core::StyleId::new(style_id)), - )?; + let replaced_accent_phrases = + internal.replace_mora_pitch(&accent_phrases, voicevox_core::StyleId::new(style_id))?; let replaced_accent_phrases_json = serde_json::to_string(&replaced_accent_phrases).expect("should not fail"); @@ -388,7 +375,7 @@ unsafe extern "system" fn Java_jp_hiroshiba_voicevoxcore_Synthesizer_rsSynthesis let style_id = style_id as u32; let internal = env - .get_rust_field::<_, _, voicevox_core::tokio::Synthesizer>( + .get_rust_field::<_, _, Arc>>( &this, "handle", )? .clone(); @@ -398,11 +385,11 @@ unsafe extern "system" fn Java_jp_hiroshiba_voicevoxcore_Synthesizer_rsSynthesis enable_interrogative_upspeak: enable_interrogative_upspeak != 0, // ..Default::default() }; - RUNTIME.block_on(internal.synthesis( + internal.synthesis( &audio_query, voicevox_core::StyleId::new(style_id), &options, - ))? + )? }; let j_bytes = env.byte_array_from_slice(&wave)?; @@ -424,7 +411,7 @@ unsafe extern "system" fn Java_jp_hiroshiba_voicevoxcore_Synthesizer_rsTtsFromKa let style_id = style_id as u32; let internal = env - .get_rust_field::<_, _, voicevox_core::tokio::Synthesizer>( + .get_rust_field::<_, _, Arc>>( &this, "handle", )? .clone(); @@ -434,11 +421,7 @@ unsafe extern "system" fn Java_jp_hiroshiba_voicevoxcore_Synthesizer_rsTtsFromKa enable_interrogative_upspeak: enable_interrogative_upspeak != 0, // ..Default::default() }; - RUNTIME.block_on(internal.tts_from_kana( - &kana, - voicevox_core::StyleId::new(style_id), - &options, - ))? + internal.tts_from_kana(&kana, voicevox_core::StyleId::new(style_id), &options)? }; let j_bytes = env.byte_array_from_slice(&wave)?; @@ -460,7 +443,7 @@ unsafe extern "system" fn Java_jp_hiroshiba_voicevoxcore_Synthesizer_rsTts<'loca let style_id = style_id as u32; let internal = env - .get_rust_field::<_, _, voicevox_core::tokio::Synthesizer>( + .get_rust_field::<_, _, Arc>>( &this, "handle", )? .clone(); @@ -470,11 +453,7 @@ unsafe extern "system" fn Java_jp_hiroshiba_voicevoxcore_Synthesizer_rsTts<'loca enable_interrogative_upspeak: enable_interrogative_upspeak != 0, // ..Default::default() }; - RUNTIME.block_on(internal.tts( - &text, - voicevox_core::StyleId::new(style_id), - &options, - ))? + internal.tts(&text, voicevox_core::StyleId::new(style_id), &options)? }; let j_bytes = env.byte_array_from_slice(&wave)?; diff --git a/crates/voicevox_core_java_api/src/user_dict.rs b/crates/voicevox_core_java_api/src/user_dict.rs index 7eb2722f4..df8b8270b 100644 --- a/crates/voicevox_core_java_api/src/user_dict.rs +++ b/crates/voicevox_core_java_api/src/user_dict.rs @@ -1,7 +1,7 @@ use jni::objects::JClass; use std::{borrow::Cow, sync::Arc}; -use crate::common::{throw_if_err, JavaApiError, RUNTIME}; +use crate::common::{throw_if_err, JavaApiError}; use jni::{ objects::{JObject, JString}, sys::jobject, @@ -14,7 +14,7 @@ unsafe extern "system" fn Java_jp_hiroshiba_voicevoxcore_UserDict_rsNew<'local>( this: JObject<'local>, ) { throw_if_err(env, (), |env| { - let internal = voicevox_core::tokio::UserDict::new(); + let internal = voicevox_core::blocking::UserDict::new(); env.set_rust_field(&this, "handle", Arc::new(internal))?; @@ -30,7 +30,7 @@ unsafe extern "system" fn Java_jp_hiroshiba_voicevoxcore_UserDict_rsAddWord<'loc ) -> jobject { throw_if_err(env, std::ptr::null_mut(), |env| { let internal = env - .get_rust_field::<_, _, Arc>(&this, "handle")? + .get_rust_field::<_, _, Arc>(&this, "handle")? .clone(); let word_json = env.get_string(&word_json)?; @@ -55,7 +55,7 @@ unsafe extern "system" fn Java_jp_hiroshiba_voicevoxcore_UserDict_rsUpdateWord<' ) { throw_if_err(env, (), |env| { let internal = env - .get_rust_field::<_, _, Arc>(&this, "handle")? + .get_rust_field::<_, _, Arc>(&this, "handle")? .clone(); let uuid = env.get_string(&uuid)?; @@ -80,7 +80,7 @@ unsafe extern "system" fn Java_jp_hiroshiba_voicevoxcore_UserDict_rsRemoveWord<' ) { throw_if_err(env, (), |env| { let internal = env - .get_rust_field::<_, _, Arc>(&this, "handle")? + .get_rust_field::<_, _, Arc>(&this, "handle")? .clone(); let uuid = env.get_string(&uuid)?; @@ -100,10 +100,10 @@ unsafe extern "system" fn Java_jp_hiroshiba_voicevoxcore_UserDict_rsImportDict<' ) { throw_if_err(env, (), |env| { let internal = env - .get_rust_field::<_, _, Arc>(&this, "handle")? + .get_rust_field::<_, _, Arc>(&this, "handle")? .clone(); let other_dict = env - .get_rust_field::<_, _, Arc>(&other_dict, "handle")? + .get_rust_field::<_, _, Arc>(&other_dict, "handle")? .clone(); internal.import(&other_dict)?; @@ -120,13 +120,13 @@ unsafe extern "system" fn Java_jp_hiroshiba_voicevoxcore_UserDict_rsLoad<'local> ) { throw_if_err(env, (), |env| { let internal = env - .get_rust_field::<_, _, Arc>(&this, "handle")? + .get_rust_field::<_, _, Arc>(&this, "handle")? .clone(); let path = env.get_string(&path)?; let path = &Cow::from(&path); - RUNTIME.block_on(internal.load(path))?; + internal.load(path)?; Ok(()) }) @@ -140,13 +140,13 @@ unsafe extern "system" fn Java_jp_hiroshiba_voicevoxcore_UserDict_rsSave<'local> ) { throw_if_err(env, (), |env| { let internal = env - .get_rust_field::<_, _, Arc>(&this, "handle")? + .get_rust_field::<_, _, Arc>(&this, "handle")? .clone(); let path = env.get_string(&path)?; let path = &Cow::from(&path); - RUNTIME.block_on(internal.save(path))?; + internal.save(path)?; Ok(()) }) @@ -159,7 +159,7 @@ unsafe extern "system" fn Java_jp_hiroshiba_voicevoxcore_UserDict_rsGetWords<'lo ) -> jobject { throw_if_err(env, std::ptr::null_mut(), |env| { let internal = env - .get_rust_field::<_, _, Arc>(&this, "handle")? + .get_rust_field::<_, _, Arc>(&this, "handle")? .clone(); let words = internal.to_json(); diff --git a/crates/voicevox_core_java_api/src/voice_model.rs b/crates/voicevox_core_java_api/src/voice_model.rs index d0ede9365..42a20544a 100644 --- a/crates/voicevox_core_java_api/src/voice_model.rs +++ b/crates/voicevox_core_java_api/src/voice_model.rs @@ -1,6 +1,6 @@ use std::{borrow::Cow, sync::Arc}; -use crate::common::{throw_if_err, RUNTIME}; +use crate::common::throw_if_err; use jni::{ objects::{JObject, JString}, sys::jobject, @@ -17,7 +17,7 @@ unsafe extern "system" fn Java_jp_hiroshiba_voicevoxcore_VoiceModel_rsFromPath<' let model_path = env.get_string(&model_path)?; let model_path = &*Cow::from(&model_path); - let internal = RUNTIME.block_on(voicevox_core::tokio::VoiceModel::from_path(model_path))?; + let internal = voicevox_core::blocking::VoiceModel::from_path(model_path)?; env.set_rust_field(&this, "handle", Arc::new(internal))?; @@ -32,7 +32,7 @@ unsafe extern "system" fn Java_jp_hiroshiba_voicevoxcore_VoiceModel_rsGetId<'loc ) -> jobject { throw_if_err(env, std::ptr::null_mut(), |env| { let internal = env - .get_rust_field::<_, _, Arc>(&this, "handle")? + .get_rust_field::<_, _, Arc>(&this, "handle")? .clone(); let id = internal.id().raw_voice_model_id(); @@ -50,7 +50,7 @@ unsafe extern "system" fn Java_jp_hiroshiba_voicevoxcore_VoiceModel_rsGetMetasJs ) -> jobject { throw_if_err(env, std::ptr::null_mut(), |env| { let internal = env - .get_rust_field::<_, _, Arc>(&this, "handle")? + .get_rust_field::<_, _, Arc>(&this, "handle")? .clone(); let metas = internal.metas();