Re-subimission of https://codereview.chromium.org/1041213003/
[chromium-blink-merge.git] / content / renderer / media / media_stream_audio_level_calculator.cc
blob320b1ab728d736b58c1a7f4450ea080e07fbb186
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/renderer/media/media_stream_audio_level_calculator.h"
7 #include "base/float_util.h"
8 #include "base/logging.h"
9 #include "base/stl_util.h"
10 #include "media/base/audio_bus.h"
12 namespace content {
14 namespace {
16 // Calculates the maximum absolute amplitude of the audio data.
17 float MaxAmplitude(const float* audio_data, int length) {
18 float max = 0.0f;
19 for (int i = 0; i < length; ++i) {
20 const float absolute = fabsf(audio_data[i]);
21 if (absolute > max)
22 max = absolute;
24 DCHECK(base::IsFinite(max));
25 return max;
28 } // namespace
30 MediaStreamAudioLevelCalculator::MediaStreamAudioLevelCalculator()
31 : counter_(0),
32 max_amplitude_(0.0f),
33 level_(0.0f) {
36 MediaStreamAudioLevelCalculator::~MediaStreamAudioLevelCalculator() {
39 float MediaStreamAudioLevelCalculator::Calculate(
40 const media::AudioBus& audio_bus) {
41 DCHECK(thread_checker_.CalledOnValidThread());
42 // |level_| is updated every 10 callbacks. For the case where callback comes
43 // every 10ms, |level_| will be updated approximately every 100ms.
44 static const int kUpdateFrequency = 10;
46 float max = 0.0f;
47 for (int i = 0; i < audio_bus.channels(); ++i) {
48 const float max_this_channel =
49 MaxAmplitude(audio_bus.channel(i), audio_bus.frames());
50 if (max_this_channel > max)
51 max = max_this_channel;
53 max_amplitude_ = std::max(max_amplitude_, max);
55 if (counter_++ == kUpdateFrequency) {
56 level_ = max_amplitude_;
58 // Decay the absolute maximum amplitude by 1/4.
59 max_amplitude_ /= 4.0f;
61 // Reset the counter.
62 counter_ = 0;
65 return level_;
68 } // namespace content