Modern Apps git

← Modern-Apps.git

library/ml: convert JNI surface to shared jni macros

Commit
80c5d67a8f7c631b17351383e707f7dfb455aff3
Author
Vayun Mathur <[email protected]>
When
2026-12-01 20:07 UTC (4 days ago)
Parents
fa131d6
LOC Phase 5 re-examination of the measured skip. The rollout
measured library/ml at -7.7% (34/68 scaffold users) because
only the with_env half of the surface fit jni_fn!. Fresh count
of bridge.rs + bridge_part1..12 (5,303 lines, 68 JNI methods):
36 with_env methods, 32 direct _env methods that never touch
their environment (13 destroy*, fd-based creates, Gemma4 handle
getters/probes), plus 2 OCR methods with a lifetime-guard
statement before with_env.

The direct half is a second repeated scaffold, captured by the
new jni_bridge companions (previous commit) without changing
exception behaviour: jni_direct! generates the same bare
extern form (no with_env/LogErrorAndDefault layer added), and
jni_destroy! also generates the identical guard-and-drop
epilogue of the 12 pure destroys (destroyOcr keeps its
OCR_LIFETIME write-lock statement and stays jni_direct!;
recognizeText/recognizeTextBuffer acquire ocr_use_guard()
before with_env and stay hand-written, since moving the guard
inside the closure would change its drop point). jni_fn!s new
unsafe arms preserve each method's pub unsafe extern type.
Conversion: 34 jni_fn!, 20 jni_direct!, 12 jni_destroy!;
bodies verified token-for-token against HEAD by script
(comments included; only rustfmt re-indentation differs).

Lines: bridge files 5,303 -> 4,735 (-568, -10.7%), clearing
the 10% bar; structure_check lines reports 93,715 lines of
headroom under baseline, structure: OK (no budget regen for a
shrinkage). Cargo.lock gains only the jni_bridge edge for
modelrunner.

Verified: nm -D on libmodelrunner.so (aarch64-linux-android)
before/after - exported symbol set identical (68/68 Java_
MlNative symbols); cargo test -p modelrunner 895 passed,
identical to baseline; cargo fmt --check -p modelrunner
-p jni_bridge clean; doc comments moved inside the invocations
so they forward onto the generated functions (zero unused-doc
warnings, as before). One inline arg comment on createGemma4
(budget) moved above the invocation, reworded to name the
argument it documents.

Diff

