Change blimp README to use Markdown.
[chromium-blink-merge.git] / media / audio / audio_input_controller.cc
blob54eda2f06169f01b965d2db4f90f27480612c6dc
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/audio_input_controller.h"
7 #include "base/bind.h"
8 #include "base/metrics/histogram_macros.h"
9 #include "base/single_thread_task_runner.h"
10 #include "base/strings/string_number_conversions.h"
11 #include "base/strings/stringprintf.h"
12 #include "base/thread_task_runner_handle.h"
13 #include "base/threading/thread_restrictions.h"
14 #include "base/time/time.h"
15 #include "media/audio/audio_input_writer.h"
16 #include "media/base/user_input_monitor.h"
18 using base::TimeDelta;
20 namespace {
22 const int kMaxInputChannels = 3;
24 // TODO(henrika): remove usage of timers and add support for proper
25 // notification of when the input device is removed. This was originally added
26 // to resolve http://crbug.com/79936 for Windows platforms. This then caused
27 // breakage (very hard to repro bugs!) on other platforms: See
28 // http://crbug.com/226327 and http://crbug.com/230972.
29 // See also that the timer has been disabled on Mac now due to
30 // crbug.com/357501.
31 const int kTimerResetIntervalSeconds = 1;
32 // We have received reports that the timer can be too trigger happy on some
33 // Mac devices and the initial timer interval has therefore been increased
34 // from 1 second to 5 seconds.
35 const int kTimerInitialIntervalSeconds = 5;
37 #if defined(AUDIO_POWER_MONITORING)
38 // Time in seconds between two successive measurements of audio power levels.
39 const int kPowerMonitorLogIntervalSeconds = 15;
41 // A warning will be logged when the microphone audio volume is below this
42 // threshold.
43 const int kLowLevelMicrophoneLevelPercent = 10;
45 // Logs if the user has enabled the microphone mute or not. This is normally
46 // done by marking a checkbox in an audio-settings UI which is unique for each
47 // platform. Elements in this enum should not be added, deleted or rearranged.
48 enum MicrophoneMuteResult {
49 MICROPHONE_IS_MUTED = 0,
50 MICROPHONE_IS_NOT_MUTED = 1,
51 MICROPHONE_MUTE_MAX = MICROPHONE_IS_NOT_MUTED
54 void LogMicrophoneMuteResult(MicrophoneMuteResult result) {
55 UMA_HISTOGRAM_ENUMERATION("Media.MicrophoneMuted",
56 result,
57 MICROPHONE_MUTE_MAX + 1);
60 // Helper method which calculates the average power of an audio bus. Unit is in
61 // dBFS, where 0 dBFS corresponds to all channels and samples equal to 1.0.
62 float AveragePower(const media::AudioBus& buffer) {
63 const int frames = buffer.frames();
64 const int channels = buffer.channels();
65 if (frames <= 0 || channels <= 0)
66 return 0.0f;
68 // Scan all channels and accumulate the sum of squares for all samples.
69 float sum_power = 0.0f;
70 for (int ch = 0; ch < channels; ++ch) {
71 const float* channel_data = buffer.channel(ch);
72 for (int i = 0; i < frames; i++) {
73 const float sample = channel_data[i];
74 sum_power += sample * sample;
78 // Update accumulated average results, with clamping for sanity.
79 const float average_power =
80 std::max(0.0f, std::min(1.0f, sum_power / (frames * channels)));
82 // Convert average power level to dBFS units, and pin it down to zero if it
83 // is insignificantly small.
84 const float kInsignificantPower = 1.0e-10f; // -100 dBFS
85 const float power_dbfs = average_power < kInsignificantPower ?
86 -std::numeric_limits<float>::infinity() : 10.0f * log10f(average_power);
88 return power_dbfs;
90 #endif // AUDIO_POWER_MONITORING
94 // Used to log the result of capture startup.
95 // This was previously logged as a boolean with only the no callback and OK
96 // options. The enum order is kept to ensure backwards compatibility.
97 // Elements in this enum should not be deleted or rearranged; the only
98 // permitted operation is to add new elements before CAPTURE_STARTUP_RESULT_MAX
99 // and update CAPTURE_STARTUP_RESULT_MAX.
100 enum CaptureStartupResult {
101 CAPTURE_STARTUP_NO_DATA_CALLBACK = 0,
102 CAPTURE_STARTUP_OK = 1,
103 CAPTURE_STARTUP_CREATE_STREAM_FAILED = 2,
104 CAPTURE_STARTUP_OPEN_STREAM_FAILED = 3,
105 CAPTURE_STARTUP_RESULT_MAX = CAPTURE_STARTUP_OPEN_STREAM_FAILED
108 void LogCaptureStartupResult(CaptureStartupResult result) {
109 UMA_HISTOGRAM_ENUMERATION("Media.AudioInputControllerCaptureStartupSuccess",
110 result,
111 CAPTURE_STARTUP_RESULT_MAX + 1);
115 namespace media {
117 // static
118 AudioInputController::Factory* AudioInputController::factory_ = NULL;
120 AudioInputController::AudioInputController(EventHandler* handler,
121 SyncWriter* sync_writer,
122 UserInputMonitor* user_input_monitor,
123 const bool agc_is_enabled)
124 : creator_task_runner_(base::ThreadTaskRunnerHandle::Get()),
125 handler_(handler),
126 stream_(NULL),
127 data_is_active_(false),
128 state_(CLOSED),
129 sync_writer_(sync_writer),
130 max_volume_(0.0),
131 user_input_monitor_(user_input_monitor),
132 agc_is_enabled_(agc_is_enabled),
133 #if defined(AUDIO_POWER_MONITORING)
134 power_measurement_is_enabled_(false),
135 log_silence_state_(false),
136 silence_state_(SILENCE_STATE_NO_MEASUREMENT),
137 #endif
138 prev_key_down_count_(0),
139 input_writer_(nullptr) {
140 DCHECK(creator_task_runner_.get());
143 AudioInputController::~AudioInputController() {
144 DCHECK_EQ(state_, CLOSED);
147 // static
148 scoped_refptr<AudioInputController> AudioInputController::Create(
149 AudioManager* audio_manager,
150 EventHandler* event_handler,
151 const AudioParameters& params,
152 const std::string& device_id,
153 UserInputMonitor* user_input_monitor) {
154 DCHECK(audio_manager);
156 if (!params.IsValid() || (params.channels() > kMaxInputChannels))
157 return NULL;
159 if (factory_) {
160 return factory_->Create(
161 audio_manager, event_handler, params, user_input_monitor);
163 scoped_refptr<AudioInputController> controller(
164 new AudioInputController(event_handler, NULL, user_input_monitor, false));
166 controller->task_runner_ = audio_manager->GetTaskRunner();
168 // Create and open a new audio input stream from the existing
169 // audio-device thread.
170 if (!controller->task_runner_->PostTask(
171 FROM_HERE,
172 base::Bind(&AudioInputController::DoCreate,
173 controller,
174 base::Unretained(audio_manager),
175 params,
176 device_id))) {
177 controller = NULL;
180 return controller;
183 // static
184 scoped_refptr<AudioInputController> AudioInputController::CreateLowLatency(
185 AudioManager* audio_manager,
186 EventHandler* event_handler,
187 const AudioParameters& params,
188 const std::string& device_id,
189 SyncWriter* sync_writer,
190 UserInputMonitor* user_input_monitor,
191 const bool agc_is_enabled) {
192 DCHECK(audio_manager);
193 DCHECK(sync_writer);
195 if (!params.IsValid() || (params.channels() > kMaxInputChannels))
196 return NULL;
198 // Create the AudioInputController object and ensure that it runs on
199 // the audio-manager thread.
200 scoped_refptr<AudioInputController> controller(new AudioInputController(
201 event_handler, sync_writer, user_input_monitor, agc_is_enabled));
202 controller->task_runner_ = audio_manager->GetTaskRunner();
204 // Create and open a new audio input stream from the existing
205 // audio-device thread. Use the provided audio-input device.
206 if (!controller->task_runner_->PostTask(
207 FROM_HERE,
208 base::Bind(&AudioInputController::DoCreateForLowLatency,
209 controller,
210 base::Unretained(audio_manager),
211 params,
212 device_id))) {
213 controller = NULL;
216 return controller;
219 // static
220 scoped_refptr<AudioInputController> AudioInputController::CreateForStream(
221 const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
222 EventHandler* event_handler,
223 AudioInputStream* stream,
224 SyncWriter* sync_writer,
225 UserInputMonitor* user_input_monitor) {
226 DCHECK(sync_writer);
227 DCHECK(stream);
229 // Create the AudioInputController object and ensure that it runs on
230 // the audio-manager thread.
231 scoped_refptr<AudioInputController> controller(new AudioInputController(
232 event_handler, sync_writer, user_input_monitor, false));
233 controller->task_runner_ = task_runner;
235 // TODO(miu): See TODO at top of file. Until that's resolved, we need to
236 // disable the error auto-detection here (since the audio mirroring
237 // implementation will reliably report error and close events). Note, of
238 // course, that we're assuming CreateForStream() has been called for the audio
239 // mirroring use case only.
240 if (!controller->task_runner_->PostTask(
241 FROM_HERE,
242 base::Bind(&AudioInputController::DoCreateForStream,
243 controller,
244 stream))) {
245 controller = NULL;
248 return controller;
251 void AudioInputController::Record() {
252 task_runner_->PostTask(FROM_HERE, base::Bind(
253 &AudioInputController::DoRecord, this));
256 void AudioInputController::Close(const base::Closure& closed_task) {
257 DCHECK(!closed_task.is_null());
258 DCHECK(creator_task_runner_->BelongsToCurrentThread());
260 task_runner_->PostTaskAndReply(
261 FROM_HERE, base::Bind(&AudioInputController::DoClose, this), closed_task);
264 void AudioInputController::SetVolume(double volume) {
265 task_runner_->PostTask(FROM_HERE, base::Bind(
266 &AudioInputController::DoSetVolume, this, volume));
269 void AudioInputController::DoCreate(AudioManager* audio_manager,
270 const AudioParameters& params,
271 const std::string& device_id) {
272 DCHECK(task_runner_->BelongsToCurrentThread());
273 SCOPED_UMA_HISTOGRAM_TIMER("Media.AudioInputController.CreateTime");
274 if (handler_)
275 handler_->OnLog(this, "AIC::DoCreate");
277 #if defined(AUDIO_POWER_MONITORING)
278 // Disable power monitoring for streams that run without AGC enabled to
279 // avoid adding logs and UMA for non-WebRTC clients.
280 power_measurement_is_enabled_ = agc_is_enabled_;
281 last_audio_level_log_time_ = base::TimeTicks::Now();
282 silence_state_ = SILENCE_STATE_NO_MEASUREMENT;
283 #endif
285 // TODO(miu): See TODO at top of file. Until that's resolved, assume all
286 // platform audio input requires the |no_data_timer_| be used to auto-detect
287 // errors. In reality, probably only Windows needs to be treated as
288 // unreliable here.
289 DoCreateForStream(audio_manager->MakeAudioInputStream(params, device_id));
292 void AudioInputController::DoCreateForLowLatency(AudioManager* audio_manager,
293 const AudioParameters& params,
294 const std::string& device_id) {
295 DCHECK(task_runner_->BelongsToCurrentThread());
297 #if defined(AUDIO_POWER_MONITORING)
298 // We only log silence state UMA stats for low latency mode and if we use a
299 // real device.
300 if (params.format() != AudioParameters::AUDIO_FAKE)
301 log_silence_state_ = true;
302 #endif
304 low_latency_create_time_ = base::TimeTicks::Now();
305 DoCreate(audio_manager, params, device_id);
308 void AudioInputController::DoCreateForStream(
309 AudioInputStream* stream_to_control) {
310 DCHECK(task_runner_->BelongsToCurrentThread());
312 DCHECK(!stream_);
313 stream_ = stream_to_control;
315 if (!stream_) {
316 if (handler_)
317 handler_->OnError(this, STREAM_CREATE_ERROR);
318 LogCaptureStartupResult(CAPTURE_STARTUP_CREATE_STREAM_FAILED);
319 return;
322 if (stream_ && !stream_->Open()) {
323 stream_->Close();
324 stream_ = NULL;
325 if (handler_)
326 handler_->OnError(this, STREAM_OPEN_ERROR);
327 LogCaptureStartupResult(CAPTURE_STARTUP_OPEN_STREAM_FAILED);
328 return;
331 DCHECK(!no_data_timer_.get());
333 // Set AGC state using mode in |agc_is_enabled_| which can only be enabled in
334 // CreateLowLatency().
335 #if defined(AUDIO_POWER_MONITORING)
336 bool agc_is_supported = false;
337 agc_is_supported = stream_->SetAutomaticGainControl(agc_is_enabled_);
338 // Disable power measurements on platforms that does not support AGC at a
339 // lower level. AGC can fail on platforms where we don't support the
340 // functionality to modify the input volume slider. One such example is
341 // Windows XP.
342 power_measurement_is_enabled_ &= agc_is_supported;
343 #else
344 stream_->SetAutomaticGainControl(agc_is_enabled_);
345 #endif
347 // Create the data timer which will call FirstCheckForNoData(). The timer
348 // is started in DoRecord() and restarted in each DoCheckForNoData()
349 // callback.
350 // The timer is enabled for logging purposes. The NO_DATA_ERROR triggered
351 // from the timer must be ignored by the EventHandler.
352 // TODO(henrika): remove usage of timer when it has been verified on Canary
353 // that we are safe doing so. Goal is to get rid of |no_data_timer_| and
354 // everything that is tied to it. crbug.com/357569.
355 no_data_timer_.reset(new base::Timer(
356 FROM_HERE, base::TimeDelta::FromSeconds(kTimerInitialIntervalSeconds),
357 base::Bind(&AudioInputController::FirstCheckForNoData,
358 base::Unretained(this)), false));
360 state_ = CREATED;
361 if (handler_)
362 handler_->OnCreated(this);
364 if (user_input_monitor_) {
365 user_input_monitor_->EnableKeyPressMonitoring();
366 prev_key_down_count_ = user_input_monitor_->GetKeyPressCount();
370 void AudioInputController::DoRecord() {
371 DCHECK(task_runner_->BelongsToCurrentThread());
372 SCOPED_UMA_HISTOGRAM_TIMER("Media.AudioInputController.RecordTime");
374 if (state_ != CREATED)
375 return;
378 base::AutoLock auto_lock(lock_);
379 state_ = RECORDING;
382 if (handler_)
383 handler_->OnLog(this, "AIC::DoRecord");
385 if (no_data_timer_) {
386 // Start the data timer. Once |kTimerResetIntervalSeconds| have passed,
387 // a callback to FirstCheckForNoData() is made.
388 no_data_timer_->Reset();
391 stream_->Start(this);
392 if (handler_)
393 handler_->OnRecording(this);
396 void AudioInputController::DoClose() {
397 DCHECK(task_runner_->BelongsToCurrentThread());
398 SCOPED_UMA_HISTOGRAM_TIMER("Media.AudioInputController.CloseTime");
400 if (state_ == CLOSED)
401 return;
403 // If this is a low-latency stream, log the total duration (since DoCreate)
404 // and add it to a UMA histogram.
405 if (!low_latency_create_time_.is_null()) {
406 base::TimeDelta duration =
407 base::TimeTicks::Now() - low_latency_create_time_;
408 UMA_HISTOGRAM_LONG_TIMES("Media.InputStreamDuration", duration);
409 if (handler_) {
410 std::string log_string =
411 base::StringPrintf("AIC::DoClose: stream duration=");
412 log_string += base::Int64ToString(duration.InSeconds());
413 log_string += " seconds";
414 handler_->OnLog(this, log_string);
418 // Delete the timer on the same thread that created it.
419 no_data_timer_.reset();
421 DoStopCloseAndClearStream();
422 SetDataIsActive(false);
424 if (SharedMemoryAndSyncSocketMode())
425 sync_writer_->Close();
427 if (user_input_monitor_)
428 user_input_monitor_->DisableKeyPressMonitoring();
430 #if defined(AUDIO_POWER_MONITORING)
431 // Send UMA stats if enabled.
432 if (log_silence_state_)
433 LogSilenceState(silence_state_);
434 log_silence_state_ = false;
435 #endif
437 input_writer_ = nullptr;
439 state_ = CLOSED;
442 void AudioInputController::DoReportError() {
443 DCHECK(task_runner_->BelongsToCurrentThread());
444 if (handler_)
445 handler_->OnError(this, STREAM_ERROR);
448 void AudioInputController::DoSetVolume(double volume) {
449 DCHECK(task_runner_->BelongsToCurrentThread());
450 DCHECK_GE(volume, 0);
451 DCHECK_LE(volume, 1.0);
453 if (state_ != CREATED && state_ != RECORDING)
454 return;
456 // Only ask for the maximum volume at first call and use cached value
457 // for remaining function calls.
458 if (!max_volume_) {
459 max_volume_ = stream_->GetMaxVolume();
462 if (max_volume_ == 0.0) {
463 DLOG(WARNING) << "Failed to access input volume control";
464 return;
467 // Set the stream volume and scale to a range matched to the platform.
468 stream_->SetVolume(max_volume_ * volume);
471 void AudioInputController::FirstCheckForNoData() {
472 DCHECK(task_runner_->BelongsToCurrentThread());
473 LogCaptureStartupResult(GetDataIsActive() ?
474 CAPTURE_STARTUP_OK :
475 CAPTURE_STARTUP_NO_DATA_CALLBACK);
476 if (handler_) {
477 handler_->OnLog(this, GetDataIsActive() ?
478 "AIC::FirstCheckForNoData => data is active" :
479 "AIC::FirstCheckForNoData => data is NOT active");
481 DoCheckForNoData();
484 void AudioInputController::DoCheckForNoData() {
485 DCHECK(task_runner_->BelongsToCurrentThread());
487 if (!GetDataIsActive()) {
488 // The data-is-active marker will be false only if it has been more than
489 // one second since a data packet was recorded. This can happen if a
490 // capture device has been removed or disabled.
491 if (handler_)
492 handler_->OnError(this, NO_DATA_ERROR);
495 // Mark data as non-active. The flag will be re-enabled in OnData() each
496 // time a data packet is received. Hence, under normal conditions, the
497 // flag will only be disabled during a very short period.
498 SetDataIsActive(false);
500 // Restart the timer to ensure that we check the flag again in
501 // |kTimerResetIntervalSeconds|.
502 no_data_timer_->Start(
503 FROM_HERE, base::TimeDelta::FromSeconds(kTimerResetIntervalSeconds),
504 base::Bind(&AudioInputController::DoCheckForNoData,
505 base::Unretained(this)));
508 void AudioInputController::OnData(AudioInputStream* stream,
509 const AudioBus* source,
510 uint32 hardware_delay_bytes,
511 double volume) {
512 // |input_writer_| should only be accessed on the audio thread, but as a means
513 // to avoid copying data and posting on the audio thread, we just check for
514 // non-null here.
515 if (input_writer_) {
516 scoped_ptr<AudioBus> source_copy =
517 AudioBus::Create(source->channels(), source->frames());
518 source->CopyTo(source_copy.get());
519 task_runner_->PostTask(
520 FROM_HERE,
521 base::Bind(
522 &AudioInputController::WriteInputDataForDebugging,
523 this,
524 base::Passed(&source_copy)));
527 // Mark data as active to ensure that the periodic calls to
528 // DoCheckForNoData() does not report an error to the event handler.
529 SetDataIsActive(true);
532 base::AutoLock auto_lock(lock_);
533 if (state_ != RECORDING)
534 return;
537 bool key_pressed = false;
538 if (user_input_monitor_) {
539 size_t current_count = user_input_monitor_->GetKeyPressCount();
540 key_pressed = current_count != prev_key_down_count_;
541 prev_key_down_count_ = current_count;
542 DVLOG_IF(6, key_pressed) << "Detected keypress.";
545 // Use SharedMemory and SyncSocket if the client has created a SyncWriter.
546 // Used by all low-latency clients except WebSpeech.
547 if (SharedMemoryAndSyncSocketMode()) {
548 sync_writer_->Write(source, volume, key_pressed, hardware_delay_bytes);
550 #if defined(AUDIO_POWER_MONITORING)
551 // Only do power-level measurements if DoCreate() has been called. It will
552 // ensure that logging will mainly be done for WebRTC and WebSpeech
553 // clients.
554 if (!power_measurement_is_enabled_)
555 return;
557 // Perform periodic audio (power) level measurements.
558 if ((base::TimeTicks::Now() - last_audio_level_log_time_).InSeconds() >
559 kPowerMonitorLogIntervalSeconds) {
560 // Calculate the average power of the signal, or the energy per sample.
561 const float average_power_dbfs = AveragePower(*source);
563 // Add current microphone volume to log and UMA histogram.
564 const int mic_volume_percent = static_cast<int>(100.0 * volume);
566 // Use event handler on the audio thread to relay a message to the ARIH
567 // in content which does the actual logging on the IO thread.
568 task_runner_->PostTask(FROM_HERE,
569 base::Bind(&AudioInputController::DoLogAudioLevels,
570 this,
571 average_power_dbfs,
572 mic_volume_percent));
574 last_audio_level_log_time_ = base::TimeTicks::Now();
576 #endif
577 return;
580 // TODO(henrika): Investigate if we can avoid the extra copy here.
581 // (see http://crbug.com/249316 for details). AFAIK, this scope is only
582 // active for WebSpeech clients.
583 scoped_ptr<AudioBus> audio_data =
584 AudioBus::Create(source->channels(), source->frames());
585 source->CopyTo(audio_data.get());
587 // Ownership of the audio buffer will be with the callback until it is run,
588 // when ownership is passed to the callback function.
589 task_runner_->PostTask(
590 FROM_HERE,
591 base::Bind(
592 &AudioInputController::DoOnData, this, base::Passed(&audio_data)));
595 void AudioInputController::DoOnData(scoped_ptr<AudioBus> data) {
596 DCHECK(task_runner_->BelongsToCurrentThread());
597 if (handler_)
598 handler_->OnData(this, data.get());
601 void AudioInputController::DoLogAudioLevels(float level_dbfs,
602 int microphone_volume_percent) {
603 #if defined(AUDIO_POWER_MONITORING)
604 DCHECK(task_runner_->BelongsToCurrentThread());
605 if (!handler_)
606 return;
608 // Detect if the user has enabled hardware mute by pressing the mute
609 // button in audio settings for the selected microphone.
610 const bool microphone_is_muted = stream_->IsMuted();
611 if (microphone_is_muted) {
612 LogMicrophoneMuteResult(MICROPHONE_IS_MUTED);
613 handler_->OnLog(this, "AIC::OnData: microphone is muted!");
614 // Return early if microphone is muted. No need to adding logs and UMA stats
615 // of audio levels if we know that the micropone is muted.
616 return;
619 LogMicrophoneMuteResult(MICROPHONE_IS_NOT_MUTED);
621 std::string log_string = base::StringPrintf(
622 "AIC::OnData: average audio level=%.2f dBFS", level_dbfs);
623 static const float kSilenceThresholdDBFS = -72.24719896f;
624 if (level_dbfs < kSilenceThresholdDBFS)
625 log_string += " <=> low audio input level!";
626 handler_->OnLog(this, log_string);
628 UpdateSilenceState(level_dbfs < kSilenceThresholdDBFS);
630 UMA_HISTOGRAM_PERCENTAGE("Media.MicrophoneVolume", microphone_volume_percent);
631 log_string = base::StringPrintf(
632 "AIC::OnData: microphone volume=%d%%", microphone_volume_percent);
633 if (microphone_volume_percent < kLowLevelMicrophoneLevelPercent)
634 log_string += " <=> low microphone level!";
635 handler_->OnLog(this, log_string);
636 #endif
639 void AudioInputController::OnError(AudioInputStream* stream) {
640 // Handle error on the audio-manager thread.
641 task_runner_->PostTask(FROM_HERE, base::Bind(
642 &AudioInputController::DoReportError, this));
645 void AudioInputController::EnableDebugRecording(
646 AudioInputWriter* input_writer) {
647 task_runner_->PostTask(FROM_HERE, base::Bind(
648 &AudioInputController::DoEnableDebugRecording,
649 this,
650 input_writer));
653 void AudioInputController::DisableDebugRecording(
654 const base::Closure& callback) {
655 DCHECK(creator_task_runner_->BelongsToCurrentThread());
656 DCHECK(!callback.is_null());
658 task_runner_->PostTaskAndReply(
659 FROM_HERE,
660 base::Bind(&AudioInputController::DoDisableDebugRecording,
661 this),
662 callback);
665 void AudioInputController::DoStopCloseAndClearStream() {
666 DCHECK(task_runner_->BelongsToCurrentThread());
668 // Allow calling unconditionally and bail if we don't have a stream to close.
669 if (stream_ != NULL) {
670 stream_->Stop();
671 stream_->Close();
672 stream_ = NULL;
675 // The event handler should not be touched after the stream has been closed.
676 handler_ = NULL;
679 void AudioInputController::SetDataIsActive(bool enabled) {
680 base::subtle::Release_Store(&data_is_active_, enabled);
683 bool AudioInputController::GetDataIsActive() {
684 return (base::subtle::Acquire_Load(&data_is_active_) != false);
687 #if defined(AUDIO_POWER_MONITORING)
688 void AudioInputController::UpdateSilenceState(bool silence) {
689 if (silence) {
690 if (silence_state_ == SILENCE_STATE_NO_MEASUREMENT) {
691 silence_state_ = SILENCE_STATE_ONLY_SILENCE;
692 } else if (silence_state_ == SILENCE_STATE_ONLY_AUDIO) {
693 silence_state_ = SILENCE_STATE_AUDIO_AND_SILENCE;
694 } else {
695 DCHECK(silence_state_ == SILENCE_STATE_ONLY_SILENCE ||
696 silence_state_ == SILENCE_STATE_AUDIO_AND_SILENCE);
698 } else {
699 if (silence_state_ == SILENCE_STATE_NO_MEASUREMENT) {
700 silence_state_ = SILENCE_STATE_ONLY_AUDIO;
701 } else if (silence_state_ == SILENCE_STATE_ONLY_SILENCE) {
702 silence_state_ = SILENCE_STATE_AUDIO_AND_SILENCE;
703 } else {
704 DCHECK(silence_state_ == SILENCE_STATE_ONLY_AUDIO ||
705 silence_state_ == SILENCE_STATE_AUDIO_AND_SILENCE);
710 void AudioInputController::LogSilenceState(SilenceState value) {
711 UMA_HISTOGRAM_ENUMERATION("Media.AudioInputControllerSessionSilenceReport",
712 value,
713 SILENCE_STATE_MAX + 1);
715 #endif
717 void AudioInputController::DoEnableDebugRecording(
718 AudioInputWriter* input_writer) {
719 DCHECK(task_runner_->BelongsToCurrentThread());
720 DCHECK(!input_writer_);
721 input_writer_ = input_writer;
724 void AudioInputController::DoDisableDebugRecording() {
725 DCHECK(task_runner_->BelongsToCurrentThread());
726 input_writer_ = nullptr;
729 void AudioInputController::WriteInputDataForDebugging(
730 scoped_ptr<AudioBus> data) {
731 DCHECK(task_runner_->BelongsToCurrentThread());
732 if (input_writer_)
733 input_writer_->Write(data.Pass());
736 } // namespace media