69 lines
1.7 KiB
C++
69 lines
1.7 KiB
C++
#include "audio/voice_activity_detector.h"
|
|
|
|
#include <cmath>
|
|
|
|
namespace borla {
|
|
|
|
VoiceActivityDetector::VoiceActivityDetector(
|
|
VoiceActivityConfig config)
|
|
: config_(config)
|
|
{
|
|
if (config_.start_frames == 0) {
|
|
config_.start_frames = 1;
|
|
}
|
|
if (config_.stop_frames == 0) {
|
|
config_.stop_frames = 1;
|
|
}
|
|
}
|
|
|
|
VoiceActivityResult VoiceActivityDetector::Process(
|
|
const int16_t* samples,
|
|
size_t sample_count)
|
|
{
|
|
if (samples == nullptr || sample_count == 0) {
|
|
return VoiceActivityResult::kSilence;
|
|
}
|
|
uint64_t energy = 0;
|
|
for (size_t index = 0; index < sample_count; ++index) {
|
|
const int32_t sample = samples[index];
|
|
energy += static_cast<uint64_t>(sample * sample);
|
|
}
|
|
last_rms_ = static_cast<uint32_t>(
|
|
std::sqrt(
|
|
static_cast<double>(energy) /
|
|
static_cast<double>(sample_count)));
|
|
const bool loud = last_rms_ >= config_.rms_threshold;
|
|
|
|
if (!speech_active_) {
|
|
quiet_frames_ = 0;
|
|
loud_frames_ = loud ? static_cast<uint8_t>(loud_frames_ + 1) : 0;
|
|
if (loud_frames_ >= config_.start_frames) {
|
|
speech_active_ = true;
|
|
loud_frames_ = 0;
|
|
return VoiceActivityResult::kSpeechStarted;
|
|
}
|
|
return VoiceActivityResult::kSilence;
|
|
}
|
|
|
|
if (loud) {
|
|
quiet_frames_ = 0;
|
|
return VoiceActivityResult::kSpeech;
|
|
}
|
|
if (++quiet_frames_ >= config_.stop_frames) {
|
|
speech_active_ = false;
|
|
quiet_frames_ = 0;
|
|
return VoiceActivityResult::kSpeechEnded;
|
|
}
|
|
return VoiceActivityResult::kSpeech;
|
|
}
|
|
|
|
void VoiceActivityDetector::Reset()
|
|
{
|
|
loud_frames_ = 0;
|
|
quiet_frames_ = 0;
|
|
speech_active_ = false;
|
|
last_rms_ = 0;
|
|
}
|
|
|
|
} // namespace borla
|