Cargo.lock
diff --git a/Cargo.lock b/Cargo.lockindex bce02e3c01..791c8a1666 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -3696,6 +3696,7 @@ version = "0.1.0" dependencies = [  "ash",  "jni",+ "jni_bridge",  "libc", ] 
library/ml/src/main/rust/Cargo.toml
diff --git a/library/ml/src/main/rust/Cargo.toml b/library/ml/src/main/rust/Cargo.tomlindex a2e459e2dd..a1183afed2 100644--- a/library/ml/src/main/rust/Cargo.toml+++ b/library/ml/src/main/rust/Cargo.toml@@ -35,6 +35,7 @@ crate-type = ["cdylib", "rlib"]  [dependencies] jni.workspace = true+jni_bridge = { path = "../../../../../library/jni-bridge/src/main/rust" }  # `default-features = false` drops the `linked` feature, so nothing links against # libvulkan at build time; `loaded` dlopens it, which is what an Android app must do
library/ml/src/main/rust/src/bridge.rs
diff --git a/library/ml/src/main/rust/src/bridge.rs b/library/ml/src/main/rust/src/bridge.rsindex fc296bc759..9733384576 100644--- a/library/ml/src/main/rust/src/bridge.rs+++ b/library/ml/src/main/rust/src/bridge.rs@@ -35,6 +35,7 @@ use jni::objects::{ }; use jni::sys::{jfloatArray, jint, jintArray, jlong, jstring}; use jni::{Env, EnvUnowned};+use jni_bridge::{jni_destroy, jni_direct, jni_fn};  use crate::nets::{     gemma4, gemma4_audio, gemma4_vision, madlad, madlad_part1, maia, mobilefacenet, modnet, nllb,@@ -69,91 +70,51 @@ struct Handle {     pixels: Vec<i32>, } -/// `SelfieSegmenter`'s constructor. Returns 0 on failure, having logged why.+jni_fn! { /// `SelfieSegmenter`'s constructor. Returns 0 on failure, having logged why. /// /// # Safety /// /// Called only by the JVM, with a valid `env` and a `weights` array it owns.-#[no_mangle]-pub extern "system" fn Java_com_vayunmathur_library_ml_MlNative_createSelfie<'l>(-    mut env: EnvUnowned<'l>,-    _class: JClass<'l>,-    weights: JByteArray<'l>,-) -> jlong {-    env.with_env(|env| -> jni::errors::Result<jlong> {-        Ok(open(env, weights, graph::SELFIE, "selfie"))-    })-    .resolve::<jni::errors::LogErrorAndDefault>()-}+Java_com_vayunmathur_library_ml_MlNative_createSelfie -> jlong; (_class: JClass<'l>, weights: JByteArray<'l>) |env| {+    Ok(open(env, weights, graph::SELFIE, "selfie"))+} } -/// `SubjectSegmenter`'s constructor. Returns 0 on failure, having logged why.+jni_fn! { /// `SubjectSegmenter`'s constructor. Returns 0 on failure, having logged why. /// /// # Safety /// /// Called only by the JVM, with a valid `env` and a `weights` array it owns.-#[no_mangle]-pub extern "system" fn Java_com_vayunmathur_library_ml_MlNative_createU2netp<'l>(-    mut env: EnvUnowned<'l>,-    _class: JClass<'l>,-    weights: JByteArray<'l>,-) -> jlong {-    env.with_env(|env| -> jni::errors::Result<jlong> {-        Ok(open(env, weights, graph::U2NETP, "u2netp"))-    })-    .resolve::<jni::errors::LogErrorAndDefault>()-}+Java_com_vayunmathur_library_ml_MlNative_createU2netp -> jlong; (_class: JClass<'l>, weights: JByteArray<'l>) |env| {+    Ok(open(env, weights, graph::U2NETP, "u2netp"))+} } -/// `FaceDetector`'s constructor: SCRFD 500M at a fixed square. Returns 0 on failure.+jni_fn! { /// `FaceDetector`'s constructor: SCRFD 500M at a fixed square. Returns 0 on failure. /// /// # Safety /// /// Called only by the JVM, with a valid `env` and a `weights` array it owns.-#[no_mangle]-pub extern "system" fn Java_com_vayunmathur_library_ml_MlNative_createScrfd<'l>(-    mut env: EnvUnowned<'l>,-    _class: JClass<'l>,-    weights: JByteArray<'l>,-) -> jlong {-    env.with_env(|env| -> jni::errors::Result<jlong> {-        Ok(open(env, weights, graph::SCRFD, "scrfd"))-    })-    .resolve::<jni::errors::LogErrorAndDefault>()-}+Java_com_vayunmathur_library_ml_MlNative_createScrfd -> jlong; (_class: JClass<'l>, weights: JByteArray<'l>) |env| {+    Ok(open(env, weights, graph::SCRFD, "scrfd"))+} } -/// `FaceEmbedder`'s constructor: MobileFaceNet at 112x112. Returns 0 on failure.+jni_fn! { /// `FaceEmbedder`'s constructor: MobileFaceNet at 112x112. Returns 0 on failure. /// /// # Safety /// /// Called only by the JVM, with a valid `env` and a `weights` array it owns.-#[no_mangle]-pub extern "system" fn Java_com_vayunmathur_library_ml_MlNative_createMobilefacenet<'l>(-    mut env: EnvUnowned<'l>,-    _class: JClass<'l>,-    weights: JByteArray<'l>,-) -> jlong {-    env.with_env(|env| -> jni::errors::Result<jlong> {-        Ok(open(env, weights, graph::MOBILEFACENET, "mobilefacenet"))-    })-    .resolve::<jni::errors::LogErrorAndDefault>()-}+Java_com_vayunmathur_library_ml_MlNative_createMobilefacenet -> jlong; (_class: JClass<'l>, weights: JByteArray<'l>) |env| {+    Ok(open(env, weights, graph::MOBILEFACENET, "mobilefacenet"))+} } -/// `ModnetSegmenter`'s constructor: MODNet photographic-portrait matting at a+jni_fn! { /// `ModnetSegmenter`'s constructor: MODNet photographic-portrait matting at a /// fixed 512x512. Returns 0 on failure. /// /// # Safety /// /// Called only by the JVM, with a valid `env` and a `weights` array it owns.-#[no_mangle]-pub extern "system" fn Java_com_vayunmathur_library_ml_MlNative_createModnet<'l>(-    mut env: EnvUnowned<'l>,-    _class: JClass<'l>,-    weights: JByteArray<'l>,-) -> jlong {-    env.with_env(|env| -> jni::errors::Result<jlong> {-        Ok(open(env, weights, graph::MODNET, "modnet"))-    })-    .resolve::<jni::errors::LogErrorAndDefault>()-}+Java_com_vayunmathur_library_ml_MlNative_createModnet -> jlong; (_class: JClass<'l>, weights: JByteArray<'l>) |env| {+    Ok(open(env, weights, graph::MODNET, "modnet"))+} }  fn open<'l>(env: &Env, weights: JByteArray<'l>, graph_id: u32, name: &str) -> jlong {     match build(env, weights, graph_id) {@@ -189,7 +150,7 @@ fn build<'l>(env: &Env, weights: JByteArray<'l>, graph_id: u32) -> Result<Handle     Ok(Handle { net: Net::new(shared, plan, &parsed, normalise)?, pixels: Vec::new() }) } -/// Run the network over `pixels` and return the mask as a `float[]`.+jni_fn! { /// Run the network over `pixels` and return the mask as a `float[]`. /// /// Returns null on failure or on a `0` handle, which the Kotlin wrapper turns into "no /// mask this frame" rather than an exception.@@ -198,64 +159,53 @@ fn build<'l>(env: &Env, weights: JByteArray<'l>, graph_id: u32) -> Result<Handle /// /// `handle` must be `0` or a value returned by one of the create functions and not yet /// destroyed.-#[no_mangle]-pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_segment<'l>(-    mut env: EnvUnowned<'l>,-    _class: JClass<'l>,-    handle: jlong,-    pixels: JIntArray<'l>,-    width: jint,-    height: jint,-) -> jfloatArray {-    env.with_env(|env| -> jni::errors::Result<jfloatArray> {-        let null = std::ptr::null_mut();-        if handle == 0 || width <= 0 || height <= 0 {+unsafe Java_com_vayunmathur_library_ml_MlNative_segment -> jfloatArray; (_class: JClass<'l>, handle: jlong, pixels: JIntArray<'l>, width: jint, height: jint) |env| {+    let null = std::ptr::null_mut();+    if handle == 0 || width <= 0 || height <= 0 {+        return Ok(null);+    }+    // SAFETY: the caller guarantees `handle` came from a create function and is live, and+    // the Kotlin side serialises `segment` against `destroy` with a lock held across the+    // whole call.+    let state = unsafe { &mut *(handle as *mut Handle) };++    let count = match env.get_array_length(&pixels) {+        Ok(n) if n >= 0 => n as usize,+        Ok(n) => {+            log(&format!("a pixel array of length {n}"));             return Ok(null);         }-        // SAFETY: the caller guarantees `handle` came from a create function and is live, and-        // the Kotlin side serialises `segment` against `destroy` with a lock held across the-        // whole call.-        let state = unsafe { &mut *(handle as *mut Handle) };--        let count = match env.get_array_length(&pixels) {-            Ok(n) if n >= 0 => n as usize,-            Ok(n) => {-                log(&format!("a pixel array of length {n}"));-                return Ok(null);-            }-            Err(e) => {-                log(&format!("cannot size the pixel array: {e}"));-                return Ok(null);-            }-        };-        if count != (width as usize) * (height as usize) {-            log(&format!("{count} pixels for a {width}x{height} bitmap"));+        Err(e) => {+            log(&format!("cannot size the pixel array: {e}"));             return Ok(null);         }-        state.pixels.resize(count, 0);-        if let Err(e) = env.get_int_array_region(&pixels, 0, &mut state.pixels) {-            log(&format!("cannot read the pixel array: {e}"));+    };+    if count != (width as usize) * (height as usize) {+        log(&format!("{count} pixels for a {width}x{height} bitmap"));+        return Ok(null);+    }+    state.pixels.resize(count, 0);+    if let Err(e) = env.get_int_array_region(&pixels, 0, &mut state.pixels) {+        log(&format!("cannot read the pixel array: {e}"));+        return Ok(null);+    }+    let mask = match state.net.infer(&state.pixels, width as u32, height as u32) {+        Ok(m) => m,+        Err(e) => {+            log(&format!("inference failed: {e}"));             return Ok(null);         }-        let mask = match state.net.infer(&state.pixels, width as u32, height as u32) {-            Ok(m) => m,-            Err(e) => {-                log(&format!("inference failed: {e}"));-                return Ok(null);-            }-        };-        Ok(match new_float_array(env, &mask) {-            Ok(array) => array,-            Err(e) => {-                log(&format!("cannot return the mask: {e}"));-                null-            }-        })+    };+    Ok(match new_float_array(env, &mask) {+        Ok(array) => array,+        Err(e) => {+            log(&format!("cannot return the mask: {e}"));+            null+        }     })-    .resolve::<jni::errors::LogErrorAndDefault>()-}+} } -/// Detect faces in `pixels` and return them flattened, fifteen floats each.+jni_fn! { /// Detect faces in `pixels` and return them flattened, fifteen floats each. /// /// The layout per face is `left, top, right, bottom, leftEyeX, leftEyeY, rightEyeX, /// rightEyeY, score, noseX, noseY, mouthLeftX, mouthLeftY, mouthRightX, mouthRightY`.@@ -274,44 +224,33 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_segment<' /// /// `handle` must be `0` or a value returned by /// [`Java_com_vayunmathur_library_ml_MlNative_createScrfd`] and not yet destroyed.-#[no_mangle]-pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_detectFaces<'l>(-    mut env: EnvUnowned<'l>,-    _class: JClass<'l>,-    handle: jlong,-    pixels: JIntArray<'l>,-    width: jint,-    height: jint,-) -> jfloatArray {-    env.with_env(|env| -> jni::errors::Result<jfloatArray> {-        let null = std::ptr::null_mut();-        if handle == 0 || width <= 0 || height <= 0 {-            return Ok(null);-        }-        // SAFETY: as `segment` — the caller guarantees the handle is live and serialises this-        // against `destroy`.-        let state = unsafe { &mut *(handle as *mut Handle) };+unsafe Java_com_vayunmathur_library_ml_MlNative_detectFaces -> jfloatArray; (_class: JClass<'l>, handle: jlong, pixels: JIntArray<'l>, width: jint, height: jint) |env| {+    let null = std::ptr::null_mut();+    if handle == 0 || width <= 0 || height <= 0 {+        return Ok(null);+    }+    // SAFETY: as `segment` — the caller guarantees the handle is live and serialises this+    // against `destroy`.+    let state = unsafe { &mut *(handle as *mut Handle) }; -        if let Err(e) = read_pixels(env, &pixels, width, height, &mut state.pixels) {-            log(&e);-            return Ok(null);-        }-        Ok(match detect(state, width as u32, height as u32) {-            Ok(flat) => match new_float_array(env, &flat) {-                Ok(array) => array,-                Err(e) => {-                    log(&format!("cannot return the detections: {e}"));-                    null-                }-            },+    if let Err(e) = read_pixels(env, &pixels, width, height, &mut state.pixels) {+        log(&e);+        return Ok(null);+    }+    Ok(match detect(state, width as u32, height as u32) {+        Ok(flat) => match new_float_array(env, &flat) {+            Ok(array) => array,             Err(e) => {-                log(&format!("face detection failed: {e}"));+                log(&format!("cannot return the detections: {e}"));                 null             }-        })+        },+        Err(e) => {+            log(&format!("face detection failed: {e}"));+            null+        }     })-    .resolve::<jni::errors::LogErrorAndDefault>()-}+} }  /// Letterbox, run, decode, suppress, and flatten. fn detect(state: &mut Handle, width: u32, height: u32) -> Result<Vec<f32>, String> {@@ -378,7 +317,7 @@ pub(crate) fn ocr_use_guard() -> std::sync::RwLockReadGuard<'static, ()> {     OCR_LIFETIME.read().unwrap_or_else(|poisoned| poisoned.into_inner()) } -/// `TextRecognizer`'s constructor: detection at a fixed square, recognition at a fixed+jni_fn! { /// `TextRecognizer`'s constructor: detection at a fixed square, recognition at a fixed /// width, and the character table. Returns 0 on failure, having logged why. /// /// Three assets rather than one because they are three files in the APK, and the dictionary@@ -388,25 +327,15 @@ pub(crate) fn ocr_use_guard() -> std::sync::RwLockReadGuard<'static, ()> { /// # Safety /// /// Called only by the JVM, with a valid `env` and arrays it owns.-#[no_mangle]-pub extern "system" fn Java_com_vayunmathur_library_ml_MlNative_createPpocr<'l>(-    mut env: EnvUnowned<'l>,-    _class: JClass<'l>,-    detection: JByteArray<'l>,-    recognition: JByteArray<'l>,-    keys: JString<'l>,-) -> jlong {-    env.with_env(|env| -> jni::errors::Result<jlong> {-        Ok(match build_ocr(env, detection, recognition, keys) {-            Ok(handle) => Box::into_raw(Box::new(handle)) as jlong,-            Err(e) => {-                log(&format!("ppocr is unavailable: {e}"));-                0-            }-        })+Java_com_vayunmathur_library_ml_MlNative_createPpocr -> jlong; (_class: JClass<'l>, detection: JByteArray<'l>, recognition: JByteArray<'l>, keys: JString<'l>) |env| {+    Ok(match build_ocr(env, detection, recognition, keys) {+        Ok(handle) => Box::into_raw(Box::new(handle)) as jlong,+        Err(e) => {+            log(&format!("ppocr is unavailable: {e}"));+            0+        }     })-    .resolve::<jni::errors::LogErrorAndDefault>()-}+} }  fn build_ocr<'l>(     env: &Env,
library/ml/src/main/rust/src/bridge_part1.rs
diff --git a/library/ml/src/main/rust/src/bridge_part1.rs b/library/ml/src/main/rust/src/bridge_part1.rsindex c4a049aefd..3fdd4dead9 100644--- a/library/ml/src/main/rust/src/bridge_part1.rs+++ b/library/ml/src/main/rust/src/bridge_part1.rs@@ -102,7 +102,7 @@ fn encode(lines: &[Line]) -> String {     out } -/// Free both networks and the dictionary.+jni_direct! { /// Free both networks and the dictionary. /// /// Separate from [`Java_com_vayunmathur_library_ml_MlNative_destroy`] because the handle is /// a different type; passing one to the other is undefined.@@ -111,12 +111,7 @@ fn encode(lines: &[Line]) -> String { /// /// `handle` must be `0` or a value returned by /// [`Java_com_vayunmathur_library_ml_MlNative_createPpocr`], and must not be used again.-#[no_mangle]-pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_destroyOcr<'l>(-    _env: EnvUnowned<'l>,-    _class: JClass<'l>,-    handle: jlong,-) {+unsafe Java_com_vayunmathur_library_ml_MlNative_destroyOcr; (_class: JClass<'l>, handle: jlong) {     if handle == 0 {         return;     }@@ -129,7 +124,7 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_destroyOc     // SAFETY: the caller guarantees this came from `createPpocr` and has not been     // destroyed; the guard guarantees no pass is using it concurrently.     drop(unsafe { Box::from_raw(handle as *mut OcrHandle) });-}+} }  /// A small deterministic-per-seed generator, seeded from the clock per utterance. ///
library/ml/src/main/rust/src/bridge_part10.rs
diff --git a/library/ml/src/main/rust/src/bridge_part10.rs b/library/ml/src/main/rust/src/bridge_part10.rsindex a7ea33e7f5..a7c9ba0b96 100644--- a/library/ml/src/main/rust/src/bridge_part10.rs+++ b/library/ml/src/main/rust/src/bridge_part10.rs@@ -117,7 +117,7 @@ impl madlad_post::Nets for MadladNets<'_> {     } } -/// Bring up MADLAD from its one `.maml` and its Unigram tokenizer table. Returns 0 on failure.+jni_fn! { /// Bring up MADLAD from its one `.maml` and its Unigram tokenizer table. Returns 0 on failure. /// /// # Safety ///@@ -126,16 +126,7 @@ impl madlad_post::Nets for MadladNets<'_> { /// `createMadlad` mirrors `createNllb`, and `translateMadlad` takes a **target tag** /// (`<2en>`) rather than two flores ids — the protocol difference vs NLLB. Agreed with /// app-eng (team `nllb-translate`).-#[no_mangle]-pub extern "system" fn Java_com_vayunmathur_library_ml_MlNative_createMadlad<'l>(-    mut env: EnvUnowned<'l>,-    _class: JClass<'l>,-    fd: jint,-    offset: jlong,-    length: jlong,-    tokenizer: JByteArray<'l>,-) -> jlong {-    env.with_env(|env| -> jni::errors::Result<jlong> {+Java_com_vayunmathur_library_ml_MlNative_createMadlad -> jlong; (_class: JClass<'l>, fd: jint, offset: jlong, length: jlong, tokenizer: JByteArray<'l>) |env| {         // The descriptor first, and adopted into an owning `File` before anything else may fail: the         // caller detached it, so a path that returns without wrapping it leaks it for the life of the         // process. Every check below the adoption is therefore free to fail; nothing above it is.@@ -153,9 +144,7 @@ pub extern "system" fn Java_com_vayunmathur_library_ml_MlNative_createMadlad<'l>                 0             }         })-    })-    .resolve::<jni::errors::LogErrorAndDefault>()-}+    } }  fn build_madlad<'l>(     env: &Env,@@ -195,7 +184,7 @@ fn build_madlad<'l>(     Ok(MadladHandle { net, weights, tokenizer }) } -/// Translate [`text`] into the language `tag` names (e.g. `"<2en>"`), or null on failure.+jni_fn! { /// Translate [`text`] into the language `tag` names (e.g. `"<2en>"`), or null on failure. /// /// `text` must already have double spaces collapsed (HF's T5 normaliser; the Unigram model /// itself is the identity). The tag is validated against the table — an unknown tag is refused@@ -208,15 +197,7 @@ fn build_madlad<'l>( /// # Safety /// /// `handle` must be a non-zero value from `createMadlad` that has not been destroyed.-#[no_mangle]-pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_translateMadlad<'l>(-    mut env: EnvUnowned<'l>,-    _class: JClass<'l>,-    handle: jlong,-    text: JString<'l>,-    tag: JString<'l>,-) -> jstring {-    env.with_env(|env| -> jni::errors::Result<jstring> {+unsafe Java_com_vayunmathur_library_ml_MlNative_translateMadlad -> jstring; (_class: JClass<'l>, handle: jlong, text: JString<'l>, tag: JString<'l>) |env| {         if handle == 0 {             return Ok(std::ptr::null_mut());         }@@ -240,9 +221,7 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_translate                 std::ptr::null_mut()             }         })-    })-    .resolve::<jni::errors::LogErrorAndDefault>()-}+    } }  fn run_madlad(handle: &mut MadladHandle, text: &str, tag: &str) -> Result<String, String> {     // Cloned so the table can borrow it while the nets borrow the handle mutably.@@ -252,7 +231,9 @@ fn run_madlad(handle: &mut MadladHandle, text: &str, tag: &str) -> Result<String     madlad_post::translate(&mut nets, &table, tag, text) } -/// Free MADLAD's net, its open weights file and its tokenizer table.+// SAFETY: the caller guarantees this handle came from `createMadlad` and has not been+// destroyed. `Net`'s Drop waits for the device to go idle before freeing.+jni_destroy! { /// Free MADLAD's net, its open weights file and its tokenizer table. /// /// Exactly once per non-zero handle from `createMadlad`. When it is the last user of the shared /// `VkDevice`, the device goes away with it.@@ -260,19 +241,7 @@ fn run_madlad(handle: &mut MadladHandle, text: &str, tag: &str) -> Result<String /// # Safety /// /// `handle` must be a non-zero value from `createMadlad`, and must not be used again.-#[no_mangle]-pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_destroyMadlad<'l>(-    _env: EnvUnowned<'l>,-    _class: JClass<'l>,-    handle: jlong,-) {-    if handle == 0 {-        return;-    }-    // SAFETY: the caller guarantees this handle came from `createMadlad` and has not been-    // destroyed. `Net`'s Drop waits for the device to go idle before freeing.-    drop(unsafe { Box::from_raw(handle as *mut MadladHandle) });-}+unsafe Java_com_vayunmathur_library_ml_MlNative_destroyMadlad; (_class: JClass<'l>, handle: jlong): MadladHandle }  /// Recogniser batch sizes, largest first. A request's strips go through the largest that fits, /// then smaller ones, then the single-line net, so a 10-line page is two submits rather than ten
library/ml/src/main/rust/src/bridge_part11.rs
diff --git a/library/ml/src/main/rust/src/bridge_part11.rs b/library/ml/src/main/rust/src/bridge_part11.rsindex d98f81b02b..7e521943ee 100644--- a/library/ml/src/main/rust/src/bridge_part11.rs+++ b/library/ml/src/main/rust/src/bridge_part11.rs@@ -85,30 +85,13 @@ fn argmax(logits: &[f32]) -> u32 {     best.1 } -/// Bring up Gemma 4 from its two `.maml`s and its tokenizer table. Returns 0 on failure.+// `budget` is the bytes of KV cache this device will spend. See `gemma4::tier_for`.+jni_fn! { /// Bring up Gemma 4 from its two `.maml`s and its tokenizer table. Returns 0 on failure. /// /// # Safety /// /// Called only by the JVM, with a valid `env`, arrays it owns, and descriptors nothing else holds.-#[no_mangle]-#[allow(clippy::too_many_arguments)]-pub extern "system" fn Java_com_vayunmathur_library_ml_MlNative_createGemma4<'l>(-    mut env: EnvUnowned<'l>,-    _class: JClass<'l>,-    text_fd: jint,-    text_offset: jlong,-    text_length: jlong,-    embed_fd: jint,-    embed_offset: jlong,-    embed_length: jlong,-    head_fd: jint,-    head_offset: jlong,-    head_length: jlong,-    tokenizer: JByteArray<'l>,-    // Bytes of KV cache this device will spend. See `gemma4::tier_for`.-    budget: jlong,-) -> jlong {-    env.with_env(|env| -> jni::errors::Result<jlong> {+#[allow(clippy::too_many_arguments)] Java_com_vayunmathur_library_ml_MlNative_createGemma4 -> jlong; (_class: JClass<'l>, text_fd: jint, text_offset: jlong, text_length: jlong, embed_fd: jint, embed_offset: jlong, embed_length: jlong, head_fd: jint, head_offset: jlong, head_length: jlong, tokenizer: JByteArray<'l>, budget: jlong) |env| {         // Both descriptors are adopted before anything may fail. The caller detached them, so a path         // that returns without wrapping one leaks it for the life of the process - and there are         // three here (the head is optional), so the usual single-`fd` shape is not enough.@@ -155,9 +138,7 @@ pub extern "system" fn Java_com_vayunmathur_library_ml_MlNative_createGemma4<'l>                 0             }         })-    })-    .resolve::<jni::errors::LogErrorAndDefault>()-}+    } }  /// The last `createGemma4` failure, for Kotlin to tell a missing or truncated file apart from a /// device or Vulkan failure (#901's undifferentiated "failed to load").@@ -177,17 +158,12 @@ fn set_gemma4_error(message: Option<String>) {     } } -/// The last `createGemma4` failure message, or null on success. Consumes the stored message.+jni_fn! { /// The last `createGemma4` failure message, or null on success. Consumes the stored message. /// /// # Safety /// /// Called only by the JVM.-#[no_mangle]-pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_lastGemma4Error<'l>(-    mut env: EnvUnowned<'l>,-    _class: JClass<'l>,-) -> jstring {-    env.with_env(|env| -> jni::errors::Result<jstring> {+unsafe Java_com_vayunmathur_library_ml_MlNative_lastGemma4Error -> jstring; (_class: JClass<'l>) |env| {         let message = gemma4_error_slot()             .lock()             .map(|mut slot| slot.take())@@ -199,9 +175,7 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_lastGemma             },             None => std::ptr::null_mut(),         })-    })-    .resolve::<jni::errors::LogErrorAndDefault>()-}+    } }  #[allow(clippy::too_many_arguments)] fn build_gemma4<'l>(@@ -315,7 +289,7 @@ fn build_gemma4<'l>(     }) } -/// Encode text to token ids, matching HuggingFace's `tokenizers` for this vocabulary.+jni_fn! { /// Encode text to token ids, matching HuggingFace's `tokenizers` for this vocabulary. /// /// `specials` are matched literally and never merged into - the chat markers a template inserts. /// Passing them from Kotlin rather than hardcoding them here is deliberate: which markers a@@ -325,15 +299,7 @@ fn build_gemma4<'l>( /// # Safety /// /// Called only by the JVM, with a live handle from `createGemma4`.-#[no_mangle]-pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_encodeGemma4<'l>(-    mut env: EnvUnowned<'l>,-    _class: JClass<'l>,-    handle: jlong,-    text: JString<'l>,-    specials: JObjectArray<'l>,-) -> jintArray {-    env.with_env(|env| -> jni::errors::Result<jintArray> {+unsafe Java_com_vayunmathur_library_ml_MlNative_encodeGemma4 -> jintArray; (_class: JClass<'l>, handle: jlong, text: JString<'l>, specials: JObjectArray<'l>) |env| {         if handle == 0 {             return Ok(std::ptr::null_mut());         }@@ -356,6 +322,4 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_encodeGem                 std::ptr::null_mut()             }         })-    })-    .resolve::<jni::errors::LogErrorAndDefault>()-}+    } }
library/ml/src/main/rust/src/bridge_part2.rs
diff --git a/library/ml/src/main/rust/src/bridge_part2.rs b/library/ml/src/main/rust/src/bridge_part2.rsindex 4a84a00fac..cfcbe5acd6 100644--- a/library/ml/src/main/rust/src/bridge_part2.rs+++ b/library/ml/src/main/rust/src/bridge_part2.rs@@ -1,4 +1,4 @@-/// `SupertonicSynthesizer`'s constructor. Returns 0 on failure, having logged why.+jni_fn! { /// `SupertonicSynthesizer`'s constructor. Returns 0 on failure, having logged why. /// /// Six assets, in two kinds. The four `.maml` plans arrive as **file descriptors** with a byte /// range each; the codepoint table and one voice's style file arrive as byte arrays, because they@@ -31,17 +31,7 @@ /// # Safety /// /// Called only by the JVM, with a valid `env`, arrays it owns, and descriptors nothing else holds.-#[no_mangle]-pub extern "system" fn Java_com_vayunmathur_library_ml_MlNative_createSupertonic<'l>(-    mut env: EnvUnowned<'l>,-    _class: JClass<'l>,-    fds: JIntArray<'l>,-    offsets: JLongArray<'l>,-    lengths: JLongArray<'l>,-    indexer: JByteArray<'l>,-    style: JByteArray<'l>,-) -> jlong {-    env.with_env(|env| -> jni::errors::Result<jlong> {+Java_com_vayunmathur_library_ml_MlNative_createSupertonic -> jlong; (_class: JClass<'l>, fds: JIntArray<'l>, offsets: JLongArray<'l>, lengths: JLongArray<'l>, indexer: JByteArray<'l>, style: JByteArray<'l>) |env| {         Ok(match build_supertonic(env, &fds, &offsets, &lengths, &indexer, &style) {             Ok(handle) => Box::into_raw(Box::new(handle)) as jlong,             Err(e) => {@@ -49,9 +39,7 @@ pub extern "system" fn Java_com_vayunmathur_library_ml_MlNative_createSupertonic                 0             }         })-    })-    .resolve::<jni::errors::LogErrorAndDefault>()-}+    } }  /// The four `.maml` graphs, in the order `createSupertonic`'s parallel arrays list them. const SUPERTONIC_GRAPHS: [u32; 4] =@@ -180,20 +168,13 @@ fn build_supertonic<'l>(     Ok(handle) } -/// Point an existing handle at another voice. Returns false on failure, having logged why.+jni_fn! { /// Point an existing handle at another voice. Returns false on failure, having logged why. /// /// # Safety /// /// `handle` must be `0` or a live value from /// [`Java_com_vayunmathur_library_ml_MlNative_createSupertonic`].-#[no_mangle]-pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_setSupertonicVoice<'l>(-    mut env: EnvUnowned<'l>,-    _class: JClass<'l>,-    handle: jlong,-    style: JByteArray<'l>,-) -> bool {-    env.with_env(|env| -> jni::errors::Result<bool> {+unsafe Java_com_vayunmathur_library_ml_MlNative_setSupertonicVoice -> bool; (_class: JClass<'l>, handle: jlong, style: JByteArray<'l>) |env| {         if handle == 0 {             return Ok(false);         }@@ -214,30 +195,18 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_setSupert                 false             }         })-    })-    .resolve::<jni::errors::LogErrorAndDefault>()-}+} } -/// Free the four networks and everything beside them.+// SAFETY: the caller guarantees this came from `createSupertonic` and has not been destroyed.+jni_destroy! { /// Free the four networks and everything beside them. /// /// # Safety /// /// `handle` must be `0` or a value from /// [`Java_com_vayunmathur_library_ml_MlNative_createSupertonic`], and must not be used again.-#[no_mangle]-pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_destroySupertonic<'l>(-    _env: EnvUnowned<'l>,-    _class: JClass<'l>,-    handle: jlong,-) {-    if handle == 0 {-        return;-    }-    // SAFETY: the caller guarantees this came from `createSupertonic` and has not been destroyed.-    drop(unsafe { Box::from_raw(handle as *mut SupertonicHandle) });-}+unsafe Java_com_vayunmathur_library_ml_MlNative_destroySupertonic; (_class: JClass<'l>, handle: jlong): SupertonicHandle } -/// Synthesise `text` in `language` and return the waveform, or null on failure.+jni_fn! { /// Synthesise `text` in `language` and return the waveform, or null on failure. /// /// `text` must already be **NFKD**-decomposed. That is the Kotlin side's job, through /// `java.text.Normalizer`, because the model has no precomposed accents and doing the@@ -255,15 +224,7 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_destroySu /// /// `handle` must be `0` or a live value from /// [`Java_com_vayunmathur_library_ml_MlNative_createSupertonic`].-#[no_mangle]-pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_synthesizeSupertonic<'l>(-    mut env: EnvUnowned<'l>,-    _class: JClass<'l>,-    handle: jlong,-    text: JString<'l>,-    language: JString<'l>,-) -> jfloatArray {-    env.with_env(|env| -> jni::errors::Result<jfloatArray> {+unsafe Java_com_vayunmathur_library_ml_MlNative_synthesizeSupertonic -> jfloatArray; (_class: JClass<'l>, handle: jlong, text: JString<'l>, language: JString<'l>) |env| {         let null = std::ptr::null_mut();         if handle == 0 {             return Ok(null);@@ -298,9 +259,7 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_synthesiz                 null             }         })-    })-    .resolve::<jni::errors::LogErrorAndDefault>()-}+    } }  /// The whole pipeline for one utterance. fn speak_supertonic(@@ -368,17 +327,12 @@ fn read_pixels<'l>(         .map_err(|e| format!("cannot read the pixel array: {e}")) } -/// The mask's width, so Kotlin does not have to know either network's input size.+jni_direct! { /// The mask's width, so Kotlin does not have to know either network's input size. /// /// # Safety /// /// As [`Java_com_vayunmathur_library_ml_MlNative_segment`].-#[no_mangle]-pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_maskWidth<'l>(-    _env: EnvUnowned<'l>,-    _class: JClass<'l>,-    handle: jlong,-) -> jint {+unsafe Java_com_vayunmathur_library_ml_MlNative_maskWidth -> jint; (_class: JClass<'l>, handle: jlong) {     if handle == 0 {         return 0;     }@@ -388,19 +342,14 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_maskWidth         .output_size()         .map(|(width, _)| width as jint)         .unwrap_or(0)-}+} } -/// The mask's height.+jni_direct! { /// The mask's height. /// /// # Safety /// /// As [`Java_com_vayunmathur_library_ml_MlNative_segment`].-#[no_mangle]-pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_maskHeight<'l>(-    _env: EnvUnowned<'l>,-    _class: JClass<'l>,-    handle: jlong,-) -> jint {+unsafe Java_com_vayunmathur_library_ml_MlNative_maskHeight -> jint; (_class: JClass<'l>, handle: jlong) {     if handle == 0 {         return 0;     }@@ -410,9 +359,11 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_maskHeigh         .output_size()         .map(|(_, height)| height as jint)         .unwrap_or(0)-}+} } -/// Free everything the handle owns, waiting for the GPU to go idle first.+// SAFETY: the caller guarantees this handle came from a create function and has not+// been destroyed. `Net`'s Drop waits for the device to go idle before freeing.+jni_destroy! { /// Free everything the handle owns, waiting for the GPU to go idle first. /// /// Must be called exactly once per non-zero handle. When it is the last segmenter, the /// shared `VkDevice` goes away with it.@@ -421,19 +372,7 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_maskHeigh /// /// As [`Java_com_vayunmathur_library_ml_MlNative_segment`], and the handle must not be /// used again afterwards.-#[no_mangle]-pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_destroy<'l>(-    _env: EnvUnowned<'l>,-    _class: JClass<'l>,-    handle: jlong,-) {-    if handle == 0 {-        return;-    }-    // SAFETY: the caller guarantees this handle came from a create function and has not-    // been destroyed. `Net`'s Drop waits for the device to go idle before freeing.-    drop(unsafe { Box::from_raw(handle as *mut Handle) });-}+unsafe Java_com_vayunmathur_library_ml_MlNative_destroy; (_class: JClass<'l>, handle: jlong): Handle }  /// `[rows, columns]` to `[columns, rows]`. ///
library/ml/src/main/rust/src/bridge_part3.rs
diff --git a/library/ml/src/main/rust/src/bridge_part3.rs b/library/ml/src/main/rust/src/bridge_part3.rsindex 243d81e21d..300b37fcdc 100644--- a/library/ml/src/main/rust/src/bridge_part3.rs+++ b/library/ml/src/main/rust/src/bridge_part3.rs@@ -96,7 +96,7 @@ impl translate::Nets for NllbNets<'_> {     } } -/// Bring up NLLB from its one `.maml` and its tokenizer table. Returns 0 on failure.+jni_fn! { /// Bring up NLLB from its one `.maml` and its tokenizer table. Returns 0 on failure. /// /// # Safety ///@@ -104,16 +104,7 @@ impl translate::Nets for NllbNets<'_> { /// /// `createNllb` mirrors the old `createSmall100`, and `translateNllb` takes **both** a source and a /// target token — the protocol flip vs small100. Agreed with app-eng (team `nllb-translate`).-#[no_mangle]-pub extern "system" fn Java_com_vayunmathur_library_ml_MlNative_createNllb<'l>(-    mut env: EnvUnowned<'l>,-    _class: JClass<'l>,-    fd: jint,-    offset: jlong,-    length: jlong,-    tokenizer: JByteArray<'l>,-) -> jlong {-    env.with_env(|env| -> jni::errors::Result<jlong> {+Java_com_vayunmathur_library_ml_MlNative_createNllb -> jlong; (_class: JClass<'l>, fd: jint, offset: jlong, length: jlong, tokenizer: JByteArray<'l>) |env| {         // The descriptor first, and adopted into an owning `File` before anything else may fail: the         // caller detached it, so a path that returns without wrapping it leaks it for the life of the         // process. Every check below the adoption is therefore free to fail; nothing above it is.@@ -131,9 +122,7 @@ pub extern "system" fn Java_com_vayunmathur_library_ml_MlNative_createNllb<'l>(                 0             }         })-    })-    .resolve::<jni::errors::LogErrorAndDefault>()-}+    } }  /// The source length translation nets record their decode step at during load. Any length /// warms the kernels; this one also sizes the arena for typical sentences, so the first@@ -178,7 +167,7 @@ fn build_nllb<'l>(     Ok(NllbHandle { net, weights, tokenizer }) } -/// Translate [`text`] from the language `source_token` names into the language `target_token`+jni_fn! { /// Translate [`text`] from the language `source_token` names into the language `target_token` /// names, or null on failure. /// /// `text` must already be NFKC — `java.text.Normalizer.normalize(text, Form.NFKC)`. The model's@@ -193,16 +182,7 @@ fn build_nllb<'l>( /// # Safety /// /// `handle` must be a non-zero value from `createNllb` that has not been destroyed.-#[no_mangle]-pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_translateNllb<'l>(-    mut env: EnvUnowned<'l>,-    _class: JClass<'l>,-    handle: jlong,-    text: JString<'l>,-    source_token: jint,-    target_token: jint,-) -> jstring {-    env.with_env(|env| -> jni::errors::Result<jstring> {+unsafe Java_com_vayunmathur_library_ml_MlNative_translateNllb -> jstring; (_class: JClass<'l>, handle: jlong, text: JString<'l>, source_token: jint, target_token: jint) |env| {         if handle == 0 {             return Ok(std::ptr::null_mut());         }@@ -226,9 +206,7 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_translate                 std::ptr::null_mut()             }         })-    })-    .resolve::<jni::errors::LogErrorAndDefault>()-}+    } }  fn run_nllb(     handle: &mut NllbHandle,@@ -247,7 +225,9 @@ fn run_nllb(     translate::translate(&mut nets, &table, source, target, text) } -/// Free NLLB's net, its open weights file and its tokenizer table.+// SAFETY: the caller guarantees this handle came from `createNllb` and has not been+// destroyed. `Net`'s Drop waits for the device to go idle before freeing.+jni_destroy! { /// Free NLLB's net, its open weights file and its tokenizer table. /// /// Exactly once per non-zero handle from `createNllb`. When it is the last user of the shared /// `VkDevice`, the device goes away with it.@@ -255,19 +235,7 @@ fn run_nllb( /// # Safety /// /// `handle` must be a non-zero value from `createNllb`, and must not be used again.-#[no_mangle]-pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_destroyNllb<'l>(-    _env: EnvUnowned<'l>,-    _class: JClass<'l>,-    handle: jlong,-) {-    if handle == 0 {-        return;-    }-    // SAFETY: the caller guarantees this handle came from `createNllb` and has not been-    // destroyed. `Net`'s Drop waits for the device to go idle before freeing.-    drop(unsafe { Box::from_raw(handle as *mut NllbHandle) });-}+unsafe Java_com_vayunmathur_library_ml_MlNative_destroyNllb; (_class: JClass<'l>, handle: jlong): NllbHandle }  /// TinyCLIP, as `:photos` holds it. Handed to Kotlin as an opaque `jlong`. ///@@ -307,7 +275,7 @@ fn tinyclip_column(out: &[f32], at: usize, len: usize) -> Result<Vec<f32>, Strin         .collect() } -/// Bring up TinyCLIP from its one `.maml`. Returns 0 on failure.+jni_direct! { /// Bring up TinyCLIP from its one `.maml`. Returns 0 on failure. /// /// The descriptor is an `AssetFileDescriptor`'s, so it carries an offset and a length: the file is /// a *range of the APK* rather than a file of its own, which is also why the asset has to be stored@@ -316,14 +284,7 @@ fn tinyclip_column(out: &[f32], at: usize, len: usize) -> Result<Vec<f32>, Strin /// # Safety /// /// Called only by the JVM, with a descriptor nothing else holds.-#[no_mangle]-pub extern "system" fn Java_com_vayunmathur_library_ml_MlNative_createTinyclip<'l>(-    _env: EnvUnowned<'l>,-    _class: JClass<'l>,-    fd: jint,-    offset: jlong,-    length: jlong,-) -> jlong {+Java_com_vayunmathur_library_ml_MlNative_createTinyclip -> jlong; (_class: JClass<'l>, fd: jint, offset: jlong, length: jlong) {     // The descriptor first, and adopted into an owning `File` before anything else may fail, as     // the old `createSmall100` did: the caller detached it, so a path that returns without wrapping     // it@@ -342,7 +303,7 @@ pub extern "system" fn Java_com_vayunmathur_library_ml_MlNative_createTinyclip<'             0         }     }-}+} }  fn build_tinyclip(file: File, offset: jlong, length: jlong) -> Result<TinyclipHandle, String> {     let (at, len) = match (u64::try_from(offset), u64::try_from(length)) {@@ -365,7 +326,7 @@ fn build_tinyclip(file: File, offset: jlong, length: jlong) -> Result<TinyclipHa     Ok(TinyclipHandle { net, weights }) } -/// The 512-d image embedding for `pixels`, or null on failure.+jni_fn! { /// The 512-d image embedding for `pixels`, or null on failure. /// /// `pixels` is `[3, 224, 224]` already normalised by CLIP's mean and standard deviation — the /// resize, the centre crop and the normalisation are `ClipEmbedder.preprocess`'s, because they are@@ -377,14 +338,7 @@ fn build_tinyclip(file: File, offset: jlong, length: jlong) -> Result<TinyclipHa /// # Safety /// /// `handle` must be a non-zero value from `createTinyclip` that has not been destroyed.-#[no_mangle]-pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_tinyclipImage<'l>(-    mut env: EnvUnowned<'l>,-    _class: JClass<'l>,-    handle: jlong,-    pixels: JFloatArray<'l>,-) -> jfloatArray {-    env.with_env(|env| -> jni::errors::Result<jfloatArray> {+unsafe Java_com_vayunmathur_library_ml_MlNative_tinyclipImage -> jfloatArray; (_class: JClass<'l>, handle: jlong, pixels: JFloatArray<'l>) |env| {         let null = std::ptr::null_mut();         if handle == 0 {             return Ok(null);@@ -403,9 +357,7 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_tinyclipI                 null             }         })-    })-    .resolve::<jni::errors::LogErrorAndDefault>()-}+    } }  fn run_tinyclip_image(handle: &mut TinyclipHandle, pixels: &[f32]) -> Result<Vec<f32>, String> {     let side = tinyclip::IMAGE_SIZE as usize;
library/ml/src/main/rust/src/bridge_part4.rs
diff --git a/library/ml/src/main/rust/src/bridge_part4.rs b/library/ml/src/main/rust/src/bridge_part4.rsindex 12d8603fc9..9df2943173 100644--- a/library/ml/src/main/rust/src/bridge_part4.rs+++ b/library/ml/src/main/rust/src/bridge_part4.rs@@ -1,4 +1,4 @@-/// The 512-d text embedding for `ids`, or null on failure.+jni_fn! { /// The 512-d text embedding for `ids`, or null on failure. /// /// `ids` must be the query's tokens **up to and including `<|endoftext|>`**, with the tokenizer's /// padding trimmed off. CLIP pools at the end-of-text position, so the caller's trim decides which@@ -10,14 +10,7 @@ /// # Safety /// /// `handle` must be a non-zero value from `createTinyclip` that has not been destroyed.-#[no_mangle]-pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_tinyclipText<'l>(-    mut env: EnvUnowned<'l>,-    _class: JClass<'l>,-    handle: jlong,-    ids: JIntArray<'l>,-) -> jfloatArray {-    env.with_env(|env| -> jni::errors::Result<jfloatArray> {+unsafe Java_com_vayunmathur_library_ml_MlNative_tinyclipText -> jfloatArray; (_class: JClass<'l>, handle: jlong, ids: JIntArray<'l>) |env| {         let null = std::ptr::null_mut();         if handle == 0 {             return Ok(null);@@ -35,9 +28,7 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_tinyclipT                 null             }         })-    })-    .resolve::<jni::errors::LogErrorAndDefault>()-}+    } }  fn run_tinyclip_text(handle: &mut TinyclipHandle, ids: &[i32]) -> Result<Vec<f32>, String> {     let tokens: Vec<u32> = ids@@ -54,7 +45,9 @@ fn run_tinyclip_text(handle: &mut TinyclipHandle, ids: &[i32]) -> Result<Vec<f32     tinyclip_column(&out, tokens.len() - 1, tokens.len()) } -/// Free TinyCLIP's net and its open weights file.+// SAFETY: the caller guarantees this handle came from `createTinyclip` and has not been+// destroyed. `Net`'s Drop waits for the device to go idle before freeing.+jni_destroy! { /// Free TinyCLIP's net and its open weights file. /// /// Exactly once per non-zero handle from `createTinyclip`. When it is the last user of the shared /// `VkDevice`, the device goes away with it.@@ -62,19 +55,7 @@ fn run_tinyclip_text(handle: &mut TinyclipHandle, ids: &[i32]) -> Result<Vec<f32 /// # Safety /// /// `handle` must be a non-zero value from `createTinyclip`, and must not be used again.-#[no_mangle]-pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_destroyTinyclip<'l>(-    _env: EnvUnowned<'l>,-    _class: JClass<'l>,-    handle: jlong,-) {-    if handle == 0 {-        return;-    }-    // SAFETY: the caller guarantees this handle came from `createTinyclip` and has not been-    // destroyed. `Net`'s Drop waits for the device to go idle before freeing.-    drop(unsafe { Box::from_raw(handle as *mut TinyclipHandle) });-}+unsafe Java_com_vayunmathur_library_ml_MlNative_destroyTinyclip; (_class: JClass<'l>, handle: jlong): TinyclipHandle }  /// Maia3-5M, as `:games:chess` holds it. Handed to Kotlin as an opaque `jlong`. ///@@ -94,7 +75,7 @@ struct MaiaHandle {     weights: Streamed, } -/// Bring up Maia3 from its one bundled `.maml`. Returns 0 on failure.+jni_direct! { /// Bring up Maia3 from its one bundled `.maml`. Returns 0 on failure. /// /// The descriptor is an `AssetFileDescriptor`'s, so it carries an offset and a length: the /// file is a *range of the APK* rather than a file of its own, which is also why the asset@@ -103,14 +84,7 @@ struct MaiaHandle { /// # Safety /// /// Called only by the JVM, with a descriptor nothing else holds.-#[no_mangle]-pub extern "system" fn Java_com_vayunmathur_library_ml_MlNative_createMaia<'l>(-    _env: EnvUnowned<'l>,-    _class: JClass<'l>,-    fd: jint,-    offset: jlong,-    length: jlong,-) -> jlong {+Java_com_vayunmathur_library_ml_MlNative_createMaia -> jlong; (_class: JClass<'l>, fd: jint, offset: jlong, length: jlong) {     if fd < 0 {         log(&format!("maia is unavailable: descriptor {fd} is not open"));         return 0;@@ -125,7 +99,7 @@ pub extern "system" fn Java_com_vayunmathur_library_ml_MlNative_createMaia<'l>(             0         }     }-}+} }  fn build_maia(file: File, offset: jlong, length: jlong) -> Result<MaiaHandle, String> {     let (at, len) = match (u64::try_from(offset), u64::try_from(length)) {@@ -141,7 +115,7 @@ fn build_maia(file: File, offset: jlong, length: jlong) -> Result<MaiaHandle, St     Ok(MaiaHandle { net, weights }) } -/// The 4352 move logits for a board, or null on failure.+jni_fn! { /// The 4352 move logits for a board, or null on failure. /// /// `planes` is the 12 board planes as `12 * 64` floats, plane-major, square `rank * 8 + file` /// — **already mirrored and colour-swapped if black is to move**, because the model only ever@@ -155,16 +129,7 @@ fn build_maia(file: File, offset: jlong, length: jlong) -> Result<MaiaHandle, St /// # Safety /// /// `handle` must be a non-zero value from `createMaia` that has not been destroyed.-#[no_mangle]-pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_maiaLogits<'l>(-    mut env: EnvUnowned<'l>,-    _class: JClass<'l>,-    handle: jlong,-    planes: JFloatArray<'l>,-    self_elo: jint,-    oppo_elo: jint,-) -> jfloatArray {-    env.with_env(|env| -> jni::errors::Result<jfloatArray> {+unsafe Java_com_vayunmathur_library_ml_MlNative_maiaLogits -> jfloatArray; (_class: JClass<'l>, handle: jlong, planes: JFloatArray<'l>, self_elo: jint, oppo_elo: jint) |env| {         let null = std::ptr::null_mut();         if handle == 0 {             return Ok(null);@@ -183,9 +148,7 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_maiaLogit                 null             }         })-    })-    .resolve::<jni::errors::LogErrorAndDefault>()-}+    } }  fn run_maia(     handle: &mut MaiaHandle,@@ -203,7 +166,9 @@ fn run_maia(     crate::post::maia::logits(scores, promo) } -/// Free Maia3's net and close its weights file.+// SAFETY: the caller guarantees this handle came from `createMaia` and has not been+// destroyed. `Net`'s Drop waits for the device to go idle before freeing.+jni_destroy! { /// Free Maia3's net and close its weights file. /// /// Exactly once per non-zero handle from `createMaia`. When it is the last user of the shared /// `VkDevice`, the device goes away with it.@@ -211,19 +176,7 @@ fn run_maia( /// # Safety /// /// `handle` must be a non-zero value from `createMaia`, and must not be used again.-#[no_mangle]-pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_destroyMaia<'l>(-    _env: EnvUnowned<'l>,-    _class: JClass<'l>,-    handle: jlong,-) {-    if handle == 0 {-        return;-    }-    // SAFETY: the caller guarantees this handle came from `createMaia` and has not been-    // destroyed. `Net`'s Drop waits for the device to go idle before freeing.-    drop(unsafe { Box::from_raw(handle as *mut MaiaHandle) });-}+unsafe Java_com_vayunmathur_library_ml_MlNative_destroyMaia; (_class: JClass<'l>, handle: jlong): MaiaHandle }  /// The Now Playing audio fingerprinter and its log-mel front end, as `:nowplaying` holds it. ///@@ -253,7 +206,7 @@ struct NnfpHandle {     frontend: crate::microfrontend::Frontend, } -/// Bring up the fingerprinter from its one bundled `.maml`. Returns 0 on failure.+jni_direct! { /// Bring up the fingerprinter from its one bundled `.maml`. Returns 0 on failure. /// /// The descriptor is an `AssetFileDescriptor`'s, so it carries an offset and a length: the file /// is a *range of the APK* rather than a file of its own, which is also why the asset has to be@@ -262,14 +215,7 @@ struct NnfpHandle { /// # Safety /// /// Called only by the JVM, with a descriptor nothing else holds.-#[no_mangle]-pub extern "system" fn Java_com_vayunmathur_library_ml_MlNative_createNnfp<'l>(-    _env: EnvUnowned<'l>,-    _class: JClass<'l>,-    fd: jint,-    offset: jlong,-    length: jlong,-) -> jlong {+Java_com_vayunmathur_library_ml_MlNative_createNnfp -> jlong; (_class: JClass<'l>, fd: jint, offset: jlong, length: jlong) {     if fd < 0 {         log(&format!("nnfp is unavailable: descriptor {fd} is not open"));         return 0;@@ -284,7 +230,7 @@ pub extern "system" fn Java_com_vayunmathur_library_ml_MlNative_createNnfp<'l>(             0         }     }-}+} }  fn build_nnfp(file: File, offset: jlong, length: jlong) -> Result<NnfpHandle, String> {     let (at, len) = match (u64::try_from(offset), u64::try_from(length)) {@@ -303,7 +249,7 @@ fn build_nnfp(file: File, offset: jlong, length: jlong) -> Result<NnfpHandle, St     Ok(NnfpHandle { net, frontend }) } -/// The 64-value fingerprint for one window of audio, or null on failure.+jni_fn! { /// The 64-value fingerprint for one window of audio, or null on failure. /// /// `pcm` is exactly [`nnfp::WINDOW_SAMPLES`] mono 16-bit samples at 16 kHz — 415 ms, the /// network's receptive field. i16 rather than f32 because that is what `AudioRecord` produces@@ -317,14 +263,7 @@ fn build_nnfp(file: File, offset: jlong, length: jlong) -> Result<NnfpHandle, St /// # Safety /// /// `handle` must be a non-zero value from `createNnfp` that has not been destroyed.-#[no_mangle]-pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_nnfpEmbed<'l>(-    mut env: EnvUnowned<'l>,-    _class: JClass<'l>,-    handle: jlong,-    pcm: JShortArray<'l>,-) -> jfloatArray {-    env.with_env(|env| -> jni::errors::Result<jfloatArray> {+unsafe Java_com_vayunmathur_library_ml_MlNative_nnfpEmbed -> jfloatArray; (_class: JClass<'l>, handle: jlong, pcm: JShortArray<'l>) |env| {         let null = std::ptr::null_mut();         if handle == 0 {             return Ok(null);@@ -343,9 +282,7 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_nnfpEmbed                 null             }         })-    })-    .resolve::<jni::errors::LogErrorAndDefault>()-}+    } }  fn run_nnfp(handle: &mut NnfpHandle, pcm: &[i16]) -> Result<Vec<f32>, String> {     if pcm.len() != nnfp::WINDOW_SAMPLES {@@ -365,7 +302,9 @@ fn run_nnfp(handle: &mut NnfpHandle, pcm: &[i16]) -> Result<Vec<f32>, String> {     Ok(embedding.clone()) } -/// Free the fingerprinter's net.+// SAFETY: the caller guarantees this handle came from `createNnfp` and has not been+// destroyed. `Net`'s Drop waits for the device to go idle before freeing.+jni_destroy! { /// Free the fingerprinter's net. /// /// Exactly once per non-zero handle from `createNnfp`. When it is the last user of the shared /// `VkDevice`, the device goes away with it.@@ -373,31 +312,15 @@ fn run_nnfp(handle: &mut NnfpHandle, pcm: &[i16]) -> Result<Vec<f32>, String> { /// # Safety /// /// `handle` must be a non-zero value from `createNnfp`, and must not be used again.-#[no_mangle]-pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_destroyNnfp<'l>(-    _env: EnvUnowned<'l>,-    _class: JClass<'l>,-    handle: jlong,-) {-    if handle == 0 {-        return;-    }-    // SAFETY: the caller guarantees this handle came from `createNnfp` and has not been-    // destroyed. `Net`'s Drop waits for the device to go idle before freeing.-    drop(unsafe { Box::from_raw(handle as *mut NnfpHandle) });-}+unsafe Java_com_vayunmathur_library_ml_MlNative_destroyNnfp; (_class: JClass<'l>, handle: jlong): NnfpHandle } -/// Now Playing's always-on music gate. Handed to Kotlin as an opaque `jlong`.+jni_direct! { /// Now Playing's always-on music gate. Handed to Kotlin as an opaque `jlong`. /// /// Unlike every other handle in this file there is no device, no plan and no asset: the /// gate is 8,200 int8 parameters embedded in the binary and it runs on the CPU. See /// [`crate::gate`] for why. Construction cannot fail for want of hardware, only if the /// front end rejects its configuration, so a zero return here means a genuine bug.-#[no_mangle]-pub extern "system" fn Java_com_vayunmathur_library_ml_MlNative_createMusicGate<'l>(-    _env: EnvUnowned<'l>,-    _class: JClass<'l>,-) -> jlong {+Java_com_vayunmathur_library_ml_MlNative_createMusicGate -> jlong; (_class: JClass<'l>) {     match crate::gate::MusicGate::new() {         Ok(handle) => Box::into_raw(Box::new(handle)) as jlong,         Err(e) => {@@ -405,9 +328,9 @@ pub extern "system" fn Java_com_vayunmathur_library_ml_MlNative_createMusicGate<             0         }     }-}+} } -/// Feed PCM and get one music probability per completed 10 ms hop, oldest first.+jni_fn! { /// Feed PCM and get one music probability per completed 10 ms hop, oldest first. /// /// Returns an empty array rather than null when a call completes no hop or the gate is /// still warming up — both are ordinary, and null is reserved for a real failure. The gate@@ -416,15 +339,7 @@ pub extern "system" fn Java_com_vayunmathur_library_ml_MlNative_createMusicGate< /// # Safety /// /// `handle` must be a live value from `createMusicGate`, and Kotlin must serialise calls.-#[no_mangle]-pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_musicGatePush<'l>(-    mut env: EnvUnowned<'l>,-    _class: JClass<'l>,-    handle: jlong,-    pcm: JShortArray<'l>,-    count: jint,-) -> jfloatArray {-    env.with_env(|env| -> jni::errors::Result<jfloatArray> {+unsafe Java_com_vayunmathur_library_ml_MlNative_musicGatePush -> jfloatArray; (_class: JClass<'l>, handle: jlong, pcm: JShortArray<'l>, count: jint) |env| {         let null = std::ptr::null_mut();         if handle == 0 {             return Ok(null);@@ -447,6 +362,4 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_musicGate                 null             }         })-    })-    .resolve::<jni::errors::LogErrorAndDefault>()-}+    } }
library/ml/src/main/rust/src/bridge_part5.rs
diff --git a/library/ml/src/main/rust/src/bridge_part5.rs b/library/ml/src/main/rust/src/bridge_part5.rsindex 0a0dbcf29c..71f5d93abf 100644--- a/library/ml/src/main/rust/src/bridge_part5.rs+++ b/library/ml/src/main/rust/src/bridge_part5.rs@@ -1,39 +1,24 @@-/// Discard the front end's partial frame and the trunk's 230 ms of context.+jni_direct! { /// Discard the front end's partial frame and the trunk's 230 ms of context. /// /// # Safety /// /// `handle` must be a live value from `createMusicGate`.-#[no_mangle]-pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_resetMusicGate<'l>(-    _env: EnvUnowned<'l>,-    _class: JClass<'l>,-    handle: jlong,-) {+unsafe Java_com_vayunmathur_library_ml_MlNative_resetMusicGate; (_class: JClass<'l>, handle: jlong) {     if handle == 0 {         return;     }     // SAFETY: the caller guarantees the handle came from `createMusicGate` and is live.     unsafe { &mut *(handle as *mut crate::gate::MusicGate) }.reset();-}+} } -/// Free the gate. Idempotent on the Kotlin side, which nulls its handle first.+// SAFETY: the caller guarantees this handle came from `createMusicGate` and has not+// been destroyed.+jni_destroy! { /// Free the gate. Idempotent on the Kotlin side, which nulls its handle first. /// /// # Safety /// /// `handle` must be a non-zero value from `createMusicGate`, and must not be used again.-#[no_mangle]-pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_destroyMusicGate<'l>(-    _env: EnvUnowned<'l>,-    _class: JClass<'l>,-    handle: jlong,-) {-    if handle == 0 {-        return;-    }-    // SAFETY: the caller guarantees this handle came from `createMusicGate` and has not-    // been destroyed.-    drop(unsafe { Box::from_raw(handle as *mut crate::gate::MusicGate) });-}+unsafe Java_com_vayunmathur_library_ml_MlNative_destroyMusicGate; (_class: JClass<'l>, handle: jlong): crate::gate::MusicGate }  /// whisper-base, as `:speech` holds it. Handed to Kotlin as an opaque `jlong`. ///@@ -127,7 +112,7 @@ impl whisper_post::Nets for WhisperNets<'_> {     } } -/// Bring up whisper-base from its one `.maml` and the ids read from `generation_config.json`.+jni_fn! { /// Bring up whisper-base from its one `.maml` and the ids read from `generation_config.json`. /// /// Returns 0 on failure. The descriptor is an `AssetFileDescriptor`'s, so it carries an offset and a /// length: the file is a range of the APK rather than a file of its own.@@ -135,19 +120,7 @@ impl whisper_post::Nets for WhisperNets<'_> { /// # Safety /// /// Called only by the JVM, with a valid `env`, arrays it owns, and a descriptor nothing else holds.-#[no_mangle]-pub extern "system" fn Java_com_vayunmathur_library_ml_MlNative_createWhisper<'l>(-    mut env: EnvUnowned<'l>,-    _class: JClass<'l>,-    fd: jint,-    offset: jlong,-    length: jlong,-    special: JIntArray<'l>,-    languages: JIntArray<'l>,-    suppress: JIntArray<'l>,-    suppress_at_begin: JIntArray<'l>,-) -> jlong {-    env.with_env(|env| -> jni::errors::Result<jlong> {+Java_com_vayunmathur_library_ml_MlNative_createWhisper -> jlong; (_class: JClass<'l>, fd: jint, offset: jlong, length: jlong, special: JIntArray<'l>, languages: JIntArray<'l>, suppress: JIntArray<'l>, suppress_at_begin: JIntArray<'l>) |env| {         // The descriptor first, and adopted into an owning `File` before anything else may fail: the         // caller detached it, so a path that returns without wrapping it leaks it for the life of the         // process.@@ -175,9 +148,7 @@ pub extern "system" fn Java_com_vayunmathur_library_ml_MlNative_createWhisper<'l                 0             }         })-    })-    .resolve::<jni::errors::LogErrorAndDefault>()-}+    } }  /// The five scalars `createWhisper` takes in its `special` array, in order. ///@@ -244,7 +215,7 @@ fn build_whisper<'l>(     Ok(WhisperHandle { net, weights, decoding }) } -/// Transcribe one log-mel window into token ids, or null on failure.+jni_fn! { /// Transcribe one log-mel window into token ids, or null on failure. /// /// `mel` is `[80 * 3000]` row-major, from `WhisperFeatures.logMel`. `language` is a `<|xx|>` token /// the caller resolved from a code, or **negative** to detect.@@ -255,15 +226,7 @@ fn build_whisper<'l>( /// # Safety /// /// `handle` must be a non-zero value from `createWhisper` that has not been destroyed.-#[no_mangle]-pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_transcribeWhisper<'l>(-    mut env: EnvUnowned<'l>,-    _class: JClass<'l>,-    handle: jlong,-    mel: JFloatArray<'l>,-    language: jint,-) -> jintArray {-    env.with_env(|env| -> jni::errors::Result<jintArray> {+unsafe Java_com_vayunmathur_library_ml_MlNative_transcribeWhisper -> jintArray; (_class: JClass<'l>, handle: jlong, mel: JFloatArray<'l>, language: jint) |env| {         let null = std::ptr::null_mut();         if handle == 0 {             return Ok(null);@@ -283,9 +246,7 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_transcrib                 null             }         })-    })-    .resolve::<jni::errors::LogErrorAndDefault>()-}+    } }  fn run_whisper(     handle: &mut WhisperHandle,@@ -302,7 +263,9 @@ fn run_whisper(         .collect() } -/// Free whisper's net, its open weights file and both caches.+// SAFETY: the caller guarantees this handle came from `createWhisper` and has not been+// destroyed. `Net`'s Drop waits for the device to go idle before freeing.+jni_destroy! { /// Free whisper's net, its open weights file and both caches. /// /// Exactly once per non-zero handle from `createWhisper`. When it is the last user of the shared /// `VkDevice`, the device goes away with it.@@ -310,19 +273,7 @@ fn run_whisper( /// # Safety /// /// `handle` must be a non-zero value from `createWhisper`, and must not be used again.-#[no_mangle]-pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_destroyWhisper<'l>(-    _env: EnvUnowned<'l>,-    _class: JClass<'l>,-    handle: jlong,-) {-    if handle == 0 {-        return;-    }-    // SAFETY: the caller guarantees this handle came from `createWhisper` and has not been-    // destroyed. `Net`'s Drop waits for the device to go idle before freeing.-    drop(unsafe { Box::from_raw(handle as *mut WhisperHandle) });-}+unsafe Java_com_vayunmathur_library_ml_MlNative_destroyWhisper; (_class: JClass<'l>, handle: jlong): WhisperHandle }  fn new_int_array(env: &mut Env, values: &[i32]) -> Result<jintArray, String> {     let array: JIntArray = env
library/ml/src/main/rust/src/bridge_part7.rs
diff --git a/library/ml/src/main/rust/src/bridge_part7.rs b/library/ml/src/main/rust/src/bridge_part7.rsindex 9b93aab8ef..36b9f79175 100644--- a/library/ml/src/main/rust/src/bridge_part7.rs+++ b/library/ml/src/main/rust/src/bridge_part7.rs@@ -21,19 +21,12 @@ fn encode_gemma4<'l>(     Ok(table.encode_with_specials(text, &borrowed).into_iter().map(|id| id as i32).collect()) } -/// Text for a run of token ids, fusing byte pieces back into characters.+jni_fn! { /// Text for a run of token ids, fusing byte pieces back into characters. /// /// # Safety /// /// Called only by the JVM, with a live handle from `createGemma4`.-#[no_mangle]-pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_decodeGemma4<'l>(-    mut env: EnvUnowned<'l>,-    _class: JClass<'l>,-    handle: jlong,-    tokens: JIntArray<'l>,-) -> jstring {-    env.with_env(|env| -> jni::errors::Result<jstring> {+unsafe Java_com_vayunmathur_library_ml_MlNative_decodeGemma4 -> jstring; (_class: JClass<'l>, handle: jlong, tokens: JIntArray<'l>) |env| {         if handle == 0 {             return Ok(std::ptr::null_mut());         }@@ -59,11 +52,9 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_decodeGem                 std::ptr::null_mut()             }         })-    })-    .resolve::<jni::errors::LogErrorAndDefault>()-}+    } } -/// Feed tokens into the cache without generating. Returns the new position, or -1.+jni_fn! { /// Feed tokens into the cache without generating. Returns the new position, or -1. /// /// The prompt path: every token but the last only fills the KV cache, so its logits are computed /// and thrown away. Doing that here rather than one JNI call at a time keeps a 500-token prompt@@ -72,14 +63,7 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_decodeGem /// # Safety /// /// Called only by the JVM, with a live handle from `createGemma4`.-#[no_mangle]-pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_pushGemma4<'l>(-    mut env: EnvUnowned<'l>,-    _class: JClass<'l>,-    handle: jlong,-    tokens: JIntArray<'l>,-) -> jint {-    env.with_env(|env| -> jni::errors::Result<jint> {+unsafe Java_com_vayunmathur_library_ml_MlNative_pushGemma4 -> jint; (_class: JClass<'l>, handle: jlong, tokens: JIntArray<'l>) |env| {         if handle == 0 {             return Ok(-1);         }@@ -104,22 +88,14 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_pushGemma                 -1             }         })-    })-    .resolve::<jni::errors::LogErrorAndDefault>()-}+    } } -/// Feed one token and return the next, greedily. -1 on failure.+jni_direct! { /// Feed one token and return the next, greedily. -1 on failure. /// /// # Safety /// /// Called only by the JVM, with a live handle from `createGemma4`.-#[no_mangle]-pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_stepGemma4<'l>(-    _env: EnvUnowned<'l>,-    _class: JClass<'l>,-    handle: jlong,-    token: jint,-) -> jint {+unsafe Java_com_vayunmathur_library_ml_MlNative_stepGemma4 -> jint; (_class: JClass<'l>, handle: jlong, token: jint) {     if handle == 0 {         return -1;     }@@ -139,9 +115,9 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_stepGemma             -1         }     }-}+} } -/// Feed one token and return its 262,144 logits for Kotlin-side sampling. Null on failure.+jni_fn! { /// Feed one token and return its 262,144 logits for Kotlin-side sampling. Null on failure. /// /// The same step [`Java_com_vayunmathur_library_ml_MlNative_stepGemma4`] runs - one token through /// all thirty-five layers plus the tied head on the host - but the logits cross the boundary@@ -152,14 +128,7 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_stepGemma /// # Safety /// /// Called only by the JVM, with a live handle from `createGemma4`.-#[no_mangle]-pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_logitsGemma4<'l>(-    mut env: EnvUnowned<'l>,-    _class: JClass<'l>,-    handle: jlong,-    token: jint,-) -> jfloatArray {-    env.with_env(|env| -> jni::errors::Result<jfloatArray> {+unsafe Java_com_vayunmathur_library_ml_MlNative_logitsGemma4 -> jfloatArray; (_class: JClass<'l>, handle: jlong, token: jint) |env| {         if handle == 0 {             return Ok(std::ptr::null_mut());         }@@ -187,28 +156,21 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_logitsGem                 std::ptr::null_mut()             }         })-    })-    .resolve::<jni::errors::LogErrorAndDefault>()-}+    } } -/// Positions currently in the KV cache.+jni_direct! { /// Positions currently in the KV cache. /// /// # Safety /// /// Called only by the JVM, with a live handle from `createGemma4`.-#[no_mangle]-pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_positionGemma4<'l>(-    _env: EnvUnowned<'l>,-    _class: JClass<'l>,-    handle: jlong,-) -> jint {+unsafe Java_com_vayunmathur_library_ml_MlNative_positionGemma4 -> jint; (_class: JClass<'l>, handle: jlong) {     if handle == 0 {         return -1;     }     // SAFETY: the caller guarantees the handle came from `createGemma4` and is still live.     let handle = unsafe { &*(handle as *const Gemma4Handle) };     jint::try_from(handle.fed()).unwrap_or(-1)-}+} }  /// A weight source for the scaling probe: every tensor at offset zero. ///@@ -251,7 +213,7 @@ impl crate::weights::Blob for ProbeBlob {     } } -/// Compare a storage-buffer read against a texel-buffer read of the same bytes. Returns -1.+jni_direct! { /// Compare a storage-buffer read against a texel-buffer read of the same bytes. Returns -1. /// /// The standing hypothesis for the remaining 3x, and the last one left: every buffer path on this /// device sits near 5 GB/s, LiteRT needs about 15 to reach its published 89 ms a token, and its@@ -261,11 +223,7 @@ impl crate::weights::Blob for ProbeBlob { /// # Safety /// /// Called only by the JVM.-#[no_mangle]-pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_imageProbeGemma4<'l>(-    _env: EnvUnowned<'l>,-    _class: JClass<'l>,-) -> jint {+unsafe Java_com_vayunmathur_library_ml_MlNative_imageProbeGemma4 -> jint; (_class: JClass<'l>) {     let Ok(context) = context::shared() else {         return -1;     };@@ -279,9 +237,9 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_imageProb         Err(why) => log(&format!("gemma4 read path probe failed: {why}")),     }     -1-}+} } -/// Log how a gemv's achieved bandwidth varies with the size of the dispatch. Returns -1 always.+jni_direct! { /// Log how a gemv's achieved bandwidth varies with the size of the dispatch. Returns -1 always. /// /// # The question this answers ///@@ -293,11 +251,7 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_imageProb /// # Safety /// /// Called only by the JVM.-#[no_mangle]-pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_scalingGemma4<'l>(-    _env: EnvUnowned<'l>,-    _class: JClass<'l>,-) -> jint {+unsafe Java_com_vayunmathur_library_ml_MlNative_scalingGemma4 -> jint; (_class: JClass<'l>) {     let Ok(context) = context::shared() else {         return -1;     };@@ -312,7 +266,7 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_scalingGe         }     }     -1-}+} }  /// Time one int4 gemv, returning its weight bytes and the rate reached. fn probe_gemv(@@ -357,7 +311,7 @@ fn probe_gemv(     Ok((weight_bytes, weight_bytes as f64 / best)) } -/// Log what this GPU can do that the shaders are not yet using. Returns -1 always.+jni_direct! { /// Log what this GPU can do that the shaders are not yet using. Returns -1 always. /// /// # Why bother ///@@ -372,11 +326,7 @@ fn probe_gemv( /// # Safety /// /// Called only by the JVM.-#[no_mangle]-pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_capabilitiesGemma4<'l>(-    _env: EnvUnowned<'l>,-    _class: JClass<'l>,-) -> jint {+unsafe Java_com_vayunmathur_library_ml_MlNative_capabilitiesGemma4 -> jint; (_class: JClass<'l>) {     let Ok(context) = context::shared() else {         return -1;     };@@ -426,9 +376,9 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_capabilit             .contains(ash::vk::SubgroupFeatureFlags::ARITHMETIC)     ));     -1-}+} } -/// Time one decode pass and one head-free pass, and log both. Returns -1 always.+jni_direct! { /// Time one decode pass and one head-free pass, and log both. Returns -1 always. /// /// # What this settles ///@@ -445,12 +395,7 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_capabilit /// # Safety /// /// Called only by the JVM, with a live handle from `createGemma4`.-#[no_mangle]-pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_benchmarkGemma4<'l>(-    _env: EnvUnowned<'l>,-    _class: JClass<'l>,-    handle: jlong,-) -> jint {+unsafe Java_com_vayunmathur_library_ml_MlNative_benchmarkGemma4 -> jint; (_class: JClass<'l>, handle: jlong) {     if handle == 0 {         return -1;     }@@ -492,4 +437,4 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_benchmark     handle.position = 0;     handle.pending.clear();     -1-}+} }
library/ml/src/main/rust/src/bridge_part8.rs
diff --git a/library/ml/src/main/rust/src/bridge_part8.rs b/library/ml/src/main/rust/src/bridge_part8.rsindex 9808c5840e..8fa1c240f3 100644--- a/library/ml/src/main/rust/src/bridge_part8.rs+++ b/library/ml/src/main/rust/src/bridge_part8.rs@@ -1,4 +1,4 @@-/// Load a baked prefix cache, so the fixed prompt is never prefilled on device. Returns the+jni_fn! { /// Load a baked prefix cache, so the fixed prompt is never prefilled on device. Returns the /// positions loaded, or -1. /// /// # What this saves@@ -15,15 +15,7 @@ /// # Safety /// /// Called only by the JVM, with a live handle from `createGemma4`.-#[no_mangle]-pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_loadPrefixGemma4<'l>(-    mut env: EnvUnowned<'l>,-    _class: JClass<'l>,-    handle: jlong,-    positions: jint,-    cache: JByteArray<'l>,-) -> jint {-    env.with_env(|env| -> jni::errors::Result<jint> {+unsafe Java_com_vayunmathur_library_ml_MlNative_loadPrefixGemma4 -> jint; (_class: JClass<'l>, handle: jlong, positions: jint, cache: JByteArray<'l>) |env| {         if handle == 0 {             return Ok(-1);         }@@ -61,30 +53,23 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_loadPrefi                 -1             }         })-    })-    .resolve::<jni::errors::LogErrorAndDefault>()-}+    } } -/// Positions the cache currently holds, or -1.+jni_direct! { /// Positions the cache currently holds, or -1. /// /// # Safety /// /// Called only by the JVM, with a live handle from `createGemma4`.-#[no_mangle]-pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_capacityGemma4<'l>(-    _env: EnvUnowned<'l>,-    _class: JClass<'l>,-    handle: jlong,-) -> jint {+unsafe Java_com_vayunmathur_library_ml_MlNative_capacityGemma4 -> jint; (_class: JClass<'l>, handle: jlong) {     if handle == 0 {         return -1;     }     // SAFETY: the caller guarantees the handle came from `createGemma4` and is still live.     let handle = unsafe { &*(handle as *const Gemma4Handle) };     jint::try_from(handle.context).unwrap_or(-1)-}+} } -/// Grow the cache so `needed` positions fit. Returns the new capacity, or -1.+jni_direct! { /// Grow the cache so `needed` positions fit. Returns the new capacity, or -1. /// /// **The cache is emptied**: a bigger arena is a different allocation and nothing is copied /// across, so the caller must feed its whole prompt again afterwards. Returning the capacity@@ -94,13 +79,7 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_capacityG /// # Safety /// /// Called only by the JVM, with a live handle from `createGemma4`.-#[no_mangle]-pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_growGemma4<'l>(-    _env: EnvUnowned<'l>,-    _class: JClass<'l>,-    handle: jlong,-    needed: jint,-) -> jint {+unsafe Java_com_vayunmathur_library_ml_MlNative_growGemma4 -> jint; (_class: JClass<'l>, handle: jlong, needed: jint) {     if handle == 0 {         return -1;     }@@ -116,9 +95,9 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_growGemma             -1         }     }-}+} } -/// Rewind the cache to `position`, keeping everything before it. Returns the new position, or -1.+jni_direct! { /// Rewind the cache to `position`, keeping everything before it. Returns the new position, or -1. /// /// # The point of this ///@@ -140,13 +119,7 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_growGemma /// # Safety /// /// Called only by the JVM, with a live handle from `createGemma4`.-#[no_mangle]-pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_seekGemma4<'l>(-    _env: EnvUnowned<'l>,-    _class: JClass<'l>,-    handle: jlong,-    position: jint,-) -> jint {+unsafe Java_com_vayunmathur_library_ml_MlNative_seekGemma4 -> jint; (_class: JClass<'l>, handle: jlong, position: jint) {     if handle == 0 {         return -1;     }@@ -170,9 +143,9 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_seekGemma             -1         }     }-}+} } -/// Start a new conversation on the same handle.+jni_direct! { /// Start a new conversation on the same handle. /// /// Only the position is reset. Attention reads `[window_start, prefix]`, so cache rows past the /// new prefix are never read again and overwriting them lazily costs nothing - clearing them@@ -181,12 +154,7 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_seekGemma /// # Safety /// /// Called only by the JVM, with a live handle from `createGemma4`.-#[no_mangle]-pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_resetGemma4<'l>(-    _env: EnvUnowned<'l>,-    _class: JClass<'l>,-    handle: jlong,-) {+unsafe Java_com_vayunmathur_library_ml_MlNative_resetGemma4; (_class: JClass<'l>, handle: jlong) {     if handle == 0 {         return;     }@@ -194,27 +162,17 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_resetGemm     let handle = unsafe { &mut *(handle as *mut Gemma4Handle) };     handle.position = 0;     handle.pending.clear();-}+} } -/// Release the handle. Idempotent from Kotlin's side, which zeroes its field first.+// SAFETY: the caller guarantees this runs once, after every other call on the handle.+jni_destroy! { /// Release the handle. Idempotent from Kotlin's side, which zeroes its field first. /// /// # Safety /// /// Called only by the JVM, once, with a handle from `createGemma4` that nothing else is using.-#[no_mangle]-pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_destroyGemma4<'l>(-    _env: EnvUnowned<'l>,-    _class: JClass<'l>,-    handle: jlong,-) {-    if handle == 0 {-        return;-    }-    // SAFETY: the caller guarantees this runs once, after every other call on the handle.-    drop(unsafe { Box::from_raw(handle as *mut Gemma4Handle) });-}+unsafe Java_com_vayunmathur_library_ml_MlNative_destroyGemma4; (_class: JClass<'l>, handle: jlong): Gemma4Handle } -/// Feed soft tokens - an encoder's output - into the decoder's cache.+jni_fn! { /// Feed soft tokens - an encoder's output - into the decoder's cache. /// /// `embeddings` is `n * 1536` floats, one row per soft token, and it advances the position by `n`. /// Returns the number fed, or -1. The logits are discarded: a soft token is never the last thing@@ -227,14 +185,7 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_destroyGe /// # Safety /// /// Called only by the JVM, with a live handle from `createGemma4`.-#[no_mangle]-pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_pushSoftGemma4<'l>(-    mut env: EnvUnowned<'l>,-    _class: JClass<'l>,-    handle: jlong,-    embeddings: JFloatArray<'l>,-) -> jint {-    env.with_env(|env| -> jni::errors::Result<jint> {+unsafe Java_com_vayunmathur_library_ml_MlNative_pushSoftGemma4 -> jint; (_class: JClass<'l>, handle: jlong, embeddings: JFloatArray<'l>) |env| {         if handle == 0 {             return Ok(-1);         }@@ -254,9 +205,7 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_pushSoftG                 -1             }         })-    })-    .resolve::<jni::errors::LogErrorAndDefault>()-}+    } }  /// Gemma 4's vision tower, which is its own `.maml` and its own graph id. ///@@ -272,19 +221,12 @@ fn gemma4_vision_plan(offsets: &Offsets, mode: gemma4_vision::Mode) -> Result<Pl     gemma4_vision::build(offsets, mode) } -/// Bring up the vision tower from its `.maml`. Returns 0 on failure, having logged why.+jni_direct! { /// Bring up the vision tower from its `.maml`. Returns 0 on failure, having logged why. /// /// # Safety /// /// Called only by the JVM, with a descriptor the caller detached and nothing else holds.-#[no_mangle]-pub extern "system" fn Java_com_vayunmathur_library_ml_MlNative_createGemma4Vision<'l>(-    _env: EnvUnowned<'l>,-    _class: JClass<'l>,-    fd: jint,-    offset: jlong,-    length: jlong,-) -> jlong {+Java_com_vayunmathur_library_ml_MlNative_createGemma4Vision -> jlong; (_class: JClass<'l>, fd: jint, offset: jlong, length: jlong) {     if fd < 0 {         log(&format!("the gemma4 vision tower is unavailable: descriptor {fd} is not open"));         return 0;@@ -299,7 +241,7 @@ pub extern "system" fn Java_com_vayunmathur_library_ml_MlNative_createGemma4Visi             0         }     }-}+} }  fn build_gemma4_vision(file: File, offset: jlong, length: jlong) -> Result<Gemma4VisionHandle, String> {     let (at, len) = match (u64::try_from(offset), u64::try_from(length)) {@@ -324,7 +266,7 @@ fn build_gemma4_vision(file: File, offset: jlong, length: jlong) -> Result<Gemma     Ok(Gemma4VisionHandle { net, weights }) } -/// The pixel size an image of `width x height` must be resized to, as `[width, height]`.+jni_fn! { /// The pixel size an image of `width x height` must be resized to, as `[width, height]`. /// /// Kotlin does the resize - it is bitmap work the platform does better, as it is for TinyCLIP - /// but it cannot choose the size, because the target is the reference preprocessor's@@ -336,15 +278,7 @@ fn build_gemma4_vision(file: File, offset: jlong, length: jlong) -> Result<Gemma /// # Safety /// /// Called only by the JVM.-#[no_mangle]-pub extern "system" fn Java_com_vayunmathur_library_ml_MlNative_gemma4VisionSize<'l>(-    mut env: EnvUnowned<'l>,-    _class: JClass<'l>,-    width: jint,-    height: jint,-    soft_tokens: jint,-) -> jintArray {-    env.with_env(|env| -> jni::errors::Result<jintArray> {+Java_com_vayunmathur_library_ml_MlNative_gemma4VisionSize -> jintArray; (_class: JClass<'l>, width: jint, height: jint, soft_tokens: jint) |env| {         let null = std::ptr::null_mut();         let sized = u32::try_from(width)             .ok()@@ -369,11 +303,9 @@ pub extern "system" fn Java_com_vayunmathur_library_ml_MlNative_gemma4VisionSize                 null             }         })-    })-    .resolve::<jni::errors::LogErrorAndDefault>()-}+} } -/// Encode one image into soft tokens: `[n, 1536]` flattened, or null.+jni_fn! { /// Encode one image into soft tokens: `[n, 1536]` flattened, or null. /// /// `pixels` is ARGB_8888 at exactly the size [`Java_com_vayunmathur_library_ml_MlNative_gemma4VisionSize`] /// asked for. The result goes straight to `pushSoftGemma4`, unscaled - the reference scatters the@@ -384,16 +316,7 @@ pub extern "system" fn Java_com_vayunmathur_library_ml_MlNative_gemma4VisionSize /// # Safety /// /// Called only by the JVM, with a live handle from `createGemma4Vision`.-#[no_mangle]-pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_encodeImageGemma4<'l>(-    mut env: EnvUnowned<'l>,-    _class: JClass<'l>,-    handle: jlong,-    pixels: JIntArray<'l>,-    width: jint,-    height: jint,-) -> jfloatArray {-    env.with_env(|env| -> jni::errors::Result<jfloatArray> {+unsafe Java_com_vayunmathur_library_ml_MlNative_encodeImageGemma4 -> jfloatArray; (_class: JClass<'l>, handle: jlong, pixels: JIntArray<'l>, width: jint, height: jint) |env| {         let null = std::ptr::null_mut();         if handle == 0 {             return Ok(null);@@ -410,9 +333,7 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_encodeIma                 null             }         })-    })-    .resolve::<jni::errors::LogErrorAndDefault>()-}+    } }  fn run_gemma4_vision(     handle: &mut Gemma4VisionHandle,@@ -444,20 +365,10 @@ fn run_gemma4_vision(     Ok(transpose(&features, width, tokens)) } -/// Release the vision tower.+// SAFETY: the caller guarantees this runs once, after every other call on the handle.+jni_destroy! { /// Release the vision tower. /// /// # Safety /// /// Called only by the JVM, once, with a handle from `createGemma4Vision` that nothing else uses.-#[no_mangle]-pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_destroyGemma4Vision<'l>(-    _env: EnvUnowned<'l>,-    _class: JClass<'l>,-    handle: jlong,-) {-    if handle == 0 {-        return;-    }-    // SAFETY: the caller guarantees this runs once, after every other call on the handle.-    drop(unsafe { Box::from_raw(handle as *mut Gemma4VisionHandle) });-}+unsafe Java_com_vayunmathur_library_ml_MlNative_destroyGemma4Vision; (_class: JClass<'l>, handle: jlong): Gemma4VisionHandle }
library/ml/src/main/rust/src/bridge_part9.rs
diff --git a/library/ml/src/main/rust/src/bridge_part9.rs b/library/ml/src/main/rust/src/bridge_part9.rsindex 666385763b..25c87eca65 100644--- a/library/ml/src/main/rust/src/bridge_part9.rs+++ b/library/ml/src/main/rust/src/bridge_part9.rs@@ -21,19 +21,12 @@ fn gemma4_audio_plan(offsets: &Offsets, mode: gemma4_audio::Mode) -> Result<Plan     gemma4_audio::build(offsets, mode) } -/// Bring up the audio tower from its `.maml`. Returns 0 on failure, having logged why.+jni_direct! { /// Bring up the audio tower from its `.maml`. Returns 0 on failure, having logged why. /// /// # Safety /// /// Called only by the JVM, with a descriptor the caller detached and nothing else holds.-#[no_mangle]-pub extern "system" fn Java_com_vayunmathur_library_ml_MlNative_createGemma4Audio<'l>(-    _env: EnvUnowned<'l>,-    _class: JClass<'l>,-    fd: jint,-    offset: jlong,-    length: jlong,-) -> jlong {+Java_com_vayunmathur_library_ml_MlNative_createGemma4Audio -> jlong; (_class: JClass<'l>, fd: jint, offset: jlong, length: jlong) {     if fd < 0 {         log(&format!("the gemma4 audio tower is unavailable: descriptor {fd} is not open"));         return 0;@@ -48,7 +41,7 @@ pub extern "system" fn Java_com_vayunmathur_library_ml_MlNative_createGemma4Audi             0         }     }-}+} }  fn build_gemma4_audio(file: File, offset: jlong, length: jlong) -> Result<Gemma4AudioHandle, String> {     let (at, len) = match (u64::try_from(offset), u64::try_from(length)) {@@ -74,7 +67,7 @@ fn build_gemma4_audio(file: File, offset: jlong, length: jlong) -> Result<Gemma4     Ok(Gemma4AudioHandle { net, mel: crate::logmel::LogMel::new() }) } -/// Encode one clip into soft tokens: `[n, 1536]` flattened, or null.+jni_fn! { /// Encode one clip into soft tokens: `[n, 1536]` flattened, or null. /// /// `samples` is **16 kHz mono** in roughly `-1.0..1.0`. The front end has no gain of its own, so /// the scale it arrives in is the scale the tower sees. The result goes straight to@@ -91,14 +84,7 @@ fn build_gemma4_audio(file: File, offset: jlong, length: jlong) -> Result<Gemma4 /// # Safety /// /// Called only by the JVM, with a live handle from `createGemma4Audio`.-#[no_mangle]-pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_encodeAudioGemma4<'l>(-    mut env: EnvUnowned<'l>,-    _class: JClass<'l>,-    handle: jlong,-    samples: JFloatArray<'l>,-) -> jfloatArray {-    env.with_env(|env| -> jni::errors::Result<jfloatArray> {+unsafe Java_com_vayunmathur_library_ml_MlNative_encodeAudioGemma4 -> jfloatArray; (_class: JClass<'l>, handle: jlong, samples: JFloatArray<'l>) |env| {         let null = std::ptr::null_mut();         if handle == 0 {             return Ok(null);@@ -115,9 +101,7 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_encodeAud                 null             }         })-    })-    .resolve::<jni::errors::LogErrorAndDefault>()-}+    } }  fn run_gemma4_audio(handle: &mut Gemma4AudioHandle, waveform: &[f32]) -> Result<Vec<f32>, String> {     // The cap is the reference's, and it is what bounds the arena at 49.8 MiB. Truncating here@@ -158,25 +142,15 @@ fn run_gemma4_audio(handle: &mut Gemma4AudioHandle, waveform: &[f32]) -> Result<     Ok(transpose(&features, width, rows)) } -/// Release the audio tower.+// SAFETY: the caller guarantees this runs once, after every other call on the handle.+jni_destroy! { /// Release the audio tower. /// /// # Safety /// /// Called only by the JVM, once, with a handle from `createGemma4Audio` that nothing else uses.-#[no_mangle]-pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_destroyGemma4Audio<'l>(-    _env: EnvUnowned<'l>,-    _class: JClass<'l>,-    handle: jlong,-) {-    if handle == 0 {-        return;-    }-    // SAFETY: the caller guarantees this runs once, after every other call on the handle.-    drop(unsafe { Box::from_raw(handle as *mut Gemma4AudioHandle) });-}+unsafe Java_com_vayunmathur_library_ml_MlNative_destroyGemma4Audio; (_class: JClass<'l>, handle: jlong): Gemma4AudioHandle } -/// Feed one token and return its `k` most likely next tokens as `[logit, id, logit, id, ...]`,+jni_fn! { /// Feed one token and return its `k` most likely next tokens as `[logit, id, logit, id, ...]`, /// highest first, ties by lower id - the order a stable descending sort of the full logits gives, /// so sampling from these candidates draws exactly what sampling the full array would whenever /// `top_k <= k`. 2k floats cross the boundary instead of 262,144. Null on failure.@@ -184,15 +158,7 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_destroyGe /// # Safety /// /// Called only by the JVM, with a live handle from `createGemma4`.-#[no_mangle]-pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_topKGemma4<'l>(-    mut env: EnvUnowned<'l>,-    _class: JClass<'l>,-    handle: jlong,-    token: jint,-    k: jint,-) -> jfloatArray {-    env.with_env(|env| -> jni::errors::Result<jfloatArray> {+unsafe Java_com_vayunmathur_library_ml_MlNative_topKGemma4 -> jfloatArray; (_class: JClass<'l>, handle: jlong, token: jint, k: jint) |env| {         if handle == 0 {             return Ok(std::ptr::null_mut());         }@@ -220,9 +186,7 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_topKGemma                 std::ptr::null_mut()             }         })-    })-    .resolve::<jni::errors::LogErrorAndDefault>()-}+    } }  /// The `k` largest of `logits` as `[logit, id, ...]`, descending, ties by lower id. Ids are below /// 2^24, so they are exact as `f32`.