Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / content / renderer / media / media_stream_audio_level_calculator.cc
blobad76a43dd2f6ad14125b5a92506990e1bbc34aaf
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 <cmath>
9 #include "base/logging.h"
10 #include "base/stl_util.h"
11 #include "media/base/audio_bus.h"
13 namespace content {
15 namespace {
17 // Calculates the maximum absolute amplitude of the audio data.
18 float MaxAmplitude(const float* audio_data, int length) {
19 float max = 0.0f;
20 for (int i = 0; i < length; ++i) {
21 const float absolute = fabsf(audio_data[i]);
22 if (absolute > max)
23 max = absolute;
25 DCHECK(std::isfinite(max));
26 return max;
29 } // namespace
31 MediaStreamAudioLevelCalculator::MediaStreamAudioLevelCalculator()
32 : counter_(0),
33 max_amplitude_(0.0f),
34 level_(0.0f) {
37 MediaStreamAudioLevelCalculator::~MediaStreamAudioLevelCalculator() {
40 float MediaStreamAudioLevelCalculator::Calculate(
41 const media::AudioBus& audio_bus) {
42 DCHECK(thread_checker_.CalledOnValidThread());
43 // |level_| is updated every 10 callbacks. For the case where callback comes
44 // every 10ms, |level_| will be updated approximately every 100ms.
45 static const int kUpdateFrequency = 10;
47 float max = 0.0f;
48 for (int i = 0; i < audio_bus.channels(); ++i) {
49 const float max_this_channel =
50 MaxAmplitude(audio_bus.channel(i), audio_bus.frames());
51 if (max_this_channel > max)
52 max = max_this_channel;
54 max_amplitude_ = std::max(max_amplitude_, max);
56 if (counter_++ == kUpdateFrequency) {
57 level_ = max_amplitude_;
59 // Decay the absolute maximum amplitude by 1/4.
60 max_amplitude_ /= 4.0f;
62 // Reset the counter.
63 counter_ = 0;
66 return level_;
69 } // namespace content