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"
9 #include "base/logging.h"
10 #include "base/stl_util.h"
11 #include "media/base/audio_bus.h"
17 // Calculates the maximum absolute amplitude of the audio data.
18 float MaxAmplitude(const float* audio_data
, int length
) {
20 for (int i
= 0; i
< length
; ++i
) {
21 const float absolute
= fabsf(audio_data
[i
]);
25 DCHECK(std::isfinite(max
));
31 MediaStreamAudioLevelCalculator::MediaStreamAudioLevelCalculator()
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;
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
;
69 } // namespace content