Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(145)

Side by Side Diff: media/audio/audio_input_controller.cc

Issue 2624403002: Refactor AudioInputController and related interfaces. (Closed)
Patch Set: Address comments Created 3 years, 11 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « media/audio/audio_input_controller.h ('k') | media/audio/audio_input_controller_unittest.cc » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 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 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "media/audio/audio_input_controller.h" 5 #include "media/audio/audio_input_controller.h"
6 6
7 #include <inttypes.h>
8
7 #include <algorithm> 9 #include <algorithm>
8 #include <limits> 10 #include <limits>
9 #include <utility> 11 #include <utility>
10 12
11 #include "base/bind.h" 13 #include "base/bind.h"
12 #include "base/metrics/histogram_macros.h" 14 #include "base/metrics/histogram_macros.h"
13 #include "base/single_thread_task_runner.h" 15 #include "base/single_thread_task_runner.h"
14 #include "base/strings/string_number_conversions.h" 16 #include "base/strings/string_number_conversions.h"
15 #include "base/strings/stringprintf.h" 17 #include "base/strings/stringprintf.h"
16 #include "base/threading/thread_restrictions.h" 18 #include "base/threading/thread_restrictions.h"
17 #include "base/threading/thread_task_runner_handle.h" 19 #include "base/threading/thread_task_runner_handle.h"
18 #include "base/time/time.h" 20 #include "base/time/time.h"
19 #include "base/trace_event/trace_event.h" 21 #include "base/trace_event/trace_event.h"
20 #include "media/audio/audio_file_writer.h" 22 #include "media/audio/audio_file_writer.h"
21 #include "media/base/user_input_monitor.h" 23 #include "media/base/user_input_monitor.h"
22 24
25 namespace media {
23 namespace { 26 namespace {
24 27
25 const int kMaxInputChannels = 3; 28 const int kMaxInputChannels = 3;
26 29
27 #if defined(AUDIO_POWER_MONITORING) 30 #if defined(AUDIO_POWER_MONITORING)
28 // Time in seconds between two successive measurements of audio power levels. 31 // Time in seconds between two successive measurements of audio power levels.
29 const int kPowerMonitorLogIntervalSeconds = 15; 32 const int kPowerMonitorLogIntervalSeconds = 15;
30 33
31 // A warning will be logged when the microphone audio volume is below this 34 // A warning will be logged when the microphone audio volume is below this
32 // threshold. 35 // threshold.
33 const int kLowLevelMicrophoneLevelPercent = 10; 36 const int kLowLevelMicrophoneLevelPercent = 10;
34 37
35 // Logs if the user has enabled the microphone mute or not. This is normally 38 // Logs if the user has enabled the microphone mute or not. This is normally
36 // done by marking a checkbox in an audio-settings UI which is unique for each 39 // done by marking a checkbox in an audio-settings UI which is unique for each
37 // platform. Elements in this enum should not be added, deleted or rearranged. 40 // platform. Elements in this enum should not be added, deleted or rearranged.
38 enum MicrophoneMuteResult { 41 enum MicrophoneMuteResult {
39 MICROPHONE_IS_MUTED = 0, 42 MICROPHONE_IS_MUTED = 0,
40 MICROPHONE_IS_NOT_MUTED = 1, 43 MICROPHONE_IS_NOT_MUTED = 1,
41 MICROPHONE_MUTE_MAX = MICROPHONE_IS_NOT_MUTED 44 MICROPHONE_MUTE_MAX = MICROPHONE_IS_NOT_MUTED
42 }; 45 };
43 46
44 void LogMicrophoneMuteResult(MicrophoneMuteResult result) { 47 void LogMicrophoneMuteResult(MicrophoneMuteResult result) {
45 UMA_HISTOGRAM_ENUMERATION("Media.MicrophoneMuted", 48 UMA_HISTOGRAM_ENUMERATION("Media.MicrophoneMuted",
46 result, 49 result,
47 MICROPHONE_MUTE_MAX + 1); 50 MICROPHONE_MUTE_MAX + 1);
48 } 51 }
49 52
50 // Helper method which calculates the average power of an audio bus. Unit is in 53 // Helper method which calculates the average power of an audio bus. Unit is in
51 // dBFS, where 0 dBFS corresponds to all channels and samples equal to 1.0. 54 // dBFS, where 0 dBFS corresponds to all channels and samples equal to 1.0.
52 float AveragePower(const media::AudioBus& buffer) { 55 float AveragePower(const AudioBus& buffer) {
53 const int frames = buffer.frames(); 56 const int frames = buffer.frames();
54 const int channels = buffer.channels(); 57 const int channels = buffer.channels();
55 if (frames <= 0 || channels <= 0) 58 if (frames <= 0 || channels <= 0)
56 return 0.0f; 59 return 0.0f;
57 60
58 // Scan all channels and accumulate the sum of squares for all samples. 61 // Scan all channels and accumulate the sum of squares for all samples.
59 float sum_power = 0.0f; 62 float sum_power = 0.0f;
60 for (int ch = 0; ch < channels; ++ch) { 63 for (int ch = 0; ch < channels; ++ch) {
61 const float* channel_data = buffer.channel(ch); 64 const float* channel_data = buffer.channel(ch);
62 for (int i = 0; i < frames; i++) { 65 for (int i = 0; i < frames; i++) {
(...skipping 11 matching lines...) Expand all
74 const float kInsignificantPower = 1.0e-10f; // -100 dBFS 77 const float kInsignificantPower = 1.0e-10f; // -100 dBFS
75 const float power_dbfs = average_power < kInsignificantPower ? 78 const float power_dbfs = average_power < kInsignificantPower ?
76 -std::numeric_limits<float>::infinity() : 10.0f * log10f(average_power); 79 -std::numeric_limits<float>::infinity() : 10.0f * log10f(average_power);
77 80
78 return power_dbfs; 81 return power_dbfs;
79 } 82 }
80 #endif // AUDIO_POWER_MONITORING 83 #endif // AUDIO_POWER_MONITORING
81 84
82 } // namespace 85 } // namespace
83 86
84 namespace media { 87 // Private subclass of AIC that covers the state while capturing audio.
88 // This class implements the callback interface from the lower level audio
89 // layer and gets called back on the audio hw thread.
90 // We implement this in a sub class instead of directly in the AIC so that
91 // - The AIC itself is not an AudioInputCallback.
92 // - The lifetime of the AudioCallback is shorter than the AIC
93 // - How tasks are posted to the AIC from the hw callback thread, is different
94 // than how tasks are posted from the AIC to itself from the main thread.
95 // So, this difference is isolated to the subclass (see below).
96 // - The callback class can gather information on what happened during capture
97 // and store it in a state that can be fetched after stopping capture
98 // (received_callback, error_during_callback).
99 // The AIC itself must not be AddRef-ed on the hw callback thread so that we
100 // can be guaranteed to not receive callbacks generated by the hw callback
101 // thread after Close() has been called on the audio manager thread and
102 // the callback object deleted. To avoid AddRef-ing the AIC and to cancel
103 // potentially pending tasks, we use a weak pointer to the AIC instance
104 // when posting.
105 class AudioInputController::AudioCallback
106 : public AudioInputStream::AudioInputCallback {
107 public:
108 explicit AudioCallback(AudioInputController* controller)
109 : controller_(controller),
110 weak_controller_(controller->weak_ptr_factory_.GetWeakPtr()) {}
111 ~AudioCallback() override {}
112
113 bool received_callback() const { return received_callback_; }
114 bool error_during_callback() const { return error_during_callback_; }
115
116 private:
117 void OnData(AudioInputStream* stream,
118 const AudioBus* source,
119 uint32_t hardware_delay_bytes,
120 double volume) override {
121 TRACE_EVENT0("audio", "AC::OnData");
122
123 received_callback_ = true;
124
125 DeliverDataToSyncWriter(source, hardware_delay_bytes, volume);
126 PerformOptionalDebugRecording(source);
127 }
128
129 void OnError(AudioInputStream* stream) override {
130 error_during_callback_ = true;
131 controller_->task_runner_->PostTask(
132 FROM_HERE,
133 base::Bind(&AudioInputController::DoReportError, weak_controller_));
134 }
135
136 void PerformOptionalDebugRecording(const AudioBus* source) {
137 // Called on the hw callback thread while recording is enabled.
138 if (!controller_->debug_writer_ || !controller_->debug_writer_->WillWrite())
139 return;
140
141 // TODO(tommi): This is costly. AudioBus heap allocs and we create a new
142 // one for every callback. We could instead have a pool of bus objects
143 // that get returned to us somehow.
144 // We should also avoid calling PostTask here since the implementation
145 // of the debug writer will basically do a PostTask straight away anyway.
146 // Might require some modifications to AudioInputDebugWriter though since
147 // there are some threading concerns there and AudioInputDebugWriter's
148 // lifetime guarantees need to be longer than that of associated active
149 // audio streams.
150 std::unique_ptr<AudioBus> source_copy =
151 AudioBus::Create(source->channels(), source->frames());
152 source->CopyTo(source_copy.get());
153 controller_->task_runner_->PostTask(
154 FROM_HERE, base::Bind(&AudioInputController::WriteInputDataForDebugging,
155 weak_controller_, base::Passed(&source_copy)));
156 }
157
158 void DeliverDataToSyncWriter(const AudioBus* source,
159 uint32_t hardware_delay_bytes,
160 double volume) {
161 bool key_pressed = controller_->CheckForKeyboardInput();
162 controller_->sync_writer_->Write(source, volume, key_pressed,
163 hardware_delay_bytes);
164
165 // The way the two classes interact here, could be done in a nicer way.
166 // As is, we call the AIC here to check the audio power, return and then
167 // post a task to the AIC based on what the AIC said.
168 // The reason for this is to keep all PostTask calls from the hw callback
169 // thread to the AIC, that use a weak pointer, in the same class.
170 float average_power_dbfs;
171 int mic_volume_percent;
172 if (controller_->CheckAudioPower(source, volume, &average_power_dbfs,
173 &mic_volume_percent)) {
174 // Use event handler on the audio thread to relay a message to the ARIH
175 // in content which does the actual logging on the IO thread.
176 controller_->task_runner_->PostTask(
177 FROM_HERE,
178 base::Bind(&AudioInputController::DoLogAudioLevels, weak_controller_,
179 average_power_dbfs, mic_volume_percent));
180 }
181 }
182
183 AudioInputController* const controller_;
184 // We do not want any pending posted tasks generated from the callback class
185 // to keep the controller object alive longer than it should. So we use
186 // a weak ptr whenever we post, we use this weak pointer.
187 base::WeakPtr<AudioInputController> weak_controller_;
188 bool received_callback_ = false;
189 bool error_during_callback_ = false;
190 };
85 191
86 // static 192 // static
87 AudioInputController::Factory* AudioInputController::factory_ = nullptr; 193 AudioInputController::Factory* AudioInputController::factory_ = nullptr;
88 194
89 AudioInputController::AudioInputController( 195 AudioInputController::AudioInputController(
196 scoped_refptr<base::SingleThreadTaskRunner> task_runner,
90 EventHandler* handler, 197 EventHandler* handler,
91 SyncWriter* sync_writer, 198 SyncWriter* sync_writer,
92 std::unique_ptr<AudioFileWriter> debug_writer, 199 std::unique_ptr<AudioFileWriter> debug_writer,
93 UserInputMonitor* user_input_monitor, 200 UserInputMonitor* user_input_monitor,
94 const bool agc_is_enabled) 201 const bool agc_is_enabled)
95 : creator_task_runner_(base::ThreadTaskRunnerHandle::Get()), 202 : creator_task_runner_(base::ThreadTaskRunnerHandle::Get()),
203 task_runner_(std::move(task_runner)),
96 handler_(handler), 204 handler_(handler),
97 stream_(nullptr), 205 stream_(nullptr),
98 should_report_stats(0),
99 state_(CLOSED),
100 sync_writer_(sync_writer), 206 sync_writer_(sync_writer),
101 max_volume_(0.0), 207 max_volume_(0.0),
102 user_input_monitor_(user_input_monitor), 208 user_input_monitor_(user_input_monitor),
103 agc_is_enabled_(agc_is_enabled), 209 agc_is_enabled_(agc_is_enabled),
104 #if defined(AUDIO_POWER_MONITORING) 210 #if defined(AUDIO_POWER_MONITORING)
105 power_measurement_is_enabled_(false), 211 power_measurement_is_enabled_(false),
106 log_silence_state_(false), 212 log_silence_state_(false),
107 silence_state_(SILENCE_STATE_NO_MEASUREMENT), 213 silence_state_(SILENCE_STATE_NO_MEASUREMENT),
108 #endif 214 #endif
109 prev_key_down_count_(0), 215 prev_key_down_count_(0),
110 debug_writer_(std::move(debug_writer)) { 216 debug_writer_(std::move(debug_writer)),
217 weak_ptr_factory_(this) {
111 DCHECK(creator_task_runner_.get()); 218 DCHECK(creator_task_runner_.get());
219 DCHECK(handler_);
220 DCHECK(sync_writer_);
112 } 221 }
113 222
114 AudioInputController::~AudioInputController() { 223 AudioInputController::~AudioInputController() {
115 DCHECK_EQ(state_, CLOSED); 224 DCHECK(!audio_callback_);
225 DCHECK(!stream_);
116 } 226 }
117 227
118 // static 228 // static
119 scoped_refptr<AudioInputController> AudioInputController::Create( 229 scoped_refptr<AudioInputController> AudioInputController::Create(
120 AudioManager* audio_manager, 230 AudioManager* audio_manager,
121 EventHandler* event_handler, 231 EventHandler* event_handler,
232 SyncWriter* sync_writer,
122 const AudioParameters& params, 233 const AudioParameters& params,
123 const std::string& device_id, 234 const std::string& device_id,
124 UserInputMonitor* user_input_monitor) { 235 UserInputMonitor* user_input_monitor) {
125 DCHECK(audio_manager); 236 DCHECK(audio_manager);
237 DCHECK(event_handler);
238 DCHECK(sync_writer);
126 239
127 if (!params.IsValid() || (params.channels() > kMaxInputChannels)) 240 if (!params.IsValid() || (params.channels() > kMaxInputChannels))
128 return nullptr; 241 return nullptr;
129 242
130 if (factory_) { 243 if (factory_) {
131 return factory_->Create(audio_manager->GetTaskRunner(), 244 return factory_->Create(audio_manager->GetTaskRunner(), sync_writer,
132 /*sync_writer*/ nullptr, audio_manager, 245 audio_manager, event_handler, params,
133 event_handler, params, user_input_monitor); 246 user_input_monitor);
134 } 247 }
135 248
136 scoped_refptr<AudioInputController> controller(new AudioInputController( 249 scoped_refptr<AudioInputController> controller(new AudioInputController(
137 event_handler, nullptr, nullptr, user_input_monitor, false)); 250 audio_manager->GetTaskRunner(), event_handler, sync_writer, nullptr,
138 251 user_input_monitor, false));
139 controller->task_runner_ = audio_manager->GetTaskRunner();
140 252
141 // Create and open a new audio input stream from the existing 253 // Create and open a new audio input stream from the existing
142 // audio-device thread. 254 // audio-device thread.
143 if (!controller->task_runner_->PostTask( 255 if (!controller->task_runner_->PostTask(
144 FROM_HERE, 256 FROM_HERE,
145 base::Bind(&AudioInputController::DoCreate, 257 base::Bind(&AudioInputController::DoCreate,
146 controller, 258 controller,
147 base::Unretained(audio_manager), 259 base::Unretained(audio_manager),
148 params, 260 params,
149 device_id))) { 261 device_id))) {
150 controller = nullptr; 262 controller = nullptr;
151 } 263 }
152 264
153 return controller; 265 return controller;
154 } 266 }
155 267
156 // static 268 // static
157 scoped_refptr<AudioInputController> AudioInputController::CreateLowLatency( 269 scoped_refptr<AudioInputController> AudioInputController::CreateLowLatency(
158 AudioManager* audio_manager, 270 AudioManager* audio_manager,
159 EventHandler* event_handler, 271 EventHandler* event_handler,
160 const AudioParameters& params, 272 const AudioParameters& params,
161 const std::string& device_id, 273 const std::string& device_id,
162 SyncWriter* sync_writer, 274 SyncWriter* sync_writer,
163 std::unique_ptr<AudioFileWriter> debug_writer, 275 std::unique_ptr<AudioFileWriter> debug_writer,
164 UserInputMonitor* user_input_monitor, 276 UserInputMonitor* user_input_monitor,
165 const bool agc_is_enabled) { 277 const bool agc_is_enabled) {
166 DCHECK(audio_manager); 278 DCHECK(audio_manager);
167 DCHECK(sync_writer); 279 DCHECK(sync_writer);
280 DCHECK(event_handler);
168 281
169 if (!params.IsValid() || (params.channels() > kMaxInputChannels)) 282 if (!params.IsValid() || (params.channels() > kMaxInputChannels))
170 return nullptr; 283 return nullptr;
171 284
172 if (factory_) { 285 if (factory_) {
173 return factory_->Create(audio_manager->GetTaskRunner(), sync_writer, 286 return factory_->Create(audio_manager->GetTaskRunner(), sync_writer,
174 audio_manager, event_handler, params, 287 audio_manager, event_handler, params,
175 user_input_monitor); 288 user_input_monitor);
176 } 289 }
177 290
178 // Create the AudioInputController object and ensure that it runs on 291 // Create the AudioInputController object and ensure that it runs on
179 // the audio-manager thread. 292 // the audio-manager thread.
180 scoped_refptr<AudioInputController> controller(new AudioInputController( 293 scoped_refptr<AudioInputController> controller(new AudioInputController(
181 event_handler, sync_writer, std::move(debug_writer), user_input_monitor, 294 audio_manager->GetTaskRunner(), event_handler, sync_writer,
182 agc_is_enabled)); 295 std::move(debug_writer), user_input_monitor, agc_is_enabled));
183 controller->task_runner_ = audio_manager->GetTaskRunner();
184 296
185 // Create and open a new audio input stream from the existing 297 // Create and open a new audio input stream from the existing
186 // audio-device thread. Use the provided audio-input device. 298 // audio-device thread. Use the provided audio-input device.
187 if (!controller->task_runner_->PostTask( 299 if (!controller->task_runner_->PostTask(
188 FROM_HERE, 300 FROM_HERE,
189 base::Bind(&AudioInputController::DoCreateForLowLatency, 301 base::Bind(&AudioInputController::DoCreateForLowLatency,
190 controller, 302 controller,
191 base::Unretained(audio_manager), 303 base::Unretained(audio_manager),
192 params, 304 params,
193 device_id))) { 305 device_id))) {
194 controller = nullptr; 306 controller = nullptr;
195 } 307 }
196 308
197 return controller; 309 return controller;
198 } 310 }
199 311
200 // static 312 // static
201 scoped_refptr<AudioInputController> AudioInputController::CreateForStream( 313 scoped_refptr<AudioInputController> AudioInputController::CreateForStream(
202 const scoped_refptr<base::SingleThreadTaskRunner>& task_runner, 314 const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
203 EventHandler* event_handler, 315 EventHandler* event_handler,
204 AudioInputStream* stream, 316 AudioInputStream* stream,
205 SyncWriter* sync_writer, 317 SyncWriter* sync_writer,
206 std::unique_ptr<AudioFileWriter> debug_writer, 318 std::unique_ptr<AudioFileWriter> debug_writer,
207 UserInputMonitor* user_input_monitor) { 319 UserInputMonitor* user_input_monitor) {
208 DCHECK(sync_writer); 320 DCHECK(sync_writer);
209 DCHECK(stream); 321 DCHECK(stream);
322 DCHECK(event_handler);
210 323
211 if (factory_) { 324 if (factory_) {
212 return factory_->Create( 325 return factory_->Create(
213 task_runner, sync_writer, AudioManager::Get(), event_handler, 326 task_runner, sync_writer, AudioManager::Get(), event_handler,
214 media::AudioParameters::UnavailableDeviceParams(), user_input_monitor); 327 AudioParameters::UnavailableDeviceParams(), user_input_monitor);
215 } 328 }
216 329
217 // Create the AudioInputController object and ensure that it runs on 330 // Create the AudioInputController object and ensure that it runs on
218 // the audio-manager thread. 331 // the audio-manager thread.
219 scoped_refptr<AudioInputController> controller(new AudioInputController( 332 scoped_refptr<AudioInputController> controller(new AudioInputController(
220 event_handler, sync_writer, std::move(debug_writer), user_input_monitor, 333 task_runner, event_handler, sync_writer, std::move(debug_writer),
221 false)); 334 user_input_monitor, false));
222 controller->task_runner_ = task_runner;
223 335
224 if (!controller->task_runner_->PostTask( 336 if (!controller->task_runner_->PostTask(
225 FROM_HERE, 337 FROM_HERE,
226 base::Bind(&AudioInputController::DoCreateForStream, 338 base::Bind(&AudioInputController::DoCreateForStream,
227 controller, 339 controller,
228 stream))) { 340 stream))) {
229 controller = nullptr; 341 controller = nullptr;
230 } 342 }
231 343
232 return controller; 344 return controller;
233 } 345 }
234 346
235 void AudioInputController::Record() { 347 void AudioInputController::Record() {
348 DCHECK(creator_task_runner_->BelongsToCurrentThread());
236 task_runner_->PostTask(FROM_HERE, base::Bind( 349 task_runner_->PostTask(FROM_HERE, base::Bind(
237 &AudioInputController::DoRecord, this)); 350 &AudioInputController::DoRecord, this));
238 } 351 }
239 352
240 void AudioInputController::Close(const base::Closure& closed_task) { 353 void AudioInputController::Close(const base::Closure& closed_task) {
241 DCHECK(!closed_task.is_null()); 354 DCHECK(!closed_task.is_null());
242 DCHECK(creator_task_runner_->BelongsToCurrentThread()); 355 DCHECK(creator_task_runner_->BelongsToCurrentThread());
243 356
244 task_runner_->PostTaskAndReply( 357 task_runner_->PostTaskAndReply(
245 FROM_HERE, base::Bind(&AudioInputController::DoClose, this), closed_task); 358 FROM_HERE, base::Bind(&AudioInputController::DoClose, this), closed_task);
246 } 359 }
247 360
248 void AudioInputController::SetVolume(double volume) { 361 void AudioInputController::SetVolume(double volume) {
362 DCHECK(creator_task_runner_->BelongsToCurrentThread());
249 task_runner_->PostTask(FROM_HERE, base::Bind( 363 task_runner_->PostTask(FROM_HERE, base::Bind(
250 &AudioInputController::DoSetVolume, this, volume)); 364 &AudioInputController::DoSetVolume, this, volume));
251 } 365 }
252 366
253 void AudioInputController::DoCreate(AudioManager* audio_manager, 367 void AudioInputController::DoCreate(AudioManager* audio_manager,
254 const AudioParameters& params, 368 const AudioParameters& params,
255 const std::string& device_id) { 369 const std::string& device_id) {
256 DCHECK(task_runner_->BelongsToCurrentThread()); 370 DCHECK(task_runner_->BelongsToCurrentThread());
371 DCHECK(!stream_);
257 SCOPED_UMA_HISTOGRAM_TIMER("Media.AudioInputController.CreateTime"); 372 SCOPED_UMA_HISTOGRAM_TIMER("Media.AudioInputController.CreateTime");
258 if (handler_) 373 handler_->OnLog(this, "AIC::DoCreate");
259 handler_->OnLog(this, "AIC::DoCreate");
260 374
261 #if defined(AUDIO_POWER_MONITORING) 375 #if defined(AUDIO_POWER_MONITORING)
262 // Disable power monitoring for streams that run without AGC enabled to 376 // Disable power monitoring for streams that run without AGC enabled to
263 // avoid adding logs and UMA for non-WebRTC clients. 377 // avoid adding logs and UMA for non-WebRTC clients.
264 power_measurement_is_enabled_ = agc_is_enabled_; 378 power_measurement_is_enabled_ = agc_is_enabled_;
265 last_audio_level_log_time_ = base::TimeTicks::Now(); 379 last_audio_level_log_time_ = base::TimeTicks::Now();
266 silence_state_ = SILENCE_STATE_NO_MEASUREMENT; 380 silence_state_ = SILENCE_STATE_NO_MEASUREMENT;
267 #endif 381 #endif
268 382
383 // MakeAudioInputStream might fail and return nullptr. If so,
384 // DoCreateForStream will handle and report it.
269 DoCreateForStream(audio_manager->MakeAudioInputStream( 385 DoCreateForStream(audio_manager->MakeAudioInputStream(
270 params, device_id, base::Bind(&AudioInputController::LogMessage, this))); 386 params, device_id, base::Bind(&AudioInputController::LogMessage, this)));
271 } 387 }
272 388
273 void AudioInputController::DoCreateForLowLatency(AudioManager* audio_manager, 389 void AudioInputController::DoCreateForLowLatency(AudioManager* audio_manager,
274 const AudioParameters& params, 390 const AudioParameters& params,
275 const std::string& device_id) { 391 const std::string& device_id) {
276 DCHECK(task_runner_->BelongsToCurrentThread()); 392 DCHECK(task_runner_->BelongsToCurrentThread());
277 393
278 #if defined(AUDIO_POWER_MONITORING) 394 #if defined(AUDIO_POWER_MONITORING)
279 // We only log silence state UMA stats for low latency mode and if we use a 395 // We only log silence state UMA stats for low latency mode and if we use a
280 // real device. 396 // real device.
281 if (params.format() != AudioParameters::AUDIO_FAKE) 397 if (params.format() != AudioParameters::AUDIO_FAKE)
282 log_silence_state_ = true; 398 log_silence_state_ = true;
283 #endif 399 #endif
284 400
285 low_latency_create_time_ = base::TimeTicks::Now(); 401 low_latency_create_time_ = base::TimeTicks::Now();
286 DoCreate(audio_manager, params, device_id); 402 DoCreate(audio_manager, params, device_id);
287 } 403 }
288 404
289 void AudioInputController::DoCreateForStream( 405 void AudioInputController::DoCreateForStream(
290 AudioInputStream* stream_to_control) { 406 AudioInputStream* stream_to_control) {
291 DCHECK(task_runner_->BelongsToCurrentThread()); 407 DCHECK(task_runner_->BelongsToCurrentThread());
408 DCHECK(!stream_);
292 409
293 DCHECK(!stream_); 410 if (!stream_to_control) {
294 stream_ = stream_to_control;
295 should_report_stats = 1;
296
297 if (!stream_) {
298 if (handler_)
299 handler_->OnError(this, STREAM_CREATE_ERROR);
300 LogCaptureStartupResult(CAPTURE_STARTUP_CREATE_STREAM_FAILED); 411 LogCaptureStartupResult(CAPTURE_STARTUP_CREATE_STREAM_FAILED);
412 handler_->OnError(this, STREAM_CREATE_ERROR);
301 return; 413 return;
302 } 414 }
303 415
304 if (stream_ && !stream_->Open()) { 416 if (!stream_to_control->Open()) {
305 stream_->Close(); 417 stream_to_control->Close();
306 stream_ = nullptr;
307 if (handler_)
308 handler_->OnError(this, STREAM_OPEN_ERROR);
309 LogCaptureStartupResult(CAPTURE_STARTUP_OPEN_STREAM_FAILED); 418 LogCaptureStartupResult(CAPTURE_STARTUP_OPEN_STREAM_FAILED);
419 handler_->OnError(this, STREAM_OPEN_ERROR);
310 return; 420 return;
311 } 421 }
312 422
313 // Set AGC state using mode in |agc_is_enabled_| which can only be enabled in 423 // Set AGC state using mode in |agc_is_enabled_| which can only be enabled in
314 // CreateLowLatency(). 424 // CreateLowLatency().
315 #if defined(AUDIO_POWER_MONITORING) 425 #if defined(AUDIO_POWER_MONITORING)
316 bool agc_is_supported = false; 426 bool agc_is_supported =
317 agc_is_supported = stream_->SetAutomaticGainControl(agc_is_enabled_); 427 stream_to_control->SetAutomaticGainControl(agc_is_enabled_);
318 // Disable power measurements on platforms that does not support AGC at a 428 // Disable power measurements on platforms that does not support AGC at a
319 // lower level. AGC can fail on platforms where we don't support the 429 // lower level. AGC can fail on platforms where we don't support the
320 // functionality to modify the input volume slider. One such example is 430 // functionality to modify the input volume slider. One such example is
321 // Windows XP. 431 // Windows XP.
322 power_measurement_is_enabled_ &= agc_is_supported; 432 power_measurement_is_enabled_ &= agc_is_supported;
323 #else 433 #else
324 stream_->SetAutomaticGainControl(agc_is_enabled_); 434 stream_to_control->SetAutomaticGainControl(agc_is_enabled_);
325 #endif 435 #endif
326 436
327 437 // Finally, keep the stream pointer around, update the state and notify.
328 state_ = CREATED; 438 stream_ = stream_to_control;
329 if (handler_) 439 handler_->OnCreated(this);
330 handler_->OnCreated(this);
331
332 if (user_input_monitor_) {
333 user_input_monitor_->EnableKeyPressMonitoring();
334 prev_key_down_count_ = user_input_monitor_->GetKeyPressCount();
335 }
336 } 440 }
337 441
338 void AudioInputController::DoRecord() { 442 void AudioInputController::DoRecord() {
339 DCHECK(task_runner_->BelongsToCurrentThread()); 443 DCHECK(task_runner_->BelongsToCurrentThread());
340 SCOPED_UMA_HISTOGRAM_TIMER("Media.AudioInputController.RecordTime"); 444 SCOPED_UMA_HISTOGRAM_TIMER("Media.AudioInputController.RecordTime");
341 445
342 if (state_ != CREATED) 446 if (!stream_ || audio_callback_)
343 return; 447 return;
344 448
345 { 449 handler_->OnLog(this, "AIC::DoRecord");
346 base::AutoLock auto_lock(lock_); 450
347 state_ = RECORDING; 451 if (user_input_monitor_) {
452 user_input_monitor_->EnableKeyPressMonitoring();
453 prev_key_down_count_ = user_input_monitor_->GetKeyPressCount();
348 } 454 }
349 455
350 if (handler_) 456 audio_callback_.reset(new AudioCallback(this));
351 handler_->OnLog(this, "AIC::DoRecord"); 457 stream_->Start(audio_callback_.get());
352
353 stream_->Start(this);
354 } 458 }
355 459
356 void AudioInputController::DoClose() { 460 void AudioInputController::DoClose() {
357 DCHECK(task_runner_->BelongsToCurrentThread()); 461 DCHECK(task_runner_->BelongsToCurrentThread());
358 SCOPED_UMA_HISTOGRAM_TIMER("Media.AudioInputController.CloseTime"); 462 SCOPED_UMA_HISTOGRAM_TIMER("Media.AudioInputController.CloseTime");
359 // If we have already logged something, this does nothing.
360 // Otherwise, we haven't recieved data.
361 LogCaptureStartupResult(CAPTURE_STARTUP_NEVER_GOT_DATA);
362 463
363 if (state_ == CLOSED) 464 if (!stream_)
364 return; 465 return;
365 466
366 // If this is a low-latency stream, log the total duration (since DoCreate) 467 // Allow calling unconditionally and bail if we don't have a stream to close.
367 // and add it to a UMA histogram. 468 if (audio_callback_) {
368 if (!low_latency_create_time_.is_null()) { 469 stream_->Stop();
369 base::TimeDelta duration = 470
370 base::TimeTicks::Now() - low_latency_create_time_; 471 if (!low_latency_create_time_.is_null()) {
371 UMA_HISTOGRAM_LONG_TIMES("Media.InputStreamDuration", duration); 472 LogCaptureStartupResult(audio_callback_->received_callback()
372 if (handler_) { 473 ? CAPTURE_STARTUP_OK
373 std::string log_string = 474 : CAPTURE_STARTUP_NEVER_GOT_DATA);
374 base::StringPrintf("AIC::DoClose: stream duration="); 475 UMA_HISTOGRAM_BOOLEAN("Media.Audio.Capture.CallbackError",
375 log_string += base::Int64ToString(duration.InSeconds()); 476 audio_callback_->error_during_callback());
376 log_string += " seconds"; 477 if (audio_callback_->received_callback()) {
377 handler_->OnLog(this, log_string); 478 // Log the total duration (since DoCreate) and update the histogram.
479 const base::TimeDelta duration =
480 base::TimeTicks::Now() - low_latency_create_time_;
481 UMA_HISTOGRAM_LONG_TIMES("Media.InputStreamDuration", duration);
482 const std::string log_string = base::StringPrintf(
483 "AIC::DoClose: stream duration=%" PRId64 " seconds",
484 duration.InSeconds());
485 handler_->OnLog(this, log_string);
486 }
378 } 487 }
488
489 audio_callback_.reset();
379 } 490 }
380 491
381 DoStopCloseAndClearStream(); 492 stream_->Close();
493 stream_ = nullptr;
382 494
383 if (SharedMemoryAndSyncSocketMode()) 495 sync_writer_->Close();
384 sync_writer_->Close();
385 496
386 if (user_input_monitor_) 497 if (user_input_monitor_)
387 user_input_monitor_->DisableKeyPressMonitoring(); 498 user_input_monitor_->DisableKeyPressMonitoring();
388 499
389 #if defined(AUDIO_POWER_MONITORING) 500 #if defined(AUDIO_POWER_MONITORING)
390 // Send UMA stats if enabled. 501 // Send UMA stats if enabled.
391 if (log_silence_state_) 502 if (log_silence_state_)
392 LogSilenceState(silence_state_); 503 LogSilenceState(silence_state_);
393 log_silence_state_ = false; 504 log_silence_state_ = false;
394 #endif 505 #endif
395 506
396 if (debug_writer_) 507 if (debug_writer_)
397 debug_writer_->Stop(); 508 debug_writer_->Stop();
398 509
399 state_ = CLOSED; 510 max_volume_ = 0.0;
511 low_latency_create_time_ = base::TimeTicks(); // Reset to null.
512 weak_ptr_factory_.InvalidateWeakPtrs();
400 } 513 }
401 514
402 void AudioInputController::DoReportError() { 515 void AudioInputController::DoReportError() {
403 DCHECK(task_runner_->BelongsToCurrentThread()); 516 DCHECK(task_runner_->BelongsToCurrentThread());
404 if (handler_) 517 handler_->OnError(this, STREAM_ERROR);
405 handler_->OnError(this, STREAM_ERROR);
406 } 518 }
407 519
408 void AudioInputController::DoSetVolume(double volume) { 520 void AudioInputController::DoSetVolume(double volume) {
409 DCHECK(task_runner_->BelongsToCurrentThread()); 521 DCHECK(task_runner_->BelongsToCurrentThread());
410 DCHECK_GE(volume, 0); 522 DCHECK_GE(volume, 0);
411 DCHECK_LE(volume, 1.0); 523 DCHECK_LE(volume, 1.0);
412 524
413 if (state_ != CREATED && state_ != RECORDING) 525 if (!stream_)
414 return; 526 return;
415 527
416 // Only ask for the maximum volume at first call and use cached value 528 // Only ask for the maximum volume at first call and use cached value
417 // for remaining function calls. 529 // for remaining function calls.
418 if (!max_volume_) { 530 if (!max_volume_) {
419 max_volume_ = stream_->GetMaxVolume(); 531 max_volume_ = stream_->GetMaxVolume();
420 } 532 }
421 533
422 if (max_volume_ == 0.0) { 534 if (max_volume_ == 0.0) {
423 DLOG(WARNING) << "Failed to access input volume control"; 535 DLOG(WARNING) << "Failed to access input volume control";
424 return; 536 return;
425 } 537 }
426 538
427 // Set the stream volume and scale to a range matched to the platform. 539 // Set the stream volume and scale to a range matched to the platform.
428 stream_->SetVolume(max_volume_ * volume); 540 stream_->SetVolume(max_volume_ * volume);
429 } 541 }
430 542
431 void AudioInputController::OnData(AudioInputStream* stream,
432 const AudioBus* source,
433 uint32_t hardware_delay_bytes,
434 double volume) {
435 TRACE_EVENT0("audio", "AudioInputController::OnData");
436 if (debug_writer_ && debug_writer_->WillWrite()) {
437 std::unique_ptr<AudioBus> source_copy =
438 AudioBus::Create(source->channels(), source->frames());
439 source->CopyTo(source_copy.get());
440 task_runner_->PostTask(
441 FROM_HERE,
442 base::Bind(
443 &AudioInputController::WriteInputDataForDebugging,
444 this,
445 base::Passed(&source_copy)));
446 }
447 // Now we have data, so we know for sure that startup was ok.
448 LogCaptureStartupResult(CAPTURE_STARTUP_OK);
449
450 {
451 base::AutoLock auto_lock(lock_);
452 if (state_ != RECORDING)
453 return;
454 }
455
456 bool key_pressed = false;
457 if (user_input_monitor_) {
458 size_t current_count = user_input_monitor_->GetKeyPressCount();
459 key_pressed = current_count != prev_key_down_count_;
460 prev_key_down_count_ = current_count;
461 DVLOG_IF(6, key_pressed) << "Detected keypress.";
462 }
463
464 // Use SharedMemory and SyncSocket if the client has created a SyncWriter.
465 // Used by all low-latency clients except WebSpeech.
466 if (SharedMemoryAndSyncSocketMode()) {
467 sync_writer_->Write(source, volume, key_pressed, hardware_delay_bytes);
468
469 #if defined(AUDIO_POWER_MONITORING)
470 // Only do power-level measurements if DoCreate() has been called. It will
471 // ensure that logging will mainly be done for WebRTC and WebSpeech
472 // clients.
473 if (!power_measurement_is_enabled_)
474 return;
475
476 // Perform periodic audio (power) level measurements.
477 if ((base::TimeTicks::Now() - last_audio_level_log_time_).InSeconds() >
478 kPowerMonitorLogIntervalSeconds) {
479 // Calculate the average power of the signal, or the energy per sample.
480 const float average_power_dbfs = AveragePower(*source);
481
482 // Add current microphone volume to log and UMA histogram.
483 const int mic_volume_percent = static_cast<int>(100.0 * volume);
484
485 // Use event handler on the audio thread to relay a message to the ARIH
486 // in content which does the actual logging on the IO thread.
487 task_runner_->PostTask(FROM_HERE,
488 base::Bind(&AudioInputController::DoLogAudioLevels,
489 this,
490 average_power_dbfs,
491 mic_volume_percent));
492
493 last_audio_level_log_time_ = base::TimeTicks::Now();
494 }
495 #endif
496 return;
497 }
498
499 // TODO(henrika): Investigate if we can avoid the extra copy here.
500 // (see http://crbug.com/249316 for details). AFAIK, this scope is only
501 // active for WebSpeech clients.
502 std::unique_ptr<AudioBus> audio_data =
503 AudioBus::Create(source->channels(), source->frames());
504 source->CopyTo(audio_data.get());
505
506 // Ownership of the audio buffer will be with the callback until it is run,
507 // when ownership is passed to the callback function.
508 task_runner_->PostTask(
509 FROM_HERE,
510 base::Bind(
511 &AudioInputController::DoOnData, this, base::Passed(&audio_data)));
512 }
513
514 void AudioInputController::DoOnData(std::unique_ptr<AudioBus> data) {
515 DCHECK(task_runner_->BelongsToCurrentThread());
516 if (handler_)
517 handler_->OnData(this, data.get());
518 }
519
520 void AudioInputController::DoLogAudioLevels(float level_dbfs, 543 void AudioInputController::DoLogAudioLevels(float level_dbfs,
521 int microphone_volume_percent) { 544 int microphone_volume_percent) {
522 #if defined(AUDIO_POWER_MONITORING) 545 #if defined(AUDIO_POWER_MONITORING)
523 DCHECK(task_runner_->BelongsToCurrentThread()); 546 DCHECK(task_runner_->BelongsToCurrentThread());
524 if (!handler_) 547 if (!stream_)
525 return; 548 return;
526 549
527 // Detect if the user has enabled hardware mute by pressing the mute 550 // Detect if the user has enabled hardware mute by pressing the mute
528 // button in audio settings for the selected microphone. 551 // button in audio settings for the selected microphone.
529 const bool microphone_is_muted = stream_->IsMuted(); 552 const bool microphone_is_muted = stream_->IsMuted();
530 if (microphone_is_muted) { 553 if (microphone_is_muted) {
531 LogMicrophoneMuteResult(MICROPHONE_IS_MUTED); 554 LogMicrophoneMuteResult(MICROPHONE_IS_MUTED);
532 handler_->OnLog(this, "AIC::OnData: microphone is muted!"); 555 handler_->OnLog(this, "AIC::OnData: microphone is muted!");
533 // Return early if microphone is muted. No need to adding logs and UMA stats 556 // Return early if microphone is muted. No need to adding logs and UMA stats
534 // of audio levels if we know that the micropone is muted. 557 // of audio levels if we know that the micropone is muted.
(...skipping 13 matching lines...) Expand all
548 571
549 UMA_HISTOGRAM_PERCENTAGE("Media.MicrophoneVolume", microphone_volume_percent); 572 UMA_HISTOGRAM_PERCENTAGE("Media.MicrophoneVolume", microphone_volume_percent);
550 log_string = base::StringPrintf( 573 log_string = base::StringPrintf(
551 "AIC::OnData: microphone volume=%d%%", microphone_volume_percent); 574 "AIC::OnData: microphone volume=%d%%", microphone_volume_percent);
552 if (microphone_volume_percent < kLowLevelMicrophoneLevelPercent) 575 if (microphone_volume_percent < kLowLevelMicrophoneLevelPercent)
553 log_string += " <=> low microphone level!"; 576 log_string += " <=> low microphone level!";
554 handler_->OnLog(this, log_string); 577 handler_->OnLog(this, log_string);
555 #endif 578 #endif
556 } 579 }
557 580
558 void AudioInputController::OnError(AudioInputStream* stream) {
559 // Handle error on the audio-manager thread.
560 task_runner_->PostTask(FROM_HERE, base::Bind(
561 &AudioInputController::DoReportError, this));
562 }
563
564 void AudioInputController::EnableDebugRecording( 581 void AudioInputController::EnableDebugRecording(
565 const base::FilePath& file_name) { 582 const base::FilePath& file_name) {
583 DCHECK(creator_task_runner_->BelongsToCurrentThread());
566 task_runner_->PostTask( 584 task_runner_->PostTask(
567 FROM_HERE, base::Bind(&AudioInputController::DoEnableDebugRecording, this, 585 FROM_HERE, base::Bind(&AudioInputController::DoEnableDebugRecording, this,
568 file_name)); 586 file_name));
569 } 587 }
570 588
571 void AudioInputController::DisableDebugRecording() { 589 void AudioInputController::DisableDebugRecording() {
572 DCHECK(creator_task_runner_->BelongsToCurrentThread()); 590 DCHECK(creator_task_runner_->BelongsToCurrentThread());
573 task_runner_->PostTask( 591 task_runner_->PostTask(
574 FROM_HERE, 592 FROM_HERE,
575 base::Bind(&AudioInputController::DoDisableDebugRecording, this)); 593 base::Bind(&AudioInputController::DoDisableDebugRecording, this));
576 } 594 }
577 595
578 void AudioInputController::DoStopCloseAndClearStream() {
579 DCHECK(task_runner_->BelongsToCurrentThread());
580
581 // Allow calling unconditionally and bail if we don't have a stream to close.
582 if (stream_ != nullptr) {
583 stream_->Stop();
584 stream_->Close();
585 stream_ = nullptr;
586 }
587
588 // The event handler should not be touched after the stream has been closed.
589 handler_ = nullptr;
590 }
591
592 #if defined(AUDIO_POWER_MONITORING) 596 #if defined(AUDIO_POWER_MONITORING)
593 void AudioInputController::UpdateSilenceState(bool silence) { 597 void AudioInputController::UpdateSilenceState(bool silence) {
594 if (silence) { 598 if (silence) {
595 if (silence_state_ == SILENCE_STATE_NO_MEASUREMENT) { 599 if (silence_state_ == SILENCE_STATE_NO_MEASUREMENT) {
596 silence_state_ = SILENCE_STATE_ONLY_SILENCE; 600 silence_state_ = SILENCE_STATE_ONLY_SILENCE;
597 } else if (silence_state_ == SILENCE_STATE_ONLY_AUDIO) { 601 } else if (silence_state_ == SILENCE_STATE_ONLY_AUDIO) {
598 silence_state_ = SILENCE_STATE_AUDIO_AND_SILENCE; 602 silence_state_ = SILENCE_STATE_AUDIO_AND_SILENCE;
599 } else { 603 } else {
600 DCHECK(silence_state_ == SILENCE_STATE_ONLY_SILENCE || 604 DCHECK(silence_state_ == SILENCE_STATE_ONLY_SILENCE ||
601 silence_state_ == SILENCE_STATE_AUDIO_AND_SILENCE); 605 silence_state_ == SILENCE_STATE_AUDIO_AND_SILENCE);
(...skipping 12 matching lines...) Expand all
614 618
615 void AudioInputController::LogSilenceState(SilenceState value) { 619 void AudioInputController::LogSilenceState(SilenceState value) {
616 UMA_HISTOGRAM_ENUMERATION("Media.AudioInputControllerSessionSilenceReport", 620 UMA_HISTOGRAM_ENUMERATION("Media.AudioInputControllerSessionSilenceReport",
617 value, 621 value,
618 SILENCE_STATE_MAX + 1); 622 SILENCE_STATE_MAX + 1);
619 } 623 }
620 #endif 624 #endif
621 625
622 void AudioInputController::LogCaptureStartupResult( 626 void AudioInputController::LogCaptureStartupResult(
623 CaptureStartupResult result) { 627 CaptureStartupResult result) {
624 // Decrement shall_report_stats and check if it was 1 before decrement, 628 UMA_HISTOGRAM_ENUMERATION("Media.AudioInputControllerCaptureStartupSuccess",
625 // which would imply that this is the first time this method is called 629 result, CAPTURE_STARTUP_RESULT_MAX + 1);
626 // after initialization. To avoid underflow, we
627 // also check if should_report_stats is one before decrementing.
628 if (base::AtomicRefCountIsOne(&should_report_stats) &&
629 !base::AtomicRefCountDec(&should_report_stats)) {
630 UMA_HISTOGRAM_ENUMERATION("Media.AudioInputControllerCaptureStartupSuccess",
631 result, CAPTURE_STARTUP_RESULT_MAX + 1);
632 }
633 } 630 }
634 631
635 void AudioInputController::DoEnableDebugRecording( 632 void AudioInputController::DoEnableDebugRecording(
636 const base::FilePath& file_name) { 633 const base::FilePath& file_name) {
637 DCHECK(task_runner_->BelongsToCurrentThread()); 634 DCHECK(task_runner_->BelongsToCurrentThread());
638 if (debug_writer_) 635 if (debug_writer_)
639 debug_writer_->Start(file_name); 636 debug_writer_->Start(file_name);
640 } 637 }
641 638
642 void AudioInputController::DoDisableDebugRecording() { 639 void AudioInputController::DoDisableDebugRecording() {
643 DCHECK(task_runner_->BelongsToCurrentThread()); 640 DCHECK(task_runner_->BelongsToCurrentThread());
644 if (debug_writer_) 641 if (debug_writer_)
645 debug_writer_->Stop(); 642 debug_writer_->Stop();
646 } 643 }
647 644
648 void AudioInputController::WriteInputDataForDebugging( 645 void AudioInputController::WriteInputDataForDebugging(
649 std::unique_ptr<AudioBus> data) { 646 std::unique_ptr<AudioBus> data) {
650 DCHECK(task_runner_->BelongsToCurrentThread()); 647 DCHECK(task_runner_->BelongsToCurrentThread());
651 if (debug_writer_) 648 if (debug_writer_)
652 debug_writer_->Write(std::move(data)); 649 debug_writer_->Write(std::move(data));
653 } 650 }
654 651
655 void AudioInputController::LogMessage(const std::string& message) { 652 void AudioInputController::LogMessage(const std::string& message) {
656 DCHECK(task_runner_->BelongsToCurrentThread()); 653 DCHECK(task_runner_->BelongsToCurrentThread());
657 handler_->OnLog(this, message); 654 handler_->OnLog(this, message);
658 } 655 }
659 656
657 bool AudioInputController::CheckForKeyboardInput() {
658 if (!user_input_monitor_)
659 return false;
660
661 const size_t current_count = user_input_monitor_->GetKeyPressCount();
662 const bool key_pressed = current_count != prev_key_down_count_;
663 prev_key_down_count_ = current_count;
664 DVLOG_IF(6, key_pressed) << "Detected keypress.";
665
666 return key_pressed;
667 }
668
669 bool AudioInputController::CheckAudioPower(const AudioBus* source,
670 double volume,
671 float* average_power_dbfs,
672 int* mic_volume_percent) {
673 #if defined(AUDIO_POWER_MONITORING)
674 // Only do power-level measurements if DoCreate() has been called. It will
675 // ensure that logging will mainly be done for WebRTC and WebSpeech
676 // clients.
677 if (!power_measurement_is_enabled_)
678 return false;
679
680 // Perform periodic audio (power) level measurements.
681 const auto now = base::TimeTicks::Now();
682 if ((now - last_audio_level_log_time_).InSeconds() <=
683 kPowerMonitorLogIntervalSeconds) {
684 return false;
685 }
686
687 *average_power_dbfs = AveragePower(*source);
688 *mic_volume_percent = static_cast<int>(100.0 * volume);
689
690 last_audio_level_log_time_ = now;
691
692 return true;
693 #else
694 return false;
695 #endif
696 }
697
660 } // namespace media 698 } // namespace media
OLDNEW
« no previous file with comments | « media/audio/audio_input_controller.h ('k') | media/audio/audio_input_controller_unittest.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698