ggerganov commited on
Commit
d5c5cb0
·
unverified ·
1 Parent(s): 0ac55b8

stream : add sliding window mode

Browse files
Files changed (1) hide show
  1. examples/stream/stream.cpp +375 -67
examples/stream/stream.cpp CHANGED
@@ -1,6 +1,7 @@
1
  // Real-time speech recognition of input from a microphone
2
  //
3
  // A very quick-n-dirty implementation serving mainly as a proof of concept.
 
4
 
5
  #include "whisper.h"
6
 
@@ -33,15 +34,19 @@ struct whisper_params {
33
  int32_t n_threads = std::min(4, (int32_t) std::thread::hardware_concurrency());
34
  int32_t step_ms = 3000;
35
  int32_t length_ms = 10000;
 
36
  int32_t capture_id = -1;
37
  int32_t max_tokens = 32;
38
  int32_t audio_ctx = 0;
39
 
 
 
 
40
  bool speed_up = false;
41
  bool translate = false;
42
- bool no_context = true;
43
  bool print_special = false;
44
- bool no_timestamps = true;
 
45
 
46
  std::string language = "en";
47
  std::string model = "models/ggml-base.en.bin";
@@ -61,13 +66,16 @@ bool whisper_params_parse(int argc, char ** argv, whisper_params & params) {
61
  else if (arg == "-t" || arg == "--threads") { params.n_threads = std::stoi(argv[++i]); }
62
  else if ( arg == "--step") { params.step_ms = std::stoi(argv[++i]); }
63
  else if ( arg == "--length") { params.length_ms = std::stoi(argv[++i]); }
 
64
  else if (arg == "-c" || arg == "--capture") { params.capture_id = std::stoi(argv[++i]); }
65
  else if (arg == "-mt" || arg == "--max-tokens") { params.max_tokens = std::stoi(argv[++i]); }
66
  else if (arg == "-ac" || arg == "--audio-ctx") { params.audio_ctx = std::stoi(argv[++i]); }
 
 
67
  else if (arg == "-su" || arg == "--speed-up") { params.speed_up = true; }
68
  else if (arg == "-tr" || arg == "--translate") { params.translate = true; }
69
- else if (arg == "-kc" || arg == "--keep-context") { params.no_context = false; }
70
  else if (arg == "-ps" || arg == "--print-special") { params.print_special = true; }
 
71
  else if (arg == "-l" || arg == "--language") { params.language = argv[++i]; }
72
  else if (arg == "-m" || arg == "--model") { params.model = argv[++i]; }
73
  else if (arg == "-f" || arg == "--file") { params.fname_out = argv[++i]; }
@@ -90,13 +98,16 @@ void whisper_print_usage(int argc, char ** argv, const whisper_params & params)
90
  fprintf(stderr, " -t N, --threads N [%-7d] number of threads to use during computation\n", params.n_threads);
91
  fprintf(stderr, " --step N [%-7d] audio step size in milliseconds\n", params.step_ms);
92
  fprintf(stderr, " --length N [%-7d] audio length in milliseconds\n", params.length_ms);
 
93
  fprintf(stderr, " -c ID, --capture ID [%-7d] capture device ID\n", params.capture_id);
94
  fprintf(stderr, " -mt N, --max-tokens N [%-7d] maximum number of tokens per audio chunk\n", params.max_tokens);
95
  fprintf(stderr, " -ac N, --audio-ctx N [%-7d] audio context size (0 - all)\n", params.audio_ctx);
 
 
96
  fprintf(stderr, " -su, --speed-up [%-7s] speed up audio by x2 (reduced accuracy)\n", params.speed_up ? "true" : "false");
97
  fprintf(stderr, " -tr, --translate [%-7s] translate from source language to english\n", params.translate ? "true" : "false");
98
- fprintf(stderr, " -kc, --keep-context [%-7s] keep context between audio chunks\n", params.no_context ? "false" : "true");
99
  fprintf(stderr, " -ps, --print-special [%-7s] print special tokens\n", params.print_special ? "true" : "false");
 
100
  fprintf(stderr, " -l LANG, --language LANG [%-7s] spoken language\n", params.language.c_str());
101
  fprintf(stderr, " -m FNAME, --model FNAME [%-7s] model path\n", params.model.c_str());
102
  fprintf(stderr, " -f FNAME, --file FNAME [%-7s] text output file name\n", params.fname_out.c_str());
@@ -107,19 +118,56 @@ void whisper_print_usage(int argc, char ** argv, const whisper_params & params)
107
  // SDL Audio capture
108
  //
109
 
110
- SDL_AudioDeviceID g_dev_id_in = 0;
 
 
 
111
 
112
- bool audio_sdl_init(const int capture_id) {
113
- if (g_dev_id_in) {
114
- fprintf(stderr, "%s: already initialized\n", __func__);
115
- return false;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116
  }
 
117
 
 
118
  SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
119
 
120
  if (SDL_Init(SDL_INIT_AUDIO) < 0) {
121
  SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError());
122
- return (1);
123
  }
124
 
125
  SDL_SetHintWithPriority(SDL_HINT_AUDIO_RESAMPLING_MODE, "medium", SDL_HINT_OVERRIDE);
@@ -138,34 +186,232 @@ bool audio_sdl_init(const int capture_id) {
138
  SDL_zero(capture_spec_requested);
139
  SDL_zero(capture_spec_obtained);
140
 
141
- capture_spec_requested.freq = WHISPER_SAMPLE_RATE;
142
  capture_spec_requested.format = AUDIO_F32;
143
  capture_spec_requested.channels = 1;
144
  capture_spec_requested.samples = 1024;
 
 
 
 
 
145
 
146
  if (capture_id >= 0) {
147
  fprintf(stderr, "%s: attempt to open capture device %d : '%s' ...\n", __func__, capture_id, SDL_GetAudioDeviceName(capture_id, SDL_TRUE));
148
- g_dev_id_in = SDL_OpenAudioDevice(SDL_GetAudioDeviceName(capture_id, SDL_TRUE), SDL_TRUE, &capture_spec_requested, &capture_spec_obtained, 0);
149
  } else {
150
  fprintf(stderr, "%s: attempt to open default capture device ...\n", __func__);
151
- g_dev_id_in = SDL_OpenAudioDevice(nullptr, SDL_TRUE, &capture_spec_requested, &capture_spec_obtained, 0);
152
  }
153
- if (!g_dev_id_in) {
 
154
  fprintf(stderr, "%s: couldn't open an audio device for capture: %s!\n", __func__, SDL_GetError());
155
- g_dev_id_in = 0;
 
 
156
  } else {
157
- fprintf(stderr, "%s: obtained spec for input device (SDL Id = %d):\n", __func__, g_dev_id_in);
158
- fprintf(stderr, "%s: - sample rate: %d\n", __func__, capture_spec_obtained.freq);
159
- fprintf(stderr, "%s: - format: %d (required: %d)\n", __func__, capture_spec_obtained.format, capture_spec_requested.format);
160
- fprintf(stderr, "%s: - channels: %d (required: %d)\n", __func__, capture_spec_obtained.channels, capture_spec_requested.channels);
161
- fprintf(stderr, "%s: - samples per frame: %d\n", __func__, capture_spec_obtained.samples);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
162
  }
163
 
164
  return true;
165
  }
166
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
167
  ///////////////////////////
168
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
169
  int main(int argc, char ** argv) {
170
  whisper_params params;
171
 
@@ -173,33 +419,46 @@ int main(int argc, char ** argv) {
173
  return 1;
174
  }
175
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
176
  // init audio
177
 
178
- if (!audio_sdl_init(params.capture_id)) {
179
- fprintf(stderr, "%s: audio_sdl_init() failed!\n", __func__);
 
180
  return 1;
181
  }
182
 
 
 
 
 
183
  if (whisper_lang_id(params.language.c_str()) == -1) {
184
  fprintf(stderr, "error: unknown language '%s'\n", params.language.c_str());
185
  whisper_print_usage(argc, argv, params);
186
  exit(0);
187
  }
188
 
189
- // whisper init
190
-
191
  struct whisper_context * ctx = whisper_init(params.model.c_str());
192
 
193
- const int n_samples = (params.step_ms/1000.0)*WHISPER_SAMPLE_RATE;
194
- const int n_samples_len = (params.length_ms/1000.0)*WHISPER_SAMPLE_RATE;
195
- const int n_samples_30s = 30*WHISPER_SAMPLE_RATE;
196
- const int n_samples_keep = 0.2*WHISPER_SAMPLE_RATE;
197
-
198
- std::vector<float> pcmf32(n_samples_30s, 0.0f);
199
- std::vector<float> pcmf32_old;
200
 
201
  std::vector<whisper_token> prompt_tokens;
202
- const int n_new_line = params.length_ms / params.step_ms - 1;
203
 
204
  // print some info about the processing
205
  {
@@ -211,23 +470,28 @@ int main(int argc, char ** argv) {
211
  fprintf(stderr, "%s: WARNING: model is not multilingual, ignoring language and translation options\n", __func__);
212
  }
213
  }
214
- fprintf(stderr, "%s: processing %d samples (step = %.1f sec / len = %.1f sec), %d threads, lang = %s, task = %s, timestamps = %d ...\n",
215
  __func__,
216
- n_samples,
217
- float(n_samples)/WHISPER_SAMPLE_RATE,
218
- float(n_samples_len)/WHISPER_SAMPLE_RATE,
 
219
  params.n_threads,
220
  params.language.c_str(),
221
  params.translate ? "translate" : "transcribe",
222
  params.no_timestamps ? 0 : 1);
223
 
224
- fprintf(stderr, "%s: n_new_line = %d\n", __func__, n_new_line);
 
 
 
 
 
225
  fprintf(stderr, "\n");
226
  }
227
 
228
- SDL_PauseAudioDevice(g_dev_id_in, 0);
229
-
230
  int n_iter = 0;
 
231
  bool is_running = true;
232
 
233
  std::ofstream fout;
@@ -242,6 +506,9 @@ int main(int argc, char ** argv) {
242
  printf("[Start speaking]");
243
  fflush(stdout);
244
 
 
 
 
245
  // main audio loop
246
  while (is_running) {
247
  // handle Ctrl + C
@@ -268,34 +535,63 @@ int main(int argc, char ** argv) {
268
  }
269
 
270
  // process new audio
271
- if (n_iter > 0 && SDL_GetQueuedAudioSize(g_dev_id_in) > 2*n_samples*sizeof(float)) {
272
- fprintf(stderr, "\n\n%s: WARNING: cannot process audio fast enough, dropping audio ...\n\n", __func__);
273
- SDL_ClearQueuedAudio(g_dev_id_in);
274
- }
275
 
276
- while (SDL_GetQueuedAudioSize(g_dev_id_in) < n_samples*sizeof(float)) {
277
- SDL_Delay(1);
278
- }
279
 
280
- const int n_samples_new = SDL_GetQueuedAudioSize(g_dev_id_in)/sizeof(float);
 
 
 
 
281
 
282
- // take one second from previous iteration
283
- //const int n_samples_take = std::min((int) pcmf32_old.size(), std::max(0, n_samples_30s/30 - n_samples_new));
 
 
284
 
285
- // take up to params.length_ms audio from previous iteration
286
- const int n_samples_take = std::min((int) pcmf32_old.size(), std::max(0, n_samples_keep + n_samples_len - n_samples_new));
287
 
288
- //printf("processing: take = %d, new = %d, old = %d\n", n_samples_take, n_samples_new, (int) pcmf32_old.size());
289
 
290
- pcmf32.resize(n_samples_new + n_samples_take);
 
291
 
292
- for (int i = 0; i < n_samples_take; i++) {
293
- pcmf32[i] = pcmf32_old[pcmf32_old.size() - n_samples_take + i];
294
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
295
 
296
- SDL_DequeueAudio(g_dev_id_in, pcmf32.data() + n_samples_take, n_samples_new*sizeof(float));
297
 
298
- pcmf32_old = pcmf32;
 
 
 
 
 
 
 
 
 
299
 
300
  // run the inference
301
  {
@@ -307,7 +603,7 @@ int main(int argc, char ** argv) {
307
  wparams.print_timestamps = !params.no_timestamps;
308
  wparams.translate = params.translate;
309
  wparams.no_context = true;
310
- wparams.single_segment = true;
311
  wparams.max_tokens = params.max_tokens;
312
  wparams.language = params.language.c_str();
313
  wparams.n_threads = params.n_threads;
@@ -325,12 +621,21 @@ int main(int argc, char ** argv) {
325
 
326
  // print result;
327
  {
328
- printf("\33[2K\r");
 
329
 
330
- // print long empty line to clear the previous line
331
- printf("%s", std::string(100, ' ').c_str());
332
 
333
- printf("\33[2K\r");
 
 
 
 
 
 
 
 
334
 
335
  const int n_segments = whisper_full_n_segments(ctx);
336
  for (int i = 0; i < n_segments; ++i) {
@@ -358,11 +663,16 @@ int main(int argc, char ** argv) {
358
  if (params.fname_out.length() > 0) {
359
  fout << std::endl;
360
  }
 
 
 
 
 
361
  }
362
 
363
  ++n_iter;
364
 
365
- if ((n_iter % n_new_line) == 0) {
366
  printf("\n");
367
 
368
  // keep part of the audio for next iteration to try to mitigate word boundary issues
@@ -384,9 +694,7 @@ int main(int argc, char ** argv) {
384
  }
385
  }
386
 
387
- if (g_dev_id_in >= 0) {
388
- SDL_CloseAudioDevice(g_dev_id_in);
389
- }
390
 
391
  whisper_print_timings(ctx);
392
  whisper_free(ctx);
 
1
  // Real-time speech recognition of input from a microphone
2
  //
3
  // A very quick-n-dirty implementation serving mainly as a proof of concept.
4
+ //
5
 
6
  #include "whisper.h"
7
 
 
34
  int32_t n_threads = std::min(4, (int32_t) std::thread::hardware_concurrency());
35
  int32_t step_ms = 3000;
36
  int32_t length_ms = 10000;
37
+ int32_t keep_ms = 200;
38
  int32_t capture_id = -1;
39
  int32_t max_tokens = 32;
40
  int32_t audio_ctx = 0;
41
 
42
+ float vad_thold = 0.6f;
43
+ float freq_thold = 100.0f;
44
+
45
  bool speed_up = false;
46
  bool translate = false;
 
47
  bool print_special = false;
48
+ bool no_context = true;
49
+ bool no_timestamps = false;
50
 
51
  std::string language = "en";
52
  std::string model = "models/ggml-base.en.bin";
 
66
  else if (arg == "-t" || arg == "--threads") { params.n_threads = std::stoi(argv[++i]); }
67
  else if ( arg == "--step") { params.step_ms = std::stoi(argv[++i]); }
68
  else if ( arg == "--length") { params.length_ms = std::stoi(argv[++i]); }
69
+ else if ( arg == "--keep") { params.keep_ms = std::stoi(argv[++i]); }
70
  else if (arg == "-c" || arg == "--capture") { params.capture_id = std::stoi(argv[++i]); }
71
  else if (arg == "-mt" || arg == "--max-tokens") { params.max_tokens = std::stoi(argv[++i]); }
72
  else if (arg == "-ac" || arg == "--audio-ctx") { params.audio_ctx = std::stoi(argv[++i]); }
73
+ else if (arg == "-vth" || arg == "--vad-thold") { params.vad_thold = std::stof(argv[++i]); }
74
+ else if (arg == "-fth" || arg == "--freq-thold") { params.freq_thold = std::stof(argv[++i]); }
75
  else if (arg == "-su" || arg == "--speed-up") { params.speed_up = true; }
76
  else if (arg == "-tr" || arg == "--translate") { params.translate = true; }
 
77
  else if (arg == "-ps" || arg == "--print-special") { params.print_special = true; }
78
+ else if (arg == "-kc" || arg == "--keep-context") { params.no_context = false; }
79
  else if (arg == "-l" || arg == "--language") { params.language = argv[++i]; }
80
  else if (arg == "-m" || arg == "--model") { params.model = argv[++i]; }
81
  else if (arg == "-f" || arg == "--file") { params.fname_out = argv[++i]; }
 
98
  fprintf(stderr, " -t N, --threads N [%-7d] number of threads to use during computation\n", params.n_threads);
99
  fprintf(stderr, " --step N [%-7d] audio step size in milliseconds\n", params.step_ms);
100
  fprintf(stderr, " --length N [%-7d] audio length in milliseconds\n", params.length_ms);
101
+ fprintf(stderr, " --keep N [%-7d] audio to keep from previous step in ms\n", params.keep_ms);
102
  fprintf(stderr, " -c ID, --capture ID [%-7d] capture device ID\n", params.capture_id);
103
  fprintf(stderr, " -mt N, --max-tokens N [%-7d] maximum number of tokens per audio chunk\n", params.max_tokens);
104
  fprintf(stderr, " -ac N, --audio-ctx N [%-7d] audio context size (0 - all)\n", params.audio_ctx);
105
+ fprintf(stderr, " -vth N, --vad-thold N [%-7.2f] voice activity detection threshold\n", params.vad_thold);
106
+ fprintf(stderr, " -fth N, --freq-thold N [%-7.2f] high-pass frequency cutoff\n", params.freq_thold);
107
  fprintf(stderr, " -su, --speed-up [%-7s] speed up audio by x2 (reduced accuracy)\n", params.speed_up ? "true" : "false");
108
  fprintf(stderr, " -tr, --translate [%-7s] translate from source language to english\n", params.translate ? "true" : "false");
 
109
  fprintf(stderr, " -ps, --print-special [%-7s] print special tokens\n", params.print_special ? "true" : "false");
110
+ fprintf(stderr, " -kc, --keep-context [%-7s] keep context between audio chunks\n", params.no_context ? "false" : "true");
111
  fprintf(stderr, " -l LANG, --language LANG [%-7s] spoken language\n", params.language.c_str());
112
  fprintf(stderr, " -m FNAME, --model FNAME [%-7s] model path\n", params.model.c_str());
113
  fprintf(stderr, " -f FNAME, --file FNAME [%-7s] text output file name\n", params.fname_out.c_str());
 
118
  // SDL Audio capture
119
  //
120
 
121
+ class audio_async {
122
+ public:
123
+ audio_async(int len_ms);
124
+ ~audio_async();
125
 
126
+ bool init(int capture_id, int sample_rate);
127
+
128
+ // start capturing audio via the provided SDL callback
129
+ // keep last len_ms seconds of audio in a circular buffer
130
+ bool resume();
131
+ bool pause();
132
+ bool clear();
133
+
134
+ // callback to be called by SDL
135
+ void callback(uint8_t * stream, int len);
136
+
137
+ // get audio data from the circular buffer
138
+ void get(int ms, std::vector<float> & audio);
139
+
140
+ private:
141
+ SDL_AudioDeviceID m_dev_id_in = 0;
142
+
143
+ int m_len_ms = 0;
144
+ int m_sample_rate = 0;
145
+
146
+ bool m_running = false;
147
+ std::mutex m_mutex;
148
+
149
+ std::vector<float> m_audio;
150
+ std::vector<float> m_audio_new;
151
+ size_t m_audio_pos = 0;
152
+ size_t m_audio_len = 0;
153
+ };
154
+
155
+ audio_async::audio_async(int len_ms) {
156
+ m_len_ms = len_ms;
157
+ }
158
+
159
+ audio_async::~audio_async() {
160
+ if (m_dev_id_in) {
161
+ SDL_CloseAudioDevice(m_dev_id_in);
162
  }
163
+ }
164
 
165
+ bool audio_async::init(int capture_id, int sample_rate) {
166
  SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
167
 
168
  if (SDL_Init(SDL_INIT_AUDIO) < 0) {
169
  SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError());
170
+ return false;
171
  }
172
 
173
  SDL_SetHintWithPriority(SDL_HINT_AUDIO_RESAMPLING_MODE, "medium", SDL_HINT_OVERRIDE);
 
186
  SDL_zero(capture_spec_requested);
187
  SDL_zero(capture_spec_obtained);
188
 
189
+ capture_spec_requested.freq = sample_rate;
190
  capture_spec_requested.format = AUDIO_F32;
191
  capture_spec_requested.channels = 1;
192
  capture_spec_requested.samples = 1024;
193
+ capture_spec_requested.callback = [](void * userdata, uint8_t * stream, int len) {
194
+ audio_async * audio = (audio_async *) userdata;
195
+ audio->callback(stream, len);
196
+ };
197
+ capture_spec_requested.userdata = this;
198
 
199
  if (capture_id >= 0) {
200
  fprintf(stderr, "%s: attempt to open capture device %d : '%s' ...\n", __func__, capture_id, SDL_GetAudioDeviceName(capture_id, SDL_TRUE));
201
+ m_dev_id_in = SDL_OpenAudioDevice(SDL_GetAudioDeviceName(capture_id, SDL_TRUE), SDL_TRUE, &capture_spec_requested, &capture_spec_obtained, 0);
202
  } else {
203
  fprintf(stderr, "%s: attempt to open default capture device ...\n", __func__);
204
+ m_dev_id_in = SDL_OpenAudioDevice(nullptr, SDL_TRUE, &capture_spec_requested, &capture_spec_obtained, 0);
205
  }
206
+
207
+ if (!m_dev_id_in) {
208
  fprintf(stderr, "%s: couldn't open an audio device for capture: %s!\n", __func__, SDL_GetError());
209
+ m_dev_id_in = 0;
210
+
211
+ return false;
212
  } else {
213
+ fprintf(stderr, "%s: obtained spec for input device (SDL Id = %d):\n", __func__, m_dev_id_in);
214
+ fprintf(stderr, "%s: - sample rate: %d\n", __func__, capture_spec_obtained.freq);
215
+ fprintf(stderr, "%s: - format: %d (required: %d)\n", __func__, capture_spec_obtained.format,
216
+ capture_spec_requested.format);
217
+ fprintf(stderr, "%s: - channels: %d (required: %d)\n", __func__, capture_spec_obtained.channels,
218
+ capture_spec_requested.channels);
219
+ fprintf(stderr, "%s: - samples per frame: %d\n", __func__, capture_spec_obtained.samples);
220
+ }
221
+
222
+ m_sample_rate = capture_spec_obtained.freq;
223
+
224
+ m_audio.resize((m_sample_rate*m_len_ms)/1000);
225
+
226
+ return true;
227
+ }
228
+
229
+ bool audio_async::resume() {
230
+ if (!m_dev_id_in) {
231
+ fprintf(stderr, "%s: no audio device to resume!\n", __func__);
232
+ return false;
233
+ }
234
+
235
+ if (m_running) {
236
+ fprintf(stderr, "%s: already running!\n", __func__);
237
+ return false;
238
+ }
239
+
240
+ SDL_PauseAudioDevice(m_dev_id_in, 0);
241
+
242
+ m_running = true;
243
+
244
+ return true;
245
+ }
246
+
247
+ bool audio_async::pause() {
248
+ if (!m_dev_id_in) {
249
+ fprintf(stderr, "%s: no audio device to pause!\n", __func__);
250
+ return false;
251
+ }
252
+
253
+ if (!m_running) {
254
+ fprintf(stderr, "%s: already paused!\n", __func__);
255
+ return false;
256
+ }
257
+
258
+ SDL_PauseAudioDevice(m_dev_id_in, 1);
259
+
260
+ m_running = false;
261
+
262
+ return true;
263
+ }
264
+
265
+ bool audio_async::clear() {
266
+ if (!m_dev_id_in) {
267
+ fprintf(stderr, "%s: no audio device to clear!\n", __func__);
268
+ return false;
269
+ }
270
+
271
+ if (!m_running) {
272
+ fprintf(stderr, "%s: not running!\n", __func__);
273
+ return false;
274
+ }
275
+
276
+ {
277
+ std::lock_guard<std::mutex> lock(m_mutex);
278
+
279
+ m_audio_pos = 0;
280
+ m_audio_len = 0;
281
  }
282
 
283
  return true;
284
  }
285
 
286
+ // callback to be called by SDL
287
+ void audio_async::callback(uint8_t * stream, int len) {
288
+ if (!m_running) {
289
+ return;
290
+ }
291
+
292
+ const size_t n_samples = len / sizeof(float);
293
+
294
+ m_audio_new.resize(n_samples);
295
+ memcpy(m_audio_new.data(), stream, n_samples * sizeof(float));
296
+
297
+ //fprintf(stderr, "%s: %zu samples, pos %zu, len %zu\n", __func__, n_samples, m_audio_pos, m_audio_len);
298
+
299
+ {
300
+ std::lock_guard<std::mutex> lock(m_mutex);
301
+
302
+ if (m_audio_pos + n_samples > m_audio.size()) {
303
+ const size_t n0 = m_audio.size() - m_audio_pos;
304
+
305
+ memcpy(&m_audio[m_audio_pos], stream, n0 * sizeof(float));
306
+ memcpy(&m_audio[0], &stream[n0], (n_samples - n0) * sizeof(float));
307
+
308
+ m_audio_pos = (m_audio_pos + n_samples) % m_audio.size();
309
+ m_audio_len = m_audio.size();
310
+ } else {
311
+ memcpy(&m_audio[m_audio_pos], stream, n_samples * sizeof(float));
312
+
313
+ m_audio_pos = (m_audio_pos + n_samples) % m_audio.size();
314
+ m_audio_len = std::min(m_audio_len + n_samples, m_audio.size());
315
+ }
316
+ }
317
+ }
318
+
319
+ void audio_async::get(int ms, std::vector<float> & result) {
320
+ if (!m_dev_id_in) {
321
+ fprintf(stderr, "%s: no audio device to get audio from!\n", __func__);
322
+ return;
323
+ }
324
+
325
+ if (!m_running) {
326
+ fprintf(stderr, "%s: not running!\n", __func__);
327
+ return;
328
+ }
329
+
330
+ result.clear();
331
+
332
+ {
333
+ std::lock_guard<std::mutex> lock(m_mutex);
334
+
335
+ if (ms <= 0) {
336
+ ms = m_len_ms;
337
+ }
338
+
339
+ size_t n_samples = (m_sample_rate * ms) / 1000;
340
+ if (n_samples > m_audio_len) {
341
+ n_samples = m_audio_len;
342
+ }
343
+
344
+ result.resize(n_samples);
345
+
346
+ int s0 = m_audio_pos - n_samples;
347
+ if (s0 < 0) {
348
+ s0 += m_audio.size();
349
+ }
350
+
351
+ if (s0 + n_samples > m_audio.size()) {
352
+ const size_t n0 = m_audio.size() - s0;
353
+
354
+ memcpy(result.data(), &m_audio[s0], n0 * sizeof(float));
355
+ memcpy(&result[n0], &m_audio[0], (n_samples - n0) * sizeof(float));
356
+ } else {
357
+ memcpy(result.data(), &m_audio[s0], n_samples * sizeof(float));
358
+ }
359
+ }
360
+ }
361
+
362
  ///////////////////////////
363
 
364
+ void high_pass_filter(std::vector<float> & data, float cutoff, float sample_rate) {
365
+ const float rc = 1.0f / (2.0f * M_PI * cutoff);
366
+ const float dt = 1.0f / sample_rate;
367
+ const float alpha = dt / (rc + dt);
368
+
369
+ float y = data[0];
370
+
371
+ for (size_t i = 1; i < data.size(); i++) {
372
+ y = alpha * (y + data[i] - data[i - 1]);
373
+ data[i] = y;
374
+ }
375
+ }
376
+
377
+ bool vad_simple(std::vector<float> & pcmf32, int sample_rate, int last_ms, float vad_thold, float freq_thold, bool verbose) {
378
+ const int n_samples = pcmf32.size();
379
+ const int n_samples_last = (sample_rate * last_ms) / 1000;
380
+
381
+ if (n_samples_last >= n_samples) {
382
+ // not enough samples - assume no speech
383
+ return false;
384
+ }
385
+
386
+ if (freq_thold > 0.0f) {
387
+ high_pass_filter(pcmf32, freq_thold, sample_rate);
388
+ }
389
+
390
+ float energy_all = 0.0f;
391
+ float energy_last = 0.0f;
392
+
393
+ for (size_t i = 0; i < n_samples; i++) {
394
+ energy_all += fabsf(pcmf32[i]);
395
+
396
+ if (i >= n_samples - n_samples_last) {
397
+ energy_last += fabsf(pcmf32[i]);
398
+ }
399
+ }
400
+
401
+ energy_all /= n_samples;
402
+ energy_last /= n_samples_last;
403
+
404
+ if (verbose) {
405
+ fprintf(stderr, "%s: energy_all: %f, energy_last: %f, vad_thold: %f, freq_thold: %f\n", __func__, energy_all, energy_last, vad_thold, freq_thold);
406
+ }
407
+
408
+ if (energy_last > vad_thold*energy_all) {
409
+ return false;
410
+ }
411
+
412
+ return true;
413
+ }
414
+
415
  int main(int argc, char ** argv) {
416
  whisper_params params;
417
 
 
419
  return 1;
420
  }
421
 
422
+ params.keep_ms = std::min(params.keep_ms, params.step_ms); // cannot be more than step_ms
423
+
424
+ const int n_samples_step = (params.step_ms *1e-3)*WHISPER_SAMPLE_RATE;
425
+ const int n_samples_len = (params.length_ms*1e-3)*WHISPER_SAMPLE_RATE;
426
+ const int n_samples_keep = (params.keep_ms *1e-3)*WHISPER_SAMPLE_RATE;
427
+ const int n_samples_30s = (30000 *1e-3)*WHISPER_SAMPLE_RATE;
428
+
429
+ const int n_new_line = params.length_ms / params.step_ms - 1; // number of steps to print new line
430
+
431
+ const bool use_vad = n_samples_step <= 0;
432
+
433
+ params.no_timestamps = !use_vad;
434
+ params.no_context = use_vad;
435
+ params.max_tokens = 0;
436
+
437
  // init audio
438
 
439
+ audio_async audio(params.length_ms);
440
+ if (!audio.init(params.capture_id, WHISPER_SAMPLE_RATE)) {
441
+ fprintf(stderr, "%s: audio.init() failed!\n", __func__);
442
  return 1;
443
  }
444
 
445
+ audio.resume();
446
+
447
+ // whisper init
448
+
449
  if (whisper_lang_id(params.language.c_str()) == -1) {
450
  fprintf(stderr, "error: unknown language '%s'\n", params.language.c_str());
451
  whisper_print_usage(argc, argv, params);
452
  exit(0);
453
  }
454
 
 
 
455
  struct whisper_context * ctx = whisper_init(params.model.c_str());
456
 
457
+ std::vector<float> pcmf32 (n_samples_30s, 0.0f);
458
+ std::vector<float> pcmf32_old(n_samples_30s, 0.0f);
459
+ std::vector<float> pcmf32_new(n_samples_30s, 0.0f);
 
 
 
 
460
 
461
  std::vector<whisper_token> prompt_tokens;
 
462
 
463
  // print some info about the processing
464
  {
 
470
  fprintf(stderr, "%s: WARNING: model is not multilingual, ignoring language and translation options\n", __func__);
471
  }
472
  }
473
+ fprintf(stderr, "%s: processing %d samples (step = %.1f sec / len = %.1f sec / keep = %.1f sec), %d threads, lang = %s, task = %s, timestamps = %d ...\n",
474
  __func__,
475
+ n_samples_step,
476
+ float(n_samples_step)/WHISPER_SAMPLE_RATE,
477
+ float(n_samples_len )/WHISPER_SAMPLE_RATE,
478
+ float(n_samples_keep)/WHISPER_SAMPLE_RATE,
479
  params.n_threads,
480
  params.language.c_str(),
481
  params.translate ? "translate" : "transcribe",
482
  params.no_timestamps ? 0 : 1);
483
 
484
+ if (!use_vad) {
485
+ fprintf(stderr, "%s: n_new_line = %d\n", __func__, n_new_line);
486
+ } else {
487
+ fprintf(stderr, "%s: using VAD, will transcribe on speech activity\n", __func__);
488
+ }
489
+
490
  fprintf(stderr, "\n");
491
  }
492
 
 
 
493
  int n_iter = 0;
494
+
495
  bool is_running = true;
496
 
497
  std::ofstream fout;
 
506
  printf("[Start speaking]");
507
  fflush(stdout);
508
 
509
+ auto t_last = std::chrono::high_resolution_clock::now();
510
+ const auto t_start = t_last;
511
+
512
  // main audio loop
513
  while (is_running) {
514
  // handle Ctrl + C
 
535
  }
536
 
537
  // process new audio
 
 
 
 
538
 
539
+ if (!use_vad) {
540
+ while (true) {
541
+ audio.get(params.step_ms, pcmf32_new);
542
 
543
+ if ((int) pcmf32_new.size() > 2*n_samples_step) {
544
+ fprintf(stderr, "\n\n%s: WARNING: cannot process audio fast enough, dropping audio ...\n\n", __func__);
545
+ audio.clear();
546
+ continue;
547
+ }
548
 
549
+ if ((int) pcmf32_new.size() >= n_samples_step) {
550
+ audio.clear();
551
+ break;
552
+ }
553
 
554
+ SDL_Delay(1);
555
+ }
556
 
557
+ const int n_samples_new = pcmf32_new.size();
558
 
559
+ // take up to params.length_ms audio from previous iteration
560
+ const int n_samples_take = std::min((int) pcmf32_old.size(), std::max(0, n_samples_keep + n_samples_len - n_samples_new));
561
 
562
+ //printf("processing: take = %d, new = %d, old = %d\n", n_samples_take, n_samples_new, (int) pcmf32_old.size());
563
+
564
+ pcmf32.resize(n_samples_new + n_samples_take);
565
+
566
+ for (int i = 0; i < n_samples_take; i++) {
567
+ pcmf32[i] = pcmf32_old[pcmf32_old.size() - n_samples_take + i];
568
+ }
569
+
570
+ memcpy(pcmf32.data() + n_samples_take, pcmf32_new.data(), n_samples_new*sizeof(float));
571
+
572
+ pcmf32_old = pcmf32;
573
+ } else {
574
+ const auto t_now = std::chrono::high_resolution_clock::now();
575
+ const auto t_diff = std::chrono::duration_cast<std::chrono::milliseconds>(t_now - t_last).count();
576
+
577
+ if (t_diff < 2000) {
578
+ std::this_thread::sleep_for(std::chrono::milliseconds(100));
579
+
580
+ continue;
581
+ }
582
 
583
+ audio.get(2000, pcmf32_new);
584
 
585
+ if (vad_simple(pcmf32_new, WHISPER_SAMPLE_RATE, 1000, params.vad_thold, params.freq_thold, false)) {
586
+ audio.get(params.length_ms, pcmf32);
587
+ } else {
588
+ std::this_thread::sleep_for(std::chrono::milliseconds(100));
589
+
590
+ continue;
591
+ }
592
+
593
+ t_last = t_now;
594
+ }
595
 
596
  // run the inference
597
  {
 
603
  wparams.print_timestamps = !params.no_timestamps;
604
  wparams.translate = params.translate;
605
  wparams.no_context = true;
606
+ wparams.single_segment = !use_vad;
607
  wparams.max_tokens = params.max_tokens;
608
  wparams.language = params.language.c_str();
609
  wparams.n_threads = params.n_threads;
 
621
 
622
  // print result;
623
  {
624
+ if (!use_vad) {
625
+ printf("\33[2K\r");
626
 
627
+ // print long empty line to clear the previous line
628
+ printf("%s", std::string(100, ' ').c_str());
629
 
630
+ printf("\33[2K\r");
631
+ } else {
632
+ const int64_t t1 = (t_last - t_start).count()/1000000;
633
+ const int64_t t0 = std::max(0.0, t1 - pcmf32.size()*1000.0/WHISPER_SAMPLE_RATE);
634
+
635
+ printf("\n");
636
+ printf("### Transcription %d START | t0 = %lld ms | t1 = %lld ms\n", n_iter, t0, t1);
637
+ printf("\n");
638
+ }
639
 
640
  const int n_segments = whisper_full_n_segments(ctx);
641
  for (int i = 0; i < n_segments; ++i) {
 
663
  if (params.fname_out.length() > 0) {
664
  fout << std::endl;
665
  }
666
+
667
+ if (use_vad){
668
+ printf("\n");
669
+ printf("### Transcription %d END\n", n_iter);
670
+ }
671
  }
672
 
673
  ++n_iter;
674
 
675
+ if (!use_vad && (n_iter % n_new_line) == 0) {
676
  printf("\n");
677
 
678
  // keep part of the audio for next iteration to try to mitigate word boundary issues
 
694
  }
695
  }
696
 
697
+ audio.pause();
 
 
698
 
699
  whisper_print_timings(ctx);
700
  whisper_free(ctx);