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"
16 // Calculates the maximum absolute amplitude of the audio data.
17 float MaxAmplitude(const float* audio_data
, int length
) {
19 for (int i
= 0; i
< length
; ++i
) {
20 const float absolute
= fabsf(audio_data
[i
]);
24 DCHECK(base::IsFinite(max
));
30 MediaStreamAudioLevelCalculator::MediaStreamAudioLevelCalculator()
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;
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
;
68 } // namespace content