rms_level.h 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. #ifndef MODULES_AUDIO_PROCESSING_RMS_LEVEL_H_
  11. #define MODULES_AUDIO_PROCESSING_RMS_LEVEL_H_
  12. #include <stddef.h>
  13. #include <stdint.h>
  14. #include "absl/types/optional.h"
  15. #include "api/array_view.h"
  16. namespace webrtc {
  17. // Computes the root mean square (RMS) level in dBFs (decibels from digital
  18. // full-scale) of audio data. The computation follows RFC 6465:
  19. // https://tools.ietf.org/html/rfc6465
  20. // with the intent that it can provide the RTP audio level indication.
  21. //
  22. // The expected approach is to provide constant-sized chunks of audio to
  23. // Analyze(). When enough chunks have been accumulated to form a packet, call
  24. // Average() to get the audio level indicator for the RTP header.
  25. class RmsLevel {
  26. public:
  27. struct Levels {
  28. int average;
  29. int peak;
  30. };
  31. enum : int { kMinLevelDb = 127 };
  32. RmsLevel();
  33. ~RmsLevel();
  34. // Can be called to reset internal states, but is not required during normal
  35. // operation.
  36. void Reset();
  37. // Pass each chunk of audio to Analyze() to accumulate the level.
  38. void Analyze(rtc::ArrayView<const int16_t> data);
  39. void Analyze(rtc::ArrayView<const float> data);
  40. // If all samples with the given |length| have a magnitude of zero, this is
  41. // a shortcut to avoid some computation.
  42. void AnalyzeMuted(size_t length);
  43. // Computes the RMS level over all data passed to Analyze() since the last
  44. // call to Average(). The returned value is positive but should be interpreted
  45. // as negative as per the RFC. It is constrained to [0, 127]. Resets the
  46. // internal state to start a new measurement period.
  47. int Average();
  48. // Like Average() above, but also returns the RMS peak value. Resets the
  49. // internal state to start a new measurement period.
  50. Levels AverageAndPeak();
  51. private:
  52. // Compares |block_size| with |block_size_|. If they are different, calls
  53. // Reset() and stores the new size.
  54. void CheckBlockSize(size_t block_size);
  55. float sum_square_;
  56. size_t sample_count_;
  57. float max_sum_square_;
  58. absl::optional<size_t> block_size_;
  59. };
  60. } // namespace webrtc
  61. #endif // MODULES_AUDIO_PROCESSING_RMS_LEVEL_H_