[microphone] Remove unnecessary std::function wrapping in callbacks

Pass wrapping lambdas directly to CallbackManager::add() instead of
first wrapping in std::function. The lambdas capture [this, callback]
(two pointers) so they hit the heap path either way, but this avoids
double-wrapping and the extra std::function overhead.

Also fix "deallaction" typo.
This commit is contained in:
J. Nick Koston
2026-03-15 22:59:19 -10:00
parent 1357de1fcd
commit 073dd3995e
2 changed files with 19 additions and 23 deletions
+7 -9
View File
@@ -23,15 +23,13 @@ class Microphone {
virtual void start() = 0;
virtual void stop() = 0;
template<typename F> void add_data_callback(F &&data_callback) {
std::function<void(const std::vector<uint8_t> &)> mute_handled_callback =
[this, data_callback](const std::vector<uint8_t> &data) {
if (this->mute_state_) {
data_callback(std::vector<uint8_t>(data.size(), 0));
} else {
data_callback(data);
};
};
this->data_callbacks_.add(std::move(mute_handled_callback));
this->data_callbacks_.add([this, data_callback](const std::vector<uint8_t> &data) {
if (this->mute_state_) {
data_callback(std::vector<uint8_t>(data.size(), 0));
} else {
data_callback(data);
}
});
}
bool is_running() const { return this->state_ == STATE_RUNNING; }
@@ -48,21 +48,19 @@ class MicrophoneSource {
void add_channel(uint8_t channel) { this->channels_.set(channel); }
template<typename F> void add_data_callback(F &&data_callback) {
std::function<void(const std::vector<uint8_t> &)> filtered_callback =
[this, data_callback](const std::vector<uint8_t> &data) {
if (this->enabled_ || this->passive_) {
if (this->processed_samples_.use_count() == 0) {
// Create vector if its unused
this->processed_samples_ = std::make_shared<std::vector<uint8_t>>();
}
this->mic_->add_data_callback([this, data_callback](const std::vector<uint8_t> &data) {
if (this->enabled_ || this->passive_) {
if (this->processed_samples_.use_count() == 0) {
// Create vector if its unused
this->processed_samples_ = std::make_shared<std::vector<uint8_t>>();
}
// Take temporary ownership of samples vector to avoid deallaction before the callback finishes
std::shared_ptr<std::vector<uint8_t>> output_samples = this->processed_samples_;
this->process_audio_(data, *output_samples);
data_callback(*output_samples);
}
};
this->mic_->add_data_callback(std::move(filtered_callback));
// Take temporary ownership of samples vector to avoid deallocation before the callback finishes
std::shared_ptr<std::vector<uint8_t>> output_samples = this->processed_samples_;
this->process_audio_(data, *output_samples);
data_callback(*output_samples);
}
});
}
void set_gain_factor(int32_t gain_factor) { this->gain_factor_ = clamp<int32_t>(gain_factor, 1, MAX_GAIN_FACTOR); }