blob: 957a7b5839b9d607f5120567d2b67939333cdc2e [file] [log] [blame]
andrew@webrtc.org382c0c22014-05-05 18:22:21 +00001/*
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#include "webrtc/modules/audio_processing/rms_level.h"
12
andrew@webrtc.org382c0c22014-05-05 18:22:21 +000013#include <math.h>
14
kwiberg9e2be5f2016-09-14 05:23:22 -070015#include "webrtc/base/checks.h"
16
andrew@webrtc.org382c0c22014-05-05 18:22:21 +000017namespace webrtc {
18
andrew@webrtc.org21299d42014-05-14 19:00:59 +000019static const float kMaxSquaredLevel = 32768 * 32768;
andrew@webrtc.org382c0c22014-05-05 18:22:21 +000020
21RMSLevel::RMSLevel()
andrew@webrtc.org21299d42014-05-14 19:00:59 +000022 : sum_square_(0),
andrew@webrtc.org382c0c22014-05-05 18:22:21 +000023 sample_count_(0) {}
24
25RMSLevel::~RMSLevel() {}
26
27void RMSLevel::Reset() {
andrew@webrtc.org21299d42014-05-14 19:00:59 +000028 sum_square_ = 0;
andrew@webrtc.org382c0c22014-05-05 18:22:21 +000029 sample_count_ = 0;
30}
31
Peter Kastingdce40cf2015-08-24 14:52:23 -070032void RMSLevel::Process(const int16_t* data, size_t length) {
33 for (size_t i = 0; i < length; ++i) {
andrew@webrtc.org382c0c22014-05-05 18:22:21 +000034 sum_square_ += data[i] * data[i];
35 }
36 sample_count_ += length;
37}
38
Peter Kastingdce40cf2015-08-24 14:52:23 -070039void RMSLevel::ProcessMuted(size_t length) {
andrew@webrtc.org382c0c22014-05-05 18:22:21 +000040 sample_count_ += length;
41}
42
43int RMSLevel::RMS() {
andrew@webrtc.org21299d42014-05-14 19:00:59 +000044 if (sample_count_ == 0 || sum_square_ == 0) {
andrew@webrtc.org382c0c22014-05-05 18:22:21 +000045 Reset();
46 return kMinLevel;
47 }
48
49 // Normalize by the max level.
50 float rms = sum_square_ / (sample_count_ * kMaxSquaredLevel);
51 // 20log_10(x^0.5) = 10log_10(x)
52 rms = 10 * log10(rms);
kwiberg9e2be5f2016-09-14 05:23:22 -070053 RTC_DCHECK_LE(rms, 0);
andrew@webrtc.org382c0c22014-05-05 18:22:21 +000054 if (rms < -kMinLevel)
55 rms = -kMinLevel;
56
57 rms = -rms;
58 Reset();
59 return static_cast<int>(rms + 0.5);
60}
61
62} // namespace webrtc