Skip to content

Commit 92981bf

Browse files
radko93barhanc
andauthored
fix: add mutex to VoiceActivityDetection to prevent race between generate() and unload() (#1056)
## Description Add thread-safety to `VoiceActivityDetection` using the same mutex pattern already established by `VisionModel`. Without this, `BaseModel::unload()` can destroy `module_` on the JS thread while `generate()` is still calling `forward()` on a worker thread, causing `SIGILL` / `SIGSEGV` crashes. ### Introduces a breaking change? - [x] No ### Type of change - [x] Bug fix (change which fixes an issue) ### Tested on - [x] Android ### Testing instructions Use `useVAD({ model: FSMN_VAD })` with continuous audio input and trigger rapid mount/unmount cycles. Confirm no crashes or deadlocks. ### Related issues Fixes #1055 --------- Co-authored-by: Bartosz Hanc <bartosz.hanc02@gmail.com>
1 parent 7dcc391 commit 92981bf

2 files changed

Lines changed: 11 additions & 0 deletions

File tree

packages/react-native-executorch/common/rnexecutorch/models/voice_activity_detection/VoiceActivityDetection.cpp

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,8 +54,14 @@ VoiceActivityDetection::preprocess(std::span<float> waveform) const {
5454
return frameBuffer;
5555
}
5656

57+
void VoiceActivityDetection::unload() noexcept {
58+
std::scoped_lock lock(inference_mutex_);
59+
BaseModel::unload();
60+
}
61+
5762
std::vector<types::Segment>
5863
VoiceActivityDetection::generate(std::span<float> waveform) const {
64+
std::scoped_lock lock(inference_mutex_);
5965

6066
auto windowedInput = preprocess(waveform);
6167
auto [chunksNumber, remainder] = std::div(

packages/react-native-executorch/common/rnexecutorch/models/voice_activity_detection/VoiceActivityDetection.h

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
#include <executorch/extension/tensor/tensor.h>
66
#include <executorch/extension/tensor/tensor_ptr.h>
77
#include <executorch/runtime/core/evalue.h>
8+
#include <mutex>
89
#include <span>
910

1011
#include "rnexecutorch/metaprogramming/ConstructorHelpers.h"
@@ -23,7 +24,11 @@ class VoiceActivityDetection : public BaseModel {
2324
[[nodiscard("Registered non-void function")]] std::vector<types::Segment>
2425
generate(std::span<float> waveform) const;
2526

27+
void unload() noexcept;
28+
2629
private:
30+
mutable std::mutex inference_mutex_;
31+
2732
std::vector<std::array<float, constants::kPaddedWindowSize>>
2833
preprocess(std::span<float> waveform) const;
2934
std::vector<types::Segment> postprocess(const std::vector<float> &scores,

0 commit comments

Comments
 (0)