whisper.rn 0.1.4 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cpp/whisper.h CHANGED
@@ -66,6 +66,7 @@ extern "C" {
66
66
  //
67
67
 
68
68
  struct whisper_context;
69
+ struct whisper_state;
69
70
 
70
71
  typedef int whisper_token;
71
72
 
@@ -101,11 +102,20 @@ extern "C" {
101
102
  WHISPER_API struct whisper_context * whisper_init_from_buffer(void * buffer, size_t buffer_size);
102
103
  WHISPER_API struct whisper_context * whisper_init(struct whisper_model_loader * loader);
103
104
 
104
- // Frees all memory allocated by the model.
105
- WHISPER_API void whisper_free(struct whisper_context * ctx);
105
+ // These are the same as the above, but the internal state of the context is not allocated automatically
106
+ // It is the responsibility of the caller to allocate the state using whisper_init_state() (#523)
107
+ WHISPER_API struct whisper_context * whisper_init_from_file_no_state(const char * path_model);
108
+ WHISPER_API struct whisper_context * whisper_init_from_buffer_no_state(void * buffer, size_t buffer_size);
109
+ WHISPER_API struct whisper_context * whisper_init_no_state(struct whisper_model_loader * loader);
110
+
111
+ WHISPER_API struct whisper_state * whisper_init_state(struct whisper_context * ctx);
112
+
113
+ // Frees all allocated memory
114
+ WHISPER_API void whisper_free (struct whisper_context * ctx);
115
+ WHISPER_API void whisper_free_state(struct whisper_state * state);
106
116
 
107
117
  // Convert RAW PCM audio to log mel spectrogram.
108
- // The resulting spectrogram is stored inside the provided whisper context.
118
+ // The resulting spectrogram is stored inside the default state of the provided whisper context.
109
119
  // Returns 0 on success
110
120
  WHISPER_API int whisper_pcm_to_mel(
111
121
  struct whisper_context * ctx,
@@ -113,17 +123,30 @@ extern "C" {
113
123
  int n_samples,
114
124
  int n_threads);
115
125
 
116
- // Convert RAW PCM audio to log mel spectrogram but applies a Phase Vocoder to speed up the audio x2.
117
- // The resulting spectrogram is stored inside the provided whisper context.
126
+ WHISPER_API int whisper_pcm_to_mel_with_state(
127
+ struct whisper_context * ctx,
128
+ struct whisper_state * state,
129
+ const float * samples,
130
+ int n_samples,
131
+ int n_threads);
132
+
133
+ // Convert RAW PCM audio to log mel spectrogram but applies a Phase Vocoder to speed up the audio x2.
134
+ // The resulting spectrogram is stored inside the default state of the provided whisper context.
118
135
  // Returns 0 on success
119
136
  WHISPER_API int whisper_pcm_to_mel_phase_vocoder(
120
- struct whisper_context* ctx,
121
- const float* samples,
122
- int n_samples,
123
- int n_threads);
124
-
125
-
126
- // This can be used to set a custom log mel spectrogram inside the provided whisper context.
137
+ struct whisper_context * ctx,
138
+ const float * samples,
139
+ int n_samples,
140
+ int n_threads);
141
+
142
+ WHISPER_API int whisper_pcm_to_mel_phase_vocoder_with_state(
143
+ struct whisper_context * ctx,
144
+ struct whisper_state * state,
145
+ const float * samples,
146
+ int n_samples,
147
+ int n_threads);
148
+
149
+ // This can be used to set a custom log mel spectrogram inside the default state of the provided whisper context.
127
150
  // Use this instead of whisper_pcm_to_mel() if you want to provide your own log mel spectrogram.
128
151
  // n_mel must be 80
129
152
  // Returns 0 on success
@@ -133,7 +156,14 @@ extern "C" {
133
156
  int n_len,
134
157
  int n_mel);
135
158
 
136
- // Run the Whisper encoder on the log mel spectrogram stored inside the provided whisper context.
159
+ WHISPER_API int whisper_set_mel_with_state(
160
+ struct whisper_context * ctx,
161
+ struct whisper_state * state,
162
+ const float * data,
163
+ int n_len,
164
+ int n_mel);
165
+
166
+ // Run the Whisper encoder on the log mel spectrogram stored inside the default state in the provided whisper context.
137
167
  // Make sure to call whisper_pcm_to_mel() or whisper_set_mel() first.
138
168
  // offset can be used to specify the offset of the first frame in the spectrogram.
139
169
  // Returns 0 on success
@@ -142,6 +172,12 @@ extern "C" {
142
172
  int offset,
143
173
  int n_threads);
144
174
 
175
+ WHISPER_API int whisper_encode_with_state(
176
+ struct whisper_context * ctx,
177
+ struct whisper_state * state,
178
+ int offset,
179
+ int n_threads);
180
+
145
181
  // Run the Whisper decoder to obtain the logits and probabilities for the next token.
146
182
  // Make sure to call whisper_encode() first.
147
183
  // tokens + n_tokens is the provided context for the decoder.
@@ -155,6 +191,14 @@ extern "C" {
155
191
  int n_past,
156
192
  int n_threads);
157
193
 
194
+ WHISPER_API int whisper_decode_with_state(
195
+ struct whisper_context * ctx,
196
+ struct whisper_state * state,
197
+ const whisper_token * tokens,
198
+ int n_tokens,
199
+ int n_past,
200
+ int n_threads);
201
+
158
202
  // Convert the provided text into tokens.
159
203
  // The tokens pointer must be large enough to hold the resulting tokens.
160
204
  // Returns the number of tokens on success, no more than n_max_tokens
@@ -190,17 +234,26 @@ extern "C" {
190
234
  int n_threads,
191
235
  float * lang_probs);
192
236
 
193
- WHISPER_API int whisper_n_len (struct whisper_context * ctx); // mel length
194
- WHISPER_API int whisper_n_vocab (struct whisper_context * ctx);
195
- WHISPER_API int whisper_n_text_ctx (struct whisper_context * ctx);
196
- WHISPER_API int whisper_n_audio_ctx (struct whisper_context * ctx);
197
- WHISPER_API int whisper_is_multilingual(struct whisper_context * ctx);
237
+ WHISPER_API int whisper_lang_auto_detect_with_state(
238
+ struct whisper_context * ctx,
239
+ struct whisper_state * state,
240
+ int offset_ms,
241
+ int n_threads,
242
+ float * lang_probs);
243
+
244
+ WHISPER_API int whisper_n_len (struct whisper_context * ctx); // mel length
245
+ WHISPER_API int whisper_n_len_from_state(struct whisper_state * state); // mel length
246
+ WHISPER_API int whisper_n_vocab (struct whisper_context * ctx);
247
+ WHISPER_API int whisper_n_text_ctx (struct whisper_context * ctx);
248
+ WHISPER_API int whisper_n_audio_ctx (struct whisper_context * ctx);
249
+ WHISPER_API int whisper_is_multilingual (struct whisper_context * ctx);
198
250
 
199
251
  // Token logits obtained from the last call to whisper_decode()
200
252
  // The logits for the last token are stored in the last row
201
253
  // Rows: n_tokens
202
254
  // Cols: n_vocab
203
- WHISPER_API float * whisper_get_logits(struct whisper_context * ctx);
255
+ WHISPER_API float * whisper_get_logits (struct whisper_context * ctx);
256
+ WHISPER_API float * whisper_get_logits_from_state(struct whisper_state * state);
204
257
 
205
258
  // Token Id -> String. Uses the vocabulary in the provided context
206
259
  WHISPER_API const char * whisper_token_to_str(struct whisper_context * ctx, whisper_token token);
@@ -218,7 +271,7 @@ extern "C" {
218
271
  WHISPER_API whisper_token whisper_token_translate (void);
219
272
  WHISPER_API whisper_token whisper_token_transcribe(void);
220
273
 
221
- // Performance information
274
+ // Performance information from the default state.
222
275
  WHISPER_API void whisper_print_timings(struct whisper_context * ctx);
223
276
  WHISPER_API void whisper_reset_timings(struct whisper_context * ctx);
224
277
 
@@ -236,18 +289,19 @@ extern "C" {
236
289
  // Text segment callback
237
290
  // Called on every newly generated text segment
238
291
  // Use the whisper_full_...() functions to obtain the text segments
239
- typedef void (*whisper_new_segment_callback)(struct whisper_context * ctx, int n_new, void * user_data);
292
+ typedef void (*whisper_new_segment_callback)(struct whisper_context * ctx, struct whisper_state * state, int n_new, void * user_data);
240
293
 
241
294
  // Encoder begin callback
242
295
  // If not NULL, called before the encoder starts
243
296
  // If it returns false, the computation is aborted
244
- typedef bool (*whisper_encoder_begin_callback)(struct whisper_context * ctx, void * user_data);
297
+ typedef bool (*whisper_encoder_begin_callback)(struct whisper_context * ctx, struct whisper_state * state, void * user_data);
245
298
 
246
299
  // Logits filter callback
247
300
  // Can be used to modify the logits before sampling
248
301
  // If not NULL, called after applying temperature to logits
249
302
  typedef void (*whisper_logits_filter_callback)(
250
303
  struct whisper_context * ctx,
304
+ struct whisper_state * state,
251
305
  const whisper_token_data * tokens,
252
306
  int n_tokens,
253
307
  float * logits,
@@ -334,6 +388,7 @@ extern "C" {
334
388
  WHISPER_API struct whisper_full_params whisper_full_default_params(enum whisper_sampling_strategy strategy);
335
389
 
336
390
  // Run the entire model: PCM -> log mel spectrogram -> encoder -> decoder -> text
391
+ // Not thread safe for same context
337
392
  // Uses the specified decoding strategy to obtain the text.
338
393
  WHISPER_API int whisper_full(
339
394
  struct whisper_context * ctx,
@@ -341,7 +396,16 @@ extern "C" {
341
396
  const float * samples,
342
397
  int n_samples);
343
398
 
344
- // Split the input audio in chunks and process each chunk separately using whisper_full()
399
+ WHISPER_API int whisper_full_with_state(
400
+ struct whisper_context * ctx,
401
+ struct whisper_state * state,
402
+ struct whisper_full_params params,
403
+ const float * samples,
404
+ int n_samples);
405
+
406
+ // Split the input audio in chunks and process each chunk separately using whisper_full_with_state()
407
+ // Result is stored in the default state of the context
408
+ // Not thread safe if executed in parallel on the same context.
345
409
  // It seems this approach can offer some speedup in some cases.
346
410
  // However, the transcription accuracy can be worse at the beginning and end of each chunk.
347
411
  WHISPER_API int whisper_full_parallel(
@@ -351,40 +415,56 @@ extern "C" {
351
415
  int n_samples,
352
416
  int n_processors);
353
417
 
354
- // Number of generated text segments.
418
+ // Number of generated text segments
355
419
  // A segment can be a few words, a sentence, or even a paragraph.
356
- WHISPER_API int whisper_full_n_segments(struct whisper_context * ctx);
420
+ WHISPER_API int whisper_full_n_segments (struct whisper_context * ctx);
421
+ WHISPER_API int whisper_full_n_segments_from_state(struct whisper_state * state);
357
422
 
358
- // Language id associated with the current context
423
+ // Language id associated with the context's default state
359
424
  WHISPER_API int whisper_full_lang_id(struct whisper_context * ctx);
360
425
 
361
- // Get the start and end time of the specified segment.
362
- WHISPER_API int64_t whisper_full_get_segment_t0(struct whisper_context * ctx, int i_segment);
363
- WHISPER_API int64_t whisper_full_get_segment_t1(struct whisper_context * ctx, int i_segment);
426
+ // Language id associated with the provided state
427
+ WHISPER_API int whisper_full_lang_id_from_state(struct whisper_state * state);
428
+
429
+ // Get the start and end time of the specified segment
430
+ WHISPER_API int64_t whisper_full_get_segment_t0 (struct whisper_context * ctx, int i_segment);
431
+ WHISPER_API int64_t whisper_full_get_segment_t0_from_state(struct whisper_state * state, int i_segment);
432
+
433
+ WHISPER_API int64_t whisper_full_get_segment_t1 (struct whisper_context * ctx, int i_segment);
434
+ WHISPER_API int64_t whisper_full_get_segment_t1_from_state(struct whisper_state * state, int i_segment);
435
+
436
+ // Get the text of the specified segment
437
+ WHISPER_API const char * whisper_full_get_segment_text (struct whisper_context * ctx, int i_segment);
438
+ WHISPER_API const char * whisper_full_get_segment_text_from_state(struct whisper_state * state, int i_segment);
364
439
 
365
- // Get the text of the specified segment.
366
- WHISPER_API const char * whisper_full_get_segment_text(struct whisper_context * ctx, int i_segment);
440
+ // Get number of tokens in the specified segment
441
+ WHISPER_API int whisper_full_n_tokens (struct whisper_context * ctx, int i_segment);
442
+ WHISPER_API int whisper_full_n_tokens_from_state(struct whisper_state * state, int i_segment);
367
443
 
368
- // Get number of tokens in the specified segment.
369
- WHISPER_API int whisper_full_n_tokens(struct whisper_context * ctx, int i_segment);
444
+ // Get the token text of the specified token in the specified segment
445
+ WHISPER_API const char * whisper_full_get_token_text (struct whisper_context * ctx, int i_segment, int i_token);
446
+ WHISPER_API const char * whisper_full_get_token_text_from_state(struct whisper_context * ctx, struct whisper_state * state, int i_segment, int i_token);
370
447
 
371
- // Get the token text of the specified token in the specified segment.
372
- WHISPER_API const char * whisper_full_get_token_text(struct whisper_context * ctx, int i_segment, int i_token);
373
- WHISPER_API whisper_token whisper_full_get_token_id (struct whisper_context * ctx, int i_segment, int i_token);
448
+ WHISPER_API whisper_token whisper_full_get_token_id (struct whisper_context * ctx, int i_segment, int i_token);
449
+ WHISPER_API whisper_token whisper_full_get_token_id_from_state(struct whisper_state * state, int i_segment, int i_token);
374
450
 
375
- // Get token data for the specified token in the specified segment.
451
+ // Get token data for the specified token in the specified segment
376
452
  // This contains probabilities, timestamps, etc.
377
- WHISPER_API whisper_token_data whisper_full_get_token_data(struct whisper_context * ctx, int i_segment, int i_token);
453
+ WHISPER_API whisper_token_data whisper_full_get_token_data (struct whisper_context * ctx, int i_segment, int i_token);
454
+ WHISPER_API whisper_token_data whisper_full_get_token_data_from_state(struct whisper_state * state, int i_segment, int i_token);
378
455
 
379
- // Get the probability of the specified token in the specified segment.
380
- WHISPER_API float whisper_full_get_token_p(struct whisper_context * ctx, int i_segment, int i_token);
456
+ // Get the probability of the specified token in the specified segment
457
+ WHISPER_API float whisper_full_get_token_p (struct whisper_context * ctx, int i_segment, int i_token);
458
+ WHISPER_API float whisper_full_get_token_p_from_state(struct whisper_state * state, int i_segment, int i_token);
381
459
 
382
460
  ////////////////////////////////////////////////////////////////////////////
383
461
 
384
462
  // Temporary helpers needed for exposing ggml interface
385
463
 
386
464
  WHISPER_API int whisper_bench_memcpy(int n_threads);
465
+ WHISPER_API const char * whisper_bench_memcpy_str(int n_threads);
387
466
  WHISPER_API int whisper_bench_ggml_mul_mat(int n_threads);
467
+ WHISPER_API const char * whisper_bench_ggml_mul_mat_str(int n_threads);
388
468
 
389
469
  #ifdef __cplusplus
390
470
  }
package/ios/RNWhisper.h CHANGED
@@ -3,9 +3,9 @@
3
3
  #import "rn-whisper.h"
4
4
  #endif
5
5
 
6
-
7
6
  #import <React/RCTBridgeModule.h>
7
+ #import <React/RCTEventEmitter.h>
8
8
 
9
- @interface RNWhisper : NSObject <RCTBridgeModule>
9
+ @interface RNWhisper : RCTEventEmitter <RCTBridgeModule>
10
10
 
11
11
  @end
package/ios/RNWhisper.mm CHANGED
@@ -1,23 +1,8 @@
1
-
2
1
  #import "RNWhisper.h"
2
+ #import "RNWhisperContext.h"
3
3
  #include <stdlib.h>
4
4
  #include <string>
5
5
 
6
- @interface WhisperContext : NSObject {
7
- }
8
-
9
- @property struct whisper_context * ctx;
10
-
11
- @end
12
-
13
- @implementation WhisperContext
14
-
15
- - (void)invalidate {
16
- whisper_free(self.ctx);
17
- }
18
-
19
- @end
20
-
21
6
  @implementation RNWhisper
22
7
 
23
8
  NSMutableDictionary *contexts;
@@ -33,10 +18,8 @@ RCT_REMAP_METHOD(initContext,
33
18
  contexts = [[NSMutableDictionary alloc] init];
34
19
  }
35
20
 
36
- WhisperContext *context = [[WhisperContext alloc] init];
37
- context.ctx = whisper_init_from_file([modelPath UTF8String]);
38
-
39
- if (context.ctx == NULL) {
21
+ RNWhisperContext *context = [RNWhisperContext initWithModelPath:modelPath];
22
+ if ([context getContext] == NULL) {
40
23
  reject(@"whisper_cpp_error", @"Failed to load the model", nil);
41
24
  return;
42
25
  }
@@ -47,123 +30,105 @@ RCT_REMAP_METHOD(initContext,
47
30
  resolve([NSNumber numberWithInt:contextId]);
48
31
  }
49
32
 
50
- RCT_REMAP_METHOD(transcribe,
33
+ RCT_REMAP_METHOD(transcribeFile,
51
34
  withContextId:(int)contextId
35
+ withJobId:(int)jobId
52
36
  withWaveFile:(NSString *)waveFilePath
53
37
  withOptions:(NSDictionary *)options
54
38
  withResolver:(RCTPromiseResolveBlock)resolve
55
39
  withRejecter:(RCTPromiseRejectBlock)reject)
56
40
  {
57
- WhisperContext *context = contexts[[NSNumber numberWithInt:contextId]];
41
+ RNWhisperContext *context = contexts[[NSNumber numberWithInt:contextId]];
58
42
 
59
43
  if (context == nil) {
60
44
  reject(@"whisper_error", @"Context not found", nil);
61
45
  return;
62
46
  }
47
+ if ([context isCapturing]) {
48
+ reject(@"whisper_error", @"The context is in realtime transcribe mode", nil);
49
+ return;
50
+ }
51
+ if ([context isTranscribing]) {
52
+ reject(@"whisper_error", @"Context is already transcribing", nil);
53
+ return;
54
+ }
63
55
 
64
56
  NSURL *url = [NSURL fileURLWithPath:waveFilePath];
65
57
 
66
58
  int count = 0;
67
59
  float *waveFile = [self decodeWaveFile:url count:&count];
68
-
69
60
  if (waveFile == nil) {
70
61
  reject(@"whisper_error", @"Invalid file", nil);
71
62
  return;
72
63
  }
73
-
74
- struct whisper_full_params params = whisper_full_default_params(WHISPER_SAMPLING_GREEDY);
75
-
76
- const int max_threads = options[@"maxThreads"] != nil ?
77
- [options[@"maxThreads"] intValue] :
78
- MIN(8, (int)[[NSProcessInfo processInfo] processorCount]) - 2;
79
-
80
- if (options[@"beamSize"] != nil) {
81
- params.strategy = WHISPER_SAMPLING_BEAM_SEARCH;
82
- params.beam_search.beam_size = [options[@"beamSize"] intValue];
64
+ int code = [context transcribeFile:jobId audioData:waveFile audioDataCount:count options:options];
65
+ if (code != 0) {
66
+ free(waveFile);
67
+ reject(@"whisper_cpp_error", [NSString stringWithFormat:@"Failed to transcribe the file. Code: %d", code], nil);
68
+ return;
83
69
  }
70
+ free(waveFile);
71
+ resolve([context getTextSegments]);
72
+ }
84
73
 
85
- params.print_realtime = false;
86
- params.print_progress = false;
87
- params.print_timestamps = false;
88
- params.print_special = false;
89
- params.speed_up = options[@"speedUp"] != nil ? [options[@"speedUp"] boolValue] : false;
90
- params.translate = options[@"translate"] != nil ? [options[@"translate"] boolValue] : false;
91
- params.language = options[@"language"] != nil ? [options[@"language"] UTF8String] : "auto";
92
- params.n_threads = max_threads;
93
- params.offset_ms = 0;
94
- params.no_context = true;
95
- params.single_segment = false;
96
-
97
- if (options[@"maxLen"] != nil) {
98
- params.max_len = [options[@"maxLen"] intValue];
99
- }
100
- params.token_timestamps = options[@"tokenTimestamps"] != nil ? [options[@"tokenTimestamps"] boolValue] : false;
74
+ - (NSArray *)supportedEvents {
75
+ return@[
76
+ @"@RNWhisper_onRealtimeTranscribe",
77
+ @"@RNWhisper_onRealtimeTranscribeEnd",
78
+ ];
79
+ }
101
80
 
102
- if (options[@"bestOf"] != nil) {
103
- params.greedy.best_of = [options[@"bestOf"] intValue];
104
- }
105
- if (options[@"maxContext"] != nil) {
106
- params.n_max_text_ctx = [options[@"maxContext"] intValue];
107
- }
108
-
109
- if (options[@"offset"] != nil) {
110
- params.offset_ms = [options[@"offset"] intValue];
111
- }
112
- if (options[@"duration"] != nil) {
113
- params.duration_ms = [options[@"duration"] intValue];
114
- }
115
- if (options[@"wordThold"] != nil) {
116
- params.thold_pt = [options[@"wordThold"] intValue];
117
- }
118
- if (options[@"temperature"] != nil) {
119
- params.temperature = [options[@"temperature"] floatValue];
120
- }
121
- if (options[@"temperatureInc"] != nil) {
122
- params.temperature_inc = [options[@"temperature_inc"] floatValue];
123
- }
124
-
125
- if (options[@"prompt"] != nil) {
126
- std::string *prompt = new std::string([options[@"prompt"] UTF8String]);
127
- rn_whisper_convert_prompt(
128
- context.ctx,
129
- params,
130
- prompt
131
- );
132
- }
81
+ RCT_REMAP_METHOD(startRealtimeTranscribe,
82
+ withContextId:(int)contextId
83
+ withJobId:(int)jobId
84
+ withOptions:(NSDictionary *)options
85
+ withResolver:(RCTPromiseResolveBlock)resolve
86
+ withRejecter:(RCTPromiseRejectBlock)reject)
87
+ {
88
+ RNWhisperContext *context = contexts[[NSNumber numberWithInt:contextId]];
133
89
 
134
- whisper_reset_timings(context.ctx);
135
- int code = whisper_full(context.ctx, params, waveFile, count);
136
- if (code != 0) {
137
- NSLog(@"Failed to run the model");
138
- free(waveFile);
139
- reject(@"whisper_cpp_error", [NSString stringWithFormat:@"Failed to run the model. Code: %d", code], nil);
90
+ if (context == nil) {
91
+ reject(@"whisper_error", @"Context not found", nil);
92
+ return;
93
+ }
94
+ if ([context isCapturing]) {
95
+ reject(@"whisper_error", @"The context is already capturing", nil);
140
96
  return;
141
97
  }
142
98
 
143
- // whisper_print_timings(context.ctx);
144
- free(waveFile);
145
-
146
- NSString *result = @"";
147
- int n_segments = whisper_full_n_segments(context.ctx);
148
-
149
- NSMutableArray *segments = [[NSMutableArray alloc] init];
150
- for (int i = 0; i < n_segments; i++) {
151
- const char * text_cur = whisper_full_get_segment_text(context.ctx, i);
152
- result = [result stringByAppendingString:[NSString stringWithUTF8String:text_cur]];
153
-
154
- const int64_t t0 = whisper_full_get_segment_t0(context.ctx, i);
155
- const int64_t t1 = whisper_full_get_segment_t1(context.ctx, i);
156
- NSDictionary *segment = @{
157
- @"text": [NSString stringWithUTF8String:text_cur],
158
- @"t0": [NSNumber numberWithLongLong:t0],
159
- @"t1": [NSNumber numberWithLongLong:t1]
160
- };
161
- [segments addObject:segment];
99
+ OSStatus status = [context transcribeRealtime:jobId
100
+ options:options
101
+ onTranscribe:^(int _jobId, NSString *type, NSDictionary *payload) {
102
+ NSString *eventName = nil;
103
+ if ([type isEqual:@"transcribe"]) {
104
+ eventName = @"@RNWhisper_onRealtimeTranscribe";
105
+ } else if ([type isEqual:@"end"]) {
106
+ eventName = @"@RNWhisper_onRealtimeTranscribeEnd";
107
+ }
108
+ if (eventName == nil) {
109
+ return;
110
+ }
111
+ [self sendEventWithName:eventName
112
+ body:@{
113
+ @"contextId": [NSNumber numberWithInt:contextId],
114
+ @"jobId": [NSNumber numberWithInt:jobId],
115
+ @"payload": payload
116
+ }
117
+ ];
118
+ }
119
+ ];
120
+ if (status == 0) {
121
+ resolve(nil);
122
+ return;
162
123
  }
163
- resolve(@{
164
- @"result": result,
165
- @"segments": segments
166
- });
124
+ reject(@"whisper_error", [NSString stringWithFormat:@"Failed to start realtime transcribe. Status: %d", status], nil);
125
+ }
126
+ RCT_REMAP_METHOD(abortTranscribe,
127
+ withContextId:(int)contextId
128
+ withJobId:(int)jobId)
129
+ {
130
+ RNWhisperContext *context = contexts[[NSNumber numberWithInt:contextId]];
131
+ [context stopTranscribe:jobId];
167
132
  }
168
133
 
169
134
  RCT_REMAP_METHOD(releaseContext,
@@ -171,7 +136,7 @@ RCT_REMAP_METHOD(releaseContext,
171
136
  withResolver:(RCTPromiseResolveBlock)resolve
172
137
  withRejecter:(RCTPromiseRejectBlock)reject)
173
138
  {
174
- WhisperContext *context = contexts[[NSNumber numberWithInt:contextId]];
139
+ RNWhisperContext *context = contexts[[NSNumber numberWithInt:contextId]];
175
140
  if (context == nil) {
176
141
  reject(@"whisper_error", @"Context not found", nil);
177
142
  return;
@@ -210,12 +175,14 @@ RCT_REMAP_METHOD(releaseAllContexts,
210
175
  }
211
176
 
212
177
  - (void)invalidate {
178
+ rn_whisper_abort_all_transcribe();
179
+
213
180
  if (contexts == nil) {
214
181
  return;
215
182
  }
216
183
 
217
184
  for (NSNumber *contextId in contexts) {
218
- WhisperContext *context = contexts[contextId];
185
+ RNWhisperContext *context = contexts[contextId];
219
186
  [context invalidate];
220
187
  }
221
188
 
@@ -0,0 +1,53 @@
1
+ #ifdef __cplusplus
2
+ #import "whisper.h"
3
+ #import "rn-whisper.h"
4
+ #endif
5
+
6
+ #import <AVFoundation/AVFoundation.h>
7
+ #import <AudioToolbox/AudioQueue.h>
8
+
9
+ #define NUM_BUFFERS 3
10
+ #define DEFAULT_MAX_AUDIO_SEC 30
11
+
12
+ typedef struct {
13
+ __unsafe_unretained id mSelf;
14
+
15
+ int jobId;
16
+ NSDictionary* options;
17
+
18
+ bool isTranscribing;
19
+ bool isRealtime;
20
+ bool isCapturing;
21
+ int maxAudioSec;
22
+ int nSamples;
23
+ int16_t* audioBufferI16;
24
+ float* audioBufferF32;
25
+
26
+ AudioQueueRef queue;
27
+ AudioStreamBasicDescription dataFormat;
28
+ AudioQueueBufferRef buffers[NUM_BUFFERS];
29
+
30
+ void (^transcribeHandler)(int, NSString *, NSDictionary *);
31
+ } RNWhisperContextRecordState;
32
+
33
+ @interface RNWhisperContext : NSObject {
34
+ struct whisper_context * ctx;
35
+ RNWhisperContextRecordState recordState;
36
+ }
37
+
38
+ + (instancetype)initWithModelPath:(NSString *)modelPath;
39
+ - (struct whisper_context *)getContext;
40
+ - (OSStatus)transcribeRealtime:(int)jobId
41
+ options:(NSDictionary *)options
42
+ onTranscribe:(void (^)(int, NSString *, NSDictionary *))onTranscribe;
43
+ - (int)transcribeFile:(int)jobId
44
+ audioData:(float *)audioData
45
+ audioDataCount:(int)audioDataCount
46
+ options:(NSDictionary *)options;
47
+ - (void)stopTranscribe:(int)jobId;
48
+ - (bool)isCapturing;
49
+ - (bool)isTranscribing;
50
+ - (NSDictionary *)getTextSegments;
51
+ - (void)invalidate;
52
+
53
+ @end