Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / content / renderer / media / media_stream_audio_processor.cc
blob56d9570720d5eb9f97005203956ca652b0b010be
1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/renderer/media/media_stream_audio_processor.h"
7 #include "base/command_line.h"
8 #include "base/metrics/field_trial.h"
9 #include "base/metrics/histogram.h"
10 #include "base/trace_event/trace_event.h"
11 #include "content/public/common/content_switches.h"
12 #include "content/renderer/media/media_stream_audio_processor_options.h"
13 #include "content/renderer/media/rtc_media_constraints.h"
14 #include "content/renderer/media/webrtc_audio_device_impl.h"
15 #include "media/audio/audio_parameters.h"
16 #include "media/base/audio_converter.h"
17 #include "media/base/audio_fifo.h"
18 #include "media/base/channel_layout.h"
19 #include "third_party/WebKit/public/platform/WebMediaConstraints.h"
20 #include "third_party/libjingle/source/talk/app/webrtc/mediaconstraintsinterface.h"
21 #include "third_party/webrtc/modules/audio_processing/typing_detection.h"
23 namespace content {
25 namespace {
27 using webrtc::AudioProcessing;
28 using webrtc::NoiseSuppression;
30 const int kAudioProcessingNumberOfChannels = 1;
32 AudioProcessing::ChannelLayout MapLayout(media::ChannelLayout media_layout) {
33 switch (media_layout) {
34 case media::CHANNEL_LAYOUT_MONO:
35 return AudioProcessing::kMono;
36 case media::CHANNEL_LAYOUT_STEREO:
37 return AudioProcessing::kStereo;
38 case media::CHANNEL_LAYOUT_STEREO_AND_KEYBOARD_MIC:
39 return AudioProcessing::kStereoAndKeyboard;
40 default:
41 NOTREACHED() << "Layout not supported: " << media_layout;
42 return AudioProcessing::kMono;
46 // This is only used for playout data where only max two channels is supported.
47 AudioProcessing::ChannelLayout ChannelsToLayout(int num_channels) {
48 switch (num_channels) {
49 case 1:
50 return AudioProcessing::kMono;
51 case 2:
52 return AudioProcessing::kStereo;
53 default:
54 NOTREACHED() << "Channels not supported: " << num_channels;
55 return AudioProcessing::kMono;
59 // Used by UMA histograms and entries shouldn't be re-ordered or removed.
60 enum AudioTrackProcessingStates {
61 AUDIO_PROCESSING_ENABLED = 0,
62 AUDIO_PROCESSING_DISABLED,
63 AUDIO_PROCESSING_IN_WEBRTC,
64 AUDIO_PROCESSING_MAX
67 void RecordProcessingState(AudioTrackProcessingStates state) {
68 UMA_HISTOGRAM_ENUMERATION("Media.AudioTrackProcessingStates",
69 state, AUDIO_PROCESSING_MAX);
72 bool IsDelayAgnosticAecEnabled() {
73 // Note: It's important to query the field trial state first, to ensure that
74 // UMA reports the correct group.
75 const std::string group_name =
76 base::FieldTrialList::FindFullName("UseDelayAgnosticAEC");
77 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
78 if (command_line->HasSwitch(switches::kEnableDelayAgnosticAec))
79 return true;
80 if (command_line->HasSwitch(switches::kDisableDelayAgnosticAec))
81 return false;
83 return (group_name == "Enabled" || group_name == "DefaultEnabled");
86 } // namespace
88 // Wraps AudioBus to provide access to the array of channel pointers, since this
89 // is the type webrtc::AudioProcessing deals in. The array is refreshed on every
90 // channel_ptrs() call, and will be valid until the underlying AudioBus pointers
91 // are changed, e.g. through calls to SetChannelData() or SwapChannels().
93 // All methods are called on one of the capture or render audio threads
94 // exclusively.
95 class MediaStreamAudioBus {
96 public:
97 MediaStreamAudioBus(int channels, int frames)
98 : bus_(media::AudioBus::Create(channels, frames)),
99 channel_ptrs_(new float*[channels]) {
100 // May be created in the main render thread and used in the audio threads.
101 thread_checker_.DetachFromThread();
104 media::AudioBus* bus() {
105 DCHECK(thread_checker_.CalledOnValidThread());
106 return bus_.get();
109 float* const* channel_ptrs() {
110 DCHECK(thread_checker_.CalledOnValidThread());
111 for (int i = 0; i < bus_->channels(); ++i) {
112 channel_ptrs_[i] = bus_->channel(i);
114 return channel_ptrs_.get();
117 private:
118 base::ThreadChecker thread_checker_;
119 scoped_ptr<media::AudioBus> bus_;
120 scoped_ptr<float*[]> channel_ptrs_;
123 // Wraps AudioFifo to provide a cleaner interface to MediaStreamAudioProcessor.
124 // It avoids the FIFO when the source and destination frames match. All methods
125 // are called on one of the capture or render audio threads exclusively. If
126 // |source_channels| is larger than |destination_channels|, only the first
127 // |destination_channels| are kept from the source.
128 class MediaStreamAudioFifo {
129 public:
130 MediaStreamAudioFifo(int source_channels,
131 int destination_channels,
132 int source_frames,
133 int destination_frames,
134 int sample_rate)
135 : source_channels_(source_channels),
136 source_frames_(source_frames),
137 sample_rate_(sample_rate),
138 destination_(
139 new MediaStreamAudioBus(destination_channels, destination_frames)),
140 data_available_(false) {
141 DCHECK_GE(source_channels, destination_channels);
142 DCHECK_GT(sample_rate_, 0);
144 if (source_channels > destination_channels) {
145 audio_source_intermediate_ =
146 media::AudioBus::CreateWrapper(destination_channels);
149 if (source_frames != destination_frames) {
150 // Since we require every Push to be followed by as many Consumes as
151 // possible, twice the larger of the two is a (probably) loose upper bound
152 // on the FIFO size.
153 const int fifo_frames = 2 * std::max(source_frames, destination_frames);
154 fifo_.reset(new media::AudioFifo(destination_channels, fifo_frames));
157 // May be created in the main render thread and used in the audio threads.
158 thread_checker_.DetachFromThread();
161 void Push(const media::AudioBus& source, base::TimeDelta audio_delay) {
162 DCHECK(thread_checker_.CalledOnValidThread());
163 DCHECK_EQ(source.channels(), source_channels_);
164 DCHECK_EQ(source.frames(), source_frames_);
166 const media::AudioBus* source_to_push = &source;
168 if (audio_source_intermediate_) {
169 for (int i = 0; i < destination_->bus()->channels(); ++i) {
170 audio_source_intermediate_->SetChannelData(
172 const_cast<float*>(source.channel(i)));
174 audio_source_intermediate_->set_frames(source.frames());
175 source_to_push = audio_source_intermediate_.get();
178 if (fifo_) {
179 CHECK_LT(fifo_->frames(), destination_->bus()->frames());
180 next_audio_delay_ = audio_delay +
181 fifo_->frames() * base::TimeDelta::FromSeconds(1) / sample_rate_;
182 fifo_->Push(source_to_push);
183 } else {
184 CHECK(!data_available_);
185 source_to_push->CopyTo(destination_->bus());
186 next_audio_delay_ = audio_delay;
187 data_available_ = true;
191 // Returns true if there are destination_frames() of data available to be
192 // consumed, and otherwise false.
193 bool Consume(MediaStreamAudioBus** destination,
194 base::TimeDelta* audio_delay) {
195 DCHECK(thread_checker_.CalledOnValidThread());
197 if (fifo_) {
198 if (fifo_->frames() < destination_->bus()->frames())
199 return false;
201 fifo_->Consume(destination_->bus(), 0, destination_->bus()->frames());
202 *audio_delay = next_audio_delay_;
203 next_audio_delay_ -=
204 destination_->bus()->frames() * base::TimeDelta::FromSeconds(1) /
205 sample_rate_;
206 } else {
207 if (!data_available_)
208 return false;
209 *audio_delay = next_audio_delay_;
210 // The data was already copied to |destination_| in this case.
211 data_available_ = false;
214 *destination = destination_.get();
215 return true;
218 private:
219 base::ThreadChecker thread_checker_;
220 const int source_channels_; // For a DCHECK.
221 const int source_frames_; // For a DCHECK.
222 const int sample_rate_;
223 scoped_ptr<media::AudioBus> audio_source_intermediate_;
224 scoped_ptr<MediaStreamAudioBus> destination_;
225 scoped_ptr<media::AudioFifo> fifo_;
227 // When using |fifo_|, this is the audio delay of the first sample to be
228 // consumed next from the FIFO. When not using |fifo_|, this is the audio
229 // delay of the first sample in |destination_|.
230 base::TimeDelta next_audio_delay_;
232 // True when |destination_| contains the data to be returned by the next call
233 // to Consume(). Only used when the FIFO is disabled.
234 bool data_available_;
237 MediaStreamAudioProcessor::MediaStreamAudioProcessor(
238 const blink::WebMediaConstraints& constraints,
239 const MediaStreamDevice::AudioDeviceParameters& input_params,
240 WebRtcPlayoutDataSource* playout_data_source)
241 : render_delay_ms_(0),
242 playout_data_source_(playout_data_source),
243 audio_mirroring_(false),
244 typing_detected_(false),
245 stopped_(false) {
246 capture_thread_checker_.DetachFromThread();
247 render_thread_checker_.DetachFromThread();
248 InitializeAudioProcessingModule(constraints, input_params);
250 aec_dump_message_filter_ = AecDumpMessageFilter::Get();
251 // In unit tests not creating a message filter, |aec_dump_message_filter_|
252 // will be NULL. We can just ignore that. Other unit tests and browser tests
253 // ensure that we do get the filter when we should.
254 if (aec_dump_message_filter_.get())
255 aec_dump_message_filter_->AddDelegate(this);
258 MediaStreamAudioProcessor::~MediaStreamAudioProcessor() {
259 DCHECK(main_thread_checker_.CalledOnValidThread());
260 Stop();
263 void MediaStreamAudioProcessor::OnCaptureFormatChanged(
264 const media::AudioParameters& input_format) {
265 DCHECK(main_thread_checker_.CalledOnValidThread());
266 // There is no need to hold a lock here since the caller guarantees that
267 // there is no more PushCaptureData() and ProcessAndConsumeData() callbacks
268 // on the capture thread.
269 InitializeCaptureFifo(input_format);
271 // Reset the |capture_thread_checker_| since the capture data will come from
272 // a new capture thread.
273 capture_thread_checker_.DetachFromThread();
276 void MediaStreamAudioProcessor::PushCaptureData(
277 const media::AudioBus& audio_source,
278 base::TimeDelta capture_delay) {
279 DCHECK(capture_thread_checker_.CalledOnValidThread());
281 capture_fifo_->Push(audio_source, capture_delay);
284 bool MediaStreamAudioProcessor::ProcessAndConsumeData(
285 int volume,
286 bool key_pressed,
287 media::AudioBus** processed_data,
288 base::TimeDelta* capture_delay,
289 int* new_volume) {
290 DCHECK(capture_thread_checker_.CalledOnValidThread());
291 DCHECK(processed_data);
292 DCHECK(capture_delay);
293 DCHECK(new_volume);
295 TRACE_EVENT0("audio", "MediaStreamAudioProcessor::ProcessAndConsumeData");
297 MediaStreamAudioBus* process_bus;
298 if (!capture_fifo_->Consume(&process_bus, capture_delay))
299 return false;
301 // Use the process bus directly if audio processing is disabled.
302 MediaStreamAudioBus* output_bus = process_bus;
303 *new_volume = 0;
304 if (audio_processing_) {
305 output_bus = output_bus_.get();
306 *new_volume = ProcessData(process_bus->channel_ptrs(),
307 process_bus->bus()->frames(), *capture_delay,
308 volume, key_pressed, output_bus->channel_ptrs());
311 // Swap channels before interleaving the data.
312 if (audio_mirroring_ &&
313 output_format_.channel_layout() == media::CHANNEL_LAYOUT_STEREO) {
314 // Swap the first and second channels.
315 output_bus->bus()->SwapChannels(0, 1);
318 *processed_data = output_bus->bus();
320 return true;
323 void MediaStreamAudioProcessor::Stop() {
324 DCHECK(main_thread_checker_.CalledOnValidThread());
325 if (stopped_)
326 return;
328 stopped_ = true;
330 if (aec_dump_message_filter_.get()) {
331 aec_dump_message_filter_->RemoveDelegate(this);
332 aec_dump_message_filter_ = NULL;
335 if (!audio_processing_.get())
336 return;
338 audio_processing_.get()->UpdateHistogramsOnCallEnd();
339 StopEchoCancellationDump(audio_processing_.get());
341 if (playout_data_source_) {
342 playout_data_source_->RemovePlayoutSink(this);
343 playout_data_source_ = NULL;
347 const media::AudioParameters& MediaStreamAudioProcessor::InputFormat() const {
348 return input_format_;
351 const media::AudioParameters& MediaStreamAudioProcessor::OutputFormat() const {
352 return output_format_;
355 void MediaStreamAudioProcessor::OnAecDumpFile(
356 const IPC::PlatformFileForTransit& file_handle) {
357 DCHECK(main_thread_checker_.CalledOnValidThread());
359 base::File file = IPC::PlatformFileForTransitToFile(file_handle);
360 DCHECK(file.IsValid());
362 if (audio_processing_)
363 StartEchoCancellationDump(audio_processing_.get(), file.Pass());
364 else
365 file.Close();
368 void MediaStreamAudioProcessor::OnDisableAecDump() {
369 DCHECK(main_thread_checker_.CalledOnValidThread());
370 if (audio_processing_)
371 StopEchoCancellationDump(audio_processing_.get());
374 void MediaStreamAudioProcessor::OnIpcClosing() {
375 DCHECK(main_thread_checker_.CalledOnValidThread());
376 aec_dump_message_filter_ = NULL;
379 void MediaStreamAudioProcessor::OnPlayoutData(media::AudioBus* audio_bus,
380 int sample_rate,
381 int audio_delay_milliseconds) {
382 DCHECK(render_thread_checker_.CalledOnValidThread());
383 DCHECK(audio_processing_->echo_control_mobile()->is_enabled() ^
384 audio_processing_->echo_cancellation()->is_enabled());
386 TRACE_EVENT0("audio", "MediaStreamAudioProcessor::OnPlayoutData");
387 DCHECK_LT(audio_delay_milliseconds,
388 std::numeric_limits<base::subtle::Atomic32>::max());
389 base::subtle::Release_Store(&render_delay_ms_, audio_delay_milliseconds);
391 InitializeRenderFifoIfNeeded(sample_rate, audio_bus->channels(),
392 audio_bus->frames());
394 render_fifo_->Push(
395 *audio_bus, base::TimeDelta::FromMilliseconds(audio_delay_milliseconds));
396 MediaStreamAudioBus* analysis_bus;
397 base::TimeDelta audio_delay;
398 while (render_fifo_->Consume(&analysis_bus, &audio_delay)) {
399 // TODO(ajm): Should AnalyzeReverseStream() account for the |audio_delay|?
400 audio_processing_->AnalyzeReverseStream(
401 analysis_bus->channel_ptrs(),
402 analysis_bus->bus()->frames(),
403 sample_rate,
404 ChannelsToLayout(audio_bus->channels()));
408 void MediaStreamAudioProcessor::OnPlayoutDataSourceChanged() {
409 DCHECK(main_thread_checker_.CalledOnValidThread());
410 // There is no need to hold a lock here since the caller guarantees that
411 // there is no more OnPlayoutData() callback on the render thread.
412 render_thread_checker_.DetachFromThread();
413 render_fifo_.reset();
416 void MediaStreamAudioProcessor::GetStats(AudioProcessorStats* stats) {
417 stats->typing_noise_detected =
418 (base::subtle::Acquire_Load(&typing_detected_) != false);
419 GetAecStats(audio_processing_.get()->echo_cancellation(), stats);
422 void MediaStreamAudioProcessor::InitializeAudioProcessingModule(
423 const blink::WebMediaConstraints& constraints,
424 const MediaStreamDevice::AudioDeviceParameters& input_params) {
425 DCHECK(main_thread_checker_.CalledOnValidThread());
426 DCHECK(!audio_processing_);
428 MediaAudioConstraints audio_constraints(constraints, input_params.effects);
430 // Audio mirroring can be enabled even though audio processing is otherwise
431 // disabled.
432 audio_mirroring_ = audio_constraints.GetProperty(
433 MediaAudioConstraints::kGoogAudioMirroring);
435 #if defined(OS_IOS)
436 // On iOS, VPIO provides built-in AGC and AEC.
437 const bool echo_cancellation = false;
438 const bool goog_agc = false;
439 #else
440 const bool echo_cancellation =
441 audio_constraints.GetEchoCancellationProperty();
442 const bool goog_agc = audio_constraints.GetProperty(
443 MediaAudioConstraints::kGoogAutoGainControl);
444 #endif
446 #if defined(OS_IOS) || defined(OS_ANDROID)
447 const bool goog_experimental_aec = false;
448 const bool goog_typing_detection = false;
449 #else
450 const bool goog_experimental_aec = audio_constraints.GetProperty(
451 MediaAudioConstraints::kGoogExperimentalEchoCancellation);
452 const bool goog_typing_detection = audio_constraints.GetProperty(
453 MediaAudioConstraints::kGoogTypingNoiseDetection);
454 #endif
456 const bool goog_ns = audio_constraints.GetProperty(
457 MediaAudioConstraints::kGoogNoiseSuppression);
458 const bool goog_experimental_ns = audio_constraints.GetProperty(
459 MediaAudioConstraints::kGoogExperimentalNoiseSuppression);
460 const bool goog_beamforming = audio_constraints.GetProperty(
461 MediaAudioConstraints::kGoogBeamforming);
462 const bool goog_high_pass_filter = audio_constraints.GetProperty(
463 MediaAudioConstraints::kGoogHighpassFilter);
464 // Return immediately if no goog constraint is enabled.
465 if (!echo_cancellation && !goog_experimental_aec && !goog_ns &&
466 !goog_high_pass_filter && !goog_typing_detection &&
467 !goog_agc && !goog_experimental_ns && !goog_beamforming) {
468 RecordProcessingState(AUDIO_PROCESSING_DISABLED);
469 return;
472 // Experimental options provided at creation.
473 webrtc::Config config;
474 if (goog_experimental_aec)
475 config.Set<webrtc::ExtendedFilter>(new webrtc::ExtendedFilter(true));
476 if (goog_experimental_ns)
477 config.Set<webrtc::ExperimentalNs>(new webrtc::ExperimentalNs(true));
478 if (IsDelayAgnosticAecEnabled())
479 config.Set<webrtc::DelayAgnostic>(new webrtc::DelayAgnostic(true));
480 if (goog_beamforming) {
481 const auto& geometry =
482 GetArrayGeometryPreferringConstraints(audio_constraints, input_params);
484 // Only enable beamforming if we have at least two mics.
485 config.Set<webrtc::Beamforming>(
486 new webrtc::Beamforming(geometry.size() > 1, geometry));
489 // Create and configure the webrtc::AudioProcessing.
490 audio_processing_.reset(webrtc::AudioProcessing::Create(config));
492 // Enable the audio processing components.
493 if (echo_cancellation) {
494 EnableEchoCancellation(audio_processing_.get());
496 if (playout_data_source_)
497 playout_data_source_->AddPlayoutSink(this);
499 // Prepare for logging echo information. If there are data remaining in
500 // |echo_information_| we simply discard it.
501 echo_information_.reset(new EchoInformation());
504 if (goog_ns) {
505 // The beamforming postfilter is effective at suppressing stationary noise,
506 // so reduce the single-channel NS aggressiveness when enabled.
507 const NoiseSuppression::Level ns_level =
508 config.Get<webrtc::Beamforming>().enabled ? NoiseSuppression::kLow
509 : NoiseSuppression::kHigh;
511 EnableNoiseSuppression(audio_processing_.get(), ns_level);
514 if (goog_high_pass_filter)
515 EnableHighPassFilter(audio_processing_.get());
517 if (goog_typing_detection) {
518 // TODO(xians): Remove this |typing_detector_| after the typing suppression
519 // is enabled by default.
520 typing_detector_.reset(new webrtc::TypingDetection());
521 EnableTypingDetection(audio_processing_.get(), typing_detector_.get());
524 if (goog_agc)
525 EnableAutomaticGainControl(audio_processing_.get());
527 RecordProcessingState(AUDIO_PROCESSING_ENABLED);
530 void MediaStreamAudioProcessor::InitializeCaptureFifo(
531 const media::AudioParameters& input_format) {
532 DCHECK(main_thread_checker_.CalledOnValidThread());
533 DCHECK(input_format.IsValid());
534 input_format_ = input_format;
536 // TODO(ajm): For now, we assume fixed parameters for the output when audio
537 // processing is enabled, to match the previous behavior. We should either
538 // use the input parameters (in which case, audio processing will convert
539 // at output) or ideally, have a backchannel from the sink to know what
540 // format it would prefer.
541 #if defined(OS_ANDROID)
542 int audio_processing_sample_rate = AudioProcessing::kSampleRate16kHz;
543 #else
544 int audio_processing_sample_rate = AudioProcessing::kSampleRate48kHz;
545 #endif
546 const int output_sample_rate = audio_processing_ ?
547 audio_processing_sample_rate :
548 input_format.sample_rate();
549 media::ChannelLayout output_channel_layout = audio_processing_ ?
550 media::GuessChannelLayout(kAudioProcessingNumberOfChannels) :
551 input_format.channel_layout();
553 // The output channels from the fifo is normally the same as input.
554 int fifo_output_channels = input_format.channels();
556 // Special case for if we have a keyboard mic channel on the input and no
557 // audio processing is used. We will then have the fifo strip away that
558 // channel. So we use stereo as output layout, and also change the output
559 // channels for the fifo.
560 if (input_format.channel_layout() ==
561 media::CHANNEL_LAYOUT_STEREO_AND_KEYBOARD_MIC &&
562 !audio_processing_) {
563 output_channel_layout = media::CHANNEL_LAYOUT_STEREO;
564 fifo_output_channels = ChannelLayoutToChannelCount(output_channel_layout);
567 // webrtc::AudioProcessing requires a 10 ms chunk size. We use this native
568 // size when processing is enabled. When disabled we use the same size as
569 // the source if less than 10 ms.
571 // TODO(ajm): This conditional buffer size appears to be assuming knowledge of
572 // the sink based on the source parameters. PeerConnection sinks seem to want
573 // 10 ms chunks regardless, while WebAudio sinks want less, and we're assuming
574 // we can identify WebAudio sinks by the input chunk size. Less fragile would
575 // be to have the sink actually tell us how much it wants (as in the above
576 // todo).
577 int processing_frames = input_format.sample_rate() / 100;
578 int output_frames = output_sample_rate / 100;
579 if (!audio_processing_ && input_format.frames_per_buffer() < output_frames) {
580 processing_frames = input_format.frames_per_buffer();
581 output_frames = processing_frames;
584 output_format_ = media::AudioParameters(
585 media::AudioParameters::AUDIO_PCM_LOW_LATENCY,
586 output_channel_layout,
587 output_sample_rate,
589 output_frames);
591 capture_fifo_.reset(
592 new MediaStreamAudioFifo(input_format.channels(),
593 fifo_output_channels,
594 input_format.frames_per_buffer(),
595 processing_frames,
596 input_format.sample_rate()));
598 if (audio_processing_) {
599 output_bus_.reset(new MediaStreamAudioBus(output_format_.channels(),
600 output_frames));
604 void MediaStreamAudioProcessor::InitializeRenderFifoIfNeeded(
605 int sample_rate, int number_of_channels, int frames_per_buffer) {
606 DCHECK(render_thread_checker_.CalledOnValidThread());
607 if (render_fifo_.get() &&
608 render_format_.sample_rate() == sample_rate &&
609 render_format_.channels() == number_of_channels &&
610 render_format_.frames_per_buffer() == frames_per_buffer) {
611 // Do nothing if the |render_fifo_| has been setup properly.
612 return;
615 render_format_ = media::AudioParameters(
616 media::AudioParameters::AUDIO_PCM_LOW_LATENCY,
617 media::GuessChannelLayout(number_of_channels),
618 sample_rate,
620 frames_per_buffer);
622 const int analysis_frames = sample_rate / 100; // 10 ms chunks.
623 render_fifo_.reset(
624 new MediaStreamAudioFifo(number_of_channels,
625 number_of_channels,
626 frames_per_buffer,
627 analysis_frames,
628 sample_rate));
631 int MediaStreamAudioProcessor::ProcessData(const float* const* process_ptrs,
632 int process_frames,
633 base::TimeDelta capture_delay,
634 int volume,
635 bool key_pressed,
636 float* const* output_ptrs) {
637 DCHECK(audio_processing_);
638 DCHECK(capture_thread_checker_.CalledOnValidThread());
640 TRACE_EVENT0("audio", "MediaStreamAudioProcessor::ProcessData");
642 base::subtle::Atomic32 render_delay_ms =
643 base::subtle::Acquire_Load(&render_delay_ms_);
644 int64 capture_delay_ms = capture_delay.InMilliseconds();
645 DCHECK_LT(capture_delay_ms,
646 std::numeric_limits<base::subtle::Atomic32>::max());
647 int total_delay_ms = capture_delay_ms + render_delay_ms;
648 if (total_delay_ms > 300) {
649 LOG(WARNING) << "Large audio delay, capture delay: " << capture_delay_ms
650 << "ms; render delay: " << render_delay_ms << "ms";
653 webrtc::AudioProcessing* ap = audio_processing_.get();
654 ap->set_stream_delay_ms(total_delay_ms);
656 DCHECK_LE(volume, WebRtcAudioDeviceImpl::kMaxVolumeLevel);
657 webrtc::GainControl* agc = ap->gain_control();
658 int err = agc->set_stream_analog_level(volume);
659 DCHECK_EQ(err, 0) << "set_stream_analog_level() error: " << err;
661 ap->set_stream_key_pressed(key_pressed);
663 err = ap->ProcessStream(process_ptrs,
664 process_frames,
665 input_format_.sample_rate(),
666 MapLayout(input_format_.channel_layout()),
667 output_format_.sample_rate(),
668 MapLayout(output_format_.channel_layout()),
669 output_ptrs);
670 DCHECK_EQ(err, 0) << "ProcessStream() error: " << err;
672 if (typing_detector_) {
673 webrtc::VoiceDetection* vad = ap->voice_detection();
674 DCHECK(vad->is_enabled());
675 bool detected = typing_detector_->Process(key_pressed,
676 vad->stream_has_voice());
677 base::subtle::Release_Store(&typing_detected_, detected);
680 if (echo_information_) {
681 echo_information_.get()->UpdateAecDelayStats(ap->echo_cancellation());
684 // Return 0 if the volume hasn't been changed, and otherwise the new volume.
685 return (agc->stream_analog_level() == volume) ?
686 0 : agc->stream_analog_level();
689 } // namespace content