From 752877b99e913cfe3545a033018dd4752b50ebed Mon Sep 17 00:00:00 2001 From: 4di-hello <4di-hello@users.noreply.github.com> Date: Sat, 28 Nov 2026 14:50:10 +0100 Subject: [PATCH 01/15] Faster recognition: audio window fitting the recording, one thread pool, whisper.cpp 1.9.6 - Whisper computed a full 30 s window (1500 audio frames) even for 3 s of speech. Below 30 s the window now fits the audio with some room (audio_ctx). - One thread pool for the CPU backend on the fastest cores, kept while the process runs (patch to whisper.cpp, applied by CMake). Without it ggml starts and ends threads for every graph, so for every decoded token. - whisper.cpp 1.7.4 -> 1.9.6, OpenMP stays off. - The log has only numbers (lengths, times), never the recognized text or the prompt. - -Pvoice.abis=arm64-v8a builds only that ABI. Co-Authored-By: Claude Opus 5.5 --- app/build.gradle.kts | 12 +-- app/src/main/cpp/CMakeLists.txt | 17 ++++- .../main/cpp/patches/whisper-threadpool.patch | 75 +++++++++++++++++++ app/src/main/cpp/whisper.cpp | 2 +- app/src/main/cpp/whisper_jni.cpp | 24 ++++-- .../voice/offline/engine/WhisperEngine.kt | 6 +- 6 files changed, 121 insertions(+), 15 deletions(-) create mode 100644 app/src/main/cpp/patches/whisper-threadpool.patch diff --git a/app/build.gradle.kts b/app/build.gradle.kts index f069571..4299f04 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -10,6 +10,8 @@ import java.util.Properties // -PcompatCpu=true builds the arm64 APK for CPUs without the ARMv8.2 dot-product and FP16 instructions val compatCpu = providers.gradleProperty("compatCpu").orNull == "true" +// -Pvoice.abis=arm64-v8a builds only these ABIs (whisper.cpp takes long to build) +val onlyAbis = providers.gradleProperty("voice.abis").orNull?.split(",")?.map { it.trim() }?.filter { it.isNotEmpty() } if (compatCpu) { // separate output, so that the fast and the compat build do not overwrite each other layout.buildDirectory.set(file("build-compat")) @@ -29,8 +31,8 @@ android { applicationId = "com.leanbitlab.leantype.voice.offline" minSdk = 21 targetSdk = 35 - versionCode = 104 - versionName = "1.0.4" + versionCode = 105 + versionName = "1.0.5-plus" // true if the arm64 library of this build needs ARMv8.2 dot-product and FP16 (see CMakeLists.txt) buildConfigField("boolean", "ARM64_NEEDS_ARMV82", (!compatCpu).toString()) @@ -105,7 +107,7 @@ android { } ndk { // the compat build is a single arm64 APK, there are no ABI splits (see below) - abiFilters += if (compatCpu) listOf("arm64-v8a") else listOf("arm64-v8a", "armeabi-v7a", "x86_64") + abiFilters += if (compatCpu) listOf("arm64-v8a") else onlyAbis ?: listOf("arm64-v8a", "armeabi-v7a", "x86_64") } } } @@ -114,8 +116,8 @@ android { abi { isEnable = !compatCpu reset() - include("arm64-v8a", "armeabi-v7a", "x86_64") - isUniversalApk = true + include(*(onlyAbis ?: listOf("arm64-v8a", "armeabi-v7a", "x86_64")).toTypedArray()) + isUniversalApk = onlyAbis == null } } diff --git a/app/src/main/cpp/CMakeLists.txt b/app/src/main/cpp/CMakeLists.txt index 969e52e..85dc2df 100644 --- a/app/src/main/cpp/CMakeLists.txt +++ b/app/src/main/cpp/CMakeLists.txt @@ -1,4 +1,4 @@ -# Pinned whisper.cpp release: v1.7.4 (commit 1fe009c) +# Pinned whisper.cpp release: v1.9.6 (commit 96ec4d9), with the patches in patches/ cmake_minimum_required(VERSION 3.22.1) project(whisper_jni C CXX) @@ -16,6 +16,8 @@ set(CMAKE_CXX_FLAGS_RELEASE "-O3 -DNDEBUG") set(WHISPER_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE) set(WHISPER_BUILD_TESTS OFF CACHE BOOL "" FORCE) set(WHISPER_NO_OPENMP ON CACHE BOOL "" FORCE) +# ggml's own thread pool (see the patch below), not OpenMP +set(GGML_OPENMP OFF CACHE BOOL "" FORCE) # The fast arm64 build uses ARMv8.2 dot-product and FP16 instructions, which CPUs before about 2018 (Cortex-A53, # A57, A72, A73) do not have. The compat build leaves the architecture at the NDK default (ARMv8-a with NEON). @@ -24,6 +26,19 @@ if (ANDROID_ABI STREQUAL "arm64-v8a" AND NOT VOICE_COMPAT_CPU) set(GGML_CPU_ARM_ARCH "armv8.2-a+dotprod+fp16" CACHE STRING "ggml ARM arch" FORCE) endif() +# LeanType patch: one thread pool for the CPU backend on the fastest cores, instead of new threads for +# every graph (every decoded token). Applied to the submodule's working tree once. +set(WHISPER_PATCH ${CMAKE_CURRENT_SOURCE_DIR}/patches/whisper-threadpool.patch) +execute_process(COMMAND git apply --reverse --check ${WHISPER_PATCH} + WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/whisper.cpp RESULT_VARIABLE WHISPER_PATCH_PRESENT OUTPUT_QUIET ERROR_QUIET) +if (NOT WHISPER_PATCH_PRESENT EQUAL 0) + execute_process(COMMAND git apply ${WHISPER_PATCH} + WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/whisper.cpp RESULT_VARIABLE WHISPER_PATCH_RESULT) + if (NOT WHISPER_PATCH_RESULT EQUAL 0) + message(FATAL_ERROR "whisper.cpp patch ${WHISPER_PATCH} does not apply") + endif() +endif() + add_subdirectory(whisper.cpp) add_library(whisper_jni SHARED whisper_jni.cpp) diff --git a/app/src/main/cpp/patches/whisper-threadpool.patch b/app/src/main/cpp/patches/whisper-threadpool.patch new file mode 100644 index 0000000..e5f7faa --- /dev/null +++ b/app/src/main/cpp/patches/whisper-threadpool.patch @@ -0,0 +1,75 @@ +diff --git a/src/whisper.cpp b/src/whisper.cpp +index 0336bf7..1033332 100644 +--- a/src/whisper.cpp ++++ b/src/whisper.cpp +@@ -6,6 +6,10 @@ + #include "ggml-cpp.h" + #include "ggml-alloc.h" + #include "ggml-backend.h" ++#include "ggml-cpu.h" ++ ++#include ++#include + + #ifdef WHISPER_USE_COREML + #include "coreml/whisper-encoder.h" +@@ -169,6 +173,48 @@ static bool ggml_graph_compute_helper( + return ggml_backend_graph_compute(backend.get(), graph) == GGML_STATUS_SUCCESS; + } + ++// LeanType: one thread pool for the CPU backend, kept while the process runs, on the fastest cores. ++// Without it ggml starts and ends threads for every graph, so for every decoded token; on phones the new ++// threads also start on slow cores. Same change in the LeanType offline AI plugin doubled its speed. ++static std::vector whisper_fast_cores(int n) { ++#if defined(__linux__) ++ cpu_set_t allowed; ++ CPU_ZERO(&allowed); ++ if (sched_getaffinity(0, sizeof(allowed), &allowed) != 0) return {}; ++ std::vector> cpus; ++ for (int i = 0; i < CPU_SETSIZE && i < GGML_MAX_N_THREADS; i++) { ++ if (!CPU_ISSET(i, &allowed)) continue; ++ long khz = 0; ++ std::ifstream file("/sys/devices/system/cpu/cpu" + std::to_string(i) + "/cpufreq/cpuinfo_max_freq"); ++ file >> khz; ++ if (khz <= 0) return {}; ++ cpus.emplace_back(khz, i); ++ } ++ std::stable_sort(cpus.begin(), cpus.end(), [](const auto & a, const auto & b) { return a.first > b.first; }); ++ std::vector chosen; ++ for (int i = 0; i < n && i < (int) cpus.size(); i++) chosen.push_back(cpus[i].second); ++ return chosen; ++#else ++ (void) n; ++ return {}; ++#endif ++} ++ ++static ggml_threadpool_t whisper_cpu_threadpool(int n_threads) { ++ static std::mutex mutex; ++ static ggml_threadpool_t pool = nullptr; ++ static int pool_threads = 0; ++ std::lock_guard lock(mutex); ++ if (pool != nullptr && pool_threads == n_threads) return pool; ++ if (pool != nullptr) ggml_threadpool_free(pool); ++ ggml_threadpool_params params = ggml_threadpool_params_default(n_threads); ++ for (int core : whisper_fast_cores(n_threads)) params.cpumask[core] = true; ++ params.strict_cpu = false; ++ pool = ggml_threadpool_new(¶ms); ++ pool_threads = pool != nullptr ? n_threads : 0; ++ return pool; ++} ++ + static bool ggml_graph_compute_helper( + ggml_backend_sched_t sched, + struct ggml_cgraph * graph, +@@ -183,6 +229,10 @@ static bool ggml_graph_compute_helper( + if (fn_set_n_threads) { + fn_set_n_threads(backend, n_threads); + } ++ if (ggml_backend_is_cpu(backend)) { ++ ggml_threadpool_t pool = whisper_cpu_threadpool(n_threads); ++ if (pool != nullptr) ggml_backend_cpu_set_threadpool(backend, pool); ++ } + } + + const bool t = (ggml_backend_sched_graph_compute(sched, graph) == GGML_STATUS_SUCCESS); diff --git a/app/src/main/cpp/whisper.cpp b/app/src/main/cpp/whisper.cpp index 1fe009c..96ec4d9 160000 --- a/app/src/main/cpp/whisper.cpp +++ b/app/src/main/cpp/whisper.cpp @@ -1 +1 @@ -Subproject commit 1fe009caeda75f69bc864d6370b10674e45a92bd +Subproject commit 96ec4d9823e9d0211944172da35f9f29134af990 diff --git a/app/src/main/cpp/whisper_jni.cpp b/app/src/main/cpp/whisper_jni.cpp index fb67f2b..70cb744 100644 --- a/app/src/main/cpp/whisper_jni.cpp +++ b/app/src/main/cpp/whisper_jni.cpp @@ -1,5 +1,8 @@ // SPDX-License-Identifier: Apache-2.0 #include +#include +#include +#include #include #include #include @@ -123,13 +126,24 @@ Java_com_leanbitlab_leantype_voice_offline_engine_WhisperNative_transcribe( params.detect_language = false; } - LOGI("Starting whisper_full: samples=%d (%.2f sec), language=%s, is_multilingual=%d, threads=%d, prompt=%s", - len, (float)len / 16000.0f, params.language, is_multilingual, params.n_threads, - params.initial_prompt ? params.initial_prompt : ""); + // Whisper computes a 30 s window (1500 audio frames, 50 per second) even for 3 s of speech. A window + // fitting the audio, with some room, makes the encoder several times faster. Only up to 30 s: longer + // audio is cut into 30 s windows, all of them full. + const float seconds = (float) len / WHISPER_SAMPLE_RATE; + if (seconds < 30.0f) { + const int frames = (int) (seconds * 50.0f) + 64; + params.audio_ctx = std::min(1500, ((frames + 63) / 64) * 64); + } + + // only numbers, never the prompt or the text: they are what the user said + LOGI("Starting whisper_full: %.2f s of audio, audio_ctx %d, language %s, threads %d, prompt %s", + seconds, params.audio_ctx, params.language, params.n_threads, params.initial_prompt ? "yes" : "no"); + const auto start = std::chrono::steady_clock::now(); int ret = whisper_full(ctx, params, samples, len); + const long long ms = std::chrono::duration_cast(std::chrono::steady_clock::now() - start).count(); - LOGI("whisper_full completed with code: %d", ret); + LOGI("whisper_full completed with code %d in %lld ms", ret, ms); if (lang_str != nullptr) { env->ReleaseStringUTFChars(language, lang_str); @@ -157,7 +171,7 @@ Java_com_leanbitlab_leantype_voice_offline_engine_WhisperNative_transcribe( } } } - LOGI("whisper_full accumulated result: '%s'", result.c_str()); + LOGI("whisper_full result: %zu bytes", result.size()); return env->NewStringUTF(result.c_str()); } diff --git a/app/src/main/java/com/leanbitlab/leantype/voice/offline/engine/WhisperEngine.kt b/app/src/main/java/com/leanbitlab/leantype/voice/offline/engine/WhisperEngine.kt index 614b3bb..8ad5f13 100644 --- a/app/src/main/java/com/leanbitlab/leantype/voice/offline/engine/WhisperEngine.kt +++ b/app/src/main/java/com/leanbitlab/leantype/voice/offline/engine/WhisperEngine.kt @@ -157,7 +157,7 @@ class WhisperEngine { if (!isCancelled.get() && utteranceBuffer.isNotEmpty()) { Log.i(TAG, "EOF flush: transcribing ${utteranceBuffer.size} samples (%.2f sec)".format(utteranceBuffer.size / 16000.0)) val text = transcribeAndEmit(utteranceBuffer, language, numThreads, customPrompt, callback) - Log.i(TAG, "EOF result: '$text'") + Log.i(TAG, "EOF result: ${text.length} chars") utteranceBuffer.clear() } else if (!isCancelled.get()) { Log.i(TAG, "EOF with empty buffer, emitting empty final") @@ -214,10 +214,10 @@ class WhisperEngine { val floatPcm = FloatArray(pcm.size) { pcm[it] / 32768.0f } return try { val rawText = WhisperNative.transcribe(contextPtr, floatPcm, language, threads, prompt) - Log.i(TAG, "JNI transcribe returned: '$rawText'") + Log.i(TAG, "JNI transcribe returned ${rawText.length} chars") val finalText = rawText.trim() if (!isCancelled.get()) { - Log.i(TAG, "Emitting onFinal: '$finalText'") + Log.i(TAG, "Emitting onFinal: ${finalText.length} chars") callback.onFinal(finalText) } finalText From b2149a7a1ddf323761a1ddb796d0deada21745c4 Mon Sep 17 00:00:00 2001 From: 4di-hello <4di-hello@users.noreply.github.com> Date: Sat, 28 Nov 2026 14:51:49 +0100 Subject: [PATCH 02/15] -Pvoice.abis: no ndk abiFilters next to the ABI splits Co-Authored-By: Claude Opus 5.5 --- app/build.gradle.kts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 4299f04..da52623 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -107,7 +107,8 @@ android { } ndk { // the compat build is a single arm64 APK, there are no ABI splits (see below) - abiFilters += if (compatCpu) listOf("arm64-v8a") else onlyAbis ?: listOf("arm64-v8a", "armeabi-v7a", "x86_64") + // with -Pvoice.abis the ABI splits alone choose (both together is an error) + if (onlyAbis == null || compatCpu) abiFilters += if (compatCpu) listOf("arm64-v8a") else listOf("arm64-v8a", "armeabi-v7a", "x86_64") } } } From 4573c16dc5a4c884819b2e4563d1bf72e16386c2 Mon Sep 17 00:00:00 2001 From: 4di-hello <4di-hello@users.noreply.github.com> Date: Sat, 28 Nov 2026 14:53:05 +0100 Subject: [PATCH 03/15] -Pvoice.abis: one APK with only these ABIs, without ABI splits The debug build type sets ndk abiFilters too, which conflicts with ABI splits. Co-Authored-By: Claude Opus 5.5 --- app/build.gradle.kts | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/app/build.gradle.kts b/app/build.gradle.kts index da52623..8bf5f20 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -107,18 +107,18 @@ android { } ndk { // the compat build is a single arm64 APK, there are no ABI splits (see below) - // with -Pvoice.abis the ABI splits alone choose (both together is an error) - if (onlyAbis == null || compatCpu) abiFilters += if (compatCpu) listOf("arm64-v8a") else listOf("arm64-v8a", "armeabi-v7a", "x86_64") + // with -Pvoice.abis one APK with only these ABIs, without splits + abiFilters += if (compatCpu) listOf("arm64-v8a") else onlyAbis ?: listOf("arm64-v8a", "armeabi-v7a", "x86_64") } } } splits { abi { - isEnable = !compatCpu + isEnable = !compatCpu && onlyAbis == null reset() - include(*(onlyAbis ?: listOf("arm64-v8a", "armeabi-v7a", "x86_64")).toTypedArray()) - isUniversalApk = onlyAbis == null + include("arm64-v8a", "armeabi-v7a", "x86_64") + isUniversalApk = true } } @@ -129,7 +129,11 @@ android { if (abi != null) { output.outputFileName = "voice_plugin-$abi.apk" } else { - output?.outputFileName = if (compatCpu) "voice_plugin-arm64-v8a-compat.apk" else "voice_plugin.apk" + output?.outputFileName = when { + compatCpu -> "voice_plugin-arm64-v8a-compat.apk" + onlyAbis != null -> "voice_plugin-${onlyAbis.joinToString("-")}.apk" + else -> "voice_plugin.apk" + } } } } From 18736578c6ed38690e55cee3baf4ec130760801f Mon Sep 17 00:00:00 2001 From: 4di-hello <4di-hello@users.noreply.github.com> Date: Sat, 28 Nov 2026 15:34:26 +0100 Subject: [PATCH 04/15] Repeated text with the shorter window: once more with the full window Measured with large-v3-turbo (not trained for a shorter window): one sentence of 3 s came out twice. If a run of at least 3 words directly repeats itself, the audio is transcribed again with the full 30 s window. Co-Authored-By: Claude Opus 5.5 --- app/build.gradle.kts | 4 +- app/src/main/cpp/whisper_jni.cpp | 72 +++++++++++++++++++++++--------- 2 files changed, 55 insertions(+), 21 deletions(-) diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 8bf5f20..9fe34ed 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -31,8 +31,8 @@ android { applicationId = "com.leanbitlab.leantype.voice.offline" minSdk = 21 targetSdk = 35 - versionCode = 105 - versionName = "1.0.5-plus" + versionCode = 106 + versionName = "1.0.6-plus" // true if the arm64 library of this build needs ARMv8.2 dot-product and FP16 (see CMakeLists.txt) buildConfigField("boolean", "ARM64_NEEDS_ARMV82", (!compatCpu).toString()) diff --git a/app/src/main/cpp/whisper_jni.cpp b/app/src/main/cpp/whisper_jni.cpp index 70cb744..7b6c94c 100644 --- a/app/src/main/cpp/whisper_jni.cpp +++ b/app/src/main/cpp/whisper_jni.cpp @@ -21,6 +21,49 @@ static void whisper_android_log_callback(enum ggml_log_level level, const char * __android_log_print(android_level, "WhisperNativeLog", "%s", text); } +/** Runs Whisper and puts the recognized text into [result]; returns the code of whisper_full */ +static int run_whisper(whisper_context *ctx, const whisper_full_params ¶ms, const float *samples, int len, + std::string &result) { + const auto start = std::chrono::steady_clock::now(); + const int ret = whisper_full(ctx, params, samples, len); + const long long ms = std::chrono::duration_cast(std::chrono::steady_clock::now() - start).count(); + LOGI("whisper_full completed with code %d in %lld ms (audio_ctx %d)", ret, ms, params.audio_ctx); + if (ret != 0) return ret; + const int n_segments = whisper_full_n_segments(ctx); + for (int i = 0; i < n_segments; ++i) { + const char *text = whisper_full_get_segment_text(ctx, i); + if (text == nullptr) continue; + std::string s(text); + if (s.find("[BLANK_AUDIO]") == std::string::npos && s.find("(blank audio)") == std::string::npos) { + result += s; + } + } + return 0; +} + +/** Whether a run of at least 3 words directly repeats itself ("a b c a b c"), ignoring case and punctuation */ +static bool has_repeated_words(const std::string &text) { + std::vector words; + std::string word; + for (const char c : text) { + if (c == ' ' || c == '\n' || c == '\t') { + if (!word.empty()) { words.push_back(word); word.clear(); } + } else if (c == '.' || c == ',' || c == '!' || c == '?' || c == ';' || c == ':' || c == '"') { + continue; + } else { + word += (char) ((c >= 'A' && c <= 'Z') ? c - 'A' + 'a' : c); + } + } + if (!word.empty()) words.push_back(word); + const size_t n = words.size(); + for (size_t length = 3; length * 2 <= n; length++) { + for (size_t i = 0; i + 2 * length <= n; i++) { + if (std::equal(words.begin() + i, words.begin() + i + length, words.begin() + i + length)) return true; + } + } + return false; +} + extern "C" { JNIEXPORT jlong JNICALL @@ -139,11 +182,16 @@ Java_com_leanbitlab_leantype_voice_offline_engine_WhisperNative_transcribe( LOGI("Starting whisper_full: %.2f s of audio, audio_ctx %d, language %s, threads %d, prompt %s", seconds, params.audio_ctx, params.language, params.n_threads, params.initial_prompt ? "yes" : "no"); - const auto start = std::chrono::steady_clock::now(); - int ret = whisper_full(ctx, params, samples, len); - const long long ms = std::chrono::duration_cast(std::chrono::steady_clock::now() - start).count(); - - LOGI("whisper_full completed with code %d in %lld ms", ret, ms); + std::string result; + int ret = run_whisper(ctx, params, samples, len, result); + // Models not trained for a shorter window (all but the ACFT ones) sometimes repeat a sentence with it: + // then once more with the full 30 s window + if (ret == 0 && params.audio_ctx > 0 && has_repeated_words(result)) { + LOGI("repetition with audio_ctx %d, again with the full window", params.audio_ctx); + params.audio_ctx = 0; + result.clear(); + ret = run_whisper(ctx, params, samples, len, result); + } if (lang_str != nullptr) { env->ReleaseStringUTFChars(language, lang_str); @@ -157,20 +205,6 @@ Java_com_leanbitlab_leantype_voice_offline_engine_WhisperNative_transcribe( LOGE("whisper_full failed with code: %d", ret); return env->NewStringUTF(""); } - - std::string result; - const int n_segments = whisper_full_n_segments(ctx); - LOGI("whisper_full segment count: %d", n_segments); - for (int i = 0; i < n_segments; ++i) { - const char *text = whisper_full_get_segment_text(ctx, i); - if (text != nullptr) { - std::string s(text); - if (s.find("[BLANK_AUDIO]") == std::string::npos && - s.find("(blank audio)") == std::string::npos) { - result += s; - } - } - } LOGI("whisper_full result: %zu bytes", result.size()); return env->NewStringUTF(result.c_str()); From e04e1bdc423de6a61f398419b12ada2438374f57 Mon Sep 17 00:00:00 2001 From: 4di-hello <4di-hello@users.noreply.github.com> Date: Sat, 28 Nov 2026 16:07:48 +0100 Subject: [PATCH 05/15] CPU backend variants loaded at runtime, like the offline AI plugin The arm64 build was compiled for ARMv8.2 (dot product, FP16) only, so newer CPUs could not use i8mm, SVE or SME. ggml's CPU backend is now built in variants (GGML_BACKEND_DL, GGML_CPU_ALL_VARIANTS, KleidiAI on arm64) and the best one for the phone is loaded at runtime from the library folder (JNI_OnLoad). The libraries are extracted for that, with the shared C++ runtime. The thread pool patch looks up the CPU backend's functions instead of linking them. Co-Authored-By: Claude Opus 5.5 --- app/build.gradle.kts | 16 +++++++++---- app/src/main/cpp/CMakeLists.txt | 20 ++++++++++++---- .../main/cpp/patches/whisper-threadpool.patch | 24 +++++++++++-------- app/src/main/cpp/whisper_jni.cpp | 18 ++++++++++++++ 4 files changed, 59 insertions(+), 19 deletions(-) diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 9fe34ed..0198bb1 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -31,15 +31,18 @@ android { applicationId = "com.leanbitlab.leantype.voice.offline" minSdk = 21 targetSdk = 35 - versionCode = 106 - versionName = "1.0.6-plus" + versionCode = 107 + versionName = "1.0.7-plus" // true if the arm64 library of this build needs ARMv8.2 dot-product and FP16 (see CMakeLists.txt) - buildConfigField("boolean", "ARM64_NEEDS_ARMV82", (!compatCpu).toString()) + // false: the CPU backend is loaded at runtime in the variant that fits the CPU (see CMakeLists.txt) + buildConfigField("boolean", "ARM64_NEEDS_ARMV82", "false") externalNativeBuild { cmake { - arguments("-DCMAKE_BUILD_TYPE=Release", "-DWHISPER_NO_OPENMP=ON", "-DVOICE_COMPAT_CPU=${if (compatCpu) "ON" else "OFF"}") + // shared C++ runtime: whisper, ggml and the CPU backend variants are separate libraries + arguments("-DCMAKE_BUILD_TYPE=Release", "-DWHISPER_NO_OPENMP=ON", "-DANDROID_STL=c++_shared", + "-DVOICE_COMPAT_CPU=${if (compatCpu) "ON" else "OFF"}") cFlags("-O3", "-DNDEBUG") cppFlags("-O3", "-DNDEBUG") } @@ -55,6 +58,11 @@ android { jvmTarget = "17" } + packaging { + // extracted to the library folder: ggml loads the CPU backend variants from there by path + jniLibs.useLegacyPackaging = true + } + buildFeatures { aidl = true buildConfig = true diff --git a/app/src/main/cpp/CMakeLists.txt b/app/src/main/cpp/CMakeLists.txt index 85dc2df..e59b003 100644 --- a/app/src/main/cpp/CMakeLists.txt +++ b/app/src/main/cpp/CMakeLists.txt @@ -19,11 +19,20 @@ set(WHISPER_NO_OPENMP ON CACHE BOOL "" FORCE) # ggml's own thread pool (see the patch below), not OpenMP set(GGML_OPENMP OFF CACHE BOOL "" FORCE) -# The fast arm64 build uses ARMv8.2 dot-product and FP16 instructions, which CPUs before about 2018 (Cortex-A53, -# A57, A72, A73) do not have. The compat build leaves the architecture at the NDK default (ARMv8-a with NEON). -option(VOICE_COMPAT_CPU "arm64 build for every ARMv8-a CPU, without dot-product and FP16 instructions" OFF) -if (ANDROID_ABI STREQUAL "arm64-v8a" AND NOT VOICE_COMPAT_CPU) - set(GGML_CPU_ARM_ARCH "armv8.2-a+dotprod+fp16" CACHE STRING "ggml ARM arch" FORCE) +# The CPU backend is built in variants for different CPU generations (arm64: ARMv8.0 up to ARMv9.2 with i8mm +# and SME, x86_64 likewise) and ggml loads the best one for the phone at runtime, as the LeanType offline AI +# plugin does. So the arm64 build runs on every ARMv8-a CPU and uses what newer ones can. +# VOICE_COMPAT_CPU is not needed any more and changes nothing. +option(VOICE_COMPAT_CPU "no effect: the CPU backend variants cover every ARMv8-a CPU" OFF) +set(BUILD_SHARED_LIBS ON CACHE BOOL "" FORCE) +set(GGML_BACKEND_DL ON CACHE BOOL "" FORCE) +set(GGML_NATIVE OFF CACHE BOOL "" FORCE) +if (ANDROID_ABI STREQUAL "arm64-v8a" OR ANDROID_ABI STREQUAL "x86_64") + set(GGML_CPU_ALL_VARIANTS ON CACHE BOOL "" FORCE) +endif() +if (ANDROID_ABI STREQUAL "arm64-v8a") + # fast kernels for quantized models on ARM (i8mm, SME), chosen at runtime + set(GGML_CPU_KLEIDIAI ON CACHE BOOL "" FORCE) endif() # LeanType patch: one thread pool for the CPU backend on the fastest cores, instead of new threads for @@ -50,5 +59,6 @@ target_include_directories(whisper_jni PRIVATE target_link_libraries(whisper_jni whisper + ggml log ) diff --git a/app/src/main/cpp/patches/whisper-threadpool.patch b/app/src/main/cpp/patches/whisper-threadpool.patch index e5f7faa..80d49b6 100644 --- a/app/src/main/cpp/patches/whisper-threadpool.patch +++ b/app/src/main/cpp/patches/whisper-threadpool.patch @@ -1,19 +1,19 @@ diff --git a/src/whisper.cpp b/src/whisper.cpp -index 0336bf7..1033332 100644 +index 0336bf7..8593ec3 100644 --- a/src/whisper.cpp +++ b/src/whisper.cpp @@ -6,6 +6,10 @@ #include "ggml-cpp.h" #include "ggml-alloc.h" #include "ggml-backend.h" -+#include "ggml-cpu.h" ++#include "ggml-cpu.h" // types only: the CPU backend may be loaded at runtime, its functions are looked up + +#include +#include #ifdef WHISPER_USE_COREML #include "coreml/whisper-encoder.h" -@@ -169,6 +173,48 @@ static bool ggml_graph_compute_helper( +@@ -169,6 +173,51 @@ static bool ggml_graph_compute_helper( return ggml_backend_graph_compute(backend.get(), graph) == GGML_STATUS_SUCCESS; } @@ -44,17 +44,20 @@ index 0336bf7..1033332 100644 +#endif +} + -+static ggml_threadpool_t whisper_cpu_threadpool(int n_threads) { ++static ggml_threadpool_t whisper_cpu_threadpool(ggml_backend_reg_t reg, int n_threads) { + static std::mutex mutex; + static ggml_threadpool_t pool = nullptr; + static int pool_threads = 0; + std::lock_guard lock(mutex); + if (pool != nullptr && pool_threads == n_threads) return pool; -+ if (pool != nullptr) ggml_threadpool_free(pool); ++ auto * new_fn = (decltype(ggml_threadpool_new) *) ggml_backend_reg_get_proc_address(reg, "ggml_threadpool_new"); ++ auto * free_fn = (decltype(ggml_threadpool_free) *) ggml_backend_reg_get_proc_address(reg, "ggml_threadpool_free"); ++ if (new_fn == nullptr || free_fn == nullptr) return nullptr; ++ if (pool != nullptr) free_fn(pool); + ggml_threadpool_params params = ggml_threadpool_params_default(n_threads); + for (int core : whisper_fast_cores(n_threads)) params.cpumask[core] = true; + params.strict_cpu = false; -+ pool = ggml_threadpool_new(¶ms); ++ pool = new_fn(¶ms); + pool_threads = pool != nullptr ? n_threads : 0; + return pool; +} @@ -62,13 +65,14 @@ index 0336bf7..1033332 100644 static bool ggml_graph_compute_helper( ggml_backend_sched_t sched, struct ggml_cgraph * graph, -@@ -183,6 +229,10 @@ static bool ggml_graph_compute_helper( +@@ -183,6 +232,11 @@ static bool ggml_graph_compute_helper( if (fn_set_n_threads) { fn_set_n_threads(backend, n_threads); } -+ if (ggml_backend_is_cpu(backend)) { -+ ggml_threadpool_t pool = whisper_cpu_threadpool(n_threads); -+ if (pool != nullptr) ggml_backend_cpu_set_threadpool(backend, pool); ++ if (dev != nullptr && reg != nullptr && ggml_backend_dev_type(dev) == GGML_BACKEND_DEVICE_TYPE_CPU) { ++ auto * set_pool_fn = (decltype(ggml_backend_cpu_set_threadpool) *) ggml_backend_reg_get_proc_address(reg, "ggml_backend_cpu_set_threadpool"); ++ ggml_threadpool_t pool = set_pool_fn != nullptr ? whisper_cpu_threadpool(reg, n_threads) : nullptr; ++ if (pool != nullptr) set_pool_fn(backend, pool); + } } diff --git a/app/src/main/cpp/whisper_jni.cpp b/app/src/main/cpp/whisper_jni.cpp index 7b6c94c..49aaa23 100644 --- a/app/src/main/cpp/whisper_jni.cpp +++ b/app/src/main/cpp/whisper_jni.cpp @@ -7,6 +7,8 @@ #include #include #include "whisper.h" +#include "ggml-backend.h" +#include #define TAG "WhisperJNI" #define LOGI(...) __android_log_print(ANDROID_LOG_INFO, TAG, __VA_ARGS__) @@ -66,6 +68,22 @@ static bool has_repeated_words(const std::string &text) { extern "C" { +// The CPU backend is loaded at runtime, the variant that fits this CPU, from the folder of this library +JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM * /* vm */, void * /* reserved */) { + Dl_info info; + if (dladdr((void *) &JNI_OnLoad, &info) != 0 && info.dli_fname != nullptr) { + std::string dir(info.dli_fname); + dir = dir.substr(0, dir.find_last_of('/')); + ggml_backend_load_all_from_path(dir.c_str()); + LOGI("ggml backends loaded from the library folder, %zu devices", ggml_backend_dev_count()); + } else { + ggml_backend_load_all(); + LOGI("ggml backends loaded, %zu devices", ggml_backend_dev_count()); + } + return JNI_VERSION_1_6; +} + + JNIEXPORT jlong JNICALL Java_com_leanbitlab_leantype_voice_offline_engine_WhisperNative_init( JNIEnv *env, From c15c9d9c30bda2c6a3e0ae2394f2b7fc85d96fae Mon Sep 17 00:00:00 2001 From: 4di-hello <4di-hello@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:18:32 +0100 Subject: [PATCH 06/15] Repetition guard: also the same 5 words twice anywhere; version 1.0.8-plus Normal Whisper Small with the shortened window wrote the first two sentences of a 12 s dictation twice, with small differences ("Bruder" / "Bode"), which the direct-repeat check missed. Then the audio is recognized again with the full window. Co-Authored-By: Claude Opus 5.5 --- app/build.gradle.kts | 4 ++-- app/src/main/cpp/whisper_jni.cpp | 15 ++++++++++++++- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 0198bb1..7816581 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -31,8 +31,8 @@ android { applicationId = "com.leanbitlab.leantype.voice.offline" minSdk = 21 targetSdk = 35 - versionCode = 107 - versionName = "1.0.7-plus" + versionCode = 108 + versionName = "1.0.8-plus" // true if the arm64 library of this build needs ARMv8.2 dot-product and FP16 (see CMakeLists.txt) // false: the CPU backend is loaded at runtime in the variant that fits the CPU (see CMakeLists.txt) diff --git a/app/src/main/cpp/whisper_jni.cpp b/app/src/main/cpp/whisper_jni.cpp index 49aaa23..389a177 100644 --- a/app/src/main/cpp/whisper_jni.cpp +++ b/app/src/main/cpp/whisper_jni.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include #include "whisper.h" @@ -43,7 +44,12 @@ static int run_whisper(whisper_context *ctx, const whisper_full_params ¶ms, return 0; } -/** Whether a run of at least 3 words directly repeats itself ("a b c a b c"), ignoring case and punctuation */ +/** + * Whether the text repeats itself: a run of at least 3 words directly repeated ("a b c a b c"), or the same + * 5 words twice anywhere. With the shortened window, normal Whisper models sometimes write a part twice, + * with small differences ("Bruder" / "Bode"); 5 identical words in a row are still in both copies, while + * people rarely say the same 5 words twice in one dictation. Ignores case and punctuation. + */ static bool has_repeated_words(const std::string &text) { std::vector words; std::string word; @@ -63,6 +69,13 @@ static bool has_repeated_words(const std::string &text) { if (std::equal(words.begin() + i, words.begin() + i + length, words.begin() + i + length)) return true; } } + constexpr size_t SAME_WORDS = 5; + std::set seen; + for (size_t i = 0; i + SAME_WORDS <= n; i++) { + std::string key; + for (size_t k = 0; k < SAME_WORDS; k++) key += words[i + k] + ' '; + if (!seen.insert(key).second) return true; + } return false; } From a15634484898b97ff2f0e2719771677e42255e51 Mon Sep 17 00:00:00 2001 From: 4di-hello <4di-hello@users.noreply.github.com> Date: Sun, 29 Nov 2026 14:40:26 +0100 Subject: [PATCH 07/15] Libraries for 16 KB memory pages; version 1.0.9-plus Co-Authored-By: Claude Opus 5.5 --- app/build.gradle.kts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 7816581..c3d13ad 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -31,8 +31,8 @@ android { applicationId = "com.leanbitlab.leantype.voice.offline" minSdk = 21 targetSdk = 35 - versionCode = 108 - versionName = "1.0.8-plus" + versionCode = 109 + versionName = "1.0.9-plus" // true if the arm64 library of this build needs ARMv8.2 dot-product and FP16 (see CMakeLists.txt) // false: the CPU backend is loaded at runtime in the variant that fits the CPU (see CMakeLists.txt) @@ -42,6 +42,8 @@ android { cmake { // shared C++ runtime: whisper, ggml and the CPU backend variants are separate libraries arguments("-DCMAKE_BUILD_TYPE=Release", "-DWHISPER_NO_OPENMP=ON", "-DANDROID_STL=c++_shared", + // 16 KB memory pages (Android 15+ devices) + "-DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON", "-DVOICE_COMPAT_CPU=${if (compatCpu) "ON" else "OFF"}") cFlags("-O3", "-DNDEBUG") cppFlags("-O3", "-DNDEBUG") From c700e74599e38227354552277a05526ba3befb94 Mon Sep 17 00:00:00 2001 From: 4di-hello <4di-hello@users.noreply.github.com> Date: Sun, 29 Nov 2026 14:53:09 +0100 Subject: [PATCH 08/15] Review: no use after free when the thread count changes, safer shorter window - One thread pool per thread count, never freed: the CPU backend pauses the pool it used before when it gets another one, so freeing it was a use after free - No CPU backend loaded: init fails cleanly instead of crashing the process - No shorter window when it would be the full 1500 frames anyway, nor for languages written without spaces (the repetition check can't see repeats there) - If the second run with the full window fails, the first result is kept - Release: no compat APK any more (the CPU variants cover every ARMv8 CPU), release notes for v1.1.0, README updated Co-Authored-By: Claude Opus 5.5 --- .github/workflows/release.yml | 5 ---- README.md | 6 ++--- .../main/cpp/patches/whisper-threadpool.patch | 26 ++++++++++--------- app/src/main/cpp/whisper_jni.cpp | 18 ++++++++++--- docs/release_notes/v1.1.0.md | 21 +++++++++++++++ 5 files changed, 52 insertions(+), 24 deletions(-) create mode 100644 docs/release_notes/v1.1.0.md diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index db0e338..48c2d74 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -46,17 +46,12 @@ jobs: - name: Build Release APK run: ./gradlew :app:assembleRelease - # arm64 build for CPUs without the ARMv8.2 dot-product and FP16 instructions (separate output folder) - - name: Build Compat arm64 APK - run: ./gradlew :app:assembleRelease -PcompatCpu=true - - name: Create GitHub Release uses: softprops/action-gh-release@v2 if: startsWith(github.ref, 'refs/tags/v') with: files: | app/build/outputs/apk/release/voice_plugin*.apk - app/build-compat/outputs/apk/release/voice_plugin-arm64-v8a-compat.apk name: Voice Plugin ${{ github.ref_name }} body_path: docs/release_notes/${{ github.ref_name }}.md draft: false diff --git a/README.md b/README.md index 75a7a7f..2816fe9 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ This plugin provides fast, on-device offline speech-to-text capabilities using [ - **Operating System**: Android 5.0 (API 21) or higher - **Supported CPU Architectures**: `arm64-v8a`, `armeabi-v7a`, `x86_64` -- **CPU feature requirement (`arm64-v8a`)**: The standard 64-bit build (`voice_plugin-arm64-v8a.apk`, and the universal APK on 64-bit devices) is compiled for ARMv8.2 with dot-product and FP16 instructions (`-march=armv8.2-a+dotprod+fp16`) for speed. This needs a CPU from roughly 2018 on (Cortex-A55/A75 class and newer). On older 64-bit CPUs (for example Cortex-A53, A57, A72 or A73 only devices) the plugin detects this and shows a message instead of crashing; install **`voice_plugin-arm64-v8a-compat.apk`** from the releases there. It runs on every ARMv8 CPU, a little slower. whisper.cpp itself has no Android version requirement beyond the plugin's minimum. +- **CPU (`arm64-v8a`)**: Since v1.1.0 the CPU part of whisper.cpp is included in variants from ARMv8.0 up to ARMv9.2 (dot-product, FP16, i8mm, SVE, SME, KleidiAI kernels), and the plugin loads the best one for the phone at runtime. So the standard build runs on every 64-bit ARM CPU and uses what newer ones can; the separate compat APK of v1.0.4 isn't needed any more. - **Host Keyboard**: [LeanType](https://github.com/LeanBitLab/LeanType) v4.1.0+ (All flavors); v4.3.3+ for the **Transcribe while speaking** option - **Permissions**: Microphone permission (`RECORD_AUDIO`) @@ -82,7 +82,7 @@ The plugin is an on-demand service. LeanType connects to it when you start voice ### 7. Troubleshooting - **"Voice plugin is not installed"**: Install the plugin APK from the [releases](https://github.com/LeanBitLab/LeanType-Voice-Plugin/releases/latest) page. - **"Failed to import model into voice plugin"**: Update the plugin to the latest release and import the `.bin` file again. -- **"This device's CPU lacks the ARMv8.2 dot-product and FP16 instructions"**: Install `voice_plugin-arm64-v8a-compat.apk` from the releases page over the current plugin. +- **"This device's CPU lacks the ARMv8.2 dot-product and FP16 instructions"** (plugin v1.0.3–v1.0.4): update to v1.1.0 or newer, it runs on every 64-bit ARM CPU. - **No text or only a part of it**: Choose a larger model, check the microphone permission of the plugin, and try a longer **Silence Timeout**. --- @@ -91,7 +91,7 @@ The plugin is an on-demand service. LeanType connects to it when you start voice ```bash ./gradlew assembleDebug ``` -The compat arm64 APK is built with `./gradlew :app:assembleRelease -PcompatCpu=true` (output in `app/build-compat`). It differs only in the compiler architecture of the native code. +`-PcompatCpu=true` has no effect since v1.1.0 (the CPU variants cover every ARMv8 CPU). `-Pvoice.abis=arm64-v8a` builds one APK with only the given ABIs, which is faster while developing. Debug builds use the package `com.leanbitlab.leantype.voice.offline.debug`, so they can be installed next to the release plugin. LeanType debug builds connect to the debug plugin when it is installed. diff --git a/app/src/main/cpp/patches/whisper-threadpool.patch b/app/src/main/cpp/patches/whisper-threadpool.patch index 80d49b6..5be1dbc 100644 --- a/app/src/main/cpp/patches/whisper-threadpool.patch +++ b/app/src/main/cpp/patches/whisper-threadpool.patch @@ -2,18 +2,19 @@ diff --git a/src/whisper.cpp b/src/whisper.cpp index 0336bf7..8593ec3 100644 --- a/src/whisper.cpp +++ b/src/whisper.cpp -@@ -6,6 +6,10 @@ +@@ -6,6 +6,11 @@ #include "ggml-cpp.h" #include "ggml-alloc.h" #include "ggml-backend.h" +#include "ggml-cpu.h" // types only: the CPU backend may be loaded at runtime, its functions are looked up + ++#include +#include +#include #ifdef WHISPER_USE_COREML #include "coreml/whisper-encoder.h" -@@ -169,6 +173,51 @@ static bool ggml_graph_compute_helper( +@@ -169,6 +174,52 @@ static bool ggml_graph_compute_helper( return ggml_backend_graph_compute(backend.get(), graph) == GGML_STATUS_SUCCESS; } @@ -44,28 +45,29 @@ index 0336bf7..8593ec3 100644 +#endif +} + ++// One pool per thread count, never freed: a CPU backend keeps a pointer to the pool it used and pauses it ++// when it gets another one, so freeing it after a change of the thread count would be a use after free. ++// A pool that isn't used sleeps. +static ggml_threadpool_t whisper_cpu_threadpool(ggml_backend_reg_t reg, int n_threads) { + static std::mutex mutex; -+ static ggml_threadpool_t pool = nullptr; -+ static int pool_threads = 0; ++ static std::map pools; + std::lock_guard lock(mutex); -+ if (pool != nullptr && pool_threads == n_threads) return pool; -+ auto * new_fn = (decltype(ggml_threadpool_new) *) ggml_backend_reg_get_proc_address(reg, "ggml_threadpool_new"); -+ auto * free_fn = (decltype(ggml_threadpool_free) *) ggml_backend_reg_get_proc_address(reg, "ggml_threadpool_free"); -+ if (new_fn == nullptr || free_fn == nullptr) return nullptr; -+ if (pool != nullptr) free_fn(pool); ++ const auto found = pools.find(n_threads); ++ if (found != pools.end()) return found->second; ++ auto * new_fn = (decltype(ggml_threadpool_new) *) ggml_backend_reg_get_proc_address(reg, "ggml_threadpool_new"); ++ if (new_fn == nullptr) return nullptr; + ggml_threadpool_params params = ggml_threadpool_params_default(n_threads); + for (int core : whisper_fast_cores(n_threads)) params.cpumask[core] = true; + params.strict_cpu = false; -+ pool = new_fn(¶ms); -+ pool_threads = pool != nullptr ? n_threads : 0; ++ ggml_threadpool_t pool = new_fn(¶ms); ++ if (pool != nullptr) pools[n_threads] = pool; + return pool; +} + static bool ggml_graph_compute_helper( ggml_backend_sched_t sched, struct ggml_cgraph * graph, -@@ -183,6 +232,11 @@ static bool ggml_graph_compute_helper( +@@ -183,6 +234,11 @@ static bool ggml_graph_compute_helper( if (fn_set_n_threads) { fn_set_n_threads(backend, n_threads); } diff --git a/app/src/main/cpp/whisper_jni.cpp b/app/src/main/cpp/whisper_jni.cpp index 389a177..7974996 100644 --- a/app/src/main/cpp/whisper_jni.cpp +++ b/app/src/main/cpp/whisper_jni.cpp @@ -115,6 +115,12 @@ Java_com_leanbitlab_leantype_voice_offline_engine_WhisperNative_init( whisper_context_params cparams = whisper_context_default_params(); cparams.use_gpu = false; + // without a loaded CPU backend whisper.cpp would crash the process instead of failing + if (ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU) == nullptr) { + LOGE("no CPU backend loaded"); + env->ReleaseStringUTFChars(model_path, path); + return 0; + } struct whisper_context *ctx = whisper_init_from_file_with_params(path, cparams); env->ReleaseStringUTFChars(model_path, path); @@ -203,10 +209,13 @@ Java_com_leanbitlab_leantype_voice_offline_engine_WhisperNative_transcribe( // Whisper computes a 30 s window (1500 audio frames, 50 per second) even for 3 s of speech. A window // fitting the audio, with some room, makes the encoder several times faster. Only up to 30 s: longer // audio is cut into 30 s windows, all of them full. + // Not for languages written without spaces: the repetition check below can't see repeats there. const float seconds = (float) len / WHISPER_SAMPLE_RATE; - if (seconds < 30.0f) { + static const std::set no_spaces = {"zh", "ja", "th", "lo", "my", "km", "bo", "yue"}; + if (seconds < 30.0f && no_spaces.count(params.language) == 0) { const int frames = (int) (seconds * 50.0f) + 64; - params.audio_ctx = std::min(1500, ((frames + 63) / 64) * 64); + const int audio_ctx = ((frames + 63) / 64) * 64; + if (audio_ctx < 1500) params.audio_ctx = audio_ctx; } // only numbers, never the prompt or the text: they are what the user said @@ -220,8 +229,9 @@ Java_com_leanbitlab_leantype_voice_offline_engine_WhisperNative_transcribe( if (ret == 0 && params.audio_ctx > 0 && has_repeated_words(result)) { LOGI("repetition with audio_ctx %d, again with the full window", params.audio_ctx); params.audio_ctx = 0; - result.clear(); - ret = run_whisper(ctx, params, samples, len, result); + std::string again; + // if the second run fails, the first result is still better than nothing + if (run_whisper(ctx, params, samples, len, again) == 0) result = again; } if (lang_str != nullptr) { diff --git a/docs/release_notes/v1.1.0.md b/docs/release_notes/v1.1.0.md new file mode 100644 index 0000000..60d3f98 --- /dev/null +++ b/docs/release_notes/v1.1.0.md @@ -0,0 +1,21 @@ +# LeanType Voice Plugin v1.1.0 + +Speed update for the **LeanType Voice Plugin**: a short dictation is recognized about 3–4 times faster, and the recognized text is no longer written to the system log. + +--- + +### Highlights & Improvements + +- **Window fitting the recording:** Whisper used to compute a full 30-second window even for 3 seconds of speech. For recordings under 30 seconds the window now fits the audio. If a model then repeats part of the text, the audio is recognized once more with the full window. +- **One thread pool on the fastest cores:** threads are no longer started and ended for every decoded token, and they run on the fastest cores. 4 threads (the default) are usually faster than 8. +- **CPU variants chosen at runtime:** the CPU part of whisper.cpp is included for ARMv8.0 up to ARMv9.2 (and x86_64 generations). The standard APK runs on every 64-bit ARM CPU; the separate compat APK is no longer needed. +- **whisper.cpp 1.9.6** (was 1.7.4). +- **Privacy:** only lengths and times are logged, never the recognized text or the vocabulary prompt. +- **Recommended models:** the FUTO ACFT models (e.g. Multilingual-244) are trained for short windows and were the fastest and most accurate in our tests. + +--- + +### Setup & Updates + +1. Download and install the APK matching your device architecture (or the universal `voice_plugin.apk`) from the release assets below. It installs over the current plugin. +2. In **LeanType Keyboard Settings > Plugins > Voice Input**, select your model and CPU threads (4 recommended). From b877e73e13c4f6b85513e073279bb5e27c15fda1 Mon Sep 17 00:00:00 2001 From: 4di-hello <4di-hello@users.noreply.github.com> Date: Sun, 29 Nov 2026 14:53:11 +0100 Subject: [PATCH 09/15] Version 1.1.0 Co-Authored-By: Claude Opus 5.5 --- app/build.gradle.kts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/build.gradle.kts b/app/build.gradle.kts index c3d13ad..f712b1b 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -31,8 +31,8 @@ android { applicationId = "com.leanbitlab.leantype.voice.offline" minSdk = 21 targetSdk = 35 - versionCode = 109 - versionName = "1.0.9-plus" + versionCode = 110 + versionName = "1.1.0" // true if the arm64 library of this build needs ARMv8.2 dot-product and FP16 (see CMakeLists.txt) // false: the CPU backend is loaded at runtime in the variant that fits the CPU (see CMakeLists.txt) From 454beb6e68dcffaeb392b1c5185d4b27f1f8f44f Mon Sep 17 00:00:00 2001 From: 4di-hello <4di-hello@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:35:35 +0100 Subject: [PATCH 10/15] Fast cores from the process, not from the calling thread ggml pins the thread that creates a thread pool to that pool's cores. The cores for the next pool were read from that same thread, so after 4 threads a pool for 6 got only the 4 fast cores: 6 threads on 4 cores, which waits at every step (measured 19-45 s instead of about 1 s). Co-Authored-By: Claude Opus 5.5 --- app/src/main/cpp/patches/whisper-threadpool.patch | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/app/src/main/cpp/patches/whisper-threadpool.patch b/app/src/main/cpp/patches/whisper-threadpool.patch index 5be1dbc..9eb8e6e 100644 --- a/app/src/main/cpp/patches/whisper-threadpool.patch +++ b/app/src/main/cpp/patches/whisper-threadpool.patch @@ -2,7 +2,7 @@ diff --git a/src/whisper.cpp b/src/whisper.cpp index 0336bf7..8593ec3 100644 --- a/src/whisper.cpp +++ b/src/whisper.cpp -@@ -6,6 +6,11 @@ +@@ -6,6 +6,12 @@ #include "ggml-cpp.h" #include "ggml-alloc.h" #include "ggml-backend.h" @@ -11,10 +11,11 @@ index 0336bf7..8593ec3 100644 +#include +#include +#include ++#include #ifdef WHISPER_USE_COREML #include "coreml/whisper-encoder.h" -@@ -169,6 +174,52 @@ static bool ggml_graph_compute_helper( +@@ -169,6 +175,54 @@ static bool ggml_graph_compute_helper( return ggml_backend_graph_compute(backend.get(), graph) == GGML_STATUS_SUCCESS; } @@ -25,7 +26,9 @@ index 0336bf7..8593ec3 100644 +#if defined(__linux__) + cpu_set_t allowed; + CPU_ZERO(&allowed); -+ if (sched_getaffinity(0, sizeof(allowed), &allowed) != 0) return {}; ++ // the cores of the process (its main thread), not of this thread: ggml pins the thread that creates a ++ // pool to that pool's cores, so after a pool for 4 threads a pool for 6 would get only those 4 cores ++ if (sched_getaffinity(getpid(), sizeof(allowed), &allowed) != 0) return {}; + std::vector> cpus; + for (int i = 0; i < CPU_SETSIZE && i < GGML_MAX_N_THREADS; i++) { + if (!CPU_ISSET(i, &allowed)) continue; @@ -67,7 +70,7 @@ index 0336bf7..8593ec3 100644 static bool ggml_graph_compute_helper( ggml_backend_sched_t sched, struct ggml_cgraph * graph, -@@ -183,6 +234,11 @@ static bool ggml_graph_compute_helper( +@@ -183,6 +237,11 @@ static bool ggml_graph_compute_helper( if (fn_set_n_threads) { fn_set_n_threads(backend, n_threads); } From a9e6ae93325612d08433127842391681f38bcffa Mon Sep 17 00:00:00 2001 From: 4di-hello <4di-hello@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:02:35 +0100 Subject: [PATCH 11/15] Review (security): threads limited to the cores, no exception through JNI, text as bytes - Threads limited to the cores the process may use: more only wait for each other, and since every thread count keeps its pool, any number from a caller could otherwise create pools without end - init and transcribe catch every exception (e.g. a model file asking for more memory than there is) instead of ending the process; JNI resources are released through guards - The text comes back as UTF-8 bytes, decoded in Kotlin: NewStringUTF only takes modified UTF-8 - Debug-level engine logs are never passed on Co-Authored-By: Claude Opus 5.5 --- app/src/main/cpp/whisper_jni.cpp | 179 +++++++++++------- .../voice/offline/engine/WhisperNative.kt | 14 +- 2 files changed, 118 insertions(+), 75 deletions(-) diff --git a/app/src/main/cpp/whisper_jni.cpp b/app/src/main/cpp/whisper_jni.cpp index 7974996..1dabcb3 100644 --- a/app/src/main/cpp/whisper_jni.cpp +++ b/app/src/main/cpp/whisper_jni.cpp @@ -10,13 +10,15 @@ #include "whisper.h" #include "ggml-backend.h" #include +#include +#include #define TAG "WhisperJNI" #define LOGI(...) __android_log_print(ANDROID_LOG_INFO, TAG, __VA_ARGS__) #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, TAG, __VA_ARGS__) static void whisper_android_log_callback(enum ggml_log_level level, const char * text, void * /* user_data */) { - if (text == nullptr) return; + if (text == nullptr || level == GGML_LOG_LEVEL_DEBUG) return; int android_level = ANDROID_LOG_INFO; if (level == GGML_LOG_LEVEL_ERROR) android_level = ANDROID_LOG_ERROR; else if (level == GGML_LOG_LEVEL_WARN) android_level = ANDROID_LOG_WARN; @@ -97,11 +99,33 @@ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM * /* vm */, void * /* reserved */) { } -JNIEXPORT jlong JNICALL -Java_com_leanbitlab_leantype_voice_offline_engine_WhisperNative_init( - JNIEnv *env, - jobject /* this */, - jstring model_path) { +/** Releases JNI resources when leaving the scope, also through an exception */ +struct ScopedUtfChars { + JNIEnv *env; jstring str; const char *chars; + ScopedUtfChars(JNIEnv *e, jstring s) : env(e), str(s), chars(s != nullptr ? e->GetStringUTFChars(s, nullptr) : nullptr) {} + ~ScopedUtfChars() { if (chars != nullptr) env->ReleaseStringUTFChars(str, chars); } +}; +struct ScopedFloats { + JNIEnv *env; jfloatArray array; jfloat *data; + ScopedFloats(JNIEnv *e, jfloatArray a) : env(e), array(a), data(e->GetFloatArrayElements(a, nullptr)) {} + ~ScopedFloats() { if (data != nullptr) env->ReleaseFloatArrayElements(array, data, JNI_ABORT); } +}; + +/** + * Threads limited to the cores the process may use (at least 1): more threads than cores only wait for + * each other, and every thread count gets its own pool that is kept, so the number of pools stays small. + */ +static int clamp_threads(int requested) { + int cores = 0; + cpu_set_t allowed; + CPU_ZERO(&allowed); + if (sched_getaffinity(getpid(), sizeof(allowed), &allowed) == 0) cores = CPU_COUNT(&allowed); + if (cores <= 0) cores = 8; + if (requested <= 0) requested = 4; + return std::max(1, std::min(requested, cores)); +} + +static jlong init_impl(JNIEnv *env, jstring model_path) { if (model_path == nullptr) { LOGE("Model path is null"); return 0; @@ -109,21 +133,19 @@ Java_com_leanbitlab_leantype_voice_offline_engine_WhisperNative_init( whisper_log_set(whisper_android_log_callback, nullptr); - const char *path = env->GetStringUTFChars(model_path, nullptr); - LOGI("Initializing whisper from file: %s", path); - - whisper_context_params cparams = whisper_context_default_params(); - cparams.use_gpu = false; - // without a loaded CPU backend whisper.cpp would crash the process instead of failing if (ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU) == nullptr) { LOGE("no CPU backend loaded"); - env->ReleaseStringUTFChars(model_path, path); return 0; } - struct whisper_context *ctx = whisper_init_from_file_with_params(path, cparams); - env->ReleaseStringUTFChars(model_path, path); + whisper_context_params cparams = whisper_context_default_params(); + cparams.use_gpu = false; + + ScopedUtfChars path(env, model_path); + if (path.chars == nullptr) return 0; + LOGI("Initializing whisper from file: %s", path.chars); + struct whisper_context *ctx = whisper_init_from_file_with_params(path.chars, cparams); if (ctx == nullptr) { LOGE("Failed to initialize whisper context from file"); return 0; @@ -133,41 +155,20 @@ Java_com_leanbitlab_leantype_voice_offline_engine_WhisperNative_init( return reinterpret_cast(ctx); } -JNIEXPORT void JNICALL -Java_com_leanbitlab_leantype_voice_offline_engine_WhisperNative_free( - JNIEnv * /* env */, - jobject /* this */, - jlong context_ptr) { - if (context_ptr != 0) { - auto *ctx = reinterpret_cast(context_ptr); - LOGI("Freeing whisper context: %p", ctx); - whisper_free(ctx); - } -} - -JNIEXPORT jstring JNICALL -Java_com_leanbitlab_leantype_voice_offline_engine_WhisperNative_transcribe( - JNIEnv *env, - jobject /* this */, - jlong context_ptr, - jfloatArray pcm_data, - jstring language, - jint threads, - jstring initial_prompt) { - if (context_ptr == 0 || pcm_data == nullptr) { - return env->NewStringUTF(""); - } +/** The recognized text as UTF-8 bytes: JNI's NewStringUTF only takes modified UTF-8, the model may emit other bytes */ +static std::string transcribe_impl(JNIEnv *env, jlong context_ptr, jfloatArray pcm_data, jstring language, + jint threads, jstring initial_prompt) { + if (context_ptr == 0 || pcm_data == nullptr) return ""; auto *ctx = reinterpret_cast(context_ptr); - jsize len = env->GetArrayLength(pcm_data); - if (len <= 0) { - return env->NewStringUTF(""); - } + const jsize len = env->GetArrayLength(pcm_data); + if (len <= 0) return ""; - jfloat *samples = env->GetFloatArrayElements(pcm_data, nullptr); + ScopedFloats samples(env, pcm_data); + if (samples.data == nullptr) return ""; whisper_full_params params = whisper_full_default_params(WHISPER_SAMPLING_GREEDY); - params.n_threads = threads > 0 ? threads : 4; + params.n_threads = clamp_threads(threads); params.single_segment = false; params.no_context = true; params.no_timestamps = true; @@ -180,25 +181,16 @@ Java_com_leanbitlab_leantype_voice_offline_engine_WhisperNative_transcribe( params.suppress_nst = true; const bool is_multilingual = whisper_is_multilingual(ctx) != 0; - const char *lang_str = nullptr; - if (language != nullptr) { - lang_str = env->GetStringUTFChars(language, nullptr); - } - - const char *prompt_str = nullptr; - if (initial_prompt != nullptr) { - prompt_str = env->GetStringUTFChars(initial_prompt, nullptr); - if (prompt_str != nullptr && strlen(prompt_str) > 0) { - params.initial_prompt = prompt_str; - } - } + ScopedUtfChars lang(env, language); + ScopedUtfChars prompt(env, initial_prompt); + if (prompt.chars != nullptr && strlen(prompt.chars) > 0) params.initial_prompt = prompt.chars; std::string active_lang = "en"; if (!is_multilingual) { params.language = "en"; params.detect_language = false; - } else if (lang_str != nullptr && std::string(lang_str) != "auto" && std::string(lang_str).length() > 0) { - active_lang = lang_str; + } else if (lang.chars != nullptr && std::string(lang.chars) != "auto" && std::string(lang.chars).length() > 0) { + active_lang = lang.chars; params.language = active_lang.c_str(); params.detect_language = false; } else { @@ -223,32 +215,73 @@ Java_com_leanbitlab_leantype_voice_offline_engine_WhisperNative_transcribe( seconds, params.audio_ctx, params.language, params.n_threads, params.initial_prompt ? "yes" : "no"); std::string result; - int ret = run_whisper(ctx, params, samples, len, result); + const int ret = run_whisper(ctx, params, samples.data, len, result); + if (ret != 0) { + LOGE("whisper_full failed with code: %d", ret); + return ""; + } // Models not trained for a shorter window (all but the ACFT ones) sometimes repeat a sentence with it: // then once more with the full 30 s window - if (ret == 0 && params.audio_ctx > 0 && has_repeated_words(result)) { + if (params.audio_ctx > 0 && has_repeated_words(result)) { LOGI("repetition with audio_ctx %d, again with the full window", params.audio_ctx); params.audio_ctx = 0; std::string again; // if the second run fails, the first result is still better than nothing - if (run_whisper(ctx, params, samples, len, again) == 0) result = again; + if (run_whisper(ctx, params, samples.data, len, again) == 0) result = again; } + LOGI("whisper_full result: %zu bytes", result.size()); + return result; +} - if (lang_str != nullptr) { - env->ReleaseStringUTFChars(language, lang_str); - } - if (prompt_str != nullptr) { - env->ReleaseStringUTFChars(initial_prompt, prompt_str); +// Every exception is caught here: one through JNI would end the process (e.g. a model file asking for +// more memory than there is). + +JNIEXPORT jlong JNICALL +Java_com_leanbitlab_leantype_voice_offline_engine_WhisperNative_init( + JNIEnv *env, + jobject /* this */, + jstring model_path) { + try { + return init_impl(env, model_path); + } catch (...) { + LOGE("loading the model failed: exception"); } - env->ReleaseFloatArrayElements(pcm_data, samples, JNI_ABORT); + return 0; +} - if (ret != 0) { - LOGE("whisper_full failed with code: %d", ret); - return env->NewStringUTF(""); +JNIEXPORT void JNICALL +Java_com_leanbitlab_leantype_voice_offline_engine_WhisperNative_free( + JNIEnv * /* env */, + jobject /* this */, + jlong context_ptr) { + if (context_ptr != 0) { + auto *ctx = reinterpret_cast(context_ptr); + LOGI("Freeing whisper context: %p", ctx); + whisper_free(ctx); } - LOGI("whisper_full result: %zu bytes", result.size()); +} - return env->NewStringUTF(result.c_str()); +JNIEXPORT jbyteArray JNICALL +Java_com_leanbitlab_leantype_voice_offline_engine_WhisperNative_transcribeBytes( + JNIEnv *env, + jobject /* this */, + jlong context_ptr, + jfloatArray pcm_data, + jstring language, + jint threads, + jstring initial_prompt) { + std::string result; + try { + result = transcribe_impl(env, context_ptr, pcm_data, language, threads, initial_prompt); + } catch (...) { + LOGE("recognition failed: exception"); + result.clear(); + } + jbyteArray bytes = env->NewByteArray((jsize) result.size()); + if (bytes != nullptr && !result.empty()) { + env->SetByteArrayRegion(bytes, 0, (jsize) result.size(), reinterpret_cast(result.data())); + } + return bytes; } } // extern "C" diff --git a/app/src/main/java/com/leanbitlab/leantype/voice/offline/engine/WhisperNative.kt b/app/src/main/java/com/leanbitlab/leantype/voice/offline/engine/WhisperNative.kt index 713c8ff..0c26076 100644 --- a/app/src/main/java/com/leanbitlab/leantype/voice/offline/engine/WhisperNative.kt +++ b/app/src/main/java/com/leanbitlab/leantype/voice/offline/engine/WhisperNative.kt @@ -27,11 +27,21 @@ object WhisperNative { external fun init(modelPath: String): Long external fun free(contextPtr: Long) - external fun transcribe( + /** The recognized text; decoded here because the native side returns plain UTF-8 bytes */ + fun transcribe( contextPtr: Long, pcmData: FloatArray, language: String?, threads: Int, initialPrompt: String? = null - ): String + ): String = transcribeBytes(contextPtr, pcmData, language, threads, initialPrompt) + ?.let { String(it, Charsets.UTF_8) } ?: "" + + private external fun transcribeBytes( + contextPtr: Long, + pcmData: FloatArray, + language: String?, + threads: Int, + initialPrompt: String? + ): ByteArray? } From ffec8661abf83dc2c0b92f379722f77958c3387c Mon Sep 17 00:00:00 2001 From: 4di-hello <4di-hello@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:06:20 +0100 Subject: [PATCH 12/15] Release notes: whisper.cpp was 1.9.2, not 1.7.4; mention CVE-2026-110810 Co-Authored-By: Claude Opus 5.5 --- docs/release_notes/v1.1.0.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/release_notes/v1.1.0.md b/docs/release_notes/v1.1.0.md index 60d3f98..db2ef75 100644 --- a/docs/release_notes/v1.1.0.md +++ b/docs/release_notes/v1.1.0.md @@ -9,7 +9,7 @@ Speed update for the **LeanType Voice Plugin**: a short dictation is recognized - **Window fitting the recording:** Whisper used to compute a full 30-second window even for 3 seconds of speech. For recordings under 30 seconds the window now fits the audio. If a model then repeats part of the text, the audio is recognized once more with the full window. - **One thread pool on the fastest cores:** threads are no longer started and ended for every decoded token, and they run on the fastest cores. 4 threads (the default) are usually faster than 8. - **CPU variants chosen at runtime:** the CPU part of whisper.cpp is included for ARMv8.0 up to ARMv9.2 (and x86_64 generations). The standard APK runs on every 64-bit ARM CPU; the separate compat APK is no longer needed. -- **whisper.cpp 1.9.6** (was 1.7.4). +- **whisper.cpp 1.9.6** (was 1.9.2); this also brings the fix for CVE-2026-110810 (out-of-bounds read when loading a model, fixed in 1.9.5). - **Privacy:** only lengths and times are logged, never the recognized text or the vocabulary prompt. - **Recommended models:** the FUTO ACFT models (e.g. Multilingual-244) are trained for short windows and were the fastest and most accurate in our tests. From ff8ce35ed9fcb493847190bd8a8e8499cd62efb9 Mon Sep 17 00:00:00 2001 From: 4di-hello <4di-hello@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:15:25 +0100 Subject: [PATCH 13/15] JNI: no further JNI calls while a Java exception is pending Co-Authored-By: Claude Opus 5.5 --- app/src/main/cpp/whisper_jni.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/app/src/main/cpp/whisper_jni.cpp b/app/src/main/cpp/whisper_jni.cpp index 1dabcb3..bbc5043 100644 --- a/app/src/main/cpp/whisper_jni.cpp +++ b/app/src/main/cpp/whisper_jni.cpp @@ -165,7 +165,7 @@ static std::string transcribe_impl(JNIEnv *env, jlong context_ptr, jfloatArray p if (len <= 0) return ""; ScopedFloats samples(env, pcm_data); - if (samples.data == nullptr) return ""; + if (samples.data == nullptr) return ""; // a Java exception is pending: no further JNI calls whisper_full_params params = whisper_full_default_params(WHISPER_SAMPLING_GREEDY); params.n_threads = clamp_threads(threads); @@ -182,7 +182,9 @@ static std::string transcribe_impl(JNIEnv *env, jlong context_ptr, jfloatArray p const bool is_multilingual = whisper_is_multilingual(ctx) != 0; ScopedUtfChars lang(env, language); + if (language != nullptr && lang.chars == nullptr) return ""; // out of memory, exception pending ScopedUtfChars prompt(env, initial_prompt); + if (initial_prompt != nullptr && prompt.chars == nullptr) return ""; if (prompt.chars != nullptr && strlen(prompt.chars) > 0) params.initial_prompt = prompt.chars; std::string active_lang = "en"; @@ -277,6 +279,8 @@ Java_com_leanbitlab_leantype_voice_offline_engine_WhisperNative_transcribeBytes( LOGE("recognition failed: exception"); result.clear(); } + // after a failed JNI call (out of memory) a Java exception is pending: return it as is + if (env->ExceptionCheck()) return nullptr; jbyteArray bytes = env->NewByteArray((jsize) result.size()); if (bytes != nullptr && !result.empty()) { env->SetByteArrayRegion(bytes, 0, (jsize) result.size(), reinterpret_cast(result.data())); From d79c332f95e698a70ab5e7cbf6dd2074f7fef01a Mon Sep 17 00:00:00 2001 From: 4di-hello <4di-hello@users.noreply.github.com> Date: Mon, 30 Nov 2026 19:33:12 +0100 Subject: [PATCH 14/15] A cancelled recognition really stops; imports report how they ended - whisper.cpp asks an abort flag before every computation step; cancelling a session (also after the keyboard's timeout) stops its running recognition instead of letting it hold up the next dictation - Each session has its own cancel flags: a new session no longer undoes the cancel of an earlier one - The model state tells whether an import is running and how the last one ended (ok, or the reason), so the keyboard can confirm that a model is really ready Co-Authored-By: Claude Opus 5.5 --- app/src/main/cpp/whisper_jni.cpp | 25 ++++++++- .../voice/offline/engine/WhisperEngine.kt | 56 +++++++++++++------ .../voice/offline/engine/WhisperNative.kt | 4 ++ .../voice/offline/model/ModelManager.kt | 32 +++++++++++ 4 files changed, 98 insertions(+), 19 deletions(-) diff --git a/app/src/main/cpp/whisper_jni.cpp b/app/src/main/cpp/whisper_jni.cpp index bbc5043..d2b5501 100644 --- a/app/src/main/cpp/whisper_jni.cpp +++ b/app/src/main/cpp/whisper_jni.cpp @@ -9,6 +9,7 @@ #include #include "whisper.h" #include "ggml-backend.h" +#include #include #include #include @@ -125,6 +126,13 @@ static int clamp_threads(int requested) { return std::max(1, std::min(requested, cores)); } +/** + * Set when the running recognition is cancelled: whisper.cpp asks before every computation step and + * stops, so a cancelled or overdue recognition does not hold up the next one + */ +static std::atomic g_abort{false}; +static bool abort_requested(void * /* data */) { return g_abort.load(std::memory_order_relaxed); } + static jlong init_impl(JNIEnv *env, jstring model_path) { if (model_path == nullptr) { LOGE("Model path is null"); @@ -179,6 +187,8 @@ static std::string transcribe_impl(JNIEnv *env, jlong context_ptr, jfloatArray p params.print_special = false; params.suppress_blank = true; params.suppress_nst = true; + params.abort_callback = abort_requested; + params.abort_callback_user_data = nullptr; const bool is_multilingual = whisper_is_multilingual(ctx) != 0; ScopedUtfChars lang(env, language); @@ -219,12 +229,13 @@ static std::string transcribe_impl(JNIEnv *env, jlong context_ptr, jfloatArray p std::string result; const int ret = run_whisper(ctx, params, samples.data, len, result); if (ret != 0) { + if (g_abort.load()) { LOGI("whisper_full cancelled"); return ""; } LOGE("whisper_full failed with code: %d", ret); return ""; } // Models not trained for a shorter window (all but the ACFT ones) sometimes repeat a sentence with it: // then once more with the full 30 s window - if (params.audio_ctx > 0 && has_repeated_words(result)) { + if (params.audio_ctx > 0 && !g_abort.load() && has_repeated_words(result)) { LOGI("repetition with audio_ctx %d, again with the full window", params.audio_ctx); params.audio_ctx = 0; std::string again; @@ -263,6 +274,18 @@ Java_com_leanbitlab_leantype_voice_offline_engine_WhisperNative_free( } } +/** Stops the running recognition at its next computation step */ +JNIEXPORT void JNICALL +Java_com_leanbitlab_leantype_voice_offline_engine_WhisperNative_abort(JNIEnv * /* env */, jobject /* this */) { + g_abort.store(true); +} + +/** Before a recognition starts: an earlier cancel must not stop it */ +JNIEXPORT void JNICALL +Java_com_leanbitlab_leantype_voice_offline_engine_WhisperNative_resetAbort(JNIEnv * /* env */, jobject /* this */) { + g_abort.store(false); +} + JNIEXPORT jbyteArray JNICALL Java_com_leanbitlab_leantype_voice_offline_engine_WhisperNative_transcribeBytes( JNIEnv *env, diff --git a/app/src/main/java/com/leanbitlab/leantype/voice/offline/engine/WhisperEngine.kt b/app/src/main/java/com/leanbitlab/leantype/voice/offline/engine/WhisperEngine.kt index 8ad5f13..516365d 100644 --- a/app/src/main/java/com/leanbitlab/leantype/voice/offline/engine/WhisperEngine.kt +++ b/app/src/main/java/com/leanbitlab/leantype/voice/offline/engine/WhisperEngine.kt @@ -18,8 +18,14 @@ class WhisperEngine { private var contextPtr: Long = 0L private var loadedModelPath: String? = null - private val isRunning = AtomicBoolean(false) - private val isCancelled = AtomicBoolean(false) + /** Each session has its own flags: a new session must not undo the cancel of an earlier one */ + private class Session { + val running = AtomicBoolean(true) + val cancelled = AtomicBoolean(false) + } + @Volatile private var currentSession: Session? = null + /** The session whose audio whisper.cpp is computing right now */ + @Volatile private var transcribingSession: Session? = null private val audioExecutor = Executors.newSingleThreadExecutor { r -> Thread(r, "WhisperAudioThread").apply { isDaemon = true } } @@ -91,6 +97,7 @@ class WhisperEngine { val floatPcm = FloatArray(pcm.size) { pcm[it] / 32768.0f } val numThreads = minOf(4, maxOf(1, Runtime.getRuntime().availableProcessors())) val lang = normalizeLanguageTag(language) + WhisperNative.resetAbort() return try { val raw = WhisperNative.transcribe(contextPtr, floatPcm, lang, numThreads) raw.trim() @@ -111,8 +118,8 @@ class WhisperEngine { return } - isRunning.set(true) - isCancelled.set(false) + val session = Session() + currentSession = session val language = normalizeLanguageTag(config?.languageTag) val numThreads = if (config != null && config.cpuThreads > 0) { config.cpuThreads @@ -134,7 +141,7 @@ class WhisperEngine { val shortBuffer = ShortArray(FRAME_SIZE_BYTES / 2) // Continuous non-blocking read loop: drains entire audio stream from host pipe - while (isRunning.get()) { + while (session.running.get()) { val bytesRead = inputStream.read(byteBuffer) if (bytesRead <= 0) { Log.i(TAG, "EOF reached on audio input stream ($bytesRead). Total read bytes: $totalReadBytes") @@ -153,13 +160,13 @@ class WhisperEngine { } // Process full speech utterance on EOF - Log.i(TAG, "Processing utterance on EOF (samples=${utteranceBuffer.size}, isCancelled=${isCancelled.get()})") - if (!isCancelled.get() && utteranceBuffer.isNotEmpty()) { + Log.i(TAG, "Processing utterance on EOF (samples=${utteranceBuffer.size}, isCancelled=${session.cancelled.get()})") + if (!session.cancelled.get() && utteranceBuffer.isNotEmpty()) { Log.i(TAG, "EOF flush: transcribing ${utteranceBuffer.size} samples (%.2f sec)".format(utteranceBuffer.size / 16000.0)) - val text = transcribeAndEmit(utteranceBuffer, language, numThreads, customPrompt, callback) + val text = transcribeAndEmit(session, utteranceBuffer, language, numThreads, customPrompt, callback) Log.i(TAG, "EOF result: ${text.length} chars") utteranceBuffer.clear() - } else if (!isCancelled.get()) { + } else if (!session.cancelled.get()) { Log.i(TAG, "EOF with empty buffer, emitting empty final") try { callback.onFinal("") @@ -169,14 +176,14 @@ class WhisperEngine { } } catch (e: Exception) { Log.e(TAG, "Whisper audio loop error", e) - if (!isCancelled.get()) { + if (!session.cancelled.get()) { try { callback.onError(VoiceConstants.VOICE_ERROR_AUDIO_START_FAILED, e.message ?: "Audio processing error") } catch (_: Exception) {} } } finally { - isRunning.set(false) - if (!isCancelled.get()) { + session.running.set(false) + if (!session.cancelled.get()) { try { Log.i(TAG, "Emitting onSessionEnded") callback.onSessionEnded() @@ -186,37 +193,45 @@ class WhisperEngine { } try { inputStream?.close() } catch (_: Exception) {} try { audioInput.close() } catch (_: Exception) {} - Log.i(TAG, "Whisper session finished. Total read: $totalReadBytes bytes (cancelled=${isCancelled.get()})") + Log.i(TAG, "Whisper session finished. Total read: $totalReadBytes bytes (cancelled=${session.cancelled.get()})") } } } private fun transcribeAndEmit( + session: Session, samples: List, language: String?, threads: Int, prompt: String?, callback: IVoiceCallback ): String { - if (isCancelled.get() || contextPtr == 0L || samples.isEmpty()) return "" + if (session.cancelled.get() || contextPtr == 0L || samples.isEmpty()) return "" val rawPcm = ShortArray(samples.size) { samples[it] } val pcm = trimLeadingAndTrailingSilence(rawPcm) if (pcm.isEmpty()) { Log.w(TAG, "Peak RMS gate triggered! Audio discarded as silence after trimming") - if (!isCancelled.get()) { + if (!session.cancelled.get()) { try { callback.onFinal("") } catch (_: Exception) {} } return "" } val floatPcm = FloatArray(pcm.size) { pcm[it] / 32768.0f } + // reset first, then mark the session, then check: a cancel in between is never lost + WhisperNative.resetAbort() + transcribingSession = session + if (session.cancelled.get()) { + transcribingSession = null + return "" + } return try { val rawText = WhisperNative.transcribe(contextPtr, floatPcm, language, threads, prompt) Log.i(TAG, "JNI transcribe returned ${rawText.length} chars") val finalText = rawText.trim() - if (!isCancelled.get()) { + if (!session.cancelled.get()) { Log.i(TAG, "Emitting onFinal: ${finalText.length} chars") callback.onFinal(finalText) } @@ -224,6 +239,8 @@ class WhisperEngine { } catch (e: Exception) { Log.e(TAG, "Whisper transcription failed", e) "" + } finally { + transcribingSession = null } } @@ -298,9 +315,12 @@ class WhisperEngine { return maxRms } + /** Cancels the current session; a recognition already running for it stops at its next computation step */ fun cancelSession() { - isCancelled.set(true) - isRunning.set(false) + val session = currentSession ?: return + session.cancelled.set(true) + session.running.set(false) + if (transcribingSession === session) WhisperNative.abort() } private fun normalizeLanguageTag(tag: String?): String? { diff --git a/app/src/main/java/com/leanbitlab/leantype/voice/offline/engine/WhisperNative.kt b/app/src/main/java/com/leanbitlab/leantype/voice/offline/engine/WhisperNative.kt index 0c26076..452fafd 100644 --- a/app/src/main/java/com/leanbitlab/leantype/voice/offline/engine/WhisperNative.kt +++ b/app/src/main/java/com/leanbitlab/leantype/voice/offline/engine/WhisperNative.kt @@ -27,6 +27,10 @@ object WhisperNative { external fun init(modelPath: String): Long external fun free(contextPtr: Long) + /** Stops the running recognition at its next computation step */ + external fun abort() + /** Called before a recognition starts, so that an earlier cancel does not stop it */ + external fun resetAbort() /** The recognized text; decoded here because the native side returns plain UTF-8 bytes */ fun transcribe( contextPtr: Long, diff --git a/app/src/main/java/com/leanbitlab/leantype/voice/offline/model/ModelManager.kt b/app/src/main/java/com/leanbitlab/leantype/voice/offline/model/ModelManager.kt index ca525f2..0480568 100644 --- a/app/src/main/java/com/leanbitlab/leantype/voice/offline/model/ModelManager.kt +++ b/app/src/main/java/com/leanbitlab/leantype/voice/offline/model/ModelManager.kt @@ -21,7 +21,27 @@ class ModelManager( private val modelsDir: File get() = File(context.filesDir, "models").apply { if (!exists()) mkdirs() } + // How the last import went, for the keyboard: the import call returns at once, the work runs later. + // Reported in the message of the model state: "[imports=N; importing]" or "[imports=N; last=ok]" or + // "[imports=N; last=failed: ]"; N counts the finished imports since the plugin started. + @Volatile private var importing = false + @Volatile private var importsDone = 0 + @Volatile private var lastImportError: String? = null + + private fun importNote(): String = when { + importing -> " [imports=$importsDone; importing]" + importsDone == 0 -> " [imports=0]" + lastImportError == null -> " [imports=$importsDone; last=ok]" + else -> " [imports=$importsDone; last=failed: $lastImportError]" + } + fun getModelState(engineType: String): ModelState { + val state = fileModelState(engineType) + if (importing) return ModelState(engineType, ModelState.STATE_LOADING, "Importing model" + importNote()) + return state.copy(message = (state.message ?: "") + importNote()) + } + + private fun fileModelState(engineType: String): ModelState { val targetFile = File(modelsDir, engineType) if (!targetFile.exists()) { return ModelState(engineType, ModelState.STATE_MISSING, "Model not imported") @@ -57,10 +77,14 @@ class ModelManager( val targetEngine = request.engineType if (targetEngine != VoiceConstants.ENGINE_WHISPER) { Log.e(TAG, "Unsupported engine type for import: $targetEngine") + lastImportError = "unsupported engine" + importsDone++ return false } val tmpFile = File(modelsDir, "${targetEngine}_${System.currentTimeMillis()}.tmp") + importing = true + var error: String? = "unknown error" try { Log.i(TAG, "Starting Whisper model import, size: ${request.sizeBytes} bytes") @@ -74,6 +98,7 @@ class ModelManager( if (sha256 != null && !verifySha256(tmpFile, sha256)) { Log.e(TAG, "SHA256 verification failed for $targetEngine") tmpFile.delete() + error = "checksum does not match" return false } @@ -82,6 +107,7 @@ class ModelManager( if (!validateWhisperModelOnImport(tmpFile)) { Log.e(TAG, "Imported file is not a valid Whisper model") + error = if (isWhisperHeaderValid(tmpFile)) "the model could not be loaded" else "not a Whisper model file" tmpFile.delete() return false } @@ -94,11 +120,17 @@ class ModelManager( tmpFile.delete() } Log.i(TAG, "Whisper model installed successfully: ${finalFile.absolutePath}") + error = null return true } catch (e: Exception) { Log.e(TAG, "Failed to import Whisper model", e) tmpFile.delete() + error = "copying the file failed" return false + } finally { + lastImportError = error + importsDone++ + importing = false } } From 2e06311e7090829c0e929e0f005fb56649b8341f Mon Sep 17 00:00:00 2001 From: 4di-hello <4di-hello@users.noreply.github.com> Date: Mon, 30 Nov 2026 19:42:20 +0100 Subject: [PATCH 15/15] Cancel: no late abort on the next session; import state and executor per process - Marking the transcribing session and aborting it happen under one lock, so a cancel that arrives just as a recognition ends can't stop the next one - Wording: whisper.cpp checks the abort flag after each encoder pass and decoding step - Import counters and the import executor live per process: a service created again during an import reports it correctly and doesn't start a second import alongside Co-Authored-By: Claude Opus 5.5 --- app/src/main/cpp/whisper_jni.cpp | 6 +++--- .../voice/offline/VoiceEngineService.kt | 8 ++++--- .../voice/offline/engine/WhisperEngine.kt | 21 +++++++++++++------ .../voice/offline/engine/WhisperNative.kt | 2 +- .../voice/offline/model/ModelManager.kt | 8 ++++--- 5 files changed, 29 insertions(+), 16 deletions(-) diff --git a/app/src/main/cpp/whisper_jni.cpp b/app/src/main/cpp/whisper_jni.cpp index d2b5501..1557c01 100644 --- a/app/src/main/cpp/whisper_jni.cpp +++ b/app/src/main/cpp/whisper_jni.cpp @@ -127,8 +127,8 @@ static int clamp_threads(int requested) { } /** - * Set when the running recognition is cancelled: whisper.cpp asks before every computation step and - * stops, so a cancelled or overdue recognition does not hold up the next one + * Set when the running recognition is cancelled: whisper.cpp checks it after each encoder pass and each + * decoding step and stops, so a cancelled or overdue recognition does not hold up the next one */ static std::atomic g_abort{false}; static bool abort_requested(void * /* data */) { return g_abort.load(std::memory_order_relaxed); } @@ -274,7 +274,7 @@ Java_com_leanbitlab_leantype_voice_offline_engine_WhisperNative_free( } } -/** Stops the running recognition at its next computation step */ +/** Stops the running recognition after its current encoder pass or decoding step */ JNIEXPORT void JNICALL Java_com_leanbitlab_leantype_voice_offline_engine_WhisperNative_abort(JNIEnv * /* env */, jobject /* this */) { g_abort.store(true); diff --git a/app/src/main/java/com/leanbitlab/leantype/voice/offline/VoiceEngineService.kt b/app/src/main/java/com/leanbitlab/leantype/voice/offline/VoiceEngineService.kt index a54d904..3052337 100644 --- a/app/src/main/java/com/leanbitlab/leantype/voice/offline/VoiceEngineService.kt +++ b/app/src/main/java/com/leanbitlab/leantype/voice/offline/VoiceEngineService.kt @@ -24,9 +24,7 @@ class VoiceEngineService : Service() { private lateinit var whisperEngine: WhisperEngine @Volatile private var isSessionActive = false - private val modelExecutor = java.util.concurrent.Executors.newSingleThreadExecutor { r -> - Thread(r, "ModelImportThread").apply { isDaemon = true } - } + private val modelExecutor get() = importExecutor private val binder = object : IVoiceEngine.Stub() { @@ -165,6 +163,10 @@ class VoiceEngineService : Service() { } companion object { + /** One import at a time per process, also when the service is created again during an import */ + private val importExecutor = java.util.concurrent.Executors.newSingleThreadExecutor { r -> + Thread(r, "ModelImportThread").apply { isDaemon = true } + } private const val TAG = "VoiceEngineService" } } diff --git a/app/src/main/java/com/leanbitlab/leantype/voice/offline/engine/WhisperEngine.kt b/app/src/main/java/com/leanbitlab/leantype/voice/offline/engine/WhisperEngine.kt index 516365d..b3e5f60 100644 --- a/app/src/main/java/com/leanbitlab/leantype/voice/offline/engine/WhisperEngine.kt +++ b/app/src/main/java/com/leanbitlab/leantype/voice/offline/engine/WhisperEngine.kt @@ -26,6 +26,8 @@ class WhisperEngine { @Volatile private var currentSession: Session? = null /** The session whose audio whisper.cpp is computing right now */ @Volatile private var transcribingSession: Session? = null + /** Marking a session as transcribing and aborting it happen under this lock, so a late abort can't hit the next one */ + private val abortLock = Any() private val audioExecutor = Executors.newSingleThreadExecutor { r -> Thread(r, "WhisperAudioThread").apply { isDaemon = true } } @@ -221,10 +223,12 @@ class WhisperEngine { val floatPcm = FloatArray(pcm.size) { pcm[it] / 32768.0f } // reset first, then mark the session, then check: a cancel in between is never lost - WhisperNative.resetAbort() - transcribingSession = session + synchronized(abortLock) { + WhisperNative.resetAbort() + transcribingSession = session + } if (session.cancelled.get()) { - transcribingSession = null + synchronized(abortLock) { transcribingSession = null } return "" } return try { @@ -240,7 +244,7 @@ class WhisperEngine { Log.e(TAG, "Whisper transcription failed", e) "" } finally { - transcribingSession = null + synchronized(abortLock) { transcribingSession = null } } } @@ -315,12 +319,17 @@ class WhisperEngine { return maxRms } - /** Cancels the current session; a recognition already running for it stops at its next computation step */ + /** + * Cancels the current session. A recognition already running for it stops after the current encoder + * pass or decoding step (whisper.cpp checks the abort flag there). + */ fun cancelSession() { val session = currentSession ?: return session.cancelled.set(true) session.running.set(false) - if (transcribingSession === session) WhisperNative.abort() + synchronized(abortLock) { + if (transcribingSession === session) WhisperNative.abort() + } } private fun normalizeLanguageTag(tag: String?): String? { diff --git a/app/src/main/java/com/leanbitlab/leantype/voice/offline/engine/WhisperNative.kt b/app/src/main/java/com/leanbitlab/leantype/voice/offline/engine/WhisperNative.kt index 452fafd..7691f1c 100644 --- a/app/src/main/java/com/leanbitlab/leantype/voice/offline/engine/WhisperNative.kt +++ b/app/src/main/java/com/leanbitlab/leantype/voice/offline/engine/WhisperNative.kt @@ -27,7 +27,7 @@ object WhisperNative { external fun init(modelPath: String): Long external fun free(contextPtr: Long) - /** Stops the running recognition at its next computation step */ + /** Stops the running recognition after its current encoder pass or decoding step */ external fun abort() /** Called before a recognition starts, so that an earlier cancel does not stop it */ external fun resetAbort() diff --git a/app/src/main/java/com/leanbitlab/leantype/voice/offline/model/ModelManager.kt b/app/src/main/java/com/leanbitlab/leantype/voice/offline/model/ModelManager.kt index 0480568..15ba771 100644 --- a/app/src/main/java/com/leanbitlab/leantype/voice/offline/model/ModelManager.kt +++ b/app/src/main/java/com/leanbitlab/leantype/voice/offline/model/ModelManager.kt @@ -24,9 +24,6 @@ class ModelManager( // How the last import went, for the keyboard: the import call returns at once, the work runs later. // Reported in the message of the model state: "[imports=N; importing]" or "[imports=N; last=ok]" or // "[imports=N; last=failed: ]"; N counts the finished imports since the plugin started. - @Volatile private var importing = false - @Volatile private var importsDone = 0 - @Volatile private var lastImportError: String? = null private fun importNote(): String = when { importing -> " [imports=$importsDone; importing]" @@ -205,6 +202,11 @@ class ModelManager( } companion object { + // per process, not per service instance: the service can be destroyed and created again while an + // import still runs + @Volatile private var importing = false + @Volatile private var importsDone = 0 + @Volatile private var lastImportError: String? = null private const val TAG = "ModelManager" } }