ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
sound_level.cpp
Go to the documentation of this file.
1#include "sound_level.h"
2
3#ifdef USE_ESP32
4
5#include "esphome/core/log.h"
6
7#include <cmath>
8#include <cstdint>
9
11
12ESPHOME_LOG_TAG(TAG, "sound_level");
13
14static const uint32_t MAX_FILL_DURATION_MS = 30;
15static const uint32_t RING_BUFFER_DURATION_MS = 120;
16
17// Square INT16_MIN since INT16_MIN^2 > INT16_MAX^2
18static const double MAX_SAMPLE_SQUARED_DENOMINATOR = INT16_MIN * INT16_MIN;
19
21 ESP_LOGCONFIG(TAG,
22 "Sound Level Component:\n"
23 " Measurement Duration: %" PRIu32 " ms",
25 LOG_SENSOR(" ", "Peak:", this->peak_sensor_);
26
27 LOG_SENSOR(" ", "RMS:", this->rms_sensor_);
28}
29
30void SoundLevelComponent::setup() {
32 std::shared_ptr<ring_buffer::RingBuffer> temp_ring_buffer = this->ring_buffer_.lock();
33 if (temp_ring_buffer != nullptr) {
34 temp_ring_buffer->write((void *) capture.data.data(), capture.data.size());
35 }
36 });
37
38 if (!this->microphone_source_->is_passive()) {
39 // Automatically start the microphone if not in passive mode
41 }
42}
43
44void SoundLevelComponent::loop() {
45 if ((this->peak_sensor_ == nullptr) && (this->rms_sensor_ == nullptr)) {
46 // No sensors configured, nothing to do
47 return;
48 }
49
50 if (this->microphone_source_->is_running() && !this->status_has_error()) {
51 // Allocate buffers
52 if (this->start_()) {
54 }
55 } else {
56 if (!this->status_has_warning()) {
57 this->status_set_warning(LOG_STR("Microphone isn't running, can't compute statistics"));
58
59 // Deallocate buffers, if necessary
60 this->stop_();
61
62 // Reset sensor outputs
63 PUBLISH_STATE(this->peak_sensor_, NAN);
64 PUBLISH_STATE(this->rms_sensor_, NAN);
65
66 // Reset accumulators
67 this->squared_peak_ = 0;
68 this->squared_samples_sum_ = 0;
69 this->sample_count_ = 0;
70 }
71
72 return;
73 }
74
75 if (this->status_has_error()) {
76 return;
77 }
78
79 // Expose a chunk of the ring buffer's internal storage - don't block to avoid slowing the main loop.
80 this->audio_source_->fill(0);
81
82 if (this->audio_source_->available() == 0) {
83 // No new audio available for processing
84 return;
85 }
86
87 const uint32_t samples_in_window =
89 const uint32_t samples_available_to_process =
91 const uint32_t samples_to_process = std::min(samples_in_window - this->sample_count_, samples_available_to_process);
92
93 // MicrophoneSource always provides int16 samples due to Python codegen settings
94 const int16_t *audio_data = reinterpret_cast<const int16_t *>(this->audio_source_->data());
95
96 // Process all the new audio samples
97 for (uint32_t i = 0; i < samples_to_process; ++i) {
98 // Squaring int16 samples won't overflow an int32
99 int32_t squared_sample = static_cast<int32_t>(audio_data[i]) * static_cast<int32_t>(audio_data[i]);
100
101 if (this->peak_sensor_ != nullptr) {
102 this->squared_peak_ = std::max(this->squared_peak_, squared_sample);
103 }
104
105 if (this->rms_sensor_ != nullptr) {
106 // Squared sum is an uint64 type - at max levels, an uint32 type would overflow after ~8 samples
107 this->squared_samples_sum_ += squared_sample;
108 }
109
110 ++this->sample_count_;
111 }
112
113 // Remove the processed samples from ``audio_source_``
114 this->audio_source_->consume(this->microphone_source_->get_audio_stream_info().samples_to_bytes(samples_to_process));
115
116 if (this->sample_count_ == samples_in_window) {
117 // Processed enough samples for the measurement window, compute and publish the sensor values
118 if (this->peak_sensor_ != nullptr) {
119 const float peak_db = 10.0f * log10f(static_cast<float>(this->squared_peak_) / MAX_SAMPLE_SQUARED_DENOMINATOR);
120 this->peak_sensor_->publish_state(peak_db);
121
122 this->squared_peak_ = 0; // reset accumulator
123 }
124
125 if (this->rms_sensor_ != nullptr) {
126 // Calculations are done with doubles instead of floats - floats lose precision for even modest window durations
127 const double rms_db = 10.0 * log10((this->squared_samples_sum_ / MAX_SAMPLE_SQUARED_DENOMINATOR) /
128 static_cast<double>(samples_in_window));
129 this->rms_sensor_->publish_state(rms_db);
130
131 this->squared_samples_sum_ = 0; // reset accumulator
132 }
133
134 this->sample_count_ = 0; // reset counter
135 }
136}
137
138void SoundLevelComponent::start() {
139 if (this->microphone_source_->is_passive()) {
140 ESP_LOGW(TAG, "Can't start the microphone in passive mode");
141 return;
142 }
143 this->microphone_source_->start();
144}
145
146void SoundLevelComponent::stop() {
147 if (this->microphone_source_->is_passive()) {
148 ESP_LOGW(TAG, "Can't stop microphone in passive mode");
149 return;
150 }
151 this->microphone_source_->stop();
152}
153
154bool SoundLevelComponent::start_() {
155 if (this->audio_source_ != nullptr) {
156 return true;
157 }
158
159 const auto &stream_info = this->microphone_source_->get_audio_stream_info();
160 const size_t bytes_per_frame = stream_info.frames_to_bytes(1);
161
162 // Allocate a ring buffer for the microphone callback to write into. Round the size down to a multiple
163 // of bytes_per_frame so the wrap boundary stays frame-aligned and avoids unnecessary single-frame splices.
164 this->ring_buffer_.reset(); // Reset pointer to any previous ring buffer allocation
165 const size_t ring_buffer_size =
166 (stream_info.ms_to_bytes(RING_BUFFER_DURATION_MS) / bytes_per_frame) * bytes_per_frame;
167 std::shared_ptr<ring_buffer::RingBuffer> temp_ring_buffer = ring_buffer::RingBuffer::create(ring_buffer_size);
168 if (temp_ring_buffer == nullptr) {
169 this->status_momentary_error(15000);
170 return false;
171 }
172
173 // Zero-copy source that reads directly from the ring buffer's internal storage. Frame-aligned reads
174 // ensure multi-channel frames are never split across the ring buffer's wrap boundary.
176 temp_ring_buffer, stream_info.ms_to_bytes(MAX_FILL_DURATION_MS), static_cast<uint8_t>(bytes_per_frame));
177 if (this->audio_source_ == nullptr) {
178 this->status_momentary_error(15000);
179 return false;
180 }
181 this->ring_buffer_ = temp_ring_buffer;
182
183 this->status_clear_error();
184 return true;
185}
186
188
189} // namespace esphome::sound_level
190
191#endif
void status_clear_error()
Definition component.h:315
virtual void dump_config()
bool status_has_warning() const
Definition component.h:293
bool status_has_error() const
Definition component.h:295
void status_momentary_error(uint32_t length=5000)
Set error status flag and clear it after length ms.
void status_clear_warning()
Definition component.h:309
size_t frames_to_bytes(uint32_t frames) const
Converts frames to bytes.
Definition audio.h:53
uint32_t ms_to_samples(uint32_t ms) const
Converts duration to samples.
Definition audio.h:68
size_t samples_to_bytes(uint32_t samples) const
Converts samples to bytes.
Definition audio.h:58
uint32_t bytes_to_samples(size_t bytes) const
Convert bytes to samples.
Definition audio.h:48
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 add_data_callback(F &&data_callback)
Same callbacks as Microphone::add_data_callback; stream_info is the processed format.
audio::AudioStreamInfo get_audio_stream_info()
Gets the AudioStreamInfo of the data after processing.
static std::unique_ptr< RingBuffer > create(size_t len, MemoryPreference preference=MemoryPreference::EXTERNAL_FIRST)
std::weak_ptr< ring_buffer::RingBuffer > ring_buffer_
Definition sound_level.h:50
microphone::MicrophoneSource * microphone_source_
Definition sound_level.h:47
void stop_()
Internal start command that, if necessary, allocates a ring buffer and a zero-copy RingBufferAudioSou...
std::unique_ptr< audio::RingBufferAudioSource > audio_source_
Definition sound_level.h:49
ESPHOME_LOG_TAG(TAG, "sound_level")
static void uint32_t
std::span< const uint8_t > data
Only valid during the callback.
Definition microphone.h:25