ESPHome 2026.10.0-dev
Loading...
Searching...
No Matches
micro_wake_word.cpp
Go to the documentation of this file.
1#include "micro_wake_word.h"
2
3#ifdef USE_ESP32
4
6#include "esphome/core/hal.h"
8#include "esphome/core/log.h"
9
11
12#include <algorithm>
13
14#ifdef USE_OTA
16#endif
17
19
20static const char *const TAG = "micro_wake_word";
21
22static const ssize_t DETECTION_QUEUE_LENGTH = 5;
23
24static const size_t DATA_TIMEOUT_MS = 50;
25
26static const uint32_t RING_BUFFER_DURATION_MS = 120;
27
28#ifdef CONFIG_IDF_TARGET_ESP32P4
29// ESP32-P4 PIE-optimized esp-nn kernels (e.g. depthwise_conv_s8_ch1_pie) require
30// significantly more stack than other variants, causing stack protection faults at 3072.
31static const uint32_t INFERENCE_TASK_STACK_SIZE = 8192;
32#else
33static const uint32_t INFERENCE_TASK_STACK_SIZE = 3072;
34#endif
35static const UBaseType_t INFERENCE_TASK_PRIORITY = 3;
36
38 COMMAND_STOP = (1 << 0), // Signals the inference task should stop
39 COMMAND_RESET_RING_BUFFER = (1 << 1), // Signals the inference task to discard buffered audio
40 COMMAND_PAUSE_MODELS = (1 << 2), // Asks the inference task to pause at a safe point so the model lists can be
41 // mutated from the main loop
42
43 TASK_STARTING = (1 << 3),
44 TASK_RUNNING = (1 << 4),
45 TASK_STOPPING = (1 << 5),
46 TASK_STOPPED = (1 << 6),
47
48 MODELS_PAUSED = (1 << 7), // Inference task acknowledges it is paused and holds no iterators
49 COMMAND_RESUME_MODELS = (1 << 8), // Main loop signals the inference task it may resume iterating
50
51 ERROR_MEMORY = (1 << 9),
52 ERROR_INFERENCE = (1 << 10),
53
55 WARNING_MODELS_RESUME_TIMEOUT = (1 << 14), // The paused inference task gave up waiting to be released
56
58 ALL_BITS = 0xfffff, // 24 total bits available in an event group
59};
60
61// How long the main loop waits for the inference task to acknowledge a pause request before giving up.
62// The task checks for the command at the top of its loop, which runs at least every DATA_TIMEOUT_MS.
63static const uint32_t MODELS_PAUSE_TIMEOUT_MS = 500;
64// How long the paused inference task waits to be resumed before rechecking on its own. Only reached if
65// the main loop abandoned the handshake (e.g. it timed out first), so recovery just needs to be bounded.
66static const uint32_t MODELS_RESUME_TIMEOUT_MS = 1000;
67
69
70static const LogString *micro_wake_word_state_to_string(State state) {
71 switch (state) {
72 case State::STARTING:
73 return LOG_STR("STARTING");
75 return LOG_STR("DETECTING_WAKE_WORD");
76 case State::STOPPING:
77 return LOG_STR("STOPPING");
78 case State::STOPPED:
79 return LOG_STR("STOPPED");
80 default:
81 return LOG_STR("UNKNOWN");
82 }
83}
84
86 ESP_LOGCONFIG(TAG, "microWakeWord:");
87 ESP_LOGCONFIG(TAG, " models:");
88 for (auto &model : this->wake_word_models_) {
89 model->log_model_config();
90 }
91#ifdef USE_MICRO_WAKE_WORD_VAD
92 this->vad_model_->log_model_config();
93#endif
94}
95
97 this->frontend_config_.window.size_ms = FEATURE_DURATION_MS;
98 this->frontend_config_.window.step_size_ms = this->features_step_size_;
99 this->frontend_config_.filterbank.num_channels = PREPROCESSOR_FEATURE_SIZE;
100 this->frontend_config_.filterbank.lower_band_limit = FILTERBANK_LOWER_BAND_LIMIT;
101 this->frontend_config_.filterbank.upper_band_limit = FILTERBANK_UPPER_BAND_LIMIT;
102 this->frontend_config_.noise_reduction.smoothing_bits = NOISE_REDUCTION_SMOOTHING_BITS;
103 this->frontend_config_.noise_reduction.even_smoothing = NOISE_REDUCTION_EVEN_SMOOTHING;
104 this->frontend_config_.noise_reduction.odd_smoothing = NOISE_REDUCTION_ODD_SMOOTHING;
105 this->frontend_config_.noise_reduction.min_signal_remaining = NOISE_REDUCTION_MIN_SIGNAL_REMAINING;
106 this->frontend_config_.pcan_gain_control.enable_pcan = PCAN_GAIN_CONTROL_ENABLE_PCAN;
107 this->frontend_config_.pcan_gain_control.strength = PCAN_GAIN_CONTROL_STRENGTH;
108 this->frontend_config_.pcan_gain_control.offset = PCAN_GAIN_CONTROL_OFFSET;
109 this->frontend_config_.pcan_gain_control.gain_bits = PCAN_GAIN_CONTROL_GAIN_BITS;
110 this->frontend_config_.log_scale.enable_log = LOG_SCALE_ENABLE_LOG;
111 this->frontend_config_.log_scale.scale_shift = LOG_SCALE_SCALE_SHIFT;
112
113 this->event_group_ = xEventGroupCreate();
114 if (this->event_group_ == nullptr) {
115 ESP_LOGE(TAG, "Failed to create event group");
116 this->mark_failed();
117 return;
118 }
119
120 this->detection_queue_ = xQueueCreate(DETECTION_QUEUE_LENGTH, sizeof(DetectionEvent));
121 if (this->detection_queue_ == nullptr) {
122 ESP_LOGE(TAG, "Failed to create detection event queue");
123 this->mark_failed();
124 return;
125 }
126
127 this->microphone_source_->add_data_callback([this](const std::vector<uint8_t> &data) {
128 if (this->state_ == State::STOPPED) {
129 return;
130 }
131 std::shared_ptr<ring_buffer::RingBuffer> temp_ring_buffer = this->ring_buffer_.lock();
132 if (temp_ring_buffer != nullptr) {
133 // Producer-only write: never touches consumer state. If the buffer is full, ask the inference task
134 // to drain it - reset() is a consumer operation and must run on the inference task's thread.
135 // Disable partial writes so audio chunks are either fully accepted or rejected and handled below.
136 if (temp_ring_buffer->write_without_replacement(data.data(), data.size(), 0, false) == 0) {
137 xEventGroupSetBits(this->event_group_,
139 }
140 }
141 });
142
143#ifdef USE_OTA_STATE_LISTENER
145#endif
146}
147
148#ifdef USE_OTA_STATE_LISTENER
149void MicroWakeWord::on_ota_global_state(ota::OTAState state, float progress, uint8_t error, ota::OTAComponent *comp) {
150 if (state == ota::OTA_STARTED) {
151 this->suspend_task_();
152 } else if (state == ota::OTA_ERROR) {
153 this->resume_task_();
154 }
155}
156#endif
157
159 MicroWakeWord *this_mww = (MicroWakeWord *) params;
160
161 xEventGroupSetBits(this_mww->event_group_, EventGroupBits::TASK_STARTING);
162
163 { // Ensures any C++ objects fall out of scope to deallocate before deleting the task
164
165 const auto &stream_info = this_mww->microphone_source_->get_audio_stream_info();
166 const size_t bytes_per_frame = stream_info.frames_to_bytes(1);
167 const size_t max_fill_bytes = stream_info.ms_to_bytes(this_mww->features_step_size_);
168 std::unique_ptr<audio::RingBufferAudioSource> audio_source;
169 int8_t features_buffer[PREPROCESSOR_FEATURE_SIZE];
170
171 if (!(xEventGroupGetBits(this_mww->event_group_) & ERROR_BITS)) {
172 // Round ring buffer size down to a frame multiple so the wrap boundary never splits an int16 sample.
173 const size_t ring_buffer_size =
174 (stream_info.ms_to_bytes(RING_BUFFER_DURATION_MS) / bytes_per_frame) * bytes_per_frame;
175 std::shared_ptr<ring_buffer::RingBuffer> temp_ring_buffer = ring_buffer::RingBuffer::create(ring_buffer_size);
176 if (temp_ring_buffer == nullptr) {
177 xEventGroupSetBits(this_mww->event_group_, EventGroupBits::ERROR_MEMORY);
178 } else {
179 audio_source = audio::RingBufferAudioSource::create(temp_ring_buffer, max_fill_bytes,
180 static_cast<uint8_t>(bytes_per_frame));
181 if (audio_source == nullptr) {
182 xEventGroupSetBits(this_mww->event_group_, EventGroupBits::ERROR_MEMORY);
183 } else {
184 this_mww->ring_buffer_ = temp_ring_buffer;
185 }
186 }
187 }
188
189 if (!(xEventGroupGetBits(this_mww->event_group_) & ERROR_BITS)) {
190 this_mww->microphone_source_->start();
191 xEventGroupSetBits(this_mww->event_group_, EventGroupBits::TASK_RUNNING);
192
193 while (!(xEventGroupGetBits(this_mww->event_group_) & (COMMAND_STOP | ERROR_BITS))) {
194 if (xEventGroupGetBits(this_mww->event_group_) & EventGroupBits::COMMAND_PAUSE_MODELS) {
195 // Safe point: no iterators into wake_word_models_ are held here. Acknowledge the pause and wait for the
196 // main loop to finish mutating the model lists before resuming.
197 xEventGroupSetBits(this_mww->event_group_, EventGroupBits::MODELS_PAUSED);
198 EventBits_t resume_bits = xEventGroupWaitBits(this_mww->event_group_, EventGroupBits::COMMAND_RESUME_MODELS,
199 pdTRUE, pdTRUE, pdMS_TO_TICKS(MODELS_RESUME_TIMEOUT_MS));
200 if (!(resume_bits & EventGroupBits::COMMAND_RESUME_MODELS)) {
201 // Nobody released us, so the main loop abandoned the handshake and did not mutate the lists.
202 // Rechecking the pause command below is safe, but the wait cost a second of detection, so report it.
203 xEventGroupSetBits(this_mww->event_group_, EventGroupBits::WARNING_MODELS_RESUME_TIMEOUT);
204 }
205 continue;
206 }
207
208 if (xEventGroupGetBits(this_mww->event_group_) & EventGroupBits::COMMAND_RESET_RING_BUFFER) {
209 // Producer asked us to drain; run the consumer-side reset from this thread.
210 audio_source->clear_buffered_data();
211 xEventGroupClearBits(this_mww->event_group_, EventGroupBits::COMMAND_RESET_RING_BUFFER);
212 }
213
214 audio_source->fill(pdMS_TO_TICKS(DATA_TIMEOUT_MS), false);
215
216 // The frontend buffers samples internally and only emits a feature once it has a full window, so we can
217 // hand it whatever the source exposes. The frontend consumes at least one sample per call, so available()
218 // strictly decreases and this loop always terminates.
219 while (audio_source->available() >= sizeof(int16_t)) {
220 const size_t samples_available = audio_source->available() / sizeof(int16_t);
221 const int16_t *audio_data = reinterpret_cast<const int16_t *>(audio_source->data());
222
223 size_t processed_samples = 0;
224 const bool feature_generated =
225 this_mww->generate_features_(audio_data, samples_available, features_buffer, &processed_samples);
226 audio_source->consume(processed_samples * sizeof(int16_t));
227
228 if (feature_generated) {
229 if (!this_mww->update_model_probabilities_(features_buffer)) {
230 xEventGroupSetBits(this_mww->event_group_, EventGroupBits::ERROR_INFERENCE);
231 break;
232 }
233
234 // Process each model's probabilities and possibly send a Detection Event to the queue
235 this_mww->process_probabilities_();
236 }
237 }
238 }
239 }
240 }
241
242 xEventGroupSetBits(this_mww->event_group_, EventGroupBits::TASK_STOPPING);
243
244 this_mww->unload_models_();
245 this_mww->microphone_source_->stop();
246 FrontendFreeStateContents(&this_mww->frontend_state_);
247
248 xEventGroupSetBits(this_mww->event_group_, EventGroupBits::TASK_STOPPED);
249 vTaskSuspend(nullptr); // Suspend this task indefinitely until the loop method deletes it
250}
251
252std::vector<WakeWordModel *> MicroWakeWord::get_wake_words() {
253 std::vector<WakeWordModel *> external_wake_word_models;
254 for (auto *model : this->wake_word_models_) {
255 if (!model->get_internal_only()) {
256 external_wake_word_models.push_back(model);
257 }
258 }
259 return external_wake_word_models;
260}
261
263
265 // When the inference task isn't running it holds no iterators into wake_word_models_, so the lists can be
266 // mutated without a handshake. The main loop is the only caller, so this state cannot change between here
267 // and the matching unlock_models_() call.
268 if (!this->inference_task_.is_created() || this->state_ == State::STOPPED) {
269 return true;
270 }
271
272 // The task is running and iterates wake_word_models_. Ask it to pause at a safe point before we mutate.
273 // Clear any stale acknowledgement from an abandoned handshake first.
274 xEventGroupClearBits(this->event_group_, EventGroupBits::MODELS_PAUSED);
275 xEventGroupSetBits(this->event_group_, EventGroupBits::COMMAND_PAUSE_MODELS);
276
277 EventBits_t bits = xEventGroupWaitBits(this->event_group_, EventGroupBits::MODELS_PAUSED, pdFALSE, pdTRUE,
278 pdMS_TO_TICKS(MODELS_PAUSE_TIMEOUT_MS));
279
280 if (!(bits & EventGroupBits::MODELS_PAUSED)) {
281 // The task never acknowledged (e.g. it is busy stopping). Withdraw the request and refuse to mutate a
282 // list it might be iterating.
283 xEventGroupClearBits(this->event_group_, EventGroupBits::COMMAND_PAUSE_MODELS);
284 return false;
285 }
286 return true;
287}
288
290 if (!this->inference_task_.is_created() || this->state_ == State::STOPPED) {
291 return; // Nothing was paused
292 }
294 xEventGroupSetBits(this->event_group_, EventGroupBits::COMMAND_RESUME_MODELS);
295}
296
297bool MicroWakeWord::add_runtime_model(std::unique_ptr<WakeWordModel> model) {
298 if (!model) {
299 ESP_LOGE(TAG, "Cannot add null runtime model");
300 return false;
301 }
302
303 const std::string model_id = model->get_id();
304
305 // A model without usable data can never load, so keep it out of the lists entirely. Otherwise it would be
306 // advertised to Home Assistant as selectable and the inference task would silently disable it again every
307 // time it was enabled.
308 if (!model->has_model_data()) {
309 ESP_LOGE(TAG, "Runtime model '%s' has no valid data", model_id.c_str());
310 return false;
311 }
312
313 // Reject a duplicate id against every model (compiled or runtime). The inference task only ever reads
314 // wake_word_models_, so scanning it here (on the main loop) needs no synchronization.
315 for (auto *existing : this->wake_word_models_) {
316 if (existing->get_id() == model_id) {
317 ESP_LOGW(TAG, "Wake word model '%s' already exists", model_id.c_str());
318 return false;
319 }
320 }
321
322 if (!this->try_lock_models_()) {
323 ESP_LOGE(TAG, "Timed out pausing inference task; not adding runtime model '%s'", model_id.c_str());
324 return false;
325 }
326
327 this->wake_word_models_.push_back(model.get());
328 this->runtime_models_.push_back(std::move(model));
329
330 this->unlock_models_();
331 ESP_LOGD(TAG, "Added runtime model '%s'", model_id.c_str());
332 return true;
333}
334
335bool MicroWakeWord::remove_runtime_model(const std::string &model_id) {
336 // Only runtime-downloaded models can be removed; compiled-in models never appear in runtime_models_.
337 auto runtime_it =
338 std::find_if(this->runtime_models_.begin(), this->runtime_models_.end(),
339 [&model_id](const std::unique_ptr<WakeWordModel> &m) { return m->get_id() == model_id; });
340 if (runtime_it == this->runtime_models_.end()) {
341 return false;
342 }
343
344 if (!this->try_lock_models_()) {
345 ESP_LOGE(TAG, "Timed out pausing inference task; not removing runtime model '%s'", model_id.c_str());
346 return false;
347 }
348
349 WakeWordModel *raw = runtime_it->get();
350 auto models_it = std::find(this->wake_word_models_.begin(), this->wake_word_models_.end(), raw);
351 if (models_it != this->wake_word_models_.end()) {
352 this->wake_word_models_.erase(models_it);
353 }
354
355 // Queued detection events hold a pointer into the model being destroyed, so drop them. The inference task
356 // is parked, so no new events can be queued concurrently. Losing an undelivered detection from another
357 // model is acceptable for this rare operation.
358 xQueueReset(this->detection_queue_);
359
360 // Free the interpreter and arenas (safe: the task is parked, not mid-inference), then destroy the model.
361 // Its ModelData releases the PSRAM model buffer once the last shared_ptr reference drops.
362 raw->unload_model();
363 this->runtime_models_.erase(runtime_it);
364
365 this->unlock_models_();
366 ESP_LOGI(TAG, "Removed runtime model '%s'", model_id.c_str());
367 return true;
368}
369
370std::vector<std::string> MicroWakeWord::get_runtime_model_ids() {
371 std::vector<std::string> ids;
372 ids.reserve(this->runtime_models_.size());
373 for (const auto &model : this->runtime_models_) {
374 ids.push_back(model->get_id());
375 }
376 return ids;
377}
378
379WakeWordModel *MicroWakeWord::get_model_by_id(const std::string &model_id) {
380 for (auto *model : this->wake_word_models_) {
381 if (model->get_id() == model_id) {
382 return model;
383 }
384 }
385 return nullptr;
386}
387
388#ifdef USE_MICRO_WAKE_WORD_VAD
389void MicroWakeWord::add_vad_model(const uint8_t *model_start, uint8_t probability_cutoff, size_t sliding_window_size,
390 size_t tensor_arena_size) {
391 this->vad_model_ = make_unique<VADModel>(model_start, probability_cutoff, sliding_window_size, tensor_arena_size);
392}
393#endif
394
396 if (this->inference_task_.is_created()) {
397 vTaskSuspend(this->inference_task_.get_handle());
398 }
399}
400
402 if (this->inference_task_.is_created()) {
403 vTaskResume(this->inference_task_.get_handle());
404 }
405}
406
408 uint32_t event_group_bits = xEventGroupGetBits(this->event_group_);
409
410 if (event_group_bits & EventGroupBits::ERROR_MEMORY) {
411 xEventGroupClearBits(this->event_group_, EventGroupBits::ERROR_MEMORY);
412 ESP_LOGE(TAG, "Encountered an error allocating buffers");
413 }
414
415 if (event_group_bits & EventGroupBits::ERROR_INFERENCE) {
416 xEventGroupClearBits(this->event_group_, EventGroupBits::ERROR_INFERENCE);
417 ESP_LOGE(TAG, "Encountered an error while performing an inference");
418 }
419
420 if (event_group_bits & EventGroupBits::WARNING_FULL_RING_BUFFER) {
421 xEventGroupClearBits(this->event_group_, EventGroupBits::WARNING_FULL_RING_BUFFER);
422 ESP_LOGW(TAG, "Not enough free bytes in ring buffer to store incoming audio data. Resetting the ring buffer. Wake "
423 "word detection accuracy will temporarily be reduced.");
424 }
425
426 if (event_group_bits & EventGroupBits::WARNING_MODELS_RESUME_TIMEOUT) {
427 xEventGroupClearBits(this->event_group_, EventGroupBits::WARNING_MODELS_RESUME_TIMEOUT);
428 ESP_LOGW(TAG, "Inference task paused for %" PRIu32 " ms without being released, so it resumed on its own",
429 MODELS_RESUME_TIMEOUT_MS);
430 }
431
432 if (event_group_bits & EventGroupBits::TASK_STARTING) {
433 ESP_LOGD(TAG, "Inference task has started, attempting to allocate memory for buffers");
434 xEventGroupClearBits(this->event_group_, EventGroupBits::TASK_STARTING);
435 }
436
437 if (event_group_bits & EventGroupBits::TASK_RUNNING) {
438 ESP_LOGD(TAG, "Inference task is running");
439
440 xEventGroupClearBits(this->event_group_, EventGroupBits::TASK_RUNNING);
442 }
443
444 if (event_group_bits & EventGroupBits::TASK_STOPPING) {
445 ESP_LOGD(TAG, "Inference task is stopping, deallocating buffers");
446 xEventGroupClearBits(this->event_group_, EventGroupBits::TASK_STOPPING);
447 }
448
449 // Retries on a subsequent loop if the task is still running on the other core
450 if ((event_group_bits & EventGroupBits::TASK_STOPPED) && this->inference_task_.deallocate()) {
451 ESP_LOGD(TAG, "Inference task is finished, freeing task resources");
452 xEventGroupClearBits(this->event_group_, ALL_BITS);
453 xQueueReset(this->detection_queue_);
455 }
456
457 if ((this->pending_start_) && (this->state_ == State::STOPPED)) {
459 this->pending_start_ = false;
460 }
461
462 if ((this->pending_stop_) && (this->state_ == State::DETECTING_WAKE_WORD)) {
464 this->pending_stop_ = false;
465 }
466
467 switch (this->state_) {
468 case State::STARTING:
469 if (!this->inference_task_.is_created() && !this->status_has_error()) {
470 // Setup preprocesor feature generator. If done in the task, it would lock the task to its initial core, as it
471 // uses floating point operations.
472 if (!FrontendPopulateState(&this->frontend_config_, &this->frontend_state_,
474 this->status_momentary_error("frontend_alloc", 1000);
475 return;
476 }
477
478 if (!this->inference_task_.create(MicroWakeWord::inference_task, "mww", INFERENCE_TASK_STACK_SIZE,
479 (void *) this, INFERENCE_TASK_PRIORITY, this->task_stack_in_psram_)) {
480 FrontendFreeStateContents(&this->frontend_state_); // Deallocate frontend state
481 this->status_momentary_error("task_start", 1000);
482 }
483 }
484 break;
486 DetectionEvent detection_event;
487 while (xQueueReceive(this->detection_queue_, &detection_event, 0)) {
488 if (detection_event.blocked_by_vad) {
489 ESP_LOGD(TAG, "Wake word model predicts '%s', but VAD model doesn't.", detection_event.wake_word->c_str());
490 } else {
491 constexpr float uint8_to_float_divisor =
492 255.0f; // Converting a quantized uint8 probability to floating point
493 ESP_LOGD(TAG, "Detected '%s' with sliding average probability is %.2f and max probability is %.2f",
494 detection_event.wake_word->c_str(), (detection_event.average_probability / uint8_to_float_divisor),
495 (detection_event.max_probability / uint8_to_float_divisor));
496 this->wake_word_detected_trigger_.trigger(*detection_event.wake_word);
497 if (this->stop_after_detection_) {
498 this->stop();
499 }
500 }
501 }
502 break;
503 }
504 case State::STOPPING:
505 xEventGroupSetBits(this->event_group_, EventGroupBits::COMMAND_STOP);
506 break;
507 case State::STOPPED:
508 break;
509 }
510}
511
513 if (!this->is_ready()) {
514 ESP_LOGW(TAG, "Wake word detection can't start as the component hasn't been setup yet");
515 return;
516 }
517
518 if (this->is_failed()) {
519 ESP_LOGW(TAG, "Wake word component is marked as failed. Please check setup logs");
520 return;
521 }
522
523 if (this->is_running()) {
524 ESP_LOGW(TAG, "Wake word detection is already running");
525 return;
526 }
527
528 ESP_LOGD(TAG, "Starting wake word detection");
529
530 this->pending_start_ = true;
531 this->pending_stop_ = false;
532}
533
535 if (this->state_ == STOPPED)
536 return;
537
538 ESP_LOGD(TAG, "Stopping wake word detection");
539
540 this->pending_start_ = false;
541 this->pending_stop_ = true;
542}
543
545 if (this->state_ != state) {
546 ESP_LOGD(TAG, "State changed from %s to %s", LOG_STR_ARG(micro_wake_word_state_to_string(this->state_)),
547 LOG_STR_ARG(micro_wake_word_state_to_string(state)));
548 this->state_ = state;
549 }
550}
551
552bool MicroWakeWord::generate_features_(const int16_t *audio_buffer, size_t samples_available,
553 int8_t features_buffer[PREPROCESSOR_FEATURE_SIZE], size_t *processed_samples) {
554 *processed_samples = 0;
555 struct FrontendOutput frontend_output =
556 FrontendProcessSamples(&this->frontend_state_, audio_buffer, samples_available, processed_samples);
557
558 if (frontend_output.size == 0) {
559 return false;
560 }
561
562 for (size_t i = 0; i < frontend_output.size; ++i) {
563 // These scaling values are set to match the TFLite audio frontend int8 output.
564 // The feature pipeline outputs 16-bit signed integers in roughly a 0 to 670
565 // range. In training, these are then arbitrarily divided by 25.6 to get
566 // float values in the rough range of 0.0 to 26.0. This scaling is performed
567 // for historical reasons, to match up with the output of other feature
568 // generators.
569 // The process is then further complicated when we quantize the model. This
570 // means we have to scale the 0.0 to 26.0 real values to the -128 (INT8_MIN)
571 // to 127 (INT8_MAX) signed integer numbers.
572 // All this means that to get matching values from our integer feature
573 // output into the tensor input, we have to perform:
574 // input = (((feature / 25.6) / 26.0) * 256) - 128
575 // To simplify this and perform it in 32-bit integer math, we rearrange to:
576 // input = (feature * 256) / (25.6 * 26.0) - 128
577 constexpr int32_t value_scale = 256;
578 constexpr int32_t value_div = 666; // 666 = 25.6 * 26.0 after rounding
579 int32_t value = ((frontend_output.values[i] * value_scale) + (value_div / 2)) / value_div;
580
581 value += INT8_MIN; // Adds a -128; i.e., subtracts 128
582 features_buffer[i] = static_cast<int8_t>(clamp<int32_t>(value, INT8_MIN, INT8_MAX));
583 }
584
585 return true;
586}
587
589#ifdef USE_MICRO_WAKE_WORD_VAD
590 DetectionEvent vad_state = this->vad_model_->determine_detected();
591
592 this->vad_state_ = vad_state.detected; // atomic write, so thread safe
593#endif
594
595 for (auto &model : this->wake_word_models_) {
596 if (model->get_unprocessed_probability_status()) {
597 // Only detect wake words if there is a new probability since the last check
598 DetectionEvent wake_word_state = model->determine_detected();
599 if (wake_word_state.detected) {
600#ifdef USE_MICRO_WAKE_WORD_VAD
601 if (vad_state.detected) {
602#endif
603 xQueueSend(this->detection_queue_, &wake_word_state, portMAX_DELAY);
604
605 // Wake main loop immediately to process wake word detection
607
608 model->reset_probabilities();
609#ifdef USE_MICRO_WAKE_WORD_VAD
610 } else {
611 wake_word_state.blocked_by_vad = true;
612 xQueueSend(this->detection_queue_, &wake_word_state, portMAX_DELAY);
613 }
614#endif
615 }
616 }
617 }
618}
619
621 for (auto &model : this->wake_word_models_) {
622 model->unload_model();
623 }
624#ifdef USE_MICRO_WAKE_WORD_VAD
625 this->vad_model_->unload_model();
626#endif
627}
628
629bool MicroWakeWord::update_model_probabilities_(const int8_t audio_features[PREPROCESSOR_FEATURE_SIZE]) {
630 bool success = true;
631
632 for (auto &model : this->wake_word_models_) {
633 // Perform inference
634 success = success & model->perform_streaming_inference(audio_features);
635 }
636#ifdef USE_MICRO_WAKE_WORD_VAD
637 success = success & this->vad_model_->perform_streaming_inference(audio_features);
638#endif
639
640 return success;
641}
642
643} // namespace esphome::micro_wake_word
644
645#endif // USE_ESP32
uint8_t m
Definition bl0906.h:1
uint8_t raw[35]
Definition bl0939.h:0
void wake_loop_threadsafe()
Wake the main event loop from another thread or callback.
void mark_failed()
Mark this component as failed.
void status_momentary_error(const char *name, uint32_t length=5000)
Set error status flag and automatically clear it after a timeout.
bool is_failed() const
Definition component.h:272
bool is_ready() const
bool create(TaskFunction_t fn, const char *name, uint32_t stack_size, void *param, UBaseType_t priority, bool use_psram)
Allocate stack and create task.
bool is_created() const
Check if the task has been created and not yet destroyed.
Definition static_task.h:19
TaskHandle_t get_handle() const
Get the FreeRTOS task handle.
Definition static_task.h:22
bool deallocate()
Delete the task (if created) and free the stack buffer.
void trigger(const Ts &...x) ESPHOME_ALWAYS_INLINE
Inform the parent automation that the event has triggered.
Definition automation.h:461
size_t frames_to_bytes(uint32_t frames) const
Converts frames to bytes.
Definition audio.h:53
uint32_t get_sample_rate() const
Definition audio.h:30
static std::unique_ptr< RingBufferAudioSource > create(std::shared_ptr< ring_buffer::RingBuffer > ring_buffer, size_t max_fill_bytes, uint8_t alignment_bytes=1)
Creates a new ring-buffer-backed audio source after validating its parameters.
void resume_task_()
Resumes the inference task.
microphone::MicrophoneSource * microphone_source_
void process_probabilities_()
Processes any new probabilities for each model.
bool remove_runtime_model(const std::string &model_id)
Removes a runtime-downloaded wake word model and frees its interpreter, arenas, and model buffer.
WakeWordModel * get_model_by_id(const std::string &model_id)
Returns the wake word model with the given id, or nullptr if none matches (compiled or runtime).
std::vector< WakeWordModel * > wake_word_models_
void suspend_task_()
Suspends the inference task.
std::vector< std::string > get_runtime_model_ids()
Returns the ids of all runtime-downloaded models. Must be called from the main loop.
Trigger< std::string > wake_word_detected_trigger_
void add_wake_word_model(WakeWordModel *model)
bool generate_features_(const int16_t *audio_buffer, size_t samples_available, int8_t features_buffer[PREPROCESSOR_FEATURE_SIZE], size_t *processed_samples)
Generates a spectrogram feature from an input buffer of audio samples.
bool try_lock_models_()
Parks the inference task at a safe point (or verifies it isn't running) so the model lists may be mut...
bool add_runtime_model(std::unique_ptr< WakeWordModel > model)
Adds a runtime-downloaded wake word model.
bool update_model_probabilities_(const int8_t audio_features[PREPROCESSOR_FEATURE_SIZE])
Runs an inference with each model using the new spectrogram features.
std::vector< std::unique_ptr< WakeWordModel > > runtime_models_
std::unique_ptr< VADModel > vad_model_
std::weak_ptr< ring_buffer::RingBuffer > ring_buffer_
void unlock_models_()
Releases the inference task parked by a successful try_lock_models_() call.
void add_vad_model(const uint8_t *model_start, uint8_t probability_cutoff, size_t sliding_window_size, size_t tensor_arena_size)
void unload_models_()
Deletes each model's TFLite interpreters and frees tensor arena memory.
std::vector< WakeWordModel * > get_wake_words()
void on_ota_global_state(ota::OTAState state, float progress, uint8_t error, ota::OTAComponent *comp) override
void unload_model()
Destroys the TFLite interpreter and frees the tensor and variable arenas' memory.
void add_data_callback(F &&data_callback)
audio::AudioStreamInfo get_audio_stream_info()
Gets the AudioStreamInfo of the data after processing.
void add_global_state_listener(OTAGlobalStateListener *listener)
static std::unique_ptr< RingBuffer > create(size_t len, MemoryPreference preference=MemoryPreference::EXTERNAL_FIRST)
bool state
Definition fan.h:2
__int64 ssize_t
Definition httplib.h:178
OTAGlobalCallback * get_global_ota_callback()
constexpr float AFTER_CONNECTION
For components that should be initialized after a data connection (API/MQTT) is connected.
Definition component.h:57
Application App
Global storage of Application pointer - only one Application can exist.
static void uint32_t