• Home
  • History
  • Annotate
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.
4 
5 #include "content/renderer/media/media_stream_audio_level_calculator.h"
6 
7 #include "base/logging.h"
8 #include "base/stl_util.h"
9 
10 namespace content {
11 
12 namespace {
13 
14 // Calculates the maximum absolute amplitude of the audio data.
15 // Note, the return value can be bigger than std::numeric_limits<int16>::max().
MaxAmplitude(const int16 * audio_data,int length)16 int MaxAmplitude(const int16* audio_data, int length) {
17   int max = 0, absolute = 0;
18   for (int i = 0; i < length; ++i) {
19     absolute = std::abs(audio_data[i]);
20     if (absolute > max)
21       max = absolute;
22   }
23   // The range of int16 is [-32768, 32767], verify the |max| should not be
24   // bigger than 32768.
25   DCHECK(max <= std::abs(std::numeric_limits<int16>::min()));
26 
27   return max;
28 }
29 
30 }  // namespace
31 
MediaStreamAudioLevelCalculator()32 MediaStreamAudioLevelCalculator::MediaStreamAudioLevelCalculator()
33     : counter_(0),
34       max_amplitude_(0),
35       level_(0) {
36 }
37 
~MediaStreamAudioLevelCalculator()38 MediaStreamAudioLevelCalculator::~MediaStreamAudioLevelCalculator() {
39 }
40 
Calculate(const int16 * audio_data,int number_of_channels,int number_of_frames,bool force_report_nonzero_energy)41 int MediaStreamAudioLevelCalculator::Calculate(
42     const int16* audio_data,
43     int number_of_channels,
44     int number_of_frames,
45     bool force_report_nonzero_energy) {
46   DCHECK(thread_checker_.CalledOnValidThread());
47   // |level_| is updated every 10 callbacks. For the case where callback comes
48   // every 10ms, |level_| will be updated approximately every 100ms.
49   static const int kUpdateFrequency = 10;
50 
51   int max = MaxAmplitude(audio_data, number_of_channels * number_of_frames);
52   max_amplitude_ = std::max(max_amplitude_, max);
53 
54   if (counter_++ == kUpdateFrequency) {
55     level_ = (max_amplitude_ == 0 ?
56         force_report_nonzero_energy : max_amplitude_);
57 
58     // Decay the absolute maximum amplitude by 1/4.
59     max_amplitude_ >>= 2;
60 
61     // Reset the counter.
62     counter_ = 0;
63   }
64 
65   return level_;
66 }
67 
68 }  // namespace content
69