rms_level.h (2511B)
1 /* 2 * Copyright (c) 2014 The WebRTC project authors. All Rights Reserved. 3 * 4 * Use of this source code is governed by a BSD-style license 5 * that can be found in the LICENSE file in the root of the source 6 * tree. An additional intellectual property rights grant can be found 7 * in the file PATENTS. All contributing project authors may 8 * be found in the AUTHORS file in the root of the source tree. 9 */ 10 11 #ifndef MODULES_AUDIO_PROCESSING_RMS_LEVEL_H_ 12 #define MODULES_AUDIO_PROCESSING_RMS_LEVEL_H_ 13 14 #include <stddef.h> 15 #include <stdint.h> 16 17 #include <optional> 18 19 #include "api/array_view.h" 20 21 namespace webrtc { 22 23 // Computes the root mean square (RMS) level in dBFs (decibels from digital 24 // full-scale) of audio data. The computation follows RFC 6465: 25 // https://tools.ietf.org/html/rfc6465 26 // with the intent that it can provide the RTP audio level indication. 27 // 28 // The expected approach is to provide constant-sized chunks of audio to 29 // Analyze(). When enough chunks have been accumulated to form a packet, call 30 // Average() to get the audio level indicator for the RTP header. 31 class RmsLevel { 32 public: 33 struct Levels { 34 int average; 35 int peak; 36 }; 37 38 enum : int { kMinLevelDb = 127, kInaudibleButNotMuted = 126 }; 39 40 RmsLevel(); 41 ~RmsLevel(); 42 43 // Can be called to reset internal states, but is not required during normal 44 // operation. 45 void Reset(); 46 47 // Pass each chunk of audio to Analyze() to accumulate the level. 48 void Analyze(ArrayView<const int16_t> data); 49 void Analyze(ArrayView<const float> data); 50 51 // If all samples with the given `length` have a magnitude of zero, this is 52 // a shortcut to avoid some computation. 53 void AnalyzeMuted(size_t length); 54 55 // Computes the RMS level over all data passed to Analyze() since the last 56 // call to Average(). The returned value is positive but should be interpreted 57 // as negative as per the RFC. It is constrained to [0, 127]. Resets the 58 // internal state to start a new measurement period. 59 int Average(); 60 61 // Like Average() above, but also returns the RMS peak value. Resets the 62 // internal state to start a new measurement period. 63 Levels AverageAndPeak(); 64 65 private: 66 // Compares `block_size` with `block_size_`. If they are different, calls 67 // Reset() and stores the new size. 68 void CheckBlockSize(size_t block_size); 69 70 float sum_square_; 71 size_t sample_count_; 72 float max_sum_square_; 73 std::optional<size_t> block_size_; 74 }; 75 76 } // namespace webrtc 77 78 #endif // MODULES_AUDIO_PROCESSING_RMS_LEVEL_H_