104 lines
2.8 KiB
C++
104 lines
2.8 KiB
C++
#include "audio/wake_word_detector.h"
|
|
|
|
#include <esp_log.h>
|
|
#include <esp_wn_iface.h>
|
|
#include <esp_wn_models.h>
|
|
#include <model_path.h>
|
|
|
|
#include <cstdio>
|
|
|
|
namespace borla {
|
|
namespace {
|
|
|
|
constexpr const char* kTag = "WakeWord2";
|
|
constexpr const char* kBorlaModelHint = "ni3hao3bo1le4";
|
|
|
|
} // namespace
|
|
|
|
WakeWordDetector::~WakeWordDetector()
|
|
{
|
|
Deinitialize();
|
|
}
|
|
|
|
bool WakeWordDetector::Initialize()
|
|
{
|
|
if (handle_ != nullptr) {
|
|
return true;
|
|
}
|
|
srmodel_list_t* models = esp_srmodel_init("model");
|
|
if (models == nullptr) {
|
|
ESP_LOGE(kTag, "model partition initialization failed");
|
|
return false;
|
|
}
|
|
char* selected = esp_srmodel_filter(
|
|
models, ESP_WN_PREFIX, kBorlaModelHint);
|
|
if (selected == nullptr) {
|
|
selected = esp_srmodel_filter(
|
|
models, ESP_WN_PREFIX, nullptr);
|
|
}
|
|
if (selected == nullptr) {
|
|
ESP_LOGE(kTag, "no WakeNet model in model partition");
|
|
esp_srmodel_deinit(models);
|
|
return false;
|
|
}
|
|
std::snprintf(
|
|
model_name_.data(), model_name_.size(), "%s", selected);
|
|
interface_ = esp_wn_handle_from_name(model_name_.data());
|
|
if (interface_ == nullptr) {
|
|
ESP_LOGE(kTag, "WakeNet interface lookup failed");
|
|
esp_srmodel_deinit(models);
|
|
return false;
|
|
}
|
|
handle_ = interface_->create(
|
|
model_name_.data(), DET_MODE_90);
|
|
esp_srmodel_deinit(models);
|
|
if (handle_ == nullptr) {
|
|
ESP_LOGE(kTag, "WakeNet instance creation failed");
|
|
interface_ = nullptr;
|
|
return false;
|
|
}
|
|
auto* model = static_cast<model_iface_data_t*>(handle_);
|
|
chunk_samples_ = static_cast<size_t>(
|
|
interface_->get_samp_chunksize(model));
|
|
const int sample_rate = interface_->get_samp_rate(model);
|
|
if (chunk_samples_ == 0 || sample_rate != 16000) {
|
|
ESP_LOGE(kTag, "invalid model format rate=%d chunk=%u",
|
|
sample_rate,
|
|
static_cast<unsigned>(chunk_samples_));
|
|
Deinitialize();
|
|
return false;
|
|
}
|
|
ESP_LOGI(kTag, "ready model=%s chunk=%u rate=%d",
|
|
model_name_.data(),
|
|
static_cast<unsigned>(chunk_samples_),
|
|
sample_rate);
|
|
return true;
|
|
}
|
|
|
|
void WakeWordDetector::Deinitialize()
|
|
{
|
|
if (interface_ != nullptr && handle_ != nullptr) {
|
|
interface_->destroy(
|
|
static_cast<model_iface_data_t*>(handle_));
|
|
}
|
|
interface_ = nullptr;
|
|
handle_ = nullptr;
|
|
chunk_samples_ = 0;
|
|
}
|
|
|
|
bool WakeWordDetector::Detect(
|
|
const int16_t* samples,
|
|
size_t sample_count)
|
|
{
|
|
if (interface_ == nullptr || handle_ == nullptr ||
|
|
samples == nullptr || sample_count != chunk_samples_) {
|
|
return false;
|
|
}
|
|
const int result = interface_->detect(
|
|
static_cast<model_iface_data_t*>(handle_),
|
|
const_cast<int16_t*>(samples));
|
|
return result > 0;
|
|
}
|
|
|
|
} // namespace borla
|