From 96d0c639969aeba30bd72a1f575e48d56d419fe9 Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Sat, 7 Nov 2026 15:43:22 -0500 Subject: [PATCH 1/3] Regenerate llama.cpp bindings from native v0.9.0 candidate headers Generated from llamadart-native main eb760895 (llama.cpp cd959bae) headers, packaged as the release workflow does, with native_header_archive.py and ffigen in a Linux container. The same procedure reproduces the committed v0.8.0-3 bindings byte for byte. --- lib/src/backends/llama_cpp/bindings.dart | 265 ++++++++++++++++++++++- 1 file changed, 255 insertions(+), 10 deletions(-) diff --git a/lib/src/backends/llama_cpp/bindings.dart b/lib/src/backends/llama_cpp/bindings.dart index 5eb95a35a..6d67882b3 100644 --- a/lib/src/backends/llama_cpp/bindings.dart +++ b/lib/src/backends/llama_cpp/bindings.dart @@ -1051,6 +1051,19 @@ external void ggml_backend_tensor_copy_async( ffi.Pointer dst, ); +@ffi.Native< + ffi.Void Function( + ffi.Pointer>, + ffi.Pointer>, + ffi.Size, + ) +>() +external void ggml_backend_tensor_copy_n( + ffi.Pointer> srcs, + ffi.Pointer> dsts, + int n_tensors, +); + @ffi.Native< ffi.Void Function( ffi.Pointer, @@ -1127,6 +1140,25 @@ external void ggml_backend_tensor_get_async( int size, ); +@ffi.Native< + ffi.Void Function( + ffi.Pointer>, + ffi.Pointer, + ffi.Pointer, + ffi.Pointer, + ffi.Pointer, + ffi.Size, + ) +>() +external void ggml_backend_tensor_get_n( + ffi.Pointer> tensors, + ffi.Pointer data, + ffi.Pointer offsets, + ffi.Pointer sizes, + ffi.Pointer data_offsets, + int n_tensors, +); + @ffi.Native< ffi.Void Function(ffi.Pointer, ffi.Uint8, ffi.Size, ffi.Size) >() @@ -1213,6 +1245,25 @@ external void ggml_backend_tensor_set_async( int size, ); +@ffi.Native< + ffi.Void Function( + ffi.Pointer>, + ffi.Pointer, + ffi.Pointer, + ffi.Pointer, + ffi.Pointer, + ffi.Size, + ) +>() +external void ggml_backend_tensor_set_n( + ffi.Pointer> tensors, + ffi.Pointer data, + ffi.Pointer offsets, + ffi.Pointer sizes, + ffi.Pointer data_offsets, + int n_tensors, +); + @ffi.Native() external void ggml_backend_unload(ggml_backend_reg_t reg); @@ -2292,6 +2343,31 @@ ggml_prec ggml_flash_attn_ext_get_prec(ffi.Pointer a) { return ggml_prec.fromValue(_ggml_flash_attn_ext_get_prec(a)); } +@ffi.Native< + ffi.Pointer Function( + ffi.Pointer, + ffi.Pointer, + ffi.Pointer, + ffi.Pointer, + ffi.Pointer, + ffi.Pointer, + ffi.Float, + ffi.Float, + ffi.Float, + ) +>() +external ffi.Pointer ggml_flash_attn_ext_rows( + ffi.Pointer ctx, + ffi.Pointer q, + ffi.Pointer k, + ffi.Pointer v, + ffi.Pointer mask, + ffi.Pointer kv_rows, + double scale, + double max_bias, + double logit_softcap, +); + @ffi.Native, ffi.Int32)>() external void ggml_flash_attn_ext_set_n_kv_max( ffi.Pointer a, @@ -7020,6 +7096,68 @@ llama_dart_tts_status llama_dart_tts_get_output_info( ); } +@ffi.Native< + ffi.Int Function( + ffi.Pointer, + ffi.Uint32, + ffi.Pointer, + ) +>(symbol: 'llama_dart_tts_get_voice_count') +external int _llama_dart_tts_get_voice_count( + ffi.Pointer mtmd, + int accepted_model_types, + ffi.Pointer out_count, +); + +llama_dart_tts_status llama_dart_tts_get_voice_count( + ffi.Pointer mtmd, + int accepted_model_types, + ffi.Pointer out_count, +) { + return llama_dart_tts_status.fromValue( + _llama_dart_tts_get_voice_count(mtmd, accepted_model_types, out_count), + ); +} + +@ffi.Native< + ffi.Int Function( + ffi.Pointer, + ffi.Uint32, + ffi.Int32, + ffi.Pointer, + ffi.Size, + ffi.Pointer, + ) +>(symbol: 'llama_dart_tts_get_voice_name') +external int _llama_dart_tts_get_voice_name( + ffi.Pointer mtmd, + int accepted_model_types, + int index, + ffi.Pointer out_name, + int out_capacity, + ffi.Pointer out_length, +); + +llama_dart_tts_status llama_dart_tts_get_voice_name( + ffi.Pointer mtmd, + int accepted_model_types, + int index, + ffi.Pointer out_name, + int out_capacity, + ffi.Pointer out_length, +) { + return llama_dart_tts_status.fromValue( + _llama_dart_tts_get_voice_name( + mtmd, + accepted_model_types, + index, + out_name, + out_capacity, + out_length, + ), + ); +} + @ffi.Native< ffi.Pointer Function( ffi.Pointer, @@ -9003,6 +9141,9 @@ external ffi.Pointer mtmd_bitmap_init_lazy( @ffi.Native)>() external bool mtmd_bitmap_is_audio(ffi.Pointer bitmap); +@ffi.Native)>() +external bool mtmd_bitmap_is_voice(ffi.Pointer bitmap); + @ffi.Native< ffi.Void Function(ffi.Pointer, ffi.Pointer) >() @@ -9065,6 +9206,17 @@ external mtmd_gen_audio_info mtmd_gen_audio_get_info( ffi.Pointer ctx, ); +@ffi.Native< + ffi.Pointer Function( + ffi.Pointer, + ffi.Pointer, + ) +>() +external ffi.Pointer mtmd_gen_audio_get_voice( + ffi.Pointer ctx, + ffi.Pointer name, +); + @ffi.Native< ffi.Int32 Function( ffi.Pointer, @@ -9080,6 +9232,29 @@ external int mtmd_gen_audio_process( ffi.Pointer out, ); +@ffi.Native< + ffi.Size Function( + ffi.Pointer, + ffi.Pointer, + ffi.Pointer, + ffi.Size, + ) +>() +external int mtmd_gen_audio_read_tensor( + ffi.Pointer ctx, + ffi.Pointer name, + ffi.Pointer out, + int n_max, +); + +@ffi.Native< + ffi.Pointer Function(ffi.Pointer, ffi.Int32) +>() +external ffi.Pointer mtmd_gen_audio_voice_name( + ffi.Pointer ctx, + int idx, +); + @ffi.Native)>() external mtmd_gen_inp mtmd_gen_inp_default(ffi.Pointer ctx); @@ -9103,6 +9278,14 @@ external mtmd_gen_state_params mtmd_gen_state_params_default(); @ffi.Native)>() external void mtmd_gen_state_reset(ffi.Pointer state); +@ffi.Native< + ffi.Int32 Function(ffi.Pointer, ffi.Pointer) +>() +external int mtmd_gen_state_set_ref( + ffi.Pointer ctx, + ffi.Pointer state, +); + @ffi.Native)>() external int mtmd_get_audio_sample_rate(ffi.Pointer ctx); @@ -9852,12 +10035,48 @@ typedef Dartggml_backend_comm_allreduce_tensor_tFunction = ffi.Pointer comm_ctx, ffi.Pointer> tensors, ); +typedef ggml_backend_comm_bootstrap_callback = + ffi.Pointer< + ffi.NativeFunction + >; +typedef ggml_backend_comm_bootstrap_callbackFunction = + ffi.Bool Function( + ffi.Pointer user_data, + ffi.Pointer send_buf, + ffi.Pointer recv_buf, + ffi.Size size, + ); +typedef Dartggml_backend_comm_bootstrap_callbackFunction = + bool Function( + ffi.Pointer user_data, + ffi.Pointer send_buf, + ffi.Pointer recv_buf, + int size, + ); typedef ggml_backend_comm_free_t = ffi.Pointer>; typedef ggml_backend_comm_free_tFunction = ffi.Void Function(ffi.Pointer comm_ctx); typedef Dartggml_backend_comm_free_tFunction = void Function(ffi.Pointer comm_ctx); +typedef ggml_backend_comm_init_rank_t = + ffi.Pointer>; +typedef ggml_backend_comm_init_rank_tFunction = + ffi.Pointer Function( + ggml_backend_t backend, + ffi.Int rank, + ffi.Int world_size, + ggml_backend_comm_bootstrap_callback bootstrap_callback, + ffi.Pointer bootstrap_callback_data, + ); +typedef Dartggml_backend_comm_init_rank_tFunction = + ffi.Pointer Function( + ggml_backend_t backend, + int rank, + int world_size, + ggml_backend_comm_bootstrap_callback bootstrap_callback, + ffi.Pointer bootstrap_callback_data, + ); typedef ggml_backend_comm_init_t = ffi.Pointer>; typedef ggml_backend_comm_init_tFunction = @@ -10257,6 +10476,17 @@ typedef Dartggml_custom_op_tFunction = ); typedef ggml_fp16_t = ffi.Uint16; typedef Dartggml_fp16_t = int; + +final class ggml_fp8_e4m3_t extends ffi.Struct { + @ffi.Uint8() + external int bits; + + static ffi.Pointer $allocate( + ffi.Allocator $allocator, { + required int bits, + }) => $allocator()..ref.bits = bits; +} + typedef ggml_from_float_t = ffi.Pointer>; typedef ggml_from_float_tFunction = @@ -10296,7 +10526,8 @@ enum ggml_ftype { GGML_FTYPE_MOSTLY_MXFP4(25), GGML_FTYPE_MOSTLY_NVFP4(26), GGML_FTYPE_MOSTLY_Q1_0(27), - GGML_FTYPE_MOSTLY_Q2_0(28); + GGML_FTYPE_MOSTLY_Q2_0(28), + GGML_FTYPE_MOSTLY_F8_E4M3(29); final int value; const ggml_ftype(this.value); @@ -10330,6 +10561,7 @@ enum ggml_ftype { 26 => GGML_FTYPE_MOSTLY_NVFP4, 27 => GGML_FTYPE_MOSTLY_Q1_0, 28 => GGML_FTYPE_MOSTLY_Q2_0, + 29 => GGML_FTYPE_MOSTLY_F8_E4M3, _ => throw ArgumentError('Unknown value for ggml_ftype: $value'), }; } @@ -11039,7 +11271,8 @@ enum ggml_type { GGML_TYPE_NVFP4(40), GGML_TYPE_Q1_0(41), GGML_TYPE_Q2_0(42), - GGML_TYPE_COUNT(43); + GGML_TYPE_F8_E4M3(43), + GGML_TYPE_COUNT(44); final int value; const ggml_type(this.value); @@ -11080,7 +11313,8 @@ enum ggml_type { 40 => GGML_TYPE_NVFP4, 41 => GGML_TYPE_Q1_0, 42 => GGML_TYPE_Q2_0, - 43 => GGML_TYPE_COUNT, + 43 => GGML_TYPE_F8_E4M3, + 44 => GGML_TYPE_COUNT, _ => throw ArgumentError('Unknown value for ggml_type: $value'), }; } @@ -11704,6 +11938,8 @@ enum llama_dart_tts_model_type { LLAMA_DART_TTS_MODEL_TYPE_QWEN3(1), LLAMA_DART_TTS_MODEL_TYPE_LFM3_AUDIO(2), LLAMA_DART_TTS_MODEL_TYPE_SOPRANO(3), + LLAMA_DART_TTS_MODEL_TYPE_CHATTERBOX(4), + LLAMA_DART_TTS_MODEL_TYPE_POCKET_TTS(5), LLAMA_DART_TTS_MODEL_TYPE_UNKNOWN(255); final int value; @@ -11714,6 +11950,8 @@ enum llama_dart_tts_model_type { 1 => LLAMA_DART_TTS_MODEL_TYPE_QWEN3, 2 => LLAMA_DART_TTS_MODEL_TYPE_LFM3_AUDIO, 3 => LLAMA_DART_TTS_MODEL_TYPE_SOPRANO, + 4 => LLAMA_DART_TTS_MODEL_TYPE_CHATTERBOX, + 5 => LLAMA_DART_TTS_MODEL_TYPE_POCKET_TTS, 255 => LLAMA_DART_TTS_MODEL_TYPE_UNKNOWN, _ => throw ArgumentError( 'Unknown value for llama_dart_tts_model_type: $value', @@ -12026,6 +12264,7 @@ enum llama_ftype { LLAMA_FTYPE_MOSTLY_NVFP4(39), LLAMA_FTYPE_MOSTLY_Q1_0(40), LLAMA_FTYPE_MOSTLY_Q2_0(41), + LLAMA_FTYPE_MOSTLY_F8_E4M3(42), LLAMA_FTYPE_GUESSED(1024); final int value; @@ -12068,6 +12307,7 @@ enum llama_ftype { 39 => LLAMA_FTYPE_MOSTLY_NVFP4, 40 => LLAMA_FTYPE_MOSTLY_Q1_0, 41 => LLAMA_FTYPE_MOSTLY_Q2_0, + 42 => LLAMA_FTYPE_MOSTLY_F8_E4M3, 1024 => LLAMA_FTYPE_GUESSED, _ => throw ArgumentError('Unknown value for llama_ftype: $value'), }; @@ -13270,15 +13510,20 @@ final class mtmd_gen_audio_info extends ffi.Struct { external ffi.Pointer model_variant; + @ffi.Int32() + external int n_voices; + static ffi.Pointer $allocate( ffi.Allocator $allocator, { required mtmd_gen_audio_type type, required int sample_rate, required ffi.Pointer model_variant, + required int n_voices, }) => $allocator() ..ref.type = type ..ref.sample_rate = sample_rate - ..ref.model_variant = model_variant; + ..ref.model_variant = model_variant + ..ref.n_voices = n_voices; } /// ////////////////////////////////////// @@ -13287,7 +13532,8 @@ enum mtmd_gen_audio_type { MTMD_GEN_AUDIO_TYPE_QWEN3TTS(1), MTMD_GEN_AUDIO_TYPE_POCKETTTS(2), MTMD_GEN_AUDIO_TYPE_SOPRANO(3), - MTMD_GEN_AUDIO_TYPE_LFM3A(4); + MTMD_GEN_AUDIO_TYPE_LFM3A(4), + MTMD_GEN_AUDIO_TYPE_CHATTERBOX(5); final int value; const mtmd_gen_audio_type(this.value); @@ -13298,6 +13544,7 @@ enum mtmd_gen_audio_type { 2 => MTMD_GEN_AUDIO_TYPE_POCKETTTS, 3 => MTMD_GEN_AUDIO_TYPE_SOPRANO, 4 => MTMD_GEN_AUDIO_TYPE_LFM3A, + 5 => MTMD_GEN_AUDIO_TYPE_CHATTERBOX, _ => throw ArgumentError('Unknown value for mtmd_gen_audio_type: $value'), }; } @@ -13559,8 +13806,6 @@ final class mtmd_helper_gen_audio_inp extends ffi.Struct { external ffi.Pointer lang; - external ffi.Pointer voice; - @ffi.Int32() external int top_k; @@ -13588,7 +13833,6 @@ final class mtmd_helper_gen_audio_inp extends ffi.Struct { required mtmd_helper_gen_audio_out_mode out_mode, required ffi.Pointer speaker_ref, required ffi.Pointer lang, - required ffi.Pointer voice, required int top_k, required double top_p, required int seed, @@ -13602,7 +13846,6 @@ final class mtmd_helper_gen_audio_inp extends ffi.Struct { ..ref.out_mode = out_mode ..ref.speaker_ref = speaker_ref ..ref.lang = lang - ..ref.voice = voice ..ref.top_k = top_k ..ref.top_p = top_p ..ref.seed = seed @@ -13822,7 +14065,8 @@ final class mtmd_video_config extends ffi.Struct { enum mtmd_video_template { MTMD_VIDEO_TEMPLATE_DEFAULT(0), MTMD_VIDEO_TEMPLATE_LFM3(1), - MTMD_VIDEO_TEMPLATE_LFM3_OMNI(2); + MTMD_VIDEO_TEMPLATE_LFM3_OMNI(2), + MTMD_VIDEO_TEMPLATE_QWEN3VL(3); final int value; const mtmd_video_template(this.value); @@ -13831,6 +14075,7 @@ enum mtmd_video_template { 0 => MTMD_VIDEO_TEMPLATE_DEFAULT, 1 => MTMD_VIDEO_TEMPLATE_LFM3, 2 => MTMD_VIDEO_TEMPLATE_LFM3_OMNI, + 3 => MTMD_VIDEO_TEMPLATE_QWEN3VL, _ => throw ArgumentError('Unknown value for mtmd_video_template: $value'), }; } From a2b8f3fe357b2ac595477a6606e8ef25b606bbbc Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Sat, 7 Nov 2026 16:00:07 -0500 Subject: [PATCH 2/3] Add Unreleased changelog entry for llama.cpp v0.9.0 adoption --- CHANGELOG.md | 2 ++ website/docs/changelog/recent-releases.md | 2 ++ 2 files changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5b6b60e6b..653dc2b13 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,7 @@ ## Unreleased +- Adopt llama.cpp `v0.9.0`, which accumulates F16 matrix products in F32 on ARM CPUs so they no longer overflow, and applies a GGUF's suppress tokens when sampling Qwen3-TTS codes. + ## 0.18.0 - Fix synthesized speech playback in the macOS chat example. diff --git a/website/docs/changelog/recent-releases.md b/website/docs/changelog/recent-releases.md index a3180a903..d0dbcdc6a 100644 --- a/website/docs/changelog/recent-releases.md +++ b/website/docs/changelog/recent-releases.md @@ -13,6 +13,8 @@ validate against the exact release tag notes. ## Unreleased +- Adopt llama.cpp `v0.9.0`, which accumulates F16 matrix products in F32 on ARM CPUs so they no longer overflow, and applies a GGUF's suppress tokens when sampling Qwen3-TTS codes. + ## 0.18.0 - Fix synthesized speech playback in the macOS chat example. From e9b814027b7fe57b448c161108bae33c49a4cfd3 Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Sat, 7 Nov 2026 19:02:36 -0500 Subject: [PATCH 3/3] Expose LFM3-Audio and Soprano speech output through the native model-type opt-in Drive llama_dart_tts_get_info_ext/init_ext/start_with_voice with the mask of types this core handles and the runtime builds, list predefined voices when the runtime exports the voice API, and add Lfm3AudioTtsAdapter, SopranoTtsAdapter, TextToSpeechRequest.voice and TextToSpeechCapabilities.supportsVoice/voices. TextToSpeechEngine.load asks the backend which models its runtime drives and refuses an adapter none of whose models it drives before loading anything, naming the required llamadart-native version. Refs #1615. --- CHANGELOG.md | 1 + README.md | 2 +- doc/testing_matrix.md | 18 +- example/basic_app/README.md | 5 + .../bin/llamadart_text_to_speech_example.dart | 89 ++++ lib/backend.dart | 1 + lib/src/backends/backend.dart | 35 ++ .../backends/llama_cpp/library_loading.dart | 68 +++ .../backends/llama_cpp/llama_cpp_backend.dart | 20 + .../backends/llama_cpp/llama_cpp_service.dart | 239 +++++++++- .../backends/llama_cpp/native_signatures.dart | 54 +++ lib/src/backends/llama_cpp/worker.dart | 7 + .../backends/llama_cpp/worker_messages.dart | 18 + lib/src/backends/native/native_backend.dart | 15 + lib/src/backends/web/web_backend.dart | 6 + lib/src/backends/webgpu/webgpu_backend.dart | 15 +- lib/src/core/speech/text_to_speech.dart | 99 +++- lib/src/core/speech/text_to_speech_model.dart | 56 +++ .../assets/capability_coverage.json | 6 +- skills/llamadart-speech/SKILL.md | 61 ++- .../llama_cpp_exit_teardown_e2e_test.dart | 8 +- .../text_to_speech_models_e2e_test.dart | 302 ++++++++++++ test/fixtures/llama_cpp_exit_probe.dart | 35 +- .../llama_cpp_request_performance_test.dart | 2 + .../llama_cpp_tts_exclusivity_test.dart | 1 + .../llama_cpp_tts_model_types_test.dart | 438 ++++++++++++++++++ test/support/synthetic_embedding_gguf.dart | 3 + .../backends/native/native_backend_test.dart | 54 ++- .../speech/text_to_speech_model_test.dart | 21 + .../unit/core/speech/text_to_speech_test.dart | 205 +++++++- test/unit/public_entrypoints_test.dart | 3 + test/unit/tooling/run_local_e2e_test.dart | 23 + tool/testing/run_local_e2e.dart | 31 ++ tool/testing/test_matrix.dart | 19 + website/docs/changelog/recent-releases.md | 1 + .../docs/getting-started/model-families.md | 2 + website/docs/guides/text-to-speech.md | 111 ++++- website/docs/platforms/support-matrix.md | 10 +- 38 files changed, 2026 insertions(+), 58 deletions(-) create mode 100644 example/basic_app/bin/llamadart_text_to_speech_example.dart create mode 100644 test/e2e/backends/text_to_speech_models_e2e_test.dart create mode 100644 test/integration/backends/llama_cpp_tts_model_types_test.dart diff --git a/CHANGELOG.md b/CHANGELOG.md index 653dc2b13..37fba2ee7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,7 @@ ## Unreleased - Adopt llama.cpp `v0.9.0`, which accumulates F16 matrix products in F32 on ARM CPUs so they no longer overflow, and applies a GGUF's suppress tokens when sampling Qwen3-TTS codes. +- Add LFM3-Audio and Soprano speech output on native llama.cpp (`Lfm3AudioTtsAdapter`, `SopranoTtsAdapter`) and predefined voice selection (`TextToSpeechRequest.voice`, `TextToSpeechCapabilities.voices`); runtimes before llamadart-native v0.8.0 refuse them with `LlamaUnsupportedException` ([#1615](https://github.com/leehack/llamadart/issues/1615)). ## 0.18.0 diff --git a/README.md b/README.md index 3a93ce52b..3d701b4e5 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ experimental. Native targets need no network once the model is on the device. - Streaming chat and text generation, with structured JSON output and cancellable task handles. - Tool calling driven by the model's chat template. - Embeddings, reranking, and image and audio input with multimodal models. -- Speech to text, text to speech, and decision models with cooperative task cancellation. +- Speech to text, text to speech (Qwen3-TTS; LFM3-Audio and Soprano on native), and decision models with cooperative task cancellation. - Image generation from text prompts on native platforms (Preview). - Runtime LoRA adapters for llama.cpp, observability hooks and typed capability checks. diff --git a/doc/testing_matrix.md b/doc/testing_matrix.md index 2e20f723c..a97852ce3 100644 --- a/doc/testing_matrix.md +++ b/doc/testing_matrix.md @@ -171,7 +171,7 @@ Pick targeted rows based on the touched surface: | Android Vulkan prompt cap, Vulkan device facts or the Vulkan 1.2 load refusal on a device | `chat-app-micro-batch-sweep` | | Isolate shutdown releases, exit teardown, a Flutter pin bump, or app-exit guidance | `chat-app-macos-quit` | | Speech-to-text API or adapter | `speech-to-text-smoke`, `web-speech-to-text-smoke`, plus `litert-lm-asr-smoke` and `litert-lm-asr-preservation` for the dedicated LiteRT-LM streaming engine | -| Text-to-speech API or adapter | `text-to-speech-smoke`, plus `web-text-to-speech-smoke` for browser synthesis/playback/export | +| Text-to-speech API or adapter | `text-to-speech-smoke`, `text-to-speech-models-smoke` for LFM3-Audio and Soprano, plus `web-text-to-speech-smoke` for browser synthesis/playback/export | | Decision engine, decision head, or safetensors reader | `decision-model-smoke`, plus `decision-model-web-smoke` for the Web decision head or bridge pin | | Image generation API or `stable_diffusion` runtime | `image-generation-smoke`, `native-hook-bundles` | | Complete image checkpoint formats or explicit role transport | `image-container-formats` (local hashed inputs and independent CPU references) | @@ -447,6 +447,18 @@ dart run tool/testing/run_local_e2e.dart \ --scenario chat-app-web-text-to-speech-smoke \ [--audio-path /path/to/speaker-reference.wav] +# Each model whose two variables are set runs; the Qwen3-ASR pair checks that +# the speech transcribes back to its text. Soprano has no published GGUF: +# convert it as the text-to-speech guide describes. WAVs go to +# build/text-to-speech-models. +LLAMADART_TTS_LFM3_MODEL_PATH=/path/to/LFM3-Audio-2B-Q4_K_M.gguf \ +LLAMADART_TTS_LFM3_MMPROJ_PATH=/path/to/mmproj-LFM3-Audio-2B-Q8_0.gguf \ +LLAMADART_TTS_SOPRANO_MODEL_PATH=/path/to/soprano.gguf \ +LLAMADART_TTS_SOPRANO_MMPROJ_PATH=/path/to/mmproj-soprano.gguf \ +LLAMADART_STT_MODEL_PATH=/path/to/Qwen3-ASR-0.6B-Q8_0.gguf \ +LLAMADART_STT_MMPROJ_PATH=/path/to/mmproj-Qwen3-ASR-0.6B-Q8_0.gguf \ +dart run tool/testing/run_local_e2e.dart --scenario text-to-speech-models-smoke + # Runs in example/basic_app, which opts into the stable_diffusion runtime, and # writes PNGs to build/image-generation-smoke. Export LLAMADART_SD_TURBO_MODEL # (and optionally LLAMADART_TAESD) first to add the SD-Turbo cases, including @@ -843,6 +855,10 @@ Raw C exit with live isolates remains a separately invocable diagnostic and is excluded from Linux qualification. These subprocess checks do not prove Flutter engine shutdown ordering. +On macOS, `EXIT_TEARDOWN_TTS_MODEL`, `EXIT_TEARDOWN_TTS_MMPROJ` and +`EXIT_TEARDOWN_TTS_ADAPTER` (`qwen3-tts`, `lfm3-audio` or `soprano`) add +`quit-speaking`, which calls C `exit` once synthesis has generated a frame. + On macOS, the row runs `test/fixtures/llama_cpp_exit_probe.dart` as a child process and ends it while llama.cpp objects are alive on Metal: C `exit` through FFI from the main isolate with a model idle, generating or loading; diff --git a/example/basic_app/README.md b/example/basic_app/README.md index 2768b7873..838a14570 100644 --- a/example/basic_app/README.md +++ b/example/basic_app/README.md @@ -17,6 +17,11 @@ For model-free lifecycle ownership across text and attached speech engines, run capabilities and closes dependants before their underlying engine. No weights are loaded; normal Dart build hooks can still prepare native assets. +To synthesize a WAV file with Qwen3-TTS, LFM3-Audio or Soprano, run +`dart run bin/llamadart_text_to_speech_example.dart -m -p + -a lfm3-audio --voice male`. It prints the listed voices; Ctrl-C +cancels the synthesis. + ## Features - **Interactive Mode**: Have a back-and-forth conversation with an LLM in your terminal. diff --git a/example/basic_app/bin/llamadart_text_to_speech_example.dart b/example/basic_app/bin/llamadart_text_to_speech_example.dart new file mode 100644 index 000000000..5bb850dba --- /dev/null +++ b/example/basic_app/bin/llamadart_text_to_speech_example.dart @@ -0,0 +1,89 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:args/args.dart'; +import 'package:llamadart/llamadart.dart'; + +const Map _adapters = { + 'qwen3-tts': Qwen3TtsAdapter(), + 'lfm3-audio': Lfm3AudioTtsAdapter(), + 'soprano': SopranoTtsAdapter(), +}; + +Future main(List arguments) async { + final parser = ArgParser() + ..addOption('model', abbr: 'm', help: 'Model GGUF path or URL.') + ..addOption('projector', abbr: 'p', help: 'Projector GGUF path or URL.') + ..addOption( + 'adapter', + abbr: 'a', + allowed: _adapters.keys, + defaultsTo: 'qwen3-tts', + help: 'Model family.', + ) + ..addOption('text', abbr: 't', defaultsTo: 'Hello from llamadart.') + ..addOption('voice', help: 'Predefined voice; see the listed voices.') + ..addOption('language', help: 'Language, for models that take one.') + ..addOption('temperature', help: 'Sampling temperature.') + ..addOption('out', abbr: 'o', defaultsTo: 'speech.wav') + ..addFlag('help', abbr: 'h', negatable: false); + final options = parser.parse(arguments); + final model = options['model'] as String?; + final projector = options['projector'] as String?; + if (options['help'] == true || model == null || projector == null) { + stdout.writeln( + 'Usage: dart run bin/llamadart_text_to_speech_example.dart ' + '-m -p [options]\n${parser.usage}', + ); + return; + } + + final TextToSpeechEngine synthesizer; + try { + synthesizer = await TextToSpeechEngine.load( + TextToSpeechModel( + ModelSource.parse(model), + projector: ModelSource.parse(projector), + adapter: _adapters[options['adapter']]!, + ), + ); + } on LlamaUnsupportedException catch (error) { + stderr.writeln('Unsupported: ${error.message}'); + exitCode = 1; + return; + } + StreamSubscription? interrupt; + try { + final capabilities = await synthesizer.capabilities; + stdout.writeln( + '${synthesizer.adapter.name}: ${capabilities.sampleRateHz} Hz, ' + 'voices: ${capabilities.voices.isEmpty ? 'none listed' : capabilities.voices.join(', ')}', + ); + final temperature = options['temperature'] as String?; + final task = await synthesizer.synthesize( + TextToSpeechRequest( + text: options['text'] as String, + voice: options['voice'] as String?, + language: options['language'] as String?, + temperature: temperature == null ? 0.8 : double.parse(temperature), + maxFrames: 1024, + ), + ); + interrupt = ProcessSignal.sigint.watch().listen((_) => task.cancel()); + task.events.listen((event) { + if (event is TextToSpeechProgressEvent) { + stdout.write('\r${event.phase.name}: ${event.framesGenerated} frames'); + } + }); + final result = await task.result; + final output = options['out'] as String; + await File(output).writeAsBytes(result.toWavBytes()); + stdout.writeln('\nWrote ${result.duration} to $output'); + } on LlamaException catch (error) { + stderr.writeln('\nSynthesis failed or was cancelled: $error'); + exitCode = 1; + } finally { + await interrupt?.cancel(); + await synthesizer.dispose(); + } +} diff --git a/lib/backend.dart b/lib/backend.dart index c296717f3..409594645 100644 --- a/lib/backend.dart +++ b/lib/backend.dart @@ -73,6 +73,7 @@ export 'src/backends/backend.dart' BackendTextToSpeech, BackendTextToSpeechCapabilities, BackendTextToSpeechModel, + BackendTextToSpeechModelSupport, BackendTextToSpeechPhase, BackendTextToSpeechProgress, BackendTextToSpeechRequest, diff --git a/lib/src/backends/backend.dart b/lib/src/backends/backend.dart index bdaec0cf2..f4e097f73 100644 --- a/lib/src/backends/backend.dart +++ b/lib/src/backends/backend.dart @@ -588,6 +588,12 @@ abstract class BackendGenerationUsageReporting { enum BackendTextToSpeechModel { /// Qwen3-TTS audio generation through llama.cpp mtmd. qwen3Tts, + + /// LFM3-Audio and LFM3-Omni speech output through llama.cpp mtmd. + lfm3Audio, + + /// Soprano speech output through llama.cpp mtmd. + soprano, } /// Phase reported while a backend synthesizes speech. @@ -625,6 +631,15 @@ class BackendTextToSpeechCapabilities { /// Whether an active synthesis can be cancelled cooperatively. final bool supportsCancellation; + /// Whether a predefined voice can be selected by name. + final bool supportsVoice; + + /// The predefined voices, in the model's order; the first one speaks when + /// a request names none. + /// + /// Empty when the model has no voices or the backend cannot list them. + final List voices; + /// Creates a backend capability snapshot. const BackendTextToSpeechCapabilities({ required this.isSupported, @@ -635,6 +650,8 @@ class BackendTextToSpeechCapabilities { this.supportsLanguage = false, this.supportsSpeakerReference = false, this.supportsCancellation = false, + this.supportsVoice = false, + this.voices = const [], }); } @@ -652,6 +669,9 @@ class BackendTextToSpeechRequest { /// Optional encoded reference-audio bytes. final Uint8List? speakerAudioBytes; + /// Optional predefined voice name, or null for the model's default. + final String? voice; + /// Maximum number of audio-codec frames to generate. final int maxFrames; @@ -679,6 +699,7 @@ class BackendTextToSpeechRequest { this.language, this.speakerAudioPath, this.speakerAudioBytes, + this.voice, this.maxFrames = 512, this.promptBatchSize = 512, this.topK = 40, @@ -739,6 +760,20 @@ class BackendTextToSpeechResult { }); } +/// Optional backend probe for the text-to-speech models its runtime drives, +/// answered before a model loads. +/// +/// `TextToSpeechEngine.load` asks it for the models its adapter accepts and +/// refuses the load when the runtime drives none of them, before downloading +/// or loading any file. +abstract class BackendTextToSpeechModelSupport { + /// Why the runtime cannot drive [model], or null when it can or cannot tell + /// without a loaded model. Must not load a model. + Future textToSpeechModelUnsupportedReason( + BackendTextToSpeechModel model, + ); +} + /// Optional backend capability for dedicated text-to-speech synthesis. abstract class BackendTextToSpeech { /// Discovers support for the loaded context and multimodal projector. diff --git a/lib/src/backends/llama_cpp/library_loading.dart b/lib/src/backends/llama_cpp/library_loading.dart index b209031bb..1657d0fb9 100644 --- a/lib/src/backends/llama_cpp/library_loading.dart +++ b/lib/src/backends/llama_cpp/library_loading.dart @@ -17,6 +17,17 @@ class _TtsApi { final _TtsSetCancelFlagDart? setCancelFlag; final ggml_backend_sched_eval_callback evalCallback; + // Model-type opt-in (llamadart-native v0.8.0). Older wrappers lack it and + // drive Qwen3-TTS only through the legacy calls. + final _TtsSupportedModelTypesDart? supportedModelTypes; + final _TtsGetInfoExtDart? getInfoExt; + final _TtsInitExtDart? initExt; + final _TtsStartWithVoiceDart? startWithVoice; + + // Predefined-voice listing (llamadart-native v0.9.0). + final _TtsGetVoiceCountDart? getVoiceCount; + final _TtsGetVoiceNameDart? getVoiceName; + const _TtsApi({ required this.apiVersion, required this.requestDefault, @@ -33,12 +44,35 @@ class _TtsApi { required this.lastError, required this.setCancelFlag, required this.evalCallback, + required this.supportedModelTypes, + required this.getInfoExt, + required this.initExt, + required this.startWithVoice, + required this.getVoiceCount, + required this.getVoiceName, }); + /// Whether the runtime has the whole model-type opt-in. + bool get hasModelTypeOptIn => + supportedModelTypes != null && + getInfoExt != null && + initExt != null && + startWithVoice != null; + + /// Whether the runtime lists predefined voices. + bool get listsVoices => getVoiceCount != null && getVoiceName != null; + static _TtsApi? tryLoad(DynamicLibrary library) { try { const setCancelFlagSymbol = 'llama_dart_tts_set_cancel_flag'; const evalCallbackSymbol = 'llama_dart_tts_eval_callback'; + bool has(String symbol) => library.providesSymbol(symbol); + const supportedModelTypesSymbol = 'llama_dart_tts_supported_model_types'; + const getInfoExtSymbol = 'llama_dart_tts_get_info_ext'; + const initExtSymbol = 'llama_dart_tts_init_ext'; + const startWithVoiceSymbol = 'llama_dart_tts_start_with_voice'; + const getVoiceCountSymbol = 'llama_dart_tts_get_voice_count'; + const getVoiceNameSymbol = 'llama_dart_tts_get_voice_name'; return _TtsApi( apiVersion: library .lookupFunction<_TtsApiVersionNative, _TtsApiVersionDart>( @@ -92,6 +126,40 @@ class _TtsApi { NativeFunction >(evalCallbackSymbol) : nullptr, + supportedModelTypes: has(supportedModelTypesSymbol) + ? library.lookupFunction< + _TtsSupportedModelTypesNative, + _TtsSupportedModelTypesDart + >(supportedModelTypesSymbol) + : null, + getInfoExt: has(getInfoExtSymbol) + ? library.lookupFunction<_TtsGetInfoExtNative, _TtsGetInfoExtDart>( + getInfoExtSymbol, + ) + : null, + initExt: has(initExtSymbol) + ? library.lookupFunction<_TtsInitExtNative, _TtsInitExtDart>( + initExtSymbol, + ) + : null, + startWithVoice: has(startWithVoiceSymbol) + ? library.lookupFunction< + _TtsStartWithVoiceNative, + _TtsStartWithVoiceDart + >(startWithVoiceSymbol) + : null, + getVoiceCount: has(getVoiceCountSymbol) + ? library.lookupFunction< + _TtsGetVoiceCountNative, + _TtsGetVoiceCountDart + >(getVoiceCountSymbol) + : null, + getVoiceName: has(getVoiceNameSymbol) + ? library + .lookupFunction<_TtsGetVoiceNameNative, _TtsGetVoiceNameDart>( + getVoiceNameSymbol, + ) + : null, ); } catch (_) { return null; diff --git a/lib/src/backends/llama_cpp/llama_cpp_backend.dart b/lib/src/backends/llama_cpp/llama_cpp_backend.dart index 0d11f85ae..9bdd3db1c 100644 --- a/lib/src/backends/llama_cpp/llama_cpp_backend.dart +++ b/lib/src/backends/llama_cpp/llama_cpp_backend.dart @@ -50,6 +50,7 @@ class NativeLlamaBackend BackendStatePersistence, BackendStateIdentity, BackendTextToSpeech, + BackendTextToSpeechModelSupport, BackendDecision, BackendGenerationCapabilitiesSupport, BackendVideoRuntimeSupport, @@ -1485,6 +1486,25 @@ class NativeLlamaBackend return res as bool; } + @override + Future textToSpeechModelUnsupportedReason( + BackendTextToSpeechModel model, + ) async { + await _ensureIsolate(); + final rp = _openResponsePort(); + _dispatchRequest(rp, TextToSpeechModelSupportRequest(model, rp.sendPort)); + final response = await _receiveResponse(rp); + if (response is TextToSpeechModelSupportResponse) { + return response.unsupportedReason; + } + if (response is ErrorResponse) { + throw _workerError(response); + } + throw LlamaTextToSpeechException( + 'Unexpected native text-to-speech model support response.', + ); + } + @override Future textToSpeechCapabilities( int contextHandle, diff --git a/lib/src/backends/llama_cpp/llama_cpp_service.dart b/lib/src/backends/llama_cpp/llama_cpp_service.dart index d4f63e494..39cdf4281 100644 --- a/lib/src/backends/llama_cpp/llama_cpp_service.dart +++ b/lib/src/backends/llama_cpp/llama_cpp_service.dart @@ -9845,57 +9845,214 @@ class LlamaCppService { ); } + final mtmd = _mtmdContexts[mmContextHandle]!; + final acceptedTypes = _ttsAcceptedModelTypes(api); final info = malloc(); try { info.ref.struct_size = sizeOf(); + final getInfoExt = api.hasModelTypeOptIn ? api.getInfoExt : null; final status = llama_dart_tts_status.fromValue( - api.getInfo(_mtmdContexts[mmContextHandle]!, info), + getInfoExt != null + ? getInfoExt(mtmd, acceptedTypes, info) + : api.getInfo(mtmd, info), ); if (status == llama_dart_tts_status.LLAMA_DART_TTS_STATUS_UNSUPPORTED) { - return const BackendTextToSpeechCapabilities( + return BackendTextToSpeechCapabilities( isSupported: false, - unsupportedReason: - 'The loaded projector does not expose supported audio generation.', + unsupportedReason: _ttsUnsupportedProjectorMessage( + api, + acceptedTypes, + ), ); } _throwForTtsStatus( status, operation: 'Text-to-speech capability probe', - barrierCall: 'llama_dart_tts_get_info', + barrierCall: getInfoExt != null + ? 'llama_dart_tts_get_info_ext' + : 'llama_dart_tts_get_info', ); - if (info.ref.model_type != - llama_dart_tts_model_type.LLAMA_DART_TTS_MODEL_TYPE_QWEN3.value) { + final model = _backendTtsModels[info.ref.model_type]; + if (model == null || acceptedTypes & (1 << info.ref.model_type) == 0) { + return BackendTextToSpeechCapabilities( + isSupported: false, + unsupportedReason: _ttsUnsupportedProjectorMessage( + api, + acceptedTypes, + ), + ); + } + if (model == BackendTextToSpeechModel.lfm3Audio && + !_modelHasTtsTemplate(contextHandle)) { return const BackendTextToSpeechCapabilities( isSupported: false, unsupportedReason: - 'Only Qwen3-TTS projectors are supported by this runtime.', + 'The loaded model has no `tts` chat template, which LFM3-Audio ' + 'speech output needs. Load the LFM3-Audio or LFM3-Omni model ' + 'that matches this projector.', ); } final flags = info.ref.capabilities; + bool has(llama_dart_tts_capability capability) => + flags & capability.value != 0; + final supportsVoice = has( + llama_dart_tts_capability.LLAMA_DART_TTS_CAPABILITY_VOICE, + ); return BackendTextToSpeechCapabilities( isSupported: true, - model: BackendTextToSpeechModel.qwen3Tts, + model: model, sampleRateHz: info.ref.sample_rate, channelCount: info.ref.channels, - supportsLanguage: - flags & - llama_dart_tts_capability - .LLAMA_DART_TTS_CAPABILITY_LANGUAGE - .value != - 0, - supportsSpeakerReference: - flags & - llama_dart_tts_capability - .LLAMA_DART_TTS_CAPABILITY_SPEAKER_REFERENCE - .value != - 0, + supportsLanguage: has( + llama_dart_tts_capability.LLAMA_DART_TTS_CAPABILITY_LANGUAGE, + ), + supportsSpeakerReference: has( + llama_dart_tts_capability.LLAMA_DART_TTS_CAPABILITY_SPEAKER_REFERENCE, + ), supportsCancellation: true, + supportsVoice: supportsVoice && api.hasModelTypeOptIn, + voices: supportsVoice && api.hasModelTypeOptIn + ? _ttsVoices(api, mtmd, acceptedTypes) + : const [], ); } finally { malloc.free(info); } } + /// Why this runtime cannot drive [model], or null when it can; reads the + /// runtime's exports only. + String? textToSpeechModelUnsupportedReason(BackendTextToSpeechModel model) { + final _TtsApi api; + try { + api = _resolveTtsApi(); + } on LlamaUnsupportedException catch (error) { + return error.message; + } + if (model == BackendTextToSpeechModel.qwen3Tts) return null; + final name = _ttsModelName(model); + if (!api.hasModelTypeOptIn) { + return '$name speech output needs the model-type opt-in ' + '(`llama_dart_tts_init_ext`) of llamadart-native v0.8.0 or later; ' + 'this llama.cpp runtime predates it.'; + } + final type = _backendTtsModels.entries + .firstWhere((entry) => entry.value == model) + .key; + if (_ttsAcceptedModelTypes(api) & (1 << type) != 0) return null; + return 'This llama.cpp runtime was built without $name speech output ' + '(`llama_dart_tts_supported_model_types`); it needs a ' + 'llamadart-native v0.8.0 or later bundle that includes it.'; + } + + static const Map _backendTtsModels = { + 1: BackendTextToSpeechModel.qwen3Tts, + 2: BackendTextToSpeechModel.lfm3Audio, + 3: BackendTextToSpeechModel.soprano, + }; + + /// The `_ext` mask of model types this core drives and the runtime can + /// create; Qwen3-TTS alone on a runtime without the opt-in. + int _ttsAcceptedModelTypes(_TtsApi api) { + const qwen3 = 1 << 1; + final supportedModelTypes = api.supportedModelTypes; + if (!api.hasModelTypeOptIn || supportedModelTypes == null) return qwen3; + var known = 0; + for (final type in _backendTtsModels.keys) { + known |= 1 << type; + } + return (supportedModelTypes() & known) | qwen3; + } + + String _ttsUnsupportedProjectorMessage(_TtsApi api, int acceptedTypes) { + const base = + 'The loaded projector does not expose supported audio generation.'; + if (!api.hasModelTypeOptIn) { + return '$base This runtime drives Qwen3-TTS only: LFM3-Audio and ' + 'Soprano speech output need the model-type opt-in ' + '(`llama_dart_tts_init_ext`) of llamadart-native v0.8.0 or later.'; + } + final missing = [ + for (final MapEntry(key: type, value: model) in _backendTtsModels.entries) + if (acceptedTypes & (1 << type) == 0) _ttsModelName(model), + ]; + if (missing.isEmpty) return base; + return '$base This runtime was built without ${missing.join(' and ')} ' + 'speech output (`llama_dart_tts_supported_model_types`); use a ' + 'llamadart-native v0.8.0 or later bundle that includes it.'; + } + + static String _ttsModelName(BackendTextToSpeechModel model) => + switch (model) { + BackendTextToSpeechModel.qwen3Tts => 'Qwen3-TTS', + BackendTextToSpeechModel.lfm3Audio => 'LFM3-Audio', + BackendTextToSpeechModel.soprano => 'Soprano', + }; + + bool _modelHasTtsTemplate(int contextHandle) { + final model = _models[_contextToModel[contextHandle]]; + if (model == null) return false; + final name = 'tts'.toNativeUtf8(); + try { + return llama_model_chat_template(model.pointer, name.cast()) != nullptr; + } finally { + malloc.free(name); + } + } + + /// The projector's predefined voices in upstream order, or none when the + /// runtime cannot list them (llamadart-native before v0.9.0). + List _ttsVoices( + _TtsApi api, + Pointer mtmd, + int acceptedTypes, + ) { + final getVoiceCount = api.getVoiceCount; + final getVoiceName = api.getVoiceName; + if (getVoiceCount == null || getVoiceName == null) { + return const []; + } + final count = malloc(); + final length = malloc(); + try { + _throwForTtsStatus( + llama_dart_tts_status.fromValue( + getVoiceCount(mtmd, acceptedTypes, count), + ), + operation: 'Text-to-speech voice listing', + barrierCall: 'llama_dart_tts_get_voice_count', + ); + final voices = []; + for (var index = 0; index < count.value; index++) { + _throwForTtsStatus( + llama_dart_tts_status.fromValue( + getVoiceName(mtmd, acceptedTypes, index, nullptr, 0, length), + ), + operation: 'Text-to-speech voice listing', + barrierCall: 'llama_dart_tts_get_voice_name', + ); + final capacity = length.value + 1; + final name = malloc(capacity); + try { + _throwForTtsStatus( + llama_dart_tts_status.fromValue( + getVoiceName(mtmd, acceptedTypes, index, name, capacity, length), + ), + operation: 'Text-to-speech voice listing', + barrierCall: 'llama_dart_tts_get_voice_name', + ); + voices.add(name.cast().toDartString(length: length.value)); + } finally { + malloc.free(name); + } + } + return List.unmodifiable(voices); + } finally { + malloc.free(count); + malloc.free(length); + } + } + /// Synthesizes complete float32 PCM with the stable native TTS wrapper. /// /// [cancelFlagAddress] is the address of a one-byte flag that another @@ -9975,6 +10132,20 @@ class LlamaCppService { if (trimmedLanguage != null && trimmedLanguage.isNotEmpty) { language = trimmedLanguage.toNativeUtf8(); } + final voiceName = request.voice; + final startWithVoice = api.hasModelTypeOptIn ? api.startWithVoice : null; + if (voiceName != null && startWithVoice == null) { + malloc.free(text); + if (language != nullptr) malloc.free(language); + throw LlamaUnsupportedException( + 'Selecting a text-to-speech voice needs the model-type opt-in ' + '(`llama_dart_tts_start_with_voice`) of llamadart-native v0.8.0 or ' + 'later; this runtime lacks it.', + ); + } + final Pointer voice = voiceName == null + ? nullptr + : voiceName.toNativeUtf8(); Pointer speakerAudio = nullptr; Uint8List? speakerBytes = request.speakerAudioBytes; @@ -9985,6 +10156,7 @@ class LlamaCppService { } catch (error) { malloc.free(text); if (language != nullptr) malloc.free(language); + if (voice != nullptr) malloc.free(voice); throw LlamaAudioFormatException( 'Unable to read speaker reference audio.', error, @@ -10019,7 +10191,15 @@ class LlamaCppService { } _calls.synchronize(context.pointer); _resetRequestPerformance(contextHandle, context); - task = api.init(context.pointer, mtmd, initStatus); + final initExt = api.hasModelTypeOptIn ? api.initExt : null; + task = initExt != null + ? initExt( + context.pointer, + mtmd, + _ttsAcceptedModelTypes(api), + initStatus, + ) + : api.init(context.pointer, mtmd, initStatus); IsolateShutdownReleases.current.hold( ShutdownStage.session, api.freeAddress, @@ -10029,7 +10209,9 @@ class LlamaCppService { _throwForTtsStatus( llama_dart_tts_status.fromValue(initStatus.value), operation: 'Text-to-speech initialization', - barrierCall: 'llama_dart_tts_init', + barrierCall: initExt != null + ? 'llama_dart_tts_init_ext' + : 'llama_dart_tts_init', context: context.pointer, ); throw LlamaTextToSpeechException( @@ -10058,11 +10240,17 @@ class LlamaCppService { requestPointer.ref.seed = request.seed; _throwForTtsStatus( - llama_dart_tts_status.fromValue(api.start(task, requestPointer)), + llama_dart_tts_status.fromValue( + voice == nullptr + ? api.start(task, requestPointer) + : startWithVoice!(task, requestPointer, voice.cast()), + ), operation: 'Text-to-speech startup', api: api, task: task, - barrierCall: 'llama_dart_tts_start', + barrierCall: voice == nullptr + ? 'llama_dart_tts_start' + : 'llama_dart_tts_start_with_voice', context: context.pointer, ); api.setCancelFlag?.call(task, cancelFlag); @@ -10179,6 +10367,7 @@ class LlamaCppService { malloc.free(progress); malloc.free(text); if (language != nullptr) malloc.free(language); + if (voice != nullptr) malloc.free(voice); if (speakerAudio != nullptr) malloc.free(speakerAudio); } } diff --git a/lib/src/backends/llama_cpp/native_signatures.dart b/lib/src/backends/llama_cpp/native_signatures.dart index d558136ce..b80cb3188 100644 --- a/lib/src/backends/llama_cpp/native_signatures.dart +++ b/lib/src/backends/llama_cpp/native_signatures.dart @@ -66,6 +66,60 @@ typedef _TtsReadPcmDart = ); typedef _TtsLastErrorNative = Pointer Function(Pointer); typedef _TtsLastErrorDart = Pointer Function(Pointer); +typedef _TtsSupportedModelTypesNative = Uint32 Function(); +typedef _TtsSupportedModelTypesDart = int Function(); +typedef _TtsGetInfoExtNative = + Int32 Function(Pointer, Uint32, Pointer); +typedef _TtsGetInfoExtDart = + int Function(Pointer, int, Pointer); +typedef _TtsInitExtNative = + Pointer Function( + Pointer, + Pointer, + Uint32, + Pointer, + ); +typedef _TtsInitExtDart = + Pointer Function( + Pointer, + Pointer, + int, + Pointer, + ); +typedef _TtsStartWithVoiceNative = + Int32 Function( + Pointer, + Pointer, + Pointer, + ); +typedef _TtsStartWithVoiceDart = + int Function( + Pointer, + Pointer, + Pointer, + ); +typedef _TtsGetVoiceCountNative = + Int32 Function(Pointer, Uint32, Pointer); +typedef _TtsGetVoiceCountDart = + int Function(Pointer, int, Pointer); +typedef _TtsGetVoiceNameNative = + Int32 Function( + Pointer, + Uint32, + Int32, + Pointer, + Size, + Pointer, + ); +typedef _TtsGetVoiceNameDart = + int Function( + Pointer, + int, + int, + Pointer, + int, + Pointer, + ); typedef _GgmlBackendInitNative = ggml_backend_reg_t Function(); typedef _GgmlBackendInitDart = ggml_backend_reg_t Function(); typedef _GgmlBackendLoadAllNative = Void Function(); diff --git a/lib/src/backends/llama_cpp/worker.dart b/lib/src/backends/llama_cpp/worker.dart index af23db13e..539d04b0a 100644 --- a/lib/src/backends/llama_cpp/worker.dart +++ b/lib/src/backends/llama_cpp/worker.dart @@ -339,6 +339,13 @@ void runLlamaWorkerForTesting( activeGenerate = generateFuture; await generateFuture; + case TextToSpeechModelSupportRequest(): + message.sendPort.send( + TextToSpeechModelSupportResponse( + service.textToSpeechModelUnsupportedReason(message.model), + ), + ); + case TextToSpeechCapabilitiesRequest(): final capabilities = service.textToSpeechCapabilities( message.contextHandle, diff --git a/lib/src/backends/llama_cpp/worker_messages.dart b/lib/src/backends/llama_cpp/worker_messages.dart index 2d4ed9a15..055210b8f 100644 --- a/lib/src/backends/llama_cpp/worker_messages.dart +++ b/lib/src/backends/llama_cpp/worker_messages.dart @@ -461,6 +461,24 @@ class TextToSpeechCapabilitiesRequest extends WorkerRequest { ); } +/// Request for why the runtime cannot drive a text-to-speech model. +class TextToSpeechModelSupportRequest extends WorkerRequest { + /// The model family to check. + final BackendTextToSpeechModel model; + + /// Creates a TTS model support request. + TextToSpeechModelSupportRequest(this.model, super.sendPort); +} + +/// Worker response to a [TextToSpeechModelSupportRequest]. +class TextToSpeechModelSupportResponse { + /// Why the runtime cannot drive the model, or null when it can. + final String? unsupportedReason; + + /// Creates a TTS model support response. + TextToSpeechModelSupportResponse(this.unsupportedReason); +} + /// Request to synthesize one complete utterance. class TextToSpeechSynthesizeRequest extends WorkerRequest { /// Handle of the loaded llama context. diff --git a/lib/src/backends/native/native_backend.dart b/lib/src/backends/native/native_backend.dart index c13884720..51936fe23 100644 --- a/lib/src/backends/native/native_backend.dart +++ b/lib/src/backends/native/native_backend.dart @@ -72,6 +72,7 @@ class NativeAutoBackend BackendPromptPenaltyGeneration, BackendDeferredEngineCreation, BackendTextToSpeech, + BackendTextToSpeechModelSupport, BackendDecision, BackendGenerationCapabilitiesSupport, BackendVideoRuntimeSupport, @@ -629,6 +630,20 @@ class NativeAutoBackend return Future.value(); } + @override + Future textToSpeechModelUnsupportedReason( + BackendTextToSpeechModel model, + ) async { + // Text-to-speech models are GGUF, which the llama.cpp delegate loads. + final delegate = _delegateKind == LlamaRuntime.llamaCpp + ? _delegate! + : await _ensureDiagnosticDelegate(); + return delegate is BackendTextToSpeechModelSupport + ? (delegate as BackendTextToSpeechModelSupport) + .textToSpeechModelUnsupportedReason(model) + : null; + } + @override Future textToSpeechCapabilities( int contextHandle, diff --git a/lib/src/backends/web/web_backend.dart b/lib/src/backends/web/web_backend.dart index eed1851ff..aa28062ff 100644 --- a/lib/src/backends/web/web_backend.dart +++ b/lib/src/backends/web/web_backend.dart @@ -47,6 +47,7 @@ class WebAutoBackend BackendLazyGrammarSupport, BackendDeferredEngineCreation, BackendTextToSpeech, + BackendTextToSpeechModelSupport, BackendDecision, BackendGenerationCapabilitiesSupport, BackendGenerationUsageReporting, @@ -346,6 +347,11 @@ class WebAutoBackend _delegate?.cancelGeneration(); } + @override + Future textToSpeechModelUnsupportedReason( + BackendTextToSpeechModel model, + ) async => webTextToSpeechModelUnsupportedReason(model); + @override Future textToSpeechCapabilities( int contextHandle, diff --git a/lib/src/backends/webgpu/webgpu_backend.dart b/lib/src/backends/webgpu/webgpu_backend.dart index c0c9ebc9d..d093a9c7f 100644 --- a/lib/src/backends/webgpu/webgpu_backend.dart +++ b/lib/src/backends/webgpu/webgpu_backend.dart @@ -49,6 +49,13 @@ typedef _WebGpuCompletionCapabilities = ({ Set speculativeDecoding, }); +/// Why Web text-to-speech cannot drive [model], or null for Qwen3-TTS. +String? webTextToSpeechModelUnsupportedReason(BackendTextToSpeechModel model) => + model == BackendTextToSpeechModel.qwen3Tts + ? null + : 'Web text-to-speech drives Qwen3-TTS only; load this model with a ' + 'native llama.cpp runtime.'; + /// Web backend backed by the llama.cpp bridge runtime. class WebGpuLlamaBackend implements @@ -61,6 +68,7 @@ class WebGpuLlamaBackend BackendMultimodalEmbeddings, BackendPromptSpeechToTextSupport, BackendTextToSpeech, + BackendTextToSpeechModelSupport, BackendDecision, BackendGenerationCapabilitiesSupport, BackendGenerationUsageReporting, @@ -2366,6 +2374,11 @@ class WebGpuLlamaBackend BackendGenerationLimit? generationLimitOf(Stream> generation) => _generationLimits[generation]; + @override + Future textToSpeechModelUnsupportedReason( + BackendTextToSpeechModel model, + ) async => webTextToSpeechModelUnsupportedReason(model); + @override Future textToSpeechCapabilities( int contextHandle, @@ -2420,7 +2433,7 @@ class WebGpuLlamaBackend isSupported: false, unsupportedReason: 'The loaded Web projector is not a supported Qwen3-TTS ' - 'projector.', + 'projector. Web text-to-speech drives Qwen3-TTS only.', ); } final sampleRate = _jsIntProperty(value, 'sampleRate'); diff --git a/lib/src/core/speech/text_to_speech.dart b/lib/src/core/speech/text_to_speech.dart index d145b367a..6d24d57c8 100644 --- a/lib/src/core/speech/text_to_speech.dart +++ b/lib/src/core/speech/text_to_speech.dart @@ -56,8 +56,18 @@ class TextToSpeechRequest { /// Optional encoded speaker-reference audio. /// /// Native backends accept files and bytes. Web accepts encoded bytes only. + /// It cannot be combined with [voice]. final SpeechAudioInput? speakerReference; + /// Optional predefined voice of the loaded model, such as `male` for + /// LFM3-Audio, or null for the model's default voice. + /// + /// Needs [TextToSpeechCapabilities.supportsVoice]. A name matches in any + /// case; one the model does not list throws [LlamaTextToSpeechException] + /// instead of falling back to the default. It cannot be combined with + /// [speakerReference]. + final String? voice; + /// Maximum number of audio-codec frames to generate. final int maxFrames; @@ -74,6 +84,9 @@ class TextToSpeechRequest { final double minP; /// Sampling temperature. + /// + /// Some models sample with their own settings and only validate [topK], + /// [topP], [minP] and this value; see their adapter. final double temperature; /// Random seed. `0xffffffff` requests the runtime's random default. @@ -84,6 +97,7 @@ class TextToSpeechRequest { required this.text, this.language, this.speakerReference, + this.voice, this.maxFrames = 512, this.promptBatchSize = 512, this.topK = 40, @@ -130,6 +144,17 @@ class TextToSpeechCapabilities implements EngineCapabilities { /// Whether speaker-reference audio can be supplied. final bool supportsSpeakerReference; + /// Whether [TextToSpeechRequest.voice] can name a predefined voice. + final bool supportsVoice; + + /// The model's predefined voices in its own order; the first one speaks + /// when a request names none. + /// + /// Empty when the model has no voices, or when [supportsVoice] is true but + /// the runtime cannot list them (llamadart-native before v0.9.0); the + /// runtime then checks the name when synthesis starts. + final List voices; + /// Whether PCM can be emitted while synthesis is still running. final bool supportsIncrementalAudio; @@ -154,6 +179,8 @@ class TextToSpeechCapabilities implements EngineCapabilities { this.supportsLanguage = false, this.supportedLanguages = const {}, this.supportsSpeakerReference = false, + this.supportsVoice = false, + this.voices = const [], this.supportsIncrementalAudio = false, this.supportsCancellation = false, this.supportsOutputBackpressure = false, @@ -490,8 +517,11 @@ class TextToSpeechEngine implements LlamadartEngine { /// Throws: /// - [LlamaArgumentException] when [download] would send credentials to /// more than one host. - /// - [LlamaUnsupportedException] when the loaded model cannot synthesize - /// speech with [TextToSpeechModel.adapter] (see [capabilities]), and when + /// - [LlamaUnsupportedException] before any file loads when the runtime + /// drives none of the models [TextToSpeechModel.adapter] accepts, such as + /// LFM3-Audio on a llama.cpp runtime older than llamadart-native v0.8.0; + /// when the loaded model cannot synthesize speech with the adapter (see + /// [capabilities]); and when /// [download] sets [ModelLoadOptions.sha256] for a model with a /// projector. /// - [LlamaStateException] when [download]'s cancel token cancels the load. @@ -505,13 +535,25 @@ class TextToSpeechEngine implements LlamadartEngine { ModelFileStore? store, LlamaBackend? backend, }) async { + final runtime = backend ?? LlamaBackend(); + final String? refusal; + try { + refusal = await _runtimeRefusal(runtime, model.adapter); + } catch (_) { + await runtime.dispose(); + rethrow; + } + if (refusal != null) { + await runtime.dispose(); + throw LlamaUnsupportedException(refusal); + } final (engine, _) = await loadLlamaEngine( LlamaModel(model.source, projector: model.projector), params: params, download: download, onProgress: onProgress, store: store, - backend: backend, + backend: runtime, operation: 'TextToSpeechEngine model loading', ); try { @@ -538,6 +580,24 @@ class TextToSpeechEngine implements LlamadartEngine { } } + /// Why [runtime] drives none of the models [adapter] accepts, or null when + /// it drives one or cannot tell before a model loads. + static Future _runtimeRefusal( + LlamaBackend runtime, + TextToSpeechAdapter adapter, + ) async { + if (runtime is! BackendTextToSpeechModelSupport) return null; + final probe = runtime as BackendTextToSpeechModelSupport; + String? refusal; + for (final candidate in BackendTextToSpeechModel.values) { + if (!adapter.supportsModel(candidate)) continue; + final reason = await probe.textToSpeechModelUnsupportedReason(candidate); + if (reason == null) return null; + refusal ??= reason; + } + return refusal; + } + /// Runs [adapter] on [engine], which the caller loaded and keeps owning. /// /// The engine needs a loaded model and its audio-generation projector; @@ -635,6 +695,10 @@ class TextToSpeechEngine implements LlamadartEngine { ? adapter.supportedLanguages : const {}, supportsSpeakerReference: backendCapabilities.supportsSpeakerReference, + supportsVoice: backendCapabilities.supportsVoice, + voices: backendCapabilities.supportsVoice + ? backendCapabilities.voices + : const [], supportsIncrementalAudio: false, supportsCancellation: backendCapabilities.supportsCancellation, supportsOutputBackpressure: false, @@ -693,6 +757,23 @@ class TextToSpeechEngine implements LlamadartEngine { 'audio.', ); } + final voice = request.voice; + if (voice != null) { + if (!currentCapabilities.supportsVoice) { + throw LlamaUnsupportedException( + 'The active text-to-speech model has no predefined voices.', + ); + } + final voices = currentCapabilities.voices; + final lowerVoice = voice.toLowerCase(); + if (voices.isNotEmpty && + !voices.any((name) => name.toLowerCase() == lowerVoice)) { + throw LlamaTextToSpeechException( + 'Unknown ${adapter.name} voice `$voice`. Use one of: ' + '${voices.join(', ')}.', + ); + } + } final task = TextToSpeechTask._( onCancel: _engine.cancelTextToSpeechBackend, @@ -779,6 +860,17 @@ class TextToSpeechEngine implements LlamadartEngine { 'Invalid text-to-speech sampling parameters.', ); } + final voice = request.voice; + if (voice != null) { + if (voice.trim().isEmpty) { + throw LlamaTextToSpeechException('voice must not be empty.'); + } + if (request.speakerReference != null) { + throw LlamaTextToSpeechException( + 'A voice and a speaker reference cannot be combined.', + ); + } + } switch (request.speakerReference) { case SpeechAudioFileInput(:final path): if (path.trim().isEmpty) { @@ -832,6 +924,7 @@ class TextToSpeechEngine implements LlamadartEngine { SpeechAudioBytesInput(:final bytes) => bytes, _ => null, }, + voice: request.voice, maxFrames: request.maxFrames, promptBatchSize: request.promptBatchSize, topK: request.topK, diff --git a/lib/src/core/speech/text_to_speech_model.dart b/lib/src/core/speech/text_to_speech_model.dart index f95f687b3..ff74e8f68 100644 --- a/lib/src/core/speech/text_to_speech_model.dart +++ b/lib/src/core/speech/text_to_speech_model.dart @@ -119,3 +119,59 @@ class Qwen3TtsAdapter extends TextToSpeechAdapter { return code; } } + +/// LFM3-Audio and LFM3-Omni speech output on llama.cpp, with the model's +/// audio projector. +/// +/// The model speaks through its `tts` chat template, so load the LFM3 model +/// that matches the projector; one without that template is unsupported. +/// Output is 24 kHz mono PCM. +/// +/// - [TextToSpeechRequest.voice] selects `female` (the default) or `male`. +/// - [TextToSpeechRequest.language] is rendered into the template as given, +/// as a code such as `en` or a language name; nothing validates it, so +/// check it against the model card. Without one the template's default, +/// English, applies. +/// - Speaker references are unsupported. +/// - Audio codes are sampled with the model's own GGUF settings: +/// [TextToSpeechRequest.topK], `topP`, `minP` and `temperature` are +/// validated but unused. [TextToSpeechRequest.seed] seeds the generation. +/// +/// Needs llamadart-native v0.8.0 or later; earlier runtimes report the +/// projector as unsupported. +class Lfm3AudioTtsAdapter extends TextToSpeechAdapter { + /// Creates the LFM3-Audio adapter. + const Lfm3AudioTtsAdapter(); + + @override + String get name => 'LFM3-Audio'; + + @override + bool supportsModel(BackendTextToSpeechModel? model) => + model == BackendTextToSpeechModel.lfm3Audio; + + @override + String normalizeLanguage(String language) => language; +} + +/// Soprano on llama.cpp, with its Vocos-decoder projector. +/// +/// Soprano takes no language, voice or speaker reference; requests with any +/// of them are unsupported. It samples with the request's settings, whose +/// default temperature is 0.8; upstream's example decodes greedily, so pass +/// `temperature: 0` to match it. Output is 32 kHz mono PCM, decoded on the +/// last generation step. Fewer than two generated frames fail the synthesis. +/// +/// No llama.cpp-format Soprano GGUF is published; see the text-to-speech +/// guide for converting one. Needs llamadart-native v0.8.0 or later. +class SopranoTtsAdapter extends TextToSpeechAdapter { + /// Creates the Soprano adapter. + const SopranoTtsAdapter(); + + @override + String get name => 'Soprano'; + + @override + bool supportsModel(BackendTextToSpeechModel? model) => + model == BackendTextToSpeechModel.soprano; +} diff --git a/packages/llamadart_validation/assets/capability_coverage.json b/packages/llamadart_validation/assets/capability_coverage.json index 43a178e21..362c2f82c 100644 --- a/packages/llamadart_validation/assets/capability_coverage.json +++ b/packages/llamadart_validation/assets/capability_coverage.json @@ -449,11 +449,13 @@ "capability:TextToSpeechCapabilities.supportsLanguage", "capability:TextToSpeechCapabilities.supportsOutputBackpressure", "capability:TextToSpeechCapabilities.supportsSpeakerReference", - "capability:TextToSpeechCapabilities.unsupportedReason" + "capability:TextToSpeechCapabilities.supportsVoice", + "capability:TextToSpeechCapabilities.unsupportedReason", + "capability:TextToSpeechCapabilities.voices" ], "exemption": { "id": "speech-capabilities", - "reason": "Dedicated speech profiles/runners exist, but their reported capability fields are not yet bound to versioned validation feature/case IDs. The web-speech-task-cancel local E2E separately covers direct/worker task isolation and bounded reuse with explicit TTS batch 512/micro-batch 256 (#1371); it does not bind these capability fields or qualify every speech flag or negative path.", + "reason": "Dedicated speech profiles/runners exist, but their reported capability fields are not yet bound to versioned validation feature/case IDs. The web-speech-task-cancel local E2E separately covers direct/worker task isolation and bounded reuse with explicit TTS batch 512/micro-batch 256 (#1371); it does not bind these capability fields or qualify every speech flag or negative path. The local-only text-to-speech-models-smoke checks LFM3-Audio and Soprano voices, refusals and an ASR round trip (#1615) without binding these fields to a locked pack.", "issue": "https://github.com/leehack/llamadart/issues/1196" } }, diff --git a/skills/llamadart-speech/SKILL.md b/skills/llamadart-speech/SKILL.md index 9ddd96d82..ee3f0af77 100644 --- a/skills/llamadart-speech/SKILL.md +++ b/skills/llamadart-speech/SKILL.md @@ -3,8 +3,8 @@ name: llamadart-speech description: >- Use when adding speech to a llamadart app: transcribing audio files with Qwen3-ASR through SpeechToTextEngine, streaming live PCM dictation with - LiteRT-LM ASR, synthesizing speech with Qwen3-TTS through - TextToSpeechEngine, saving WAV output, handling LlamaAudioFormatException or + LiteRT-LM ASR, synthesizing speech with Qwen3-TTS, LFM3-Audio or Soprano + through TextToSpeechEngine, selecting predefined voices, saving WAV output, handling LlamaAudioFormatException or LlamaSpeechTranscriptTruncatedException, or checking speech support on native and Web runtimes. --- @@ -78,6 +78,18 @@ description: >- bridge assets). LiteRT-LM (native and Web) has no TTS. Synthesis is runtime-native, so a custom `TextToSpeechAdapter` can target only a model the runtime reports as a `BackendTextToSpeechModel`. + - LFM3-Audio / LFM3-Omni: `Lfm3AudioTtsAdapter` with the LFM3 model that has + the `tts` chat template and its mmproj; voices `female` (default) and + `male`; `language` is passed through unvalidated; request sampling + settings are validated but unused (the GGUF's own apply); no speaker + reference. 24 kHz. + - Soprano: `SopranoTtsAdapter`; no language, voice or speaker reference; + default `temperature` 0.8, pass 0 to match upstream's greedy example. + 32 kHz. No published llama.cpp GGUF: convert it (text-to-speech guide). + - LFM3-Audio and Soprano are native llama.cpp only and need + llamadart-native v0.8.0 or later. On an older runtime (or Apple companion + lock) `load` throws `LlamaUnsupportedException` naming the release before + loading any file. Web drives Qwen3-TTS only. - After `attach`, `await recognizer.capabilities` / `synthesizer.capabilities` and gate on `isSupported`, showing `unsupportedReason`. A loaded projector does not prove audio support or a @@ -89,7 +101,7 @@ description: >- - Use the capability fields instead of assuming: `inputKinds`, `encodedAudioFormats`, `supportsPartialResults`, `supportsStreamingInput` (STT); `sampleRateHz`, `supportedLanguages`, `supportsSpeakerReference`, - `speakerReferenceInputKinds` (TTS). + `speakerReferenceInputKinds`, `supportsVoice`, `voices` (TTS). - Audio input types are `SpeechAudioFileInput(path)`, `SpeechAudioBytesInput(bytes)` and `SpeechAudioPcmInput(Float32List)`, each with optional `SpeechAudioFormat(sampleRateHz, channelCount, encoding, @@ -162,9 +174,9 @@ description: >- engine share a lease. Do not start chat generation on an attached engine until `task.done` completes. A LiteRT-LM recognizer allows one task per instance. - TTS returns one complete buffer of interleaved float32 PCM (24 kHz mono for - Qwen3-TTS; read `result.sampleRateHz` and `channelCount` rather than - hard-coding). There are no playable chunks (`supportsIncrementalAudio` is - false). + Qwen3-TTS and LFM3-Audio, 32 kHz for Soprano; read `result.sampleRateHz` + and `channelCount` rather than hard-coding). There are no playable chunks + (`supportsIncrementalAudio` is false). - `TextToSpeechProgressEvent` (`phase`, `promptTokensRemaining`, `framesGenerated`) is for status UI only. - `result.truncated` is true when generation hit `maxFrames` (default @@ -175,6 +187,12 @@ description: >- `ko`, `de`, `fr`, `ru`, `pt`, `es`, `it`) or their English names (`'English'` becomes `en`). Anything else, empty text, or bad sampling values throw `LlamaTextToSpeechException` before the task starts. +- `TextToSpeechRequest.voice` names one of `capabilities.voices` (any case; + null speaks the first). An unlisted name, or a voice with a speaker + reference, throws `LlamaTextToSpeechException`; a voice for a model without + `supportsVoice` throws `LlamaUnsupportedException`. Runtimes before + llamadart-native v0.9.0 report `supportsVoice` with empty `voices` and check + the name at startup. - Speaker references must be encoded audio (`SpeechAudioBytesInput` is portable; file paths are native only; PCM throws). Treat them as sensitive user data. @@ -355,6 +373,37 @@ Future speak( } ``` +Speak with an LFM3-Audio voice (native llama.cpp, llamadart-native v0.8.0 or +later): + +```dart +import 'package:llamadart/llamadart.dart'; + +Future speakAsMale( + ModelSource model, + ModelSource projector, + String text, +) async { + final TextToSpeechEngine synthesizer = await TextToSpeechEngine.load( + TextToSpeechModel( + model, + projector: projector, + adapter: const Lfm3AudioTtsAdapter(), + ), + ); + try { + final TextToSpeechCapabilities capabilities = + await synthesizer.capabilities; + final String? voice = capabilities.voices.contains('male') ? 'male' : null; + return await synthesizer.synthesizeOnce( + TextToSpeechRequest(text: text, voice: voice), + ); + } finally { + await synthesizer.dispose(); + } +} +``` + ## More - Speech to text: https://llamadart.leehack.com/docs/guides/speech-to-text diff --git a/test/e2e/backends/llama_cpp_exit_teardown_e2e_test.dart b/test/e2e/backends/llama_cpp_exit_teardown_e2e_test.dart index 94dbef943..ff3ef7cc8 100644 --- a/test/e2e/backends/llama_cpp_exit_teardown_e2e_test.dart +++ b/test/e2e/backends/llama_cpp_exit_teardown_e2e_test.dart @@ -17,13 +17,18 @@ import 'package:test/test.dart'; /// repeats each scenario (default 3). `EXIT_TEARDOWN_MMPROJ`, that model's /// projector, adds the projector scenario; `EXIT_TEARDOWN_DECISION_MODEL` and /// `EXIT_TEARDOWN_DECISION_HEAD`, an encoder GGUF and its decision head, add -/// the decision scenario. +/// the decision scenario; `EXIT_TEARDOWN_TTS_MODEL`, `EXIT_TEARDOWN_TTS_MMPROJ` +/// and `EXIT_TEARDOWN_TTS_ADAPTER` (`qwen3-tts`, `lfm3-audio` or `soprano`) +/// add the scenario that exits during synthesis. void main() { final environment = Platform.environment; final model = environment['EXIT_TEARDOWN_MODEL']; final projector = environment['EXIT_TEARDOWN_MMPROJ']; final decisionModel = environment['EXIT_TEARDOWN_DECISION_MODEL']; final decisionHead = environment['EXIT_TEARDOWN_DECISION_HEAD']; + final ttsModel = environment['EXIT_TEARDOWN_TTS_MODEL']; + final ttsProjector = environment['EXIT_TEARDOWN_TTS_MMPROJ']; + final ttsAdapter = environment['EXIT_TEARDOWN_TTS_ADAPTER']; final runs = int.parse(environment['EXIT_TEARDOWN_RUNS'] ?? '3'); // A scenario of test/fixtures/llama_cpp_exit_probe.dart with its remaining @@ -57,6 +62,7 @@ void main() { ('quit-projector', [model, projector], 0, 'Metal'), ('quit-disposing', [model, projector], 0, null), ('quit-decision', [decisionModel, decisionHead], 0, 'MTL'), + ('quit-speaking', [ttsModel, ttsProjector, ttsAdapter], 0, null), ('throw-generating', [model], 255, 'Metal'), ('throw-loading', [model], 255, null), ('kill-loading', [model], 0, null), diff --git a/test/e2e/backends/text_to_speech_models_e2e_test.dart b/test/e2e/backends/text_to_speech_models_e2e_test.dart new file mode 100644 index 000000000..96ad80a95 --- /dev/null +++ b/test/e2e/backends/text_to_speech_models_e2e_test.dart @@ -0,0 +1,302 @@ +@TestOn('vm') +@Tags(['local-only', 'e2e']) +@Timeout(Duration(minutes: 30)) +library; + +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:llamadart/llamadart.dart'; +import 'package:test/test.dart'; + +const _asrModelKey = 'LLAMADART_STT_MODEL_PATH'; +const _asrMmprojKey = 'LLAMADART_STT_MMPROJ_PATH'; +const _outputDirectoryKey = 'LLAMADART_TTS_OUTPUT_DIR'; +const _gpuKey = 'LLAMADART_TTS_GPU'; +const _text = 'Good morning. The weather is sunny and warm today.'; + +const _params = ModelParams( + contextSize: 4096, + numberOfThreads: 2, + numberOfThreadsBatch: 2, + preferredBackend: GpuBackend.cpu, + gpuLayers: 0, +); +const _gpuParams = ModelParams( + contextSize: 4096, + numberOfThreads: 2, + numberOfThreadsBatch: 2, + gpuLayers: ModelParams.maxGpuLayers, +); + +class _Spec { + final String name; + final String key; + final TextToSpeechAdapter adapter; + final int sampleRateHz; + final List voices; + final bool supportsLanguage; + final double temperature; + + const _Spec({ + required this.name, + required this.key, + required this.adapter, + required this.sampleRateHz, + this.voices = const [], + this.supportsLanguage = false, + this.temperature = 0.8, + }); + + String get modelKey => 'LLAMADART_TTS_${key}_MODEL_PATH'; + String get mmprojKey => 'LLAMADART_TTS_${key}_MMPROJ_PATH'; +} + +const _specs = <_Spec>[ + _Spec( + name: 'LFM3-Audio', + key: 'LFM3', + adapter: Lfm3AudioTtsAdapter(), + sampleRateHz: 24000, + voices: ['female', 'male'], + supportsLanguage: true, + ), + _Spec( + name: 'Soprano', + key: 'SOPRANO', + adapter: SopranoTtsAdapter(), + sampleRateHz: 32000, + temperature: 0, + ), +]; + +void main() { + SpeechToTextEngine? recognizer; + + setUpAll(() async { + final model = _file(_asrModelKey); + final projector = _file(_asrMmprojKey); + if (model == null || projector == null) return; + recognizer = await SpeechToTextEngine.load( + SpeechToTextModel( + ModelSource.path(model), + projector: ModelSource.path(projector), + adapter: const Qwen3AsrAdapter(), + ), + params: _params, + ); + }); + + tearDownAll(() async => recognizer?.dispose()); + + for (final spec in _specs) { + group(spec.name, () { + TextToSpeechEngine? synthesizer; + + setUpAll(() async { + final model = _file(spec.modelKey); + final projector = _file(spec.mmprojKey); + if (model == null || projector == null) return; + synthesizer = await TextToSpeechEngine.load( + TextToSpeechModel( + ModelSource.path(model), + projector: ModelSource.path(projector), + adapter: spec.adapter, + ), + params: Platform.environment[_gpuKey] == '1' ? _gpuParams : _params, + ); + }); + + tearDownAll(() async => synthesizer?.dispose()); + + TextToSpeechEngine? engine() { + final value = synthesizer; + if (value == null) { + markTestSkipped( + 'Set ${spec.modelKey} and ${spec.mmprojKey} to run the ' + '${spec.name} E2E.', + ); + } + return value; + } + + TextToSpeechRequest request({String? voice, int seed = 1}) => + TextToSpeechRequest( + text: _text, + voice: voice, + maxFrames: 1024, + temperature: spec.temperature, + seed: seed, + ); + + test('reports the model capabilities', () async { + final tts = engine(); + if (tts == null) return; + final capabilities = await tts.capabilities; + expect( + capabilities.isSupported, + isTrue, + reason: capabilities.unsupportedReason, + ); + expect(capabilities.sampleRateHz, spec.sampleRateHz); + expect(capabilities.channelCount, 1); + expect(capabilities.supportsVoice, spec.voices.isNotEmpty); + expect(capabilities.voices, spec.voices); + expect(capabilities.supportsLanguage, spec.supportsLanguage); + expect(capabilities.supportsSpeakerReference, isFalse); + }); + + test('speech transcribes back to the text', () async { + final tts = engine(); + if (tts == null) return; + final result = await tts.synthesizeOnce(request()); + expect(result.sampleRateHz, spec.sampleRateHz); + expect(result.truncated, isFalse); + await _expectTranscript(recognizer, result, '${spec.key}-default'); + }); + + test('each listed voice speaks the text and changes the audio', () async { + final tts = engine(); + if (tts == null) return; + if (spec.voices.length < 2) { + markTestSkipped('${spec.name} lists fewer than two voices.'); + return; + } + final first = await tts.synthesizeOnce( + request(voice: spec.voices.first), + ); + final last = await tts.synthesizeOnce( + request(voice: spec.voices.last.toUpperCase()), + ); + expect(last.samples, isNot(orderedEquals(first.samples))); + await _expectTranscript( + recognizer, + last, + '${spec.key}-${spec.voices.last}', + ); + }); + + test('rejects what the model does not take before synthesis', () async { + final tts = engine(); + if (tts == null) return; + if (spec.voices.isEmpty) { + await expectLater( + tts.synthesize(request(voice: 'female')), + throwsA(isA()), + ); + } else { + await expectLater( + tts.synthesize(request(voice: 'no-such-voice')), + throwsA(isA()), + ); + } + if (!spec.supportsLanguage) { + await expectLater( + tts.synthesize( + const TextToSpeechRequest(text: _text, language: 'en'), + ), + throwsA(isA()), + ); + } + await expectLater( + tts.synthesize( + TextToSpeechRequest( + text: _text, + speakerReference: SpeechAudioBytesInput( + Uint8List.fromList(const [1, 2, 3]), + ), + ), + ), + throwsA(isA()), + ); + }); + + test('a fixed seed repeats after a cancelled task', () async { + final tts = engine(); + if (tts == null) return; + final first = await tts.synthesizeOnce(request()); + final cancelled = await tts.synthesize(request()); + await cancelled.events.firstWhere( + (event) => event is TextToSpeechProgressEvent, + ); + cancelled.cancel(); + expect( + (await cancelled.done).state, + TextToSpeechCompletionState.cancelled, + ); + final repeated = await tts.synthesizeOnce(request()); + expect(repeated.framesGenerated, first.framesGenerated); + expect(repeated.samples, orderedEquals(first.samples)); + }); + }); + } +} + +Future _expectTranscript( + SpeechToTextEngine? recognizer, + TextToSpeechResult result, + String name, +) async { + final wav = result.toWavBytes(); + final directory = Platform.environment[_outputDirectoryKey]; + if (directory != null && directory.isNotEmpty) { + File('$directory/$name.wav') + ..parent.createSync(recursive: true) + ..writeAsBytesSync(wav, flush: true); + } + if (recognizer == null) { + markTestSkipped( + 'Set $_asrModelKey and $_asrMmprojKey to check the speech content.', + ); + return; + } + final transcript = (await recognizer.transcribeOnce( + SpeechToTextRequest( + audio: SpeechAudioBytesInput( + wav, + format: const SpeechAudioFormat(encoding: 'wav'), + ), + ), + )).text; + print('TRANSCRIPT $name: $transcript'); + expect( + _wordErrorRate(_text, transcript), + lessThanOrEqualTo(0.25), + reason: 'transcript: $transcript', + ); +} + +double _wordErrorRate(String reference, String hypothesis) { + List words(String text) => text + .toLowerCase() + .replaceAll(RegExp(r"[^a-z0-9' ]"), ' ') + .split(RegExp(r'\s+')) + .where((word) => word.isNotEmpty) + .toList(); + final expected = words(reference); + final actual = words(hypothesis); + var previous = List.generate(actual.length + 1, (index) => index); + for (var i = 1; i <= expected.length; i++) { + final current = List.filled(actual.length + 1, 0)..[0] = i; + for (var j = 1; j <= actual.length; j++) { + final substitution = + previous[j - 1] + (expected[i - 1] == actual[j - 1] ? 0 : 1); + current[j] = [ + previous[j] + 1, + current[j - 1] + 1, + substitution, + ].reduce((a, b) => a < b ? a : b); + } + previous = current; + } + return previous[actual.length] / expected.length; +} + +String? _file(String key) { + final value = Platform.environment[key]; + if (value == null || value.isEmpty) return null; + if (!File(value).existsSync()) { + throw StateError('$key does not exist.'); + } + return value; +} diff --git a/test/fixtures/llama_cpp_exit_probe.dart b/test/fixtures/llama_cpp_exit_probe.dart index 8ad165f7b..52d5e5720 100644 --- a/test/fixtures/llama_cpp_exit_probe.dart +++ b/test/fixtures/llama_cpp_exit_probe.dart @@ -1,7 +1,9 @@ // Subprocess fixture: ends the process in one way while llama.cpp objects are // alive. Arguments: the scenario and a GGUF chat model; `quit-projector` and // `quit-disposing` also take that model's projector, and `quit-decision` -// takes an encoder GGUF and its decision head instead. `quit-disposing` exits +// takes an encoder GGUF and its decision head instead; `quit-speaking` takes +// a text-to-speech GGUF, its projector and an adapter name (`qwen3-tts`, +// `lfm3-audio`, `soprano`) and exits during synthesis. `quit-disposing` exits // `EXIT_PROBE_DISPOSE_DELAY_US` microseconds (default 1000) after the owning // isolate starts to dispose. // @@ -70,6 +72,37 @@ Future main(List args) async { // A timer is too coarse for the few milliseconds the frees take. while (delay.elapsedMicroseconds < micros) {} _cExit(); + case 'quit-speaking': + final [projectorPath, adapter] = extra; + final synthesizer = await TextToSpeechEngine.load( + TextToSpeechModel( + ModelSource.path(modelPath), + projector: ModelSource.path(projectorPath), + adapter: switch (adapter) { + 'qwen3-tts' => const Qwen3TtsAdapter(), + 'lfm3-audio' => const Lfm3AudioTtsAdapter(), + 'soprano' => const SopranoTtsAdapter(), + _ => throw ArgumentError.value(adapter, 'adapter'), + }, + ), + params: const ModelParams(contextSize: 2048), + ); + final frame = Completer(); + final task = await synthesizer.synthesize( + const TextToSpeechRequest( + text: 'Count from one to twenty, slowly and clearly.', + maxFrames: 2048, + ), + ); + task.events.listen((event) { + if (event is TextToSpeechProgressEvent && + event.framesGenerated > 0 && + !frame.isCompleted) { + frame.complete(); + } + }); + await frame.future; + _quit(scenario); case 'quit-decision': final decisions = await DecisionEngine.load( DecisionModel( diff --git a/test/integration/backends/llama_cpp_request_performance_test.dart b/test/integration/backends/llama_cpp_request_performance_test.dart index 1b0b8f840..0d714978d 100644 --- a/test/integration/backends/llama_cpp_request_performance_test.dart +++ b/test/integration/backends/llama_cpp_request_performance_test.dart @@ -226,6 +226,8 @@ void main() { 'test stops before speech model execution', ); }; + // Keep the legacy init this fake replaces on runtimes with the opt-in. + fields[#initExt] = null; mirror.setField( symbol('_ttsApi'), original.type.newInstance(Symbol.empty, [], fields).reflectee, diff --git a/test/integration/backends/llama_cpp_tts_exclusivity_test.dart b/test/integration/backends/llama_cpp_tts_exclusivity_test.dart index 4cd3c126f..4c5da8e8e 100644 --- a/test/integration/backends/llama_cpp_tts_exclusivity_test.dart +++ b/test/integration/backends/llama_cpp_tts_exclusivity_test.dart @@ -321,6 +321,7 @@ class _Harness { fields[#free] = (Pointer task) {}; fields[#cancel] = (Pointer task) {}; fields[#setCancelFlag] = null; + fields[#initExt] = null; mirror.setField( symbol('_ttsApi'), original.type.newInstance(Symbol.empty, [], fields).reflectee, diff --git a/test/integration/backends/llama_cpp_tts_model_types_test.dart b/test/integration/backends/llama_cpp_tts_model_types_test.dart new file mode 100644 index 000000000..678d503c9 --- /dev/null +++ b/test/integration/backends/llama_cpp_tts_model_types_test.dart @@ -0,0 +1,438 @@ +@TestOn('vm') +library; + +import 'dart:ffi'; +import 'dart:io'; +import 'dart:mirrors'; + +import 'package:ffi/ffi.dart'; +import 'package:llamadart/backend.dart'; +import 'package:llamadart/llamadart.dart'; +import 'package:llamadart/src/backends/llama_cpp/bindings.dart'; +import 'package:llamadart/src/backends/llama_cpp/llama_cpp_service.dart'; +import 'package:test/test.dart'; + +import '../../support/synthetic_embedding_gguf.dart'; + +const _params = ModelParams( + numberOfThreads: 2, + numberOfThreadsBatch: 2, + device: ComputeDevice.cpu, + gpuLayers: 0, + contextSize: 64, +); +const _qwen3 = 1; +const _lfm3 = 2; +const _soprano = 3; +const _voiceCapability = 4; +const _languageCapability = 1; + +void main() { + late _Harness h; + setUp(() => h = _Harness()); + tearDown(() => h.dispose()); + + group('a runtime with the model-type opt-in', () { + test('accepts the types this core drives and the runtime builds', () { + h.runtimeTypes = 0x3e; + h.reportedType = _soprano; + + final capabilities = h.capabilities(); + + expect(capabilities.isSupported, isTrue); + expect(capabilities.model, BackendTextToSpeechModel.soprano); + expect(h.acceptedMasks.toSet(), {0xe}); + expect(capabilities.supportsVoice, isFalse); + expect(capabilities.voices, isEmpty); + expect(h.legacyInfoCalls, 0); + }); + + test('lists predefined voices in order', () { + h.reportedType = _lfm3; + h.model = h.ttsModel; + h.reportedCapabilities = _voiceCapability | _languageCapability; + h.voices = ['female', 'male']; + + final capabilities = h.capabilities(); + + expect(capabilities.isSupported, isTrue, reason: capabilities.reason); + expect(capabilities.model, BackendTextToSpeechModel.lfm3Audio); + expect(capabilities.supportsLanguage, isTrue); + expect(capabilities.supportsVoice, isTrue); + expect(capabilities.voices, ['female', 'male']); + expect(() => capabilities.voices.add('x'), throwsUnsupportedError); + }); + + test('reports voice selection without listing on a runtime before the ' + 'voice API', () { + h.reportedType = _lfm3; + h.model = h.ttsModel; + h.reportedCapabilities = _voiceCapability; + h.voices = null; + + final capabilities = h.capabilities(); + + expect(capabilities.supportsVoice, isTrue); + expect(capabilities.voices, isEmpty); + }); + + test('refuses LFM3-Audio on a model without a tts chat template', () { + h.reportedType = _lfm3; + + final capabilities = h.capabilities(); + + expect(capabilities.isSupported, isFalse); + expect(capabilities.reason, contains('no `tts` chat template')); + }); + + test('names the generators a runtime was built without', () { + h.runtimeTypes = 0x2; + h.reportedType = 0; + h.infoStatus = + llama_dart_tts_status.LLAMA_DART_TTS_STATUS_UNSUPPORTED.value; + + final capabilities = h.capabilities(); + + expect(capabilities.isSupported, isFalse); + expect(h.acceptedMasks.toSet(), {0x2}); + expect( + capabilities.reason, + contains('built without LFM3-Audio and Soprano speech output'), + ); + }); + + test('tells which models it drives without a loaded model', () { + h.runtimeTypes = 0x6; + h.capabilities(); + + String? reason(BackendTextToSpeechModel model) => + h.service.textToSpeechModelUnsupportedReason(model); + expect(reason(BackendTextToSpeechModel.qwen3Tts), isNull); + expect(reason(BackendTextToSpeechModel.lfm3Audio), isNull); + expect( + reason(BackendTextToSpeechModel.soprano), + allOf( + contains('built without Soprano speech output'), + contains('llamadart-native v0.8.0'), + ), + ); + }); + + test('passes the mask to init and the voice to start', () async { + h.reportedType = _lfm3; + h.model = h.ttsModel; + + await h.synthesize(voice: 'male'); + + expect(h.initMasks, [0xe]); + expect(h.startedVoices, ['male']); + expect(h.legacyInitCalls, 0); + expect(h.legacyStartCalls, 0); + }); + + test('starts without a voice through the plain start', () async { + await h.synthesize(); + + expect(h.initMasks, [0xe]); + expect(h.legacyStartCalls, 1); + expect(h.startedVoices, isEmpty); + }); + }); + + group('a runtime without the model-type opt-in', () { + setUp(() => h.withoutOptIn = true); + + test('drives Qwen3-TTS through the legacy calls', () async { + final capabilities = h.capabilities(); + expect(capabilities.isSupported, isTrue); + expect(capabilities.model, BackendTextToSpeechModel.qwen3Tts); + expect(capabilities.supportsVoice, isFalse); + expect(h.legacyInfoCalls, 1); + + await h.synthesize(); + expect(h.legacyInitCalls, 1); + expect(h.initMasks, isEmpty); + }); + + test('refuses other projectors naming the required runtime', () { + h.reportedType = 0; + h.infoStatus = + llama_dart_tts_status.LLAMA_DART_TTS_STATUS_UNSUPPORTED.value; + + final capabilities = h.capabilities(); + + expect(capabilities.isSupported, isFalse); + expect( + capabilities.reason, + allOf( + contains('Qwen3-TTS only'), + contains('llama_dart_tts_init_ext'), + contains('llamadart-native v0.8.0'), + ), + ); + }); + + test('refuses other models without a loaded model', () { + h.capabilities(); + + expect( + h.service.textToSpeechModelUnsupportedReason( + BackendTextToSpeechModel.qwen3Tts, + ), + isNull, + ); + expect( + h.service.textToSpeechModelUnsupportedReason( + BackendTextToSpeechModel.lfm3Audio, + ), + allOf( + contains('LFM3-Audio speech output needs'), + contains('llama_dart_tts_init_ext'), + contains('llamadart-native v0.8.0'), + ), + ); + }); + + test('refuses a voice before creating a task', () async { + await expectLater( + h.synthesize(voice: 'male'), + throwsA( + isA().having( + (error) => error.message, + 'message', + contains('llama_dart_tts_start_with_voice'), + ), + ), + ); + expect(h.legacyInitCalls, 0); + }); + }); +} + +extension on BackendTextToSpeechCapabilities { + String? get reason => unsupportedReason; +} + +class _Harness { + final directory = Directory.systemTemp.createTempSync('tts_model_types_'); + final service = LlamaCppService()..initializeBackend(); + final flag = calloc(); + late final int plainModel; + late final int ttsModel; + late int model; + final Map contexts = {}; + late final InstanceMirror mirror; + late final LibraryMirror library; + late final Map projectors; + late final Map modelProjectors; + + bool withoutOptIn = false; + int runtimeTypes = 0x0f; + int reportedType = _qwen3; + int reportedCapabilities = 0; + int infoStatus = 0; + List? voices = const []; + int legacyInfoCalls = 0; + int legacyInitCalls = 0; + int legacyStartCalls = 0; + final acceptedMasks = []; + final initMasks = []; + final startedVoices = []; + + Symbol symbol(String name) => MirrorSystem.getSymbol(name, library); + + _Harness() { + final plainPath = '${directory.path}/model.gguf'; + writeSyntheticLlamaGguf(plainPath); + plainModel = service.loadModel(plainPath, _params); + final ttsPath = '${directory.path}/tts-model.gguf'; + writeSyntheticLlamaGguf( + ttsPath, + stringMetadata: const {'tokenizer.chat_template.tts': '{{ text }}'}, + ); + ttsModel = service.loadModel(ttsPath, _params); + model = plainModel; + library = reflectClass(LlamaCppService).owner as LibraryMirror; + mirror = reflect(service); + projectors = mirror.getField(symbol('_mtmdContexts')).reflectee as Map; + modelProjectors = mirror.getField(symbol('_modelToMtmd')).reflectee as Map; + } + + int _context() => contexts.putIfAbsent(model, () { + final context = service.createContext(model, _params); + projectors[900 + model] = Pointer.fromAddress(1); + modelProjectors[model] = 900 + model; + return context; + }); + + void _installApi() { + mirror.setField(symbol('_ttsApi'), null); + mirror.setField(symbol('_ttsApiLookupAttempted'), false); + final original = mirror.invoke(symbol('_resolveTtsApi'), []); + final fields = { + for (final field + in original.type.declarations.values.whereType()) + if (!field.isStatic) + field.simpleName: original.getField(field.simpleName).reflectee, + }; + int fillInfo(Pointer info) { + info.ref.model_type = reportedType; + info.ref.capabilities = reportedCapabilities; + info.ref.sample_rate = 24000; + info.ref.channels = 1; + return infoStatus; + } + + fields[#getInfo] = + (Pointer mtmd, Pointer info) { + legacyInfoCalls++; + return fillInfo(info); + }; + fields[#init] = + (Pointer c, Pointer m, Pointer s) { + legacyInitCalls++; + return Pointer.fromAddress(123); + }; + fields[#start] = + (Pointer task, Pointer r) { + legacyStartCalls++; + return 0; + }; + fields[#step] = + (Pointer task, Pointer p) { + p.ref.state = + llama_dart_tts_state.LLAMA_DART_TTS_STATE_COMPLETED.value; + p.ref.frames_generated = 2; + return 0; + }; + fields[#getOutputInfo] = + (Pointer task, Pointer i) { + i.ref.sample_count = 1; + i.ref.sample_rate = 24000; + i.ref.channels = 1; + return 0; + }; + fields[#readPcm] = + ( + Pointer task, + int offset, + Pointer pcm, + int capacity, + Pointer count, + ) { + pcm[0] = 0.25; + count.value = 1; + return 0; + }; + fields[#reset] = (Pointer task) => 0; + fields[#free] = (Pointer task) {}; + fields[#cancel] = (Pointer task) {}; + fields[#setCancelFlag] = null; + if (withoutOptIn) { + for (final name in [ + #supportedModelTypes, + #getInfoExt, + #initExt, + #startWithVoice, + #getVoiceCount, + #getVoiceName, + ]) { + fields[name] = null; + } + } else { + fields[#supportedModelTypes] = () => runtimeTypes; + fields[#getInfoExt] = + ( + Pointer mtmd, + int mask, + Pointer info, + ) { + acceptedMasks.add(mask); + return fillInfo(info); + }; + fields[#initExt] = + ( + Pointer c, + Pointer m, + int mask, + Pointer s, + ) { + initMasks.add(mask); + return Pointer.fromAddress(123); + }; + fields[#startWithVoice] = + ( + Pointer task, + Pointer r, + Pointer voice, + ) { + startedVoices.add(voice.cast().toDartString()); + return 0; + }; + final listed = voices; + fields[#getVoiceCount] = listed == null + ? null + : (Pointer m, int mask, Pointer count) { + acceptedMasks.add(mask); + count.value = listed.length; + return 0; + }; + fields[#getVoiceName] = listed == null + ? null + : ( + Pointer m, + int mask, + int index, + Pointer name, + int capacity, + Pointer length, + ) { + final bytes = listed[index].codeUnits; + length.value = bytes.length; + if (name == nullptr) return 0; + if (capacity <= bytes.length) { + return llama_dart_tts_status + .LLAMA_DART_TTS_STATUS_INVALID_ARGUMENT + .value; + } + final out = name.cast(); + for (var i = 0; i < bytes.length; i++) { + out[i] = bytes[i]; + } + out[bytes.length] = 0; + return 0; + }; + } + mirror.setField( + symbol('_ttsApi'), + original.type.newInstance(Symbol.empty, [], fields).reflectee, + ); + } + + BackendTextToSpeechCapabilities capabilities() { + final context = _context(); + _installApi(); + return service.textToSpeechCapabilities(context, 900 + model); + } + + Future synthesize({String? voice}) { + final context = _context(); + _installApi(); + return service.synthesizeTextToSpeech( + context, + 900 + model, + BackendTextToSpeechRequest(text: 'hello', voice: voice), + flag.address, + ); + } + + void dispose() { + for (final model in contexts.keys) { + projectors.remove(900 + model); + modelProjectors.remove(model); + } + service.dispose(); + calloc.free(flag); + directory.deleteSync(recursive: true); + } +} diff --git a/test/support/synthetic_embedding_gguf.dart b/test/support/synthetic_embedding_gguf.dart index c6bb1a1d4..74c7f9678 100644 --- a/test/support/synthetic_embedding_gguf.dart +++ b/test/support/synthetic_embedding_gguf.dart @@ -76,6 +76,7 @@ File writeSyntheticLlamaGguf( String path, { String architecture = 'llama', Map uint32Metadata = const {}, + Map stringMetadata = const {}, int? eosTokenId, int? poolingType, bool? causalAttention, @@ -102,6 +103,8 @@ File writeSyntheticLlamaGguf( '$arch.pooling_type': _GgufValue.uint32(poolingType), for (final MapEntry(:key, :value) in uint32Metadata.entries) key: _GgufValue.uint32(value), + for (final MapEntry(:key, :value) in stringMetadata.entries) + key: _GgufValue.string(value), }, tensors: { 'token_embd.weight': _weights(random, [_embd, _tokens.length]), diff --git a/test/unit/backends/native/native_backend_test.dart b/test/unit/backends/native/native_backend_test.dart index f579d47d3..2b3ffcf9a 100644 --- a/test/unit/backends/native/native_backend_test.dart +++ b/test/unit/backends/native/native_backend_test.dart @@ -1654,6 +1654,49 @@ void main() { } }); + test('asks the llama.cpp runtime which text-to-speech models it drives ' + 'before a load and keeps that runtime for the load', () async { + var created = 0; + final llama = _TextToSpeechFakeBackend(handle: 11); + final backend = NativeAutoBackend( + llamaCppFactory: () { + created++; + return llama; + }, + liteRtLmFactory: () => _FakeBackend(handle: 22), + ); + + try { + expect( + await backend.textToSpeechModelUnsupportedReason( + BackendTextToSpeechModel.soprano, + ), + 'no soprano', + ); + expect( + await backend.textToSpeechModelUnsupportedReason( + BackendTextToSpeechModel.lfm3Audio, + ), + isNull, + ); + await backend.modelLoad('/models/lfm3.gguf', const ModelParams()); + expect( + await backend.textToSpeechModelUnsupportedReason( + BackendTextToSpeechModel.lfm3Audio, + ), + isNull, + ); + expect(llama.probedModels, [ + BackendTextToSpeechModel.soprano, + BackendTextToSpeechModel.lfm3Audio, + BackendTextToSpeechModel.lfm3Audio, + ]); + expect(created, 1); + } finally { + await backend.dispose(); + } + }); + test('rejects decision calls before a model load', () async { final llama = _DecisionFakeBackend(handle: 11); final backend = NativeAutoBackend( @@ -2758,11 +2801,20 @@ class _ToolResultMediaFakeBackend extends _FakeBackend } class _TextToSpeechFakeBackend extends _FakeBackend - implements BackendTextToSpeech { + implements BackendTextToSpeech, BackendTextToSpeechModelSupport { _TextToSpeechFakeBackend({required super.handle}); (int, int)? capabilityHandles; (int, int)? synthesisHandles; + final List probedModels = []; + + @override + Future textToSpeechModelUnsupportedReason( + BackendTextToSpeechModel model, + ) async { + probedModels.add(model); + return model == BackendTextToSpeechModel.soprano ? 'no soprano' : null; + } @override Future textToSpeechCapabilities( diff --git a/test/unit/core/speech/text_to_speech_model_test.dart b/test/unit/core/speech/text_to_speech_model_test.dart index 75c3f9f7d..fea6f0ff9 100644 --- a/test/unit/core/speech/text_to_speech_model_test.dart +++ b/test/unit/core/speech/text_to_speech_model_test.dart @@ -44,6 +44,27 @@ void main() { }); }); + test('the LFM3-Audio and Soprano adapters drive their models only', () { + const lfm3 = Lfm3AudioTtsAdapter(); + const soprano = SopranoTtsAdapter(); + + expect(lfm3.name, 'LFM3-Audio'); + expect(soprano.name, 'Soprano'); + for (final model in BackendTextToSpeechModel.values) { + expect( + lfm3.supportsModel(model), + model == BackendTextToSpeechModel.lfm3Audio, + ); + expect( + soprano.supportsModel(model), + model == BackendTextToSpeechModel.soprano, + ); + } + expect(lfm3.supportsModel(null), isFalse); + expect(lfm3.normalizeLanguage('English'), 'English'); + expect(lfm3.supportedLanguages, isEmpty); + }); + test('a minimal adapter lowercases languages and lists none', () { const adapter = _MinimalAdapter(); diff --git a/test/unit/core/speech/text_to_speech_test.dart b/test/unit/core/speech/text_to_speech_test.dart index c5696a2a5..5babc43f2 100644 --- a/test/unit/core/speech/text_to_speech_test.dart +++ b/test/unit/core/speech/text_to_speech_test.dart @@ -462,6 +462,164 @@ void main() { expect(backend.lastRequest, isNull); }); + group('voices', () { + setUp(() { + backend.capabilities = const BackendTextToSpeechCapabilities( + isSupported: true, + model: BackendTextToSpeechModel.lfm3Audio, + sampleRateHz: 24000, + channelCount: 1, + supportsLanguage: true, + supportsCancellation: true, + supportsVoice: true, + voices: ['female', 'male'], + ); + speechEngine = TextToSpeechEngine.attach( + llamaEngine, + adapter: const Lfm3AudioTtsAdapter(), + ); + }); + + test('reports the listed voices and passes the selected one', () async { + await _loadTextToSpeechModel(llamaEngine); + + final capabilities = await speechEngine.capabilities; + expect(capabilities.supportsVoice, isTrue); + expect(capabilities.voices, ['female', 'male']); + expect(capabilities.supportsSpeakerReference, isFalse); + expect(capabilities.supportedLanguages, isEmpty); + + await speechEngine.synthesizeOnce( + const TextToSpeechRequest( + text: 'Hello.', + voice: 'MALE', + language: 'English', + ), + ); + expect(backend.lastRequest?.voice, 'MALE'); + expect(backend.lastRequest?.language, 'English'); + + await speechEngine.synthesizeOnce( + const TextToSpeechRequest(text: 'Hello.'), + ); + expect(backend.lastRequest?.voice, isNull); + }); + + test('rejects an unlisted voice without starting', () async { + await _loadTextToSpeechModel(llamaEngine); + + await expectLater( + speechEngine.synthesize( + const TextToSpeechRequest(text: 'Hello.', voice: 'alto'), + ), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'Unknown LFM3-Audio voice `alto`. Use one of: female, male.', + ), + ), + ); + expect(backend.lastRequest, isNull); + }); + + test( + 'leaves an unlisted voice to a runtime that cannot list voices', + () async { + backend.capabilities = const BackendTextToSpeechCapabilities( + isSupported: true, + model: BackendTextToSpeechModel.lfm3Audio, + sampleRateHz: 24000, + channelCount: 1, + supportsVoice: true, + ); + await _loadTextToSpeechModel(llamaEngine); + + await speechEngine.synthesizeOnce( + const TextToSpeechRequest(text: 'Hello.', voice: 'alto'), + ); + expect(backend.lastRequest?.voice, 'alto'); + }, + ); + + test('rejects a voice for a model without voices', () async { + backend.capabilities = const BackendTextToSpeechCapabilities( + isSupported: true, + model: BackendTextToSpeechModel.soprano, + sampleRateHz: 32000, + channelCount: 1, + supportsCancellation: true, + voices: ['ignored'], + ); + speechEngine = TextToSpeechEngine.attach( + llamaEngine, + adapter: const SopranoTtsAdapter(), + ); + await _loadTextToSpeechModel(llamaEngine); + + final capabilities = await speechEngine.capabilities; + expect(capabilities.supportsVoice, isFalse); + expect(capabilities.voices, isEmpty); + await expectLater( + speechEngine.synthesize( + const TextToSpeechRequest(text: 'Hello.', voice: 'ignored'), + ), + throwsA(isA()), + ); + await expectLater( + speechEngine.synthesize( + const TextToSpeechRequest(text: 'Hello.', language: 'en'), + ), + throwsA(isA()), + ); + expect(backend.lastRequest, isNull); + }); + + test('rejects a blank voice and a voice with a speaker reference ' + 'before the capability lookup', () async { + await _loadTextToSpeechModel(llamaEngine); + + await expectLater( + speechEngine.synthesize( + const TextToSpeechRequest(text: 'Hello.', voice: ' '), + ), + throwsA(isA()), + ); + await expectLater( + speechEngine.synthesize( + TextToSpeechRequest( + text: 'Hello.', + voice: 'female', + speakerReference: SpeechAudioBytesInput( + Uint8List.fromList([1]), + ), + ), + ), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'A voice and a speaker reference cannot be combined.', + ), + ), + ); + expect(backend.lastCapabilitiesContextHandle, isNull); + }); + + test('a Qwen3-TTS adapter refuses an LFM3-Audio projector', () async { + speechEngine = TextToSpeechEngine.attach( + llamaEngine, + adapter: const Qwen3TtsAdapter(), + ); + await _loadTextToSpeechModel(llamaEngine); + + expect( + (await speechEngine.capabilities).unsupportedReason, + 'The loaded projector is not a supported Qwen3-TTS projector.', + ); + }); + }); + test('returns typed task failure and releases the lease', () async { backend.synthesisError = StateError('codec failed'); await _loadTextToSpeechModel(llamaEngine); @@ -636,6 +794,40 @@ void main() { }, ); + test('refuses an adapter whose models the runtime cannot drive before ' + 'loading anything', () async { + backend.modelRefusals = { + BackendTextToSpeechModel.lfm3Audio: 'needs llamadart-native v0.8.0', + }; + await expectLater( + TextToSpeechEngine.load( + model(adapter: const Lfm3AudioTtsAdapter()), + backend: backend, + ), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'needs llamadart-native v0.8.0', + ), + ), + ); + expect(backend.lastModelParams, isNull); + expect(backend.disposeCalls, 1); + }); + + test('loads when the runtime drives a model the adapter accepts', () async { + backend.modelRefusals = { + BackendTextToSpeechModel.lfm3Audio: 'needs llamadart-native v0.8.0', + }; + final synthesizer = await TextToSpeechEngine.load( + model(), + backend: backend, + ); + await synthesizer.dispose(); + expect(backend.lastModelParams, isNotNull); + }); + test('a runtime without text-to-speech leaves nothing loaded', () async { backend.capabilities = const BackendTextToSpeechCapabilities( isSupported: false, @@ -769,8 +961,19 @@ Future _loadTextToSpeechModel(LlamaEngine engine) async { } class _TextToSpeechBackend - implements LlamaBackend, BackendMultimodalSupport, BackendTextToSpeech { + implements + LlamaBackend, + BackendMultimodalSupport, + BackendTextToSpeech, + BackendTextToSpeechModelSupport { bool _ready = false; + Map modelRefusals = const {}; + + @override + Future textToSpeechModelUnsupportedReason( + BackendTextToSpeechModel model, + ) async => modelRefusals[model]; + BackendTextToSpeechCapabilities capabilities = const BackendTextToSpeechCapabilities( isSupported: true, diff --git a/test/unit/public_entrypoints_test.dart b/test/unit/public_entrypoints_test.dart index 1f79c435a..28a763a04 100644 --- a/test/unit/public_entrypoints_test.dart +++ b/test/unit/public_entrypoints_test.dart @@ -107,6 +107,7 @@ const _appNames = { 'ImageVaeTiling', 'TiledImageGenerationRequest', 'KvCacheType', + 'Lfm3AudioTtsAdapter', 'LiteRtLmActivationDataType', 'LiteRtLmAsrAdapter', 'LiteRtLmAsrBackend', @@ -224,6 +225,7 @@ const _appNames = { 'NoulQuestion', 'Qwen3AsrAdapter', 'Qwen3TtsAdapter', + 'SopranoTtsAdapter', 'ReferenceImageEditingRequest', 'RemoteModelUrl', 'ScoreAnswer', @@ -387,6 +389,7 @@ void main() { 'BackendTextToSpeech', 'BackendTextToSpeechCapabilities', 'BackendTextToSpeechModel', + 'BackendTextToSpeechModelSupport', 'BackendTextToSpeechPhase', 'BackendTextToSpeechProgress', 'BackendTextToSpeechRequest', diff --git a/test/unit/tooling/run_local_e2e_test.dart b/test/unit/tooling/run_local_e2e_test.dart index e8c93e3fc..aeab26736 100644 --- a/test/unit/tooling/run_local_e2e_test.dart +++ b/test/unit/tooling/run_local_e2e_test.dart @@ -2339,6 +2339,29 @@ Future main(List args) async { ); }); + test( + 'dry-runs the text-to-speech model families from the environment', + () async { + final result = await runLocalE2e( + const ['--scenario', 'text-to-speech-models-smoke', '--dry-run'], + projectRoot: '/repo', + displayShell: LocalE2eDisplayShell.posix, + ); + + expect(result.exitCode, 0); + expect( + result.stdout, + contains( + 'LLAMADART_TTS_OUTPUT_DIR=/repo/build/text-to-speech-models', + ), + ); + expect( + result.stdout, + contains('test/e2e/backends/text_to_speech_models_e2e_test.dart'), + ); + }, + ); + test('requires a model and projector for text-to-speech', () async { final result = await runLocalE2e( const [ diff --git a/tool/testing/run_local_e2e.dart b/tool/testing/run_local_e2e.dart index 9126d11c6..4b3504145 100644 --- a/tool/testing/run_local_e2e.dart +++ b/tool/testing/run_local_e2e.dart @@ -948,6 +948,37 @@ List buildLocalE2eScenarios({String? projectRoot}) { ), ], ), + LocalE2eScenario( + name: 'text-to-speech-models-smoke', + group: LocalE2eScenarioGroup.dartLocalOnly, + description: + 'Run typed native LFM3-Audio and Soprano synthesis with voices, ' + 'refusals, seed repeats and an ASR round trip, for each model whose ' + 'LLAMADART_TTS__MODEL_PATH and _MMPROJ_PATH are set.', + requiresDevice: false, + stepsBuilder: (context) => [ + LocalE2eCommandStep( + workingDirectory: context.projectRoot, + executable: 'dart', + arguments: const [ + 'test', + '-p', + 'vm', + '-j', + '1', + '--run-skipped', + '-t', + 'local-only', + 'test/e2e/backends/text_to_speech_models_e2e_test.dart', + ], + environment: { + 'LLAMADART_TTS_OUTPUT_DIR': + '${context.projectRoot}/build/text-to-speech-models', + }, + description: 'Typed text-to-speech model family smoke', + ), + ], + ), LocalE2eScenario( name: 'image-generation-smoke', group: LocalE2eScenarioGroup.dartLocalOnly, diff --git a/tool/testing/test_matrix.dart b/tool/testing/test_matrix.dart index 295c06f39..1b629720d 100644 --- a/tool/testing/test_matrix.dart +++ b/tool/testing/test_matrix.dart @@ -650,6 +650,25 @@ const List testMatrixRows = [ 'Text-to-speech API, native audio generation, Qwen3-TTS projector, or ' 'chat-app synthesis changes.', ), + TestMatrixRow( + id: 'text-to-speech-models-smoke', + tier: 'targeted', + mode: 'local-only', + covers: + 'real native LFM3-Audio and Soprano capabilities, listed voices, ' + 'voice/language/speaker-reference refusals, seed repeat after a ' + 'cancel, and a Qwen3-ASR round trip of the synthesized speech', + command: + 'LLAMADART_TTS_LFM3_MODEL_PATH= ' + 'LLAMADART_TTS_LFM3_MMPROJ_PATH= ' + 'LLAMADART_STT_MODEL_PATH= ' + 'LLAMADART_STT_MMPROJ_PATH= ' + 'dart run tool/testing/run_local_e2e.dart --scenario ' + 'text-to-speech-models-smoke', + useWhen: + 'Text-to-speech model-type opt-in, voices, LFM3-Audio or Soprano ' + 'adapters, or llama.cpp pin changes. Set the SOPRANO variables too.', + ), TestMatrixRow( id: 'image-generation-smoke', tier: 'targeted', diff --git a/website/docs/changelog/recent-releases.md b/website/docs/changelog/recent-releases.md index d0dbcdc6a..13c088870 100644 --- a/website/docs/changelog/recent-releases.md +++ b/website/docs/changelog/recent-releases.md @@ -14,6 +14,7 @@ validate against the exact release tag notes. ## Unreleased - Adopt llama.cpp `v0.9.0`, which accumulates F16 matrix products in F32 on ARM CPUs so they no longer overflow, and applies a GGUF's suppress tokens when sampling Qwen3-TTS codes. +- Add LFM3-Audio and Soprano speech output on native llama.cpp (`Lfm3AudioTtsAdapter`, `SopranoTtsAdapter`) and predefined voice selection (`TextToSpeechRequest.voice`, `TextToSpeechCapabilities.voices`); runtimes before llamadart-native v0.8.0 refuse them with `LlamaUnsupportedException` ([#1615](https://github.com/leehack/llamadart/issues/1615)). ## 0.18.0 diff --git a/website/docs/getting-started/model-families.md b/website/docs/getting-started/model-families.md index f7d51b836..b57aa4676 100644 --- a/website/docs/getting-started/model-families.md +++ b/website/docs/getting-started/model-families.md @@ -90,6 +90,8 @@ examples use. `.litertlm` bundles process media themselves. See | Speech to text (whole file) | Qwen3-ASR 0.6B | Validated | `ggml-org/Qwen3-ASR-0.6B-GGUF` | | Speech to text (live, LiteRT-LM) | Moonshine Tiny | Validated | `litert-community/moonshine-tiny` | | Text to speech | Qwen3-TTS 1.7B | Validated | `ggml-org/Qwen3-TTS-12Hz-1.7B-Base-GGUF` | +| Text to speech | LFM3-Audio 2B | Checked on macOS arm64 | `LiquidAI/LFM3-Audio-2B-GGUF` | +| Text to speech | Soprano 1.1 80M | Checked on macOS arm64 | Convert `ekwek/Soprano-1.1-80M` ([guide](../guides/text-to-speech#soprano)) | | Embeddings | EmbeddingGemma 300M | Used by the basic example | `ggml-org/embeddinggemma-300M-GGUF` | | Decision models | Laya (ModernBERT) | Validated | `fr0stbit3/laya-gguf` | diff --git a/website/docs/guides/text-to-speech.md b/website/docs/guides/text-to-speech.md index d5ffe6df8..d26de1f78 100644 --- a/website/docs/guides/text-to-speech.md +++ b/website/docs/guides/text-to-speech.md @@ -1,7 +1,7 @@ --- title: On-device text to speech sidebar_label: Text to speech -description: Generate complete PCM and WAV audio with the experimental typed llama.cpp Qwen3-TTS API on native and WebGPU runtimes. +description: Generate complete PCM and WAV audio with the experimental typed llama.cpp text-to-speech API (Qwen3-TTS, LFM3-Audio, Soprano) on native and WebGPU runtimes. --- `TextToSpeechEngine` is the typed API for speech synthesis. It is separate from @@ -9,20 +9,85 @@ description: Generate complete PCM and WAV audio with the experimental typed lla progress, cancellation, and output buffering are not chat-token semantics. Text to speech is experimental and deliberately narrow. It supports -Qwen3-TTS through native llama.cpp or WebGPU (pinned bridge assets) with the -matching audio-generation projector. It reports prompt/frame progress, then -returns one complete 24 kHz mono float32 PCM buffer. It does not stream playable -audio chunks yet. +Qwen3-TTS through native llama.cpp or WebGPU (pinned bridge assets), and +LFM3-Audio and Soprano through native llama.cpp, each with the matching +audio-generation projector. It reports prompt/frame progress, then returns one +complete mono float32 PCM buffer. It does not stream playable audio chunks yet. ## Current support matrix | Runtime | Typed `TextToSpeechEngine` | Output | | --- | --- | --- | -| Native llama.cpp / GGUF | Experimental Qwen3-TTS adapter | Complete float32 PCM; WAV helper | +| Native llama.cpp / GGUF | Experimental Qwen3-TTS, LFM3-Audio and Soprano adapters | Complete float32 PCM; WAV helper | | WebGPU / GGUF | Experimental Qwen3-TTS adapter (pinned bridge assets) | Complete float32 PCM; WAV helper | | Native LiteRT-LM / `.litertlm` | Unsupported by the pinned native artifact | None | | LiteRT-LM Web | Unsupported | None | +## Models + +Pick the adapter for the model; `capabilities` reports what the loaded pair +takes, and a request that asks for anything else throws before synthesis. + +| Model | Adapter | Output | Language | Voices | Speaker reference | Sampling | +| --- | --- | --- | --- | --- | --- | --- | +| Qwen3-TTS | `Qwen3TtsAdapter` | 24 kHz | 10 codes, see below | None | Yes | Request settings | +| LFM3-Audio, LFM3-Omni | `Lfm3AudioTtsAdapter` | 24 kHz | Any, not validated | `female` (default), `male` | No | The GGUF's own; request settings are validated, unused | +| Soprano | `SopranoTtsAdapter` | 32 kHz | No | None | No | Request settings | + +LFM3-Audio and Soprano need native llama.cpp from llamadart-native v0.8.0, the +release that added the model-type opt-in (`llama_dart_tts_init_ext`). An older +runtime, such as an older Apple companion lock, keeps Qwen3-TTS working: +`load` asks it which models it drives and throws `LlamaUnsupportedException` +naming the required release before loading any file, and `capabilities` on an +attached engine reports the same in `unsupportedReason`. Web drives Qwen3-TTS +only. + +On Android, GPU work stays off on the Adreno 750 driver that llama.cpp Vulkan +miscomputes on ([llamadart-native#79](https://github.com/leehack/llamadart-native/issues/79)): +there Soprano returns the same non-speech audio for every input and LFM3-Audio +fails to create its pipelines. On that driver automatic device selection +falls back to the CPU with a warning, and `ComputeDevice.gpu` throws. + +### LFM3-Audio + +Load the LFM3-Audio (or LFM3-Omni) model with its projector, for example +`LFM3-Audio-2B-Q4_K_M.gguf` and `mmproj-LFM3-Audio-2B-Q8_0.gguf` from +[`LiquidAI/LFM3-Audio-2B-GGUF`](https://huggingface.co/LiquidAI/LFM3-Audio-2B-GGUF). +It speaks through the model's `tts` chat template; a model without one is +reported unsupported. `language` is rendered into that template as given (a +code such as `en` or a language name) and is not validated, so check it +against the model card; without one the template's default, English, applies. +The model samples audio codes with its own GGUF settings, so `topK`, `topP`, +`minP` and `temperature` are validated but unused; `seed` still makes a +synthesis repeatable. + +### Soprano + +Soprano takes no language, voice or speaker reference. It samples with the +request's settings; the default temperature is 0.8, while upstream's example +decodes greedily, so pass `temperature: 0` to match it. Fewer than two +generated frames fail the synthesis. + +No llama.cpp-format Soprano GGUF is published. Convert +[`ekwek/Soprano-1.1-80M`](https://huggingface.co/ekwek/Soprano-1.1-80M) (or +Soprano-80M) with `convert_hf_to_gguf.py` from the llama.cpp revision the +runtime pins, both files from the same model directory, including +`decoder.pth`: + +```sh +python convert_hf_to_gguf.py path/to/Soprano-1.1-80M --outtype f16 --outfile soprano.gguf +python convert_hf_to_gguf.py path/to/Soprano-1.1-80M --mmproj --outtype f16 --outfile mmproj-soprano.gguf +``` + +Upstream's README converts the backbone as `f32`; an `f16` backbone also +passes the ASR round trip at half the size. With torch 2.10 and later the +projector conversion can fail with `Soprano requires a periodic Hann window`: +the published decoder's ISTFT window differs from `torch.hann_window` by one +float32 ulp (about 6e-8), and the converter compares them exactly. Replace +that `torch.equal` in `conversion/soprano.py` with +`torch.allclose(..., atol=1e-6)` for the conversion; the window itself is not +stored, since the runtime builds its own. + ## Load Qwen3-TTS Use a matching model and projector pair. The chat example pins the Q4_K_M base @@ -103,7 +168,8 @@ unsupported with that reason and `synthesize` throws `LlamaStateException`: crea The runtime generates the audio itself and reports which audio-generation model it loaded, so an adapter can target only a model the runtime supports. -`Qwen3TtsAdapter` accepts Qwen3-TTS and maps request languages to its codes. +`Qwen3TtsAdapter` accepts Qwen3-TTS and maps request languages to its codes; +`Lfm3AudioTtsAdapter` and `SopranoTtsAdapter` accept their models. `TextToSpeechAdapter` is open for another family once a runtime reports it: `supportsModel` accepts the `BackendTextToSpeechModel` it drives, `supportedLanguages` lists its codes, and `normalizeLanguage` maps a request @@ -166,6 +232,29 @@ Native applications may alternatively use `SpeechAudioFileInput('/recordings/reference.wav')`. Browser runtimes cannot read arbitrary local filesystem paths. +## Voices + +A model with predefined voices reports `supportsVoice`, and `voices` lists +them in the model's order; the first one speaks when a request names none. +Select one by name: + +```dart +final capabilities = await synthesizer.capabilities; +if (capabilities.voices.contains('male')) { + final result = await synthesizer.synthesizeOnce( + const TextToSpeechRequest(text: 'Hello from llamadart.', voice: 'male'), + ); +} +``` + +A name matches in any case. One the model does not list throws +`LlamaTextToSpeechException` before synthesis, never falling back to the +default; a voice together with a speaker reference does too, and a voice for a +model without voices throws `LlamaUnsupportedException`. Runtimes before +llamadart-native v0.9.0 can select a voice but not list them: `voices` is then +empty while `supportsVoice` is true, and the runtime checks the name when +synthesis starts. + For Qwen3-TTS, the canonical language codes are `zh`, `en`, `ja`, `ko`, `de`, `fr`, `ru`, `pt`, `es`, and `it`. Common English names are normalized to those codes, so `language: 'English'` is equivalent to `language: 'en'`. Other values @@ -209,9 +298,11 @@ The [chat app](../examples/chat-app) has a Qwen3-TTS mode built on this API. ## Known limits -- Output is complete 24 kHz mono output only; no incremental - audio chunks, timestamps, or output backpressure are available. -- Qwen3-TTS and llama.cpp audio generation are experimental. Voice quality, +- Output is complete mono PCM at the model's rate (`sampleRateHz`); no + incremental audio chunks, timestamps, or output backpressure are available. +- Qwen3-TTS, LFM3-Audio, Soprano and llama.cpp audio generation are + experimental. LFM3-Audio and Soprano were checked on macOS arm64 (CPU) with + an ASR round trip; other hosts are unqualified. Voice quality, latency, supported reference formats, and accelerator behavior remain model/device dependent. - Web requires the pinned bridge assets, WebAssembly memory64 for the diff --git a/website/docs/platforms/support-matrix.md b/website/docs/platforms/support-matrix.md index 0308ca838..5b14056ba 100644 --- a/website/docs/platforms/support-matrix.md +++ b/website/docs/platforms/support-matrix.md @@ -32,11 +32,11 @@ unchecked. See [scope and limits](./diagnose-setup#isolated-native-check). | Platform | GGUF backends | LiteRT-LM backends | Minimum OS | Speech to text | Text to speech | Decision models | Image generation (Preview) | Status | | --- | --- | --- | --- | --- | --- | --- | --- | --- | -| Android (arm64, x64) | CPU; Vulkan experimental, device-dependent; OpenCL opt-in | CPU, GPU, NPU | Not set by llamadart | Qwen3-ASR (GGUF); LiteRT-LM ASR | Qwen3-TTS | Untested | arm64 CPU; validated on Pixel 9 Pro, Galaxy S24 and A53 | Supported | -| iOS (arm64, arm64 simulator, x86_64 simulator) | CPU, Metal; on a simulator Metal returns incorrect output and `auto` uses the CPU ([#950](https://github.com/leehack/llamadart/issues/950)) | CPU, GPU; none on the x86_64 simulator | iOS 16.4 deployment target; LiteRT-LM run on a device only on iOS 18.3.2 | Qwen3-ASR (GGUF); LiteRT-LM ASR | Qwen3-TTS | Untested | Metal, iOS 16.4; validated on iPhone 16 Pro and SE 3; `vaeDirectConvolution: true` throws on Metal ([#1044](https://github.com/leehack/llamadart/issues/1044)) | Supported | -| macOS (arm64, x86_64) | CPU, Metal; on x86_64, Rosetta included, `auto` uses the CPU because Metal returns garbled output on Intel Macs with AMD GPUs ([#1597](https://github.com/leehack/llamadart/issues/1597)) | arm64: CPU, GPU; x86_64: none ([litert-lm-native#72](https://github.com/leehack/litert-lm-native/issues/72)) | macOS 14.0 (Flutter) | Qwen3-ASR (GGUF); LiteRT-LM ASR | Qwen3-TTS | Validated on Metal and CPU | Metal, macOS 13.3; validated on arm64 | Supported | -| Linux (arm64, x64) | CPU, Vulkan; BLAS opt-in; x64: CUDA, HIP opt-in | arm64: CPU; x64: CPU, explicit GPU | Not set by llamadart | Qwen3-ASR (GGUF); LiteRT-LM ASR | Qwen3-TTS | Untested | CPU or Vulkan; x64 needs AVX2; validated on x64 (CPU, NVIDIA L4) | Supported | -| Windows (arm64, x64) | CPU, Vulkan; BLAS opt-in; x64: CUDA opt-in | x64: CPU, explicit GPU ([Qwen unqualified](./known-platform-issues#linux-and-windows)); arm64: none | Not set by llamadart | Qwen3-ASR (GGUF); LiteRT-LM ASR on x64 | Qwen3-TTS | Untested | x64 CPU or Vulkan, needs AVX2 and the Visual C++ runtime; validated on Windows Server 2022 (CPU, NVIDIA L4) | Supported | +| Android (arm64, x64) | CPU; Vulkan experimental, device-dependent; OpenCL opt-in | CPU, GPU, NPU | Not set by llamadart | Qwen3-ASR (GGUF); LiteRT-LM ASR | Qwen3-TTS; LFM3-Audio, Soprano | Untested | arm64 CPU; validated on Pixel 9 Pro, Galaxy S24 and A53 | Supported | +| iOS (arm64, arm64 simulator, x86_64 simulator) | CPU, Metal; on a simulator Metal returns incorrect output and `auto` uses the CPU ([#950](https://github.com/leehack/llamadart/issues/950)) | CPU, GPU; none on the x86_64 simulator | iOS 16.4 deployment target; LiteRT-LM run on a device only on iOS 18.3.2 | Qwen3-ASR (GGUF); LiteRT-LM ASR | Qwen3-TTS; LFM3-Audio, Soprano | Untested | Metal, iOS 16.4; validated on iPhone 16 Pro and SE 3; `vaeDirectConvolution: true` throws on Metal ([#1044](https://github.com/leehack/llamadart/issues/1044)) | Supported | +| macOS (arm64, x86_64) | CPU, Metal; on x86_64, Rosetta included, `auto` uses the CPU because Metal returns garbled output on Intel Macs with AMD GPUs ([#1597](https://github.com/leehack/llamadart/issues/1597)) | arm64: CPU, GPU; x86_64: none ([litert-lm-native#72](https://github.com/leehack/litert-lm-native/issues/72)) | macOS 14.0 (Flutter) | Qwen3-ASR (GGUF); LiteRT-LM ASR | Qwen3-TTS; LFM3-Audio, Soprano | Validated on Metal and CPU | Metal, macOS 13.3; validated on arm64 | Supported | +| Linux (arm64, x64) | CPU, Vulkan; BLAS opt-in; x64: CUDA, HIP opt-in | arm64: CPU; x64: CPU, explicit GPU | Not set by llamadart | Qwen3-ASR (GGUF); LiteRT-LM ASR | Qwen3-TTS; LFM3-Audio, Soprano | Untested | CPU or Vulkan; x64 needs AVX2; validated on x64 (CPU, NVIDIA L4) | Supported | +| Windows (arm64, x64) | CPU, Vulkan; BLAS opt-in; x64: CUDA opt-in | x64: CPU, explicit GPU ([Qwen unqualified](./known-platform-issues#linux-and-windows)); arm64: none | Not set by llamadart | Qwen3-ASR (GGUF); LiteRT-LM ASR on x64 | Qwen3-TTS; LFM3-Audio, Soprano | Untested | x64 CPU or Vulkan, needs AVX2 and the Visual C++ runtime; validated on Windows Server 2022 (CPU, NVIDIA L4) | Supported | | Web | WebGPU, WebAssembly CPU | CPU, GPU through `@litert-lm/core` | Chrome 128, Firefox 129, Safari 17.4 (LiteRT-LM GPU checked in Safari 27 on Apple silicon, [#1025](https://github.com/leehack/llamadart/issues/1025)) | Qwen3-ASR, WAV, MP3 or FLAC bytes | Qwen3-TTS, memory64 | Checked in headless Chromium on macOS | Not yet ([#969](https://github.com/leehack/llamadart/issues/969)) | Experimental | On Windows, the llama.cpp and LiteRT-LM bundles ship the Visual C++ runtime