Refactor JNI - #3107
Refactor JNI#3107
Conversation
📝 WalkthroughWalkthroughThis PR adds defensive null-pointer validation to constructors across nine native-backed Java classes, expands the OfflineTts API with getNumSpeakers() and Consumer-based callback overloads alongside OfflineTtsCallback variants, and unifies the JNI callback mechanism in offline-tts.cc from multiple specialized handlers to a single CallCallback pattern. Changes
Sequence DiagramsequenceDiagram
participant JavaApp as Java Application
participant OfflineTts as OfflineTts.java
participant Adapter as Callback Adapter
participant JNI as offline-tts.cc
participant Native as Native TTS Engine
JavaApp->>OfflineTts: generateWithCallback(text, Consumer)
OfflineTts->>Adapter: convert Consumer to OfflineTtsCallback
OfflineTts->>JNI: generateWithCallbackImpl(ptr, text, callback)
JNI->>Native: Generate(config, callback_wrapper)
loop For each audio chunk
Native->>JNI: callback_wrapper(audio_chunk)
JNI->>Adapter: convert float[] chunk
Adapter->>OfflineTts: invoke(float[])
OfflineTts->>JavaApp: Consumer.accept(float[])
JavaApp-->>OfflineTts: (implicit return 1)
OfflineTts-->>JNI: return 1 (continue)
end
JNI-->>OfflineTts: GeneratedAudio
OfflineTts-->>JavaApp: return GeneratedAudio
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Suggested labels
Poem
🚥 Pre-merge checks | ✅ 1 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (1 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Summary of ChangesHello @csukuangfj, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request significantly refactors the Java Native Interface (JNI) layer for the Highlights
Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here. You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension. Footnotes
|
There was a problem hiding this comment.
Code Review
This pull request significantly refactors the JNI layer, especially for TTS callbacks, enhancing type safety by replacing generic Object types with the specific OfflineTtsCallback functional interface. This is a great improvement. The introduction of Consumer<float[]> overloads provides a more convenient API for users. Additionally, the widespread addition of null checks in constructors after native object creation improves the robustness of the code. The changes are well-implemented and raise the quality of the API. I have a few minor suggestions to further improve code readability and maintainability.
| ) { | ||
|
|
||
| return generateWithCallback(text, sid, 1.0f, consumer); |
| std::function<int32_t(const float *, int32_t, float)> callback_wrapper = | ||
| [env, callback](const float *samples, int32_t n, float) -> int32_t { | ||
| jfloatArray samples_arr = env->NewFloatArray(n); | ||
| env->SetFloatArrayRegion(samples_arr, 0, n, samples); | ||
| int32_t ret = CallCallback(env, callback, samples_arr); | ||
| env->DeleteLocalRef(samples_arr); | ||
| return ret; | ||
| }; |
There was a problem hiding this comment.
This callback_wrapper lambda is identical to the one in Java_com_k2fsa_sherpa_onnx_OfflineTts_generateWithCallbackImpl on lines 456-463. To avoid code duplication and improve maintainability, I suggest extracting this logic into a static helper function.
For example:
static std::function<int32_t(const float *, int32_t, float)>
CreateCallbackWrapper(JNIEnv *env, jobject callback) {
return [env, callback](const float *samples, int32_t n, float) -> int32_t {
jfloatArray samples_arr = env->NewFloatArray(n);
env->SetFloatArrayRegion(samples_arr, 0, n, samples);
int32_t ret = CallCallback(env, callback, samples_arr);
env->DeleteLocalRef(samples_arr);
return ret;
};
}You could then use this helper in both generateWithCallbackImpl and generateWithConfigImpl.
There was a problem hiding this comment.
Pull request overview
This PR refactors the JNI layer for offline TTS functionality, simplifying callback handling and improving error handling across Java API classes. The refactoring removes direct JNI support for Consumer and Function callbacks in favor of a single OfflineTtsCallback interface, while maintaining backward compatibility through Java-level adapter methods.
Changes:
- Simplified JNI callback mechanism by removing
CallConsumerCallbackandCallFunctionCallbackfunctions, replacing them with a unifiedCallCallbackthat only handlesOfflineTtsCallback - Added null-safety checks for callbacks in JNI layer, avoiding unnecessary lambda creation when callback is null
- Added comprehensive error handling to constructors of 10 Java classes, throwing
IllegalArgumentExceptionwhen native object creation fails - Introduced
getNumSpeakers()method to query speaker count from TTS engine - Added Consumer-based convenience overloads for callback methods, internally converting to
OfflineTtsCallback - Added Javadoc to
OfflineTtsCallbackinterface clarifying return value semantics
Reviewed changes
Copilot reviewed 14 out of 14 changed files in this pull request and generated 3 comments.
Show a summary per file
| File | Description |
|---|---|
| sherpa-onnx/jni/offline-tts.cc | Refactored callback handling to use single unified approach, added null callback checks |
| sherpa-onnx/java-api/.../OfflineTts.java | Changed callback parameter types to specific interface, added Consumer overloads, added getNumSpeakers() method, added error handling |
| sherpa-onnx/java-api/.../OfflineTtsCallback.java | Added Javadoc documentation for callback behavior |
| sherpa-onnx/java-api/.../Vad.java | Added constructor error handling |
| sherpa-onnx/java-api/.../SpokenLanguageIdentification.java | Added constructor error handling |
| sherpa-onnx/java-api/.../SpeakerEmbeddingExtractor.java | Added constructor error handling |
| sherpa-onnx/java-api/.../OnlineRecognizer.java | Added constructor error handling |
| sherpa-onnx/java-api/.../OfflineSpeechDenoiser.java | Added constructor error handling |
| sherpa-onnx/java-api/.../OfflineSpeakerDiarization.java | Added constructor error handling, minor whitespace change |
| sherpa-onnx/java-api/.../OfflineRecognizer.java | Added constructor error handling |
| sherpa-onnx/java-api/.../OfflinePunctuation.java | Added constructor error handling |
| sherpa-onnx/java-api/.../KeywordSpotter.java | Added constructor error handling |
| sherpa-onnx/java-api/.../AudioTagging.java | Added constructor error handling |
| java-api-examples/PocketTts.java | Updated example to use new callback API, removed unused imports |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| public int getNumSpeakers() { | ||
| return getNumSpeakers(ptr); | ||
| } |
There was a problem hiding this comment.
Missing documentation for this public method. Consider adding Javadoc to explain its purpose and return value, similar to the getSampleRate method above it.
|
|
||
| private native OfflineSpeakerDiarizationSegment[] processWithCallback(long ptr, float[] samples, OfflineSpeakerDiarizationCallback callback, long arg); | ||
| } No newline at end of file | ||
| } |
There was a problem hiding this comment.
This appears to be an unintentional whitespace-only change. The closing brace was moved from line 60 to line 61 without any functional modification.
| int sid, | ||
| Consumer<float[]> consumer | ||
| ) { | ||
|
|
There was a problem hiding this comment.
This extra blank line is inconsistent with the formatting of other methods in this file. Consider removing it for consistency.
Summary by CodeRabbit
Release Notes
New Features
Bug Fixes
Documentation
✏️ Tip: You can customize this high-level summary in your review settings.