[MemSheriff] More sendto parameter issues.
[chromium-blink-merge.git] / media / audio / fake_audio_input_stream.cc
blobce65c69046bd4ccc7552f98a823325ea24820690
1 // Copyright (c) 2012 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 "media/audio/fake_audio_input_stream.h"
7 #include "base/bind.h"
8 #include "base/command_line.h"
9 #include "base/files/file.h"
10 #include "base/lazy_instance.h"
11 #include "media/audio/audio_manager_base.h"
12 #include "media/base/audio_bus.h"
13 #include "media/base/media_switches.h"
15 using base::TimeTicks;
16 using base::TimeDelta;
18 namespace media {
20 namespace {
22 // These values are based on experiments for local-to-local
23 // PeerConnection to demonstrate audio/video synchronization.
24 const int kBeepDurationMilliseconds = 20;
25 const int kBeepFrequency = 400;
27 // Intervals between two automatic beeps.
28 const int kAutomaticBeepIntervalInMs = 500;
30 // Automatic beep will be triggered every |kAutomaticBeepIntervalInMs| unless
31 // users explicitly call BeepOnce(), which will disable the automatic beep.
32 class BeepContext {
33 public:
34 BeepContext() : beep_once_(false), automatic_beep_(true) {}
36 void SetBeepOnce(bool enable) {
37 base::AutoLock auto_lock(lock_);
38 beep_once_ = enable;
40 // Disable the automatic beep if users explicit set |beep_once_| to true.
41 if (enable)
42 automatic_beep_ = false;
44 bool beep_once() const {
45 base::AutoLock auto_lock(lock_);
46 return beep_once_;
48 bool automatic_beep() const {
49 base::AutoLock auto_lock(lock_);
50 return automatic_beep_;
53 private:
54 mutable base::Lock lock_;
55 bool beep_once_;
56 bool automatic_beep_;
59 // Opens |wav_filename|, reads it and loads it as a wav file. This function will
60 // bluntly trigger CHECKs if we can't read the file or if it's malformed. The
61 // caller takes ownership of the returned data. The size of the data is stored
62 // in |read_length|.
63 scoped_ptr<uint8[]> ReadWavFile(const base::FilePath& wav_filename,
64 size_t* file_length) {
65 base::File wav_file(
66 wav_filename, base::File::FLAG_OPEN | base::File::FLAG_READ);
67 if (!wav_file.IsValid()) {
68 CHECK(false) << "Failed to read " << wav_filename.value() << " as input to "
69 << "the fake device.";
70 return nullptr;
73 size_t wav_file_length = wav_file.GetLength();
75 uint8* wav_file_data = new uint8[wav_file_length];
76 size_t read_bytes = wav_file.Read(0, reinterpret_cast<char*>(wav_file_data),
77 wav_file_length);
78 if (read_bytes != wav_file_length) {
79 CHECK(false) << "Failed to read all bytes of " << wav_filename.value();
80 return nullptr;
82 *file_length = wav_file_length;
83 return scoped_ptr<uint8[]>(wav_file_data);
86 // Opens |wav_filename|, reads it and loads it as a Wav file. This function will
87 // bluntly trigger CHECKs if the file doesn't have the sampling frequency, bits
88 // per sample or number of channels as specified in |expected_params|. We also
89 // trigger CHECKs if we can't read the file or if it's malformed.
90 scoped_ptr<media::WavAudioHandler> CreateWavAudioHandler(
91 const base::FilePath& wav_filename, const uint8* wav_file_data,
92 size_t wav_file_length, const AudioParameters& expected_params) {
93 base::StringPiece wav_data(reinterpret_cast<const char*>(wav_file_data),
94 wav_file_length);
95 scoped_ptr<media::WavAudioHandler> wav_audio_handler(
96 new media::WavAudioHandler(wav_data));
98 // Ensure the input file matches what the audio bus wants, otherwise bail out.
99 CHECK_EQ(wav_audio_handler->params().channels(),
100 expected_params.channels())
101 << "Failed to read " << wav_filename.value() << " to fake device.";
102 CHECK_EQ(wav_audio_handler->params().sample_rate(),
103 expected_params.sample_rate())
104 << "Failed to read " << wav_filename.value() << " to fake device.";
105 CHECK_EQ(wav_audio_handler->params().bits_per_sample(),
106 expected_params.bits_per_sample())
107 << "Failed to read " << wav_filename.value() << " to fake device.";
109 return wav_audio_handler.Pass();
112 static base::LazyInstance<BeepContext> g_beep_context =
113 LAZY_INSTANCE_INITIALIZER;
115 } // namespace
117 AudioInputStream* FakeAudioInputStream::MakeFakeStream(
118 AudioManagerBase* manager,
119 const AudioParameters& params) {
120 return new FakeAudioInputStream(manager, params);
123 FakeAudioInputStream::FakeAudioInputStream(AudioManagerBase* manager,
124 const AudioParameters& params)
125 : audio_manager_(manager),
126 callback_(NULL),
127 buffer_size_((params.channels() * params.bits_per_sample() *
128 params.frames_per_buffer()) /
130 params_(params),
131 task_runner_(manager->GetTaskRunner()),
132 callback_interval_(base::TimeDelta::FromMilliseconds(
133 (params.frames_per_buffer() * 1000) / params.sample_rate())),
134 beep_duration_in_buffers_(kBeepDurationMilliseconds *
135 params.sample_rate() /
136 params.frames_per_buffer() /
137 1000),
138 beep_generated_in_buffers_(0),
139 beep_period_in_frames_(params.sample_rate() / kBeepFrequency),
140 audio_bus_(AudioBus::Create(params)),
141 wav_file_read_pos_(0),
142 weak_factory_(this) {
143 DCHECK(audio_manager_->GetTaskRunner()->BelongsToCurrentThread());
146 FakeAudioInputStream::~FakeAudioInputStream() {}
148 bool FakeAudioInputStream::Open() {
149 DCHECK(audio_manager_->GetTaskRunner()->BelongsToCurrentThread());
150 buffer_.reset(new uint8[buffer_size_]);
151 memset(buffer_.get(), 0, buffer_size_);
152 audio_bus_->Zero();
154 if (CommandLine::ForCurrentProcess()->HasSwitch(
155 switches::kUseFileForFakeAudioCapture)) {
156 OpenInFileMode(CommandLine::ForCurrentProcess()->GetSwitchValuePath(
157 switches::kUseFileForFakeAudioCapture));
160 return true;
163 void FakeAudioInputStream::Start(AudioInputCallback* callback) {
164 DCHECK(audio_manager_->GetTaskRunner()->BelongsToCurrentThread());
165 DCHECK(!callback_);
166 callback_ = callback;
167 last_callback_time_ = TimeTicks::Now();
169 task_runner_->PostDelayedTask(
170 FROM_HERE,
171 base::Bind(&FakeAudioInputStream::DoCallback, weak_factory_.GetWeakPtr()),
172 callback_interval_);
175 void FakeAudioInputStream::DoCallback() {
176 DCHECK(callback_);
178 const TimeTicks now = TimeTicks::Now();
179 base::TimeDelta next_callback_time =
180 last_callback_time_ + callback_interval_ * 2 - now;
182 // If we are falling behind, try to catch up as much as we can in the next
183 // callback.
184 if (next_callback_time < base::TimeDelta())
185 next_callback_time = base::TimeDelta();
187 if (PlayingFromFile()) {
188 PlayFileLooping();
189 } else {
190 PlayBeep();
193 last_callback_time_ = now;
195 task_runner_->PostDelayedTask(
196 FROM_HERE,
197 base::Bind(&FakeAudioInputStream::DoCallback, weak_factory_.GetWeakPtr()),
198 next_callback_time);
201 void FakeAudioInputStream::OpenInFileMode(const base::FilePath& wav_filename) {
202 CHECK(!wav_filename.empty())
203 << "You must pass the file to use as argument to --"
204 << switches::kUseFileForFakeAudioCapture << ".";
206 // Read the file, and put its data in a scoped_ptr so it gets deleted later.
207 size_t file_length = 0;
208 wav_file_data_ = ReadWavFile(wav_filename, &file_length);
209 wav_audio_handler_ = CreateWavAudioHandler(
210 wav_filename, wav_file_data_.get(), file_length, params_);
213 bool FakeAudioInputStream::PlayingFromFile() {
214 return wav_audio_handler_.get() != nullptr;
217 void FakeAudioInputStream::PlayFileLooping() {
218 // Unfilled frames will be zeroed by CopyTo.
219 size_t bytes_written;
220 wav_audio_handler_->CopyTo(audio_bus_.get(), wav_file_read_pos_,
221 &bytes_written);
222 wav_file_read_pos_ += bytes_written;
223 if (wav_audio_handler_->AtEnd(wav_file_read_pos_))
224 wav_file_read_pos_ = 0;
225 callback_->OnData(this, audio_bus_.get(), buffer_size_, 1.0);
228 void FakeAudioInputStream::PlayBeep() {
229 // Accumulate the time from the last beep.
230 interval_from_last_beep_ += TimeTicks::Now() - last_callback_time_;
232 memset(buffer_.get(), 0, buffer_size_);
233 bool should_beep = false;
235 BeepContext* beep_context = g_beep_context.Pointer();
236 if (beep_context->automatic_beep()) {
237 base::TimeDelta delta = interval_from_last_beep_ -
238 TimeDelta::FromMilliseconds(kAutomaticBeepIntervalInMs);
239 if (delta > base::TimeDelta()) {
240 should_beep = true;
241 interval_from_last_beep_ = delta;
243 } else {
244 should_beep = beep_context->beep_once();
245 beep_context->SetBeepOnce(false);
249 // If this object was instructed to generate a beep or has started to
250 // generate a beep sound.
251 if (should_beep || beep_generated_in_buffers_) {
252 // Compute the number of frames to output high value. Then compute the
253 // number of bytes based on channels and bits per channel.
254 int high_frames = beep_period_in_frames_ / 2;
255 int high_bytes = high_frames * params_.bits_per_sample() *
256 params_.channels() / 8;
258 // Separate high and low with the same number of bytes to generate a
259 // square wave.
260 int position = 0;
261 while (position + high_bytes <= buffer_size_) {
262 // Write high values first.
263 memset(buffer_.get() + position, 128, high_bytes);
264 // Then leave low values in the buffer with |high_bytes|.
265 position += high_bytes * 2;
268 ++beep_generated_in_buffers_;
269 if (beep_generated_in_buffers_ >= beep_duration_in_buffers_)
270 beep_generated_in_buffers_ = 0;
273 audio_bus_->FromInterleaved(
274 buffer_.get(), audio_bus_->frames(), params_.bits_per_sample() / 8);
275 callback_->OnData(this, audio_bus_.get(), buffer_size_, 1.0);
278 void FakeAudioInputStream::Stop() {
279 DCHECK(audio_manager_->GetTaskRunner()->BelongsToCurrentThread());
280 weak_factory_.InvalidateWeakPtrs();
281 callback_ = NULL;
284 void FakeAudioInputStream::Close() {
285 DCHECK(audio_manager_->GetTaskRunner()->BelongsToCurrentThread());
286 audio_manager_->ReleaseInputStream(this);
289 double FakeAudioInputStream::GetMaxVolume() {
290 DCHECK(audio_manager_->GetTaskRunner()->BelongsToCurrentThread());
291 return 1.0;
294 void FakeAudioInputStream::SetVolume(double volume) {
295 DCHECK(audio_manager_->GetTaskRunner()->BelongsToCurrentThread());
298 double FakeAudioInputStream::GetVolume() {
299 DCHECK(audio_manager_->GetTaskRunner()->BelongsToCurrentThread());
300 return 1.0;
303 bool FakeAudioInputStream::IsMuted() {
304 DCHECK(audio_manager_->GetTaskRunner()->BelongsToCurrentThread());
305 return false;
308 void FakeAudioInputStream::SetAutomaticGainControl(bool enabled) {}
310 bool FakeAudioInputStream::GetAutomaticGainControl() {
311 return true;
314 // static
315 void FakeAudioInputStream::BeepOnce() {
316 BeepContext* beep_context = g_beep_context.Pointer();
317 beep_context->SetBeepOnce(true);
320 } // namespace media