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/build.gradle.kts b/app/build.gradle.kts index c9c9d1f..f712b1b 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,15 +31,20 @@ android { applicationId = "com.leanbitlab.leantype.voice.offline" minSdk = 21 targetSdk = 35 - versionCode = 105 - versionName = "1.0.5" + versionCode = 110 + versionName = "1.1.0" // 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", + // 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") } @@ -53,6 +60,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 @@ -105,14 +117,15 @@ 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") + // 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("arm64-v8a", "armeabi-v7a", "x86_64") isUniversalApk = true @@ -126,7 +139,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" + } } } } diff --git a/app/src/main/cpp/CMakeLists.txt b/app/src/main/cpp/CMakeLists.txt index 969e52e..e59b003 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,12 +16,36 @@ 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). -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 +# 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) @@ -35,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 new file mode 100644 index 0000000..9eb8e6e --- /dev/null +++ b/app/src/main/cpp/patches/whisper-threadpool.patch @@ -0,0 +1,84 @@ +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,12 @@ + #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 ++#include + + #ifdef WHISPER_USE_COREML + #include "coreml/whisper-encoder.h" +@@ -169,6 +175,54 @@ 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); ++ // 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; ++ 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 ++} ++ ++// 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 std::map pools; ++ std::lock_guard lock(mutex); ++ 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; ++ 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 +237,11 @@ static bool ggml_graph_compute_helper( + if (fn_set_n_threads) { + fn_set_n_threads(backend, n_threads); + } ++ 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); ++ } + } + + 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..1557c01 100644 --- a/app/src/main/cpp/whisper_jni.cpp +++ b/app/src/main/cpp/whisper_jni.cpp @@ -1,16 +1,25 @@ // SPDX-License-Identifier: Apache-2.0 #include +#include +#include +#include #include +#include #include #include #include "whisper.h" +#include "ggml-backend.h" +#include +#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; @@ -18,13 +27,113 @@ 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 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; + 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; + } + } + 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; +} + extern "C" { -JNIEXPORT jlong JNICALL -Java_com_leanbitlab_leantype_voice_offline_engine_WhisperNative_init( - JNIEnv *env, - jobject /* this */, - jstring model_path) { +// 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; +} + + +/** 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)); +} + +/** + * 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); } + +static jlong init_impl(JNIEnv *env, jstring model_path) { if (model_path == nullptr) { LOGE("Model path is null"); return 0; @@ -32,15 +141,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); + // 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"); + return 0; + } whisper_context_params cparams = whisper_context_default_params(); cparams.use_gpu = false; - struct whisper_context *ctx = whisper_init_from_file_with_params(path, cparams); - env->ReleaseStringUTFChars(model_path, path); - + 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; @@ -50,41 +163,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 ""; // a Java exception is pending: no further JNI calls 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; @@ -95,27 +187,22 @@ Java_com_leanbitlab_leantype_voice_offline_engine_WhisperNative_transcribe( 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; - 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); + 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"; 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 { @@ -123,43 +210,105 @@ 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 : ""); - - int ret = whisper_full(ctx, params, samples, len); + // 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; + 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; + const int audio_ctx = ((frames + 63) / 64) * 64; + if (audio_ctx < 1500) params.audio_ctx = audio_ctx; + } - LOGI("whisper_full completed with code: %d", ret); + // 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"); - if (lang_str != nullptr) { - env->ReleaseStringUTFChars(language, lang_str); + 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 ""; } - if (prompt_str != nullptr) { - env->ReleaseStringUTFChars(initial_prompt, prompt_str); + // 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 && !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; + // if the second run fails, the first result is still better than nothing + if (run_whisper(ctx, params, samples.data, len, again) == 0) result = again; } - env->ReleaseFloatArrayElements(pcm_data, samples, JNI_ABORT); + LOGI("whisper_full result: %zu bytes", result.size()); + return result; +} - if (ret != 0) { - LOGE("whisper_full failed with code: %d", ret); - return env->NewStringUTF(""); +// 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"); } + return 0; +} - 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; - } - } +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 accumulated result: '%s'", result.c_str()); +} + +/** 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); +} - return env->NewStringUTF(result.c_str()); +/** 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, + 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(); + } + // 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())); + } + return bytes; } } // extern "C" 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 02511ea..350566d 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 @@ -25,9 +25,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 fun enforceHost() = CallerCheck.enforceHost(packageManager) @@ -177,6 +175,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 614b3bb..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 @@ -18,8 +18,16 @@ 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 + /** 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 } } @@ -91,6 +99,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 +120,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 +143,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 +162,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) - Log.i(TAG, "EOF result: '$text'") + 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 +178,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,44 +195,56 @@ 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 + synchronized(abortLock) { + WhisperNative.resetAbort() + transcribingSession = session + } + if (session.cancelled.get()) { + synchronized(abortLock) { transcribingSession = null } + return "" + } 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'") + if (!session.cancelled.get()) { + Log.i(TAG, "Emitting onFinal: ${finalText.length} chars") callback.onFinal(finalText) } finalText } catch (e: Exception) { Log.e(TAG, "Whisper transcription failed", e) "" + } finally { + synchronized(abortLock) { transcribingSession = null } } } @@ -298,9 +319,17 @@ class WhisperEngine { return maxRms } + /** + * 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() { - isCancelled.set(true) - isRunning.set(false) + val session = currentSession ?: return + session.cancelled.set(true) + session.running.set(false) + 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 713c8ff..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,11 +27,25 @@ object WhisperNative { external fun init(modelPath: String): Long external fun free(contextPtr: Long) - external fun transcribe( + /** 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() + /** 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? } 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 af5544f..81de980 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,9 +21,25 @@ 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. + + 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 { if (!isKnownEngine(engineType)) return ModelState(engineType, ModelState.STATE_MISSING, "Unsupported engine") + 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") @@ -59,10 +75,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") @@ -76,6 +96,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 } @@ -84,6 +105,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 } @@ -96,11 +118,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 } } @@ -177,6 +205,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" internal fun isKnownEngine(engineType: String): Boolean = engineType == VoiceConstants.ENGINE_WHISPER diff --git a/docs/release_notes/v1.1.0.md b/docs/release_notes/v1.1.0.md new file mode 100644 index 0000000..db2ef75 --- /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.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. + +--- + +### 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).