arduino-audio-tools
Loading...
Searching...
No Matches
AutomaticGainControlStream.h
Go to the documentation of this file.
1#pragma once
2
3#include <math.h>
4
7
8namespace audio_tools {
9
22 // Desired average RMS level.
23 float target_db = -18.0f;
24
25 // Maximum automatic amplification.
26 float max_gain_db = 6.0f;
27
28 // Maximum automatic attenuation.
29 float min_gain_db = -24.0f;
30
31 // Time to reduce gain when the input gets louder.
32 float attack_seconds = 0.25f;
33
34 // Time to increase gain when the input gets quieter.
35 //
36 // Keep this relatively long to preserve fades.
37 float release_seconds = 3.0f;
38
39 // Below this RMS level the signal is considered silence.
40 //
41 // The normalizer will NOT increase gain below this level.
42 float silence_db = -55.0f;
43
44 // Maximum allowed peak after normalization.
45 //
46 // -1 dBFS leaves a small amount of digital headroom.
47 float peak_headroom_db = -1.0f;
48
49 // Reset gain and detector state when AudioInfo changes.
51};
52
64template <typename T>
66
67template <>
69 static constexpr float max_sample = 32768.0f;
70 static constexpr float min_value = -32768.0f;
71 static constexpr float max_value = 32767.0f;
72 static constexpr int fixed_shift = 0;
73};
74
75template <>
77 static constexpr float max_sample = 8388608.0f;
78 static constexpr float min_value = -8388608.0f;
79 static constexpr float max_value = 8388607.0f;
80 static constexpr int fixed_shift = 8;
81};
82
83template <>
85 static constexpr float max_sample = 2147483648.0f;
86 static constexpr float min_value = -2147483648.0f;
87 // 2147483647.0f would be 2^31, which does not fit into an int32_t: use the
88 // largest float below it
89 static constexpr float max_value = 2147483520.0f;
90 static constexpr int fixed_shift = 16;
91};
92
110 public:
113
116
120 setStream(out);
121 }
122
126 setOutput(out);
127 }
128
130 void setStream(Stream& in) override {
131 p_in = &in;
132 p_out = p_in;
133 }
134
136 void setOutput(Print& out) override { p_out = &out; }
137
142
144 bool begin() override { return begin(info); }
145
147 bool begin(AudioInfo cfg) {
148 setAudioInfo(cfg);
149 reset();
150 is_started = true;
151 return true;
152 }
153
156 config = cfg;
158 reset();
159 is_started = true;
160 return true;
161 }
162
164 void end() override { is_started = false; }
165
168
171
173 void reset() {
174 current_gain_db = 0.0f;
175 measured_db = -100.0f;
176 has_level = false;
177 }
178
180 void setAudioInfo(AudioInfo cfg) override {
182
184 reset();
185 }
186
188 channels = cfg.channels;
190
191 if (sample_rate == 0) {
192 sample_rate = 44100;
193 }
194 }
195
197 size_t readBytes(uint8_t* data, size_t len) override {
198 if (data == nullptr || p_in == nullptr) {
199 return 0;
200 }
201
202 size_t result = p_in->readBytes(data, len);
203
204 if (result > 0 && is_started) {
205 process(data, result);
206 }
207
208 return result;
209 }
210
212 size_t write(const uint8_t* data, size_t len) override {
213 if (data == nullptr || p_out == nullptr) {
214 return 0;
215 }
216
217 if (is_started && len > 0) {
218 process(data, len);
219 }
220
221 return p_out->write(data, len);
222 }
223
225 int availableForWrite() override {
226 return p_out == nullptr ? 0 : p_out->availableForWrite();
227 }
228
230 int available() override { return p_in == nullptr ? 0 : p_in->available(); }
231
232 void flush() override {
233 if (p_out != nullptr) p_out->flush();
234 }
235
236 protected:
237 Print* p_out = nullptr;
238 Stream* p_in = nullptr;
240 bool is_started = false;
242 uint16_t channels = 2;
243 uint16_t bits_per_sample = 16;
244 float current_gain_db = 0.0f;
245 float measured_db = -100.0f;
246 bool has_level = false;
247
248 static float dbToLinear(float db) { return powf(10.0f, db / 20.0f); }
249
250 static float linearToDb(float value) {
251 if (value <= 0.0000001f) {
252 return -100.0f;
253 }
254
255 return 20.0f * log10f(value);
256 }
257
265 float smoothingCoefficient(float seconds, size_t samples) const {
266 if (seconds <= 0.0f) {
267 return 1.0f;
268 }
269
270 if (sample_rate == 0 || channels == 0 || samples == 0) {
271 return 1.0f;
272 }
273
274 float block_seconds = static_cast<float>(samples) /
275 static_cast<float>(sample_rate * channels);
276
277 return 1.0f - expf(-block_seconds / seconds);
278 }
279
289 template <typename T>
290 void analyze(const T* data, size_t samples, float& rms, float& peak) {
291#if PREFER_FIXEDPOINT
292 constexpr int shift = AGCPCMTraits<T>::fixed_shift;
293 constexpr float max_sample = AGCPCMTraits<T>::max_sample;
294
295 int64_t sum_sq = 0;
296 int32_t peak_raw = 0;
297
298 for (size_t i = 0; i < samples; ++i) {
299 // int24_t's conversion operators are not const-qualified, so a
300 // local (non-const) copy is needed before the cast.
301 T sample = data[i];
302 int32_t value = static_cast<int32_t>(sample) >> shift;
303 int32_t abs_value = value < 0 ? -value : value;
304
305 if (abs_value > peak_raw) {
306 peak_raw = abs_value;
307 }
308
309 sum_sq += static_cast<int64_t>(value) * value;
310 }
311
312 float scaled_max = max_sample / static_cast<float>(1 << shift);
313
314 rms = samples == 0 ? 0.0f
315 : sqrtf(static_cast<float>(sum_sq) /
316 static_cast<float>(samples)) /
317 scaled_max;
318 peak = static_cast<float>(peak_raw) / scaled_max;
319#else
320 float sum = 0.0f;
321 peak = 0.0f;
322
323 constexpr float max_sample = AGCPCMTraits<T>::max_sample;
324
325 for (size_t i = 0; i < samples; ++i) {
326 // int24_t's conversion operators are not const-qualified, so a
327 // local (non-const) copy is needed before the cast.
328 T sample = data[i];
329 float value = static_cast<float>(sample) / max_sample;
330
331 float abs_value = fabsf(value);
332
333 sum += value * value;
334
335 if (abs_value > peak) {
336 peak = abs_value;
337 }
338 }
339
340 rms = samples == 0 ? 0.0f : sqrtf(sum / static_cast<float>(samples));
341#endif
342 }
343
347 bool analyze(const uint8_t* buffer, size_t bytes, float& rms, float& peak) {
348 if (channels == 0) {
349 return false;
350 }
351
352 switch (bits_per_sample) {
353 case 16:
354 analyze(reinterpret_cast<const int16_t*>(buffer),
355 bytes / sizeof(int16_t), rms, peak);
356 return true;
357
358 case 24:
359 analyze(reinterpret_cast<const int24_t*>(buffer),
360 bytes / sizeof(int24_t), rms, peak);
361 return true;
362
363 case 32:
364 analyze(reinterpret_cast<const int32_t*>(buffer),
365 bytes / sizeof(int32_t), rms, peak);
366 return true;
367
368 default:
369 return false;
370 }
371 }
372
376 float desiredGainDb(float rms_db, float peak_db) const {
377 /*
378 * Do not amplify silence.
379 *
380 * This is particularly important for fades and prevents
381 * background noise from being amplified after a song becomes
382 * quiet.
383 */
384 if (rms_db <= config.silence_db) {
385 return current_gain_db;
386 }
387
388 /*
389 * RMS normalization.
390 *
391 * Example:
392 *
393 * target = -18 dB
394 * measured = -24 dB
395 *
396 * desired = +6 dB
397 */
398 float desired = config.target_db - rms_db;
399
400 /*
401 * Automatic gain limits.
402 */
403 if (desired > config.max_gain_db) {
404 desired = config.max_gain_db;
405 }
406
407 if (desired < config.min_gain_db) {
408 desired = config.min_gain_db;
409 }
410
411 /*
412 * Peak protection.
413 *
414 * Never intentionally request enough gain to put the detected
415 * peak above the configured headroom.
416 */
417 float peak_after_gain = peak_db + desired;
418
419 if (peak_after_gain > config.peak_headroom_db) {
420 float peak_limited_gain = config.peak_headroom_db - peak_db;
421
422 if (peak_limited_gain < desired) {
423 desired = peak_limited_gain;
424 }
425 }
426
427 /*
428 * Peak limiting can have pushed the gain below our configured
429 * lower bound, so apply the minimum one final time.
430 */
431 if (desired < config.min_gain_db) {
432 desired = config.min_gain_db;
433 }
434
435 return desired;
436 }
437
438 void updateGain(float desired_gain_db, size_t samples) {
439 float coefficient;
440
441 if (desired_gain_db < current_gain_db) {
442 /*
443 * Input got louder.
444 *
445 * Reduce gain relatively quickly.
446 */
447 coefficient = smoothingCoefficient(config.attack_seconds, samples);
448
449 } else {
450 /*
451 * Input got quieter.
452 *
453 * Increase gain slowly.
454 *
455 * This is what preserves fades.
456 */
457 coefficient = smoothingCoefficient(config.release_seconds, samples);
458 }
459
460 current_gain_db += coefficient * (desired_gain_db - current_gain_db);
461
462 /*
463 * Avoid unnecessary floating point movement when we are
464 * already effectively at the target.
465 */
466 if (fabsf(current_gain_db - desired_gain_db) < 0.001f) {
467 current_gain_db = desired_gain_db;
468 }
469 }
470
485 template <typename T>
486 void apply(T* data, size_t samples, float gain) {
487#if PREFER_FIXEDPOINT
488 q1_14_t fixed_gain(gain);
489
490 for (size_t i = 0; i < samples; ++i) {
491 data[i] = fixed_gain.scale(data[i]);
492 }
493#else
494 constexpr float min_value = AGCPCMTraits<T>::min_value;
495
496 constexpr float max_value = AGCPCMTraits<T>::max_value;
497
498 const float dgain = static_cast<float>(gain);
499
500 for (size_t i = 0; i < samples; ++i) {
501 float value = static_cast<float>(data[i]) * dgain;
502
503 if (value > max_value) {
504 value = max_value;
505 }
506
507 if (value < min_value) {
508 value = min_value;
509 }
510
511 data[i] = static_cast<T>(value);
512 }
513#endif
514 }
515
519 void apply(uint8_t* buffer, size_t bytes, float gain) {
520 switch (bits_per_sample) {
521 case 16:
522 apply(reinterpret_cast<int16_t*>(buffer), bytes / sizeof(int16_t),
523 gain);
524 break;
525
526 case 24:
527 apply(reinterpret_cast<int24_t*>(buffer), bytes / sizeof(int24_t),
528 gain);
529 break;
530
531 case 32:
532 apply(reinterpret_cast<int32_t*>(buffer), bytes / sizeof(int32_t),
533 gain);
534 break;
535
536 default:
537 break;
538 }
539 }
540
541 void process(const uint8_t* input, size_t bytes) {
542 if (input == nullptr || bytes == 0 || channels == 0) {
543 return;
544 }
545
546 /*
547 * VolumeStream also modifies the supplied PCM buffer in-place,
548 * so AutomaticGainControlStream follows the same ModifyingStream
549 * convention.
550 */
551 uint8_t* buffer = const_cast<uint8_t*>(input);
552
553 float rms = 0.0;
554 float peak = 0.0;
555
556 /*
557 * First analyze the ORIGINAL signal.
558 *
559 * It is important that this happens before applying the new
560 * gain.
561 */
562 if (!analyze(buffer, bytes, rms, peak)) {
563 return;
564 }
565
566 /*
567 * Convert RMS and peak to dBFS.
568 */
569 float rms_db = linearToDb(static_cast<float>(rms));
570
571 float peak_db = linearToDb(static_cast<float>(peak));
572
573 measured_db = rms_db;
574 has_level = true;
575
576 size_t sample_size = bits_per_sample / 8;
577
578 if (sample_size == 0) {
579 return;
580 }
581
582 size_t samples = bytes / sample_size;
583
584 /*
585 * Determine desired gain.
586 */
587 float desired_gain_db = desiredGainDb(rms_db, peak_db);
588
589 /*
590 * Move current gain towards desired gain using asymmetric
591 * attack/release smoothing.
592 */
593 updateGain(desired_gain_db, samples);
594
595 /*
596 * Convert dB gain into a linear multiplier.
597 */
598 float gain = dbToLinear(current_gain_db);
599
600 /*
601 * Apply gain to the PCM data.
602 */
603 apply(buffer, bytes, gain);
604 }
605};
606
607} // namespace audio_tools
Definition Arduino.h:56
virtual int availableForWrite()
Definition Arduino.h:128
virtual size_t write(const uint8_t *data, size_t len)
Definition Arduino.h:120
virtual void flush()
Definition Arduino.h:130
Definition Arduino.h:136
virtual size_t readBytes(uint8_t *data, size_t len)
Definition Arduino.h:140
virtual int available()
Definition Arduino.h:139
virtual void setAudioInfo(AudioInfo info)=0
Defines the input AudioInfo.
Abstract Audio Ouptut class.
Definition AudioOutput.h:25
Base class for all Audio Streams. It support the boolean operator to test if the object is ready with...
Definition BaseStream.h:120
AudioInfo info
Definition BaseStream.h:171
Slow automatic loudness normalization for PCM audio.
Definition AutomaticGainControlStream.h:109
void updateGain(float desired_gain_db, size_t samples)
Definition AutomaticGainControlStream.h:438
void flush() override
Definition AutomaticGainControlStream.h:232
void setOutput(Print &out) override
Defines the output Print target.
Definition AutomaticGainControlStream.h:136
uint16_t channels
Definition AutomaticGainControlStream.h:242
AutomaticGainControlStream(AudioOutput &out)
Definition AutomaticGainControlStream.h:125
Stream * p_in
Definition AutomaticGainControlStream.h:238
uint32_t sample_rate
Definition AutomaticGainControlStream.h:241
float measured_db
Definition AutomaticGainControlStream.h:245
bool begin(AutomaticGainControlStreamConfig cfg)
Starts processing with the given AutomaticGainControlStreamConfig.
Definition AutomaticGainControlStream.h:155
static float dbToLinear(float db)
Definition AutomaticGainControlStream.h:248
size_t readBytes(uint8_t *data, size_t len) override
Reads and gain-adjusts PCM data from the input Stream.
Definition AutomaticGainControlStream.h:197
bool is_started
Definition AutomaticGainControlStream.h:240
uint16_t bits_per_sample
Definition AutomaticGainControlStream.h:243
AutomaticGainControlStreamConfig config
Definition AutomaticGainControlStream.h:239
AutomaticGainControlStreamConfig & getConfig()
Provides access to the current configuration.
Definition AutomaticGainControlStream.h:170
AutomaticGainControlStream(AudioStream &out)
Definition AutomaticGainControlStream.h:119
AutomaticGainControlStreamConfig defaultConfig()
Provides the default configuration.
Definition AutomaticGainControlStream.h:139
void end() override
Stops processing; the underlying Stream/Print is left untouched.
Definition AutomaticGainControlStream.h:164
int available() override
Provides the available data of the input.
Definition AutomaticGainControlStream.h:230
float smoothingCoefficient(float seconds, size_t samples) const
Definition AutomaticGainControlStream.h:265
size_t write(const uint8_t *data, size_t len) override
Gain-adjusts PCM data in place and writes it to the output.
Definition AutomaticGainControlStream.h:212
void analyze(const T *data, size_t samples, float &rms, float &peak)
Definition AutomaticGainControlStream.h:290
void apply(uint8_t *buffer, size_t bytes, float gain)
Definition AutomaticGainControlStream.h:519
AutomaticGainControlStream()=default
Default constructor: call setStream()/setOutput() before begin()
int availableForWrite() override
Provides the available space of the output.
Definition AutomaticGainControlStream.h:225
static float linearToDb(float value)
Definition AutomaticGainControlStream.h:250
void setConfig(const AutomaticGainControlStreamConfig &cfg)
Updates the configuration without resetting the current gain state.
Definition AutomaticGainControlStream.h:167
Print * p_out
Definition AutomaticGainControlStream.h:237
void apply(T *data, size_t samples, float gain)
Definition AutomaticGainControlStream.h:486
bool begin() override
Starts processing using the current AudioInfo.
Definition AutomaticGainControlStream.h:144
void reset()
Resets the current gain and level detector state.
Definition AutomaticGainControlStream.h:173
float desiredGainDb(float rms_db, float peak_db) const
Definition AutomaticGainControlStream.h:376
bool has_level
Definition AutomaticGainControlStream.h:246
void setStream(Stream &in) override
Defines the input Stream; output is set to the same Stream.
Definition AutomaticGainControlStream.h:130
float current_gain_db
Definition AutomaticGainControlStream.h:244
AutomaticGainControlStream(Stream &out)
Constructs the stream with a bidirectional Stream as input and output.
Definition AutomaticGainControlStream.h:115
void setAudioInfo(AudioInfo cfg) override
Updates the AudioInfo; resets state when reset_on_audio_change is set.
Definition AutomaticGainControlStream.h:180
void process(const uint8_t *input, size_t bytes)
Definition AutomaticGainControlStream.h:541
bool begin(AudioInfo cfg)
Starts processing with the given AudioInfo, keeping the current config.
Definition AutomaticGainControlStream.h:147
bool analyze(const uint8_t *buffer, size_t bytes, float &rms, float &peak)
Definition AutomaticGainControlStream.h:347
Abstract class: Objects can be put into a pipleline.
Definition AudioStreams.h:68
24bit integer which is used for I2S sound processing. The values are represented as int32_t,...
Definition int24_4bytes_t.h:22
Fixed-point Q1.14 number: a plain 16-bit signed integer holding 1 integer bit and 14 fractional bits ...
Definition q1_14_t.h:16
int16_t scale(int16_t sample) const
scales a 16-bit PCM sample by this Q1.14 factor
Definition q1_14_t.h:83
Generic Implementation of sound input and output for desktop environments using portaudio.
Definition LMSEchoCancellationStream.h:6
Definition AutomaticGainControlStream.h:65
Basic Audio information which drives e.g. I2S.
Definition AudioTypes.h:56
sample_rate_t sample_rate
Sample Rate: e.g 44100.
Definition AudioTypes.h:58
uint16_t channels
Number of channels: 2=stereo, 1=mono.
Definition AudioTypes.h:60
uint8_t bits_per_sample
Number of bits per sample (int16_t = 16 bits)
Definition AudioTypes.h:62
Configuration for AutomaticGainControlStream.
Definition AutomaticGainControlStream.h:21
float silence_db
Definition AutomaticGainControlStream.h:42
float peak_headroom_db
Definition AutomaticGainControlStream.h:47
float release_seconds
Definition AutomaticGainControlStream.h:37
float target_db
Definition AutomaticGainControlStream.h:23
float attack_seconds
Definition AutomaticGainControlStream.h:32
float max_gain_db
Definition AutomaticGainControlStream.h:26
float min_gain_db
Definition AutomaticGainControlStream.h:29
bool reset_on_audio_change
Definition AutomaticGainControlStream.h:50