1 // Copyright 2013 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 "media/cast/test/audio_utility.h" 6 7 #include "base/time/time.h" 8 #include "media/base/audio_bus.h" 9 #include "media/cast/cast_config.h" 10 11 namespace media { 12 namespace cast { 13 14 TestAudioBusFactory::TestAudioBusFactory(int num_channels, 15 int sample_rate, 16 float sine_wave_frequency, 17 float volume) 18 : num_channels_(num_channels), 19 sample_rate_(sample_rate), 20 volume_(volume), 21 source_(num_channels, sine_wave_frequency, sample_rate) { 22 CHECK_LT(0, num_channels); 23 CHECK_LT(0, sample_rate); 24 CHECK_LE(0.0f, volume_); 25 CHECK_LE(volume_, 1.0f); 26 } 27 28 TestAudioBusFactory::~TestAudioBusFactory() {} 29 30 scoped_ptr<AudioBus> TestAudioBusFactory::NextAudioBus( 31 const base::TimeDelta& duration) { 32 const int num_samples = static_cast<int>( 33 (sample_rate_ * duration) / base::TimeDelta::FromSeconds(1)); 34 scoped_ptr<AudioBus> bus(AudioBus::Create(num_channels_, num_samples)); 35 source_.OnMoreData(bus.get(), AudioBuffersState()); 36 bus->Scale(volume_); 37 return bus.Pass(); 38 } 39 40 scoped_ptr<PcmAudioFrame> ToPcmAudioFrame(const AudioBus& audio_bus, 41 int sample_rate) { 42 scoped_ptr<PcmAudioFrame> audio_frame(new PcmAudioFrame()); 43 audio_frame->channels = audio_bus.channels(); 44 audio_frame->frequency = sample_rate; 45 audio_frame->samples.resize(audio_bus.channels() * audio_bus.frames()); 46 audio_bus.ToInterleaved( 47 audio_bus.frames(), sizeof(audio_frame->samples.front()), 48 &audio_frame->samples.front()); 49 return audio_frame.Pass(); 50 } 51 52 int CountZeroCrossings(const std::vector<int16>& samples) { 53 // The sample values must pass beyond |kAmplitudeThreshold| on the opposite 54 // side of zero before a crossing will be counted. 55 const int kAmplitudeThreshold = 1000; // Approx. 3% of max amplitude. 56 57 int count = 0; 58 std::vector<int16>::const_iterator i = samples.begin(); 59 int16 last = 0; 60 for (; i != samples.end() && abs(last) < kAmplitudeThreshold; ++i) 61 last = *i; 62 for (; i != samples.end(); ++i) { 63 if (abs(*i) >= kAmplitudeThreshold && 64 (last < 0) != (*i < 0)) { 65 ++count; 66 last = *i; 67 } 68 } 69 return count; 70 } 71 72 } // namespace cast 73 } // namespace media 74