// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "media/audio/audio_power_monitor.h" #include #include #include "base/float_util.h" #include "base/logging.h" #include "base/time/time.h" #include "media/base/audio_bus.h" namespace media { AudioPowerMonitor::AudioPowerMonitor( int sample_rate, const base::TimeDelta& time_constant) : sample_weight_( 1.0f - expf(-1.0f / (sample_rate * time_constant.InSecondsF()))) { Reset(); } AudioPowerMonitor::~AudioPowerMonitor() { } void AudioPowerMonitor::Reset() { power_reading_ = average_power_ = 0.0f; clipped_reading_ = has_clipped_ = false; } void AudioPowerMonitor::Scan(const AudioBus& buffer, int num_frames) { DCHECK_LE(num_frames, buffer.frames()); const int num_channels = buffer.channels(); if (num_frames <= 0 || num_channels <= 0) return; // Calculate a new average power by applying a first-order low-pass filter // over the audio samples in |buffer|. // // TODO(miu): Implement optimized SSE/NEON to more efficiently compute the // results (in media/base/vector_math) in soon-upcoming change. float sum_power = 0.0f; for (int i = 0; i < num_channels; ++i) { float average_power_this_channel = average_power_; bool clipped = false; const float* p = buffer.channel(i); const float* const end_of_samples = p + num_frames; for (; p < end_of_samples; ++p) { const float sample = *p; const float sample_squared = sample * sample; clipped |= (sample_squared > 1.0f); average_power_this_channel += (sample_squared - average_power_this_channel) * sample_weight_; } // If data in audio buffer is garbage, ignore its effect on the result. if (base::IsNaN(average_power_this_channel)) { average_power_this_channel = average_power_; clipped = false; } sum_power += average_power_this_channel; has_clipped_ |= clipped; } // Update accumulated results, with clamping for sanity. average_power_ = std::max(0.0f, std::min(1.0f, sum_power / num_channels)); // Push results for reading by other threads, non-blocking. if (reading_lock_.Try()) { power_reading_ = average_power_; if (has_clipped_) { clipped_reading_ = true; has_clipped_ = false; } reading_lock_.Release(); } } std::pair AudioPowerMonitor::ReadCurrentPowerAndClip() { base::AutoLock for_reading(reading_lock_); // Convert power level to dBFS units, and pin it down to zero if it is // insignificantly small. const float kInsignificantPower = 1.0e-10f; // -100 dBFS const float power_dbfs = power_reading_ < kInsignificantPower ? zero_power() : 10.0f * log10f(power_reading_); const bool clipped = clipped_reading_; clipped_reading_ = false; return std::make_pair(power_dbfs, clipped); } } // namespace media