Delete chrome.mediaGalleriesPrivate because the functionality unique to it has since...
[chromium-blink-merge.git] / media / audio / fake_audio_input_stream.cc
blob4632b258eda2abaf261bb7dba214ab6aba15d8bb
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();
74 CHECK_GT(wav_file_length, 0u)
75 << "Input file to fake device is empty: " << wav_filename.value();
77 uint8* wav_file_data = new uint8[wav_file_length];
78 size_t read_bytes = wav_file.Read(0, reinterpret_cast<char*>(wav_file_data),
79 wav_file_length);
80 if (read_bytes != wav_file_length) {
81 CHECK(false) << "Failed to read all bytes of " << wav_filename.value();
82 return nullptr;
84 *file_length = wav_file_length;
85 return scoped_ptr<uint8[]>(wav_file_data);
88 // Opens |wav_filename|, reads it and loads it as a Wav file. This function will
89 // bluntly 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));
97 return wav_audio_handler.Pass();
100 static base::LazyInstance<BeepContext> g_beep_context =
101 LAZY_INSTANCE_INITIALIZER;
103 } // namespace
105 AudioInputStream* FakeAudioInputStream::MakeFakeStream(
106 AudioManagerBase* manager,
107 const AudioParameters& params) {
108 return new FakeAudioInputStream(manager, params);
111 FakeAudioInputStream::FakeAudioInputStream(AudioManagerBase* manager,
112 const AudioParameters& params)
113 : audio_manager_(manager),
114 callback_(NULL),
115 buffer_size_((params.channels() * params.bits_per_sample() *
116 params.frames_per_buffer()) /
118 params_(params),
119 task_runner_(manager->GetTaskRunner()),
120 callback_interval_(base::TimeDelta::FromMilliseconds(
121 (params.frames_per_buffer() * 1000) / params.sample_rate())),
122 beep_duration_in_buffers_(kBeepDurationMilliseconds *
123 params.sample_rate() /
124 params.frames_per_buffer() /
125 1000),
126 beep_generated_in_buffers_(0),
127 beep_period_in_frames_(params.sample_rate() / kBeepFrequency),
128 audio_bus_(AudioBus::Create(params)),
129 wav_file_read_pos_(0),
130 weak_factory_(this) {
131 DCHECK(audio_manager_->GetTaskRunner()->BelongsToCurrentThread());
134 FakeAudioInputStream::~FakeAudioInputStream() {}
136 bool FakeAudioInputStream::Open() {
137 DCHECK(audio_manager_->GetTaskRunner()->BelongsToCurrentThread());
138 buffer_.reset(new uint8[buffer_size_]);
139 memset(buffer_.get(), 0, buffer_size_);
140 audio_bus_->Zero();
142 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
143 switches::kUseFileForFakeAudioCapture)) {
144 OpenInFileMode(base::CommandLine::ForCurrentProcess()->GetSwitchValuePath(
145 switches::kUseFileForFakeAudioCapture));
148 return true;
151 void FakeAudioInputStream::Start(AudioInputCallback* callback) {
152 DCHECK(audio_manager_->GetTaskRunner()->BelongsToCurrentThread());
153 DCHECK(!callback_);
154 callback_ = callback;
155 last_callback_time_ = TimeTicks::Now();
157 task_runner_->PostDelayedTask(
158 FROM_HERE,
159 base::Bind(&FakeAudioInputStream::DoCallback, weak_factory_.GetWeakPtr()),
160 callback_interval_);
163 void FakeAudioInputStream::DoCallback() {
164 DCHECK(callback_);
166 const TimeTicks now = TimeTicks::Now();
167 base::TimeDelta next_callback_time =
168 last_callback_time_ + callback_interval_ * 2 - now;
170 // If we are falling behind, try to catch up as much as we can in the next
171 // callback.
172 if (next_callback_time < base::TimeDelta())
173 next_callback_time = base::TimeDelta();
175 if (PlayingFromFile()) {
176 PlayFile();
177 } else {
178 PlayBeep();
181 last_callback_time_ = now;
183 task_runner_->PostDelayedTask(
184 FROM_HERE,
185 base::Bind(&FakeAudioInputStream::DoCallback, weak_factory_.GetWeakPtr()),
186 next_callback_time);
189 void FakeAudioInputStream::OpenInFileMode(const base::FilePath& wav_filename) {
190 CHECK(!wav_filename.empty())
191 << "You must pass the file to use as argument to --"
192 << switches::kUseFileForFakeAudioCapture << ".";
194 // Read the file, and put its data in a scoped_ptr so it gets deleted later.
195 size_t file_length = 0;
196 wav_file_data_ = ReadWavFile(wav_filename, &file_length);
197 wav_audio_handler_ = CreateWavAudioHandler(
198 wav_filename, wav_file_data_.get(), file_length, params_);
200 // Hook us up so we pull in data from the file into the converter. We need to
201 // modify the wav file's audio parameters since we'll be reading small slices
202 // of it at a time and not the whole thing (like 10 ms at a time).
203 AudioParameters file_audio_slice(
204 wav_audio_handler_->params().format(),
205 wav_audio_handler_->params().channel_layout(),
206 wav_audio_handler_->params().sample_rate(),
207 wav_audio_handler_->params().bits_per_sample(),
208 params_.frames_per_buffer());
210 file_audio_converter_.reset(
211 new AudioConverter(file_audio_slice, params_, false));
212 file_audio_converter_->AddInput(this);
215 bool FakeAudioInputStream::PlayingFromFile() {
216 return wav_audio_handler_.get() != nullptr;
219 void FakeAudioInputStream::PlayFile() {
220 // Stop playing if we've played out the whole file.
221 if (wav_audio_handler_->AtEnd(wav_file_read_pos_))
222 return;
224 file_audio_converter_->Convert(audio_bus_.get());
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 bool FakeAudioInputStream::SetAutomaticGainControl(bool enabled) {
309 return false;
312 bool FakeAudioInputStream::GetAutomaticGainControl() {
313 return false;
316 // static
317 void FakeAudioInputStream::BeepOnce() {
318 BeepContext* beep_context = g_beep_context.Pointer();
319 beep_context->SetBeepOnce(true);
322 double FakeAudioInputStream::ProvideInput(AudioBus* audio_bus_into_converter,
323 base::TimeDelta buffer_delay) {
324 // Unfilled frames will be zeroed by CopyTo.
325 size_t bytes_written;
326 wav_audio_handler_->CopyTo(audio_bus_into_converter, wav_file_read_pos_,
327 &bytes_written);
328 wav_file_read_pos_ += bytes_written;
329 return 1.0;
332 } // namespace media