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 #if defined(OS_CHROMEOS)
24 #include "base/sys_info.h"
31 using webrtc::AudioProcessing
;
32 using webrtc::NoiseSuppression
;
34 const int kAudioProcessingNumberOfChannels
= 1;
36 AudioProcessing::ChannelLayout
MapLayout(media::ChannelLayout media_layout
) {
37 switch (media_layout
) {
38 case media::CHANNEL_LAYOUT_MONO
:
39 return AudioProcessing::kMono
;
40 case media::CHANNEL_LAYOUT_STEREO
:
41 return AudioProcessing::kStereo
;
42 case media::CHANNEL_LAYOUT_STEREO_AND_KEYBOARD_MIC
:
43 return AudioProcessing::kStereoAndKeyboard
;
45 NOTREACHED() << "Layout not supported: " << media_layout
;
46 return AudioProcessing::kMono
;
50 // This is only used for playout data where only max two channels is supported.
51 AudioProcessing::ChannelLayout
ChannelsToLayout(int num_channels
) {
52 switch (num_channels
) {
54 return AudioProcessing::kMono
;
56 return AudioProcessing::kStereo
;
58 NOTREACHED() << "Channels not supported: " << num_channels
;
59 return AudioProcessing::kMono
;
63 // Used by UMA histograms and entries shouldn't be re-ordered or removed.
64 enum AudioTrackProcessingStates
{
65 AUDIO_PROCESSING_ENABLED
= 0,
66 AUDIO_PROCESSING_DISABLED
,
67 AUDIO_PROCESSING_IN_WEBRTC
,
71 void RecordProcessingState(AudioTrackProcessingStates state
) {
72 UMA_HISTOGRAM_ENUMERATION("Media.AudioTrackProcessingStates",
73 state
, AUDIO_PROCESSING_MAX
);
76 bool IsDelayAgnosticAecEnabled() {
77 // Note: It's important to query the field trial state first, to ensure that
78 // UMA reports the correct group.
79 const std::string group_name
=
80 base::FieldTrialList::FindFullName("UseDelayAgnosticAEC");
81 base::CommandLine
* command_line
= base::CommandLine::ForCurrentProcess();
82 if (command_line
->HasSwitch(switches::kEnableDelayAgnosticAec
))
84 if (command_line
->HasSwitch(switches::kDisableDelayAgnosticAec
))
87 return (group_name
== "Enabled" || group_name
== "DefaultEnabled");
90 bool IsBeamformingEnabled(const MediaAudioConstraints
& audio_constraints
) {
91 return base::FieldTrialList::FindFullName("ChromebookBeamforming") ==
93 audio_constraints
.GetProperty(MediaAudioConstraints::kGoogBeamforming
);
96 void ConfigureBeamforming(webrtc::Config
* config
,
97 const std::string
& geometry_str
) {
98 std::vector
<webrtc::Point
> geometry
= ParseArrayGeometry(geometry_str
);
99 #if defined(OS_CHROMEOS)
100 if (geometry
.empty()) {
101 const std::string
& board
= base::SysInfo::GetLsbReleaseBoard();
102 if (board
.find("nyan_kitty") != std::string::npos
) {
103 geometry
.push_back(webrtc::Point(-0.03f
, 0.f
, 0.f
));
104 geometry
.push_back(webrtc::Point(0.03f
, 0.f
, 0.f
));
105 } else if (board
.find("peach_pi") != std::string::npos
) {
106 geometry
.push_back(webrtc::Point(-0.025f
, 0.f
, 0.f
));
107 geometry
.push_back(webrtc::Point(0.025f
, 0.f
, 0.f
));
108 } else if (board
.find("samus") != std::string::npos
) {
109 geometry
.push_back(webrtc::Point(-0.032f
, 0.f
, 0.f
));
110 geometry
.push_back(webrtc::Point(0.032f
, 0.f
, 0.f
));
111 } else if (board
.find("swanky") != std::string::npos
) {
112 geometry
.push_back(webrtc::Point(-0.026f
, 0.f
, 0.f
));
113 geometry
.push_back(webrtc::Point(0.026f
, 0.f
, 0.f
));
117 config
->Set
<webrtc::Beamforming
>(
118 new webrtc::Beamforming(geometry
.size() > 1, geometry
));
123 // Wraps AudioBus to provide access to the array of channel pointers, since this
124 // is the type webrtc::AudioProcessing deals in. The array is refreshed on every
125 // channel_ptrs() call, and will be valid until the underlying AudioBus pointers
126 // are changed, e.g. through calls to SetChannelData() or SwapChannels().
128 // All methods are called on one of the capture or render audio threads
130 class MediaStreamAudioBus
{
132 MediaStreamAudioBus(int channels
, int frames
)
133 : bus_(media::AudioBus::Create(channels
, frames
)),
134 channel_ptrs_(new float*[channels
]) {
135 // May be created in the main render thread and used in the audio threads.
136 thread_checker_
.DetachFromThread();
139 media::AudioBus
* bus() {
140 DCHECK(thread_checker_
.CalledOnValidThread());
144 float* const* channel_ptrs() {
145 DCHECK(thread_checker_
.CalledOnValidThread());
146 for (int i
= 0; i
< bus_
->channels(); ++i
) {
147 channel_ptrs_
[i
] = bus_
->channel(i
);
149 return channel_ptrs_
.get();
153 base::ThreadChecker thread_checker_
;
154 scoped_ptr
<media::AudioBus
> bus_
;
155 scoped_ptr
<float*[]> channel_ptrs_
;
158 // Wraps AudioFifo to provide a cleaner interface to MediaStreamAudioProcessor.
159 // It avoids the FIFO when the source and destination frames match. All methods
160 // are called on one of the capture or render audio threads exclusively. If
161 // |source_channels| is larger than |destination_channels|, only the first
162 // |destination_channels| are kept from the source.
163 class MediaStreamAudioFifo
{
165 MediaStreamAudioFifo(int source_channels
,
166 int destination_channels
,
168 int destination_frames
,
170 : source_channels_(source_channels
),
171 source_frames_(source_frames
),
172 sample_rate_(sample_rate
),
174 new MediaStreamAudioBus(destination_channels
, destination_frames
)),
175 data_available_(false) {
176 DCHECK_GE(source_channels
, destination_channels
);
177 DCHECK_GT(sample_rate_
, 0);
179 if (source_channels
> destination_channels
) {
180 audio_source_intermediate_
=
181 media::AudioBus::CreateWrapper(destination_channels
);
184 if (source_frames
!= destination_frames
) {
185 // Since we require every Push to be followed by as many Consumes as
186 // possible, twice the larger of the two is a (probably) loose upper bound
188 const int fifo_frames
= 2 * std::max(source_frames
, destination_frames
);
189 fifo_
.reset(new media::AudioFifo(destination_channels
, fifo_frames
));
192 // May be created in the main render thread and used in the audio threads.
193 thread_checker_
.DetachFromThread();
196 void Push(const media::AudioBus
& source
, base::TimeDelta audio_delay
) {
197 DCHECK(thread_checker_
.CalledOnValidThread());
198 DCHECK_EQ(source
.channels(), source_channels_
);
199 DCHECK_EQ(source
.frames(), source_frames_
);
201 const media::AudioBus
* source_to_push
= &source
;
203 if (audio_source_intermediate_
) {
204 for (int i
= 0; i
< destination_
->bus()->channels(); ++i
) {
205 audio_source_intermediate_
->SetChannelData(
207 const_cast<float*>(source
.channel(i
)));
209 audio_source_intermediate_
->set_frames(source
.frames());
210 source_to_push
= audio_source_intermediate_
.get();
214 next_audio_delay_
= audio_delay
+
215 fifo_
->frames() * base::TimeDelta::FromSeconds(1) / sample_rate_
;
216 fifo_
->Push(source_to_push
);
218 source_to_push
->CopyTo(destination_
->bus());
219 next_audio_delay_
= audio_delay
;
220 data_available_
= true;
224 // Returns true if there are destination_frames() of data available to be
225 // consumed, and otherwise false.
226 bool Consume(MediaStreamAudioBus
** destination
,
227 base::TimeDelta
* audio_delay
) {
228 DCHECK(thread_checker_
.CalledOnValidThread());
231 if (fifo_
->frames() < destination_
->bus()->frames())
234 fifo_
->Consume(destination_
->bus(), 0, destination_
->bus()->frames());
235 *audio_delay
= next_audio_delay_
;
237 destination_
->bus()->frames() * base::TimeDelta::FromSeconds(1) /
240 if (!data_available_
)
242 *audio_delay
= next_audio_delay_
;
243 // The data was already copied to |destination_| in this case.
244 data_available_
= false;
247 *destination
= destination_
.get();
252 base::ThreadChecker thread_checker_
;
253 const int source_channels_
; // For a DCHECK.
254 const int source_frames_
; // For a DCHECK.
255 const int sample_rate_
;
256 scoped_ptr
<media::AudioBus
> audio_source_intermediate_
;
257 scoped_ptr
<MediaStreamAudioBus
> destination_
;
258 scoped_ptr
<media::AudioFifo
> fifo_
;
260 // When using |fifo_|, this is the audio delay of the first sample to be
261 // consumed next from the FIFO. When not using |fifo_|, this is the audio
262 // delay of the first sample in |destination_|.
263 base::TimeDelta next_audio_delay_
;
265 // True when |destination_| contains the data to be returned by the next call
266 // to Consume(). Only used when the FIFO is disabled.
267 bool data_available_
;
270 MediaStreamAudioProcessor::MediaStreamAudioProcessor(
271 const blink::WebMediaConstraints
& constraints
,
273 WebRtcPlayoutDataSource
* playout_data_source
)
274 : render_delay_ms_(0),
275 playout_data_source_(playout_data_source
),
276 audio_mirroring_(false),
277 typing_detected_(false),
279 capture_thread_checker_
.DetachFromThread();
280 render_thread_checker_
.DetachFromThread();
281 InitializeAudioProcessingModule(constraints
, effects
);
283 aec_dump_message_filter_
= AecDumpMessageFilter::Get();
284 // In unit tests not creating a message filter, |aec_dump_message_filter_|
285 // will be NULL. We can just ignore that. Other unit tests and browser tests
286 // ensure that we do get the filter when we should.
287 if (aec_dump_message_filter_
.get())
288 aec_dump_message_filter_
->AddDelegate(this);
291 MediaStreamAudioProcessor::~MediaStreamAudioProcessor() {
292 DCHECK(main_thread_checker_
.CalledOnValidThread());
296 void MediaStreamAudioProcessor::OnCaptureFormatChanged(
297 const media::AudioParameters
& input_format
) {
298 DCHECK(main_thread_checker_
.CalledOnValidThread());
299 // There is no need to hold a lock here since the caller guarantees that
300 // there is no more PushCaptureData() and ProcessAndConsumeData() callbacks
301 // on the capture thread.
302 InitializeCaptureFifo(input_format
);
304 // Reset the |capture_thread_checker_| since the capture data will come from
305 // a new capture thread.
306 capture_thread_checker_
.DetachFromThread();
309 void MediaStreamAudioProcessor::PushCaptureData(
310 const media::AudioBus
& audio_source
,
311 base::TimeDelta capture_delay
) {
312 DCHECK(capture_thread_checker_
.CalledOnValidThread());
314 capture_fifo_
->Push(audio_source
, capture_delay
);
317 bool MediaStreamAudioProcessor::ProcessAndConsumeData(
320 media::AudioBus
** processed_data
,
321 base::TimeDelta
* capture_delay
,
323 DCHECK(capture_thread_checker_
.CalledOnValidThread());
324 DCHECK(processed_data
);
325 DCHECK(capture_delay
);
328 TRACE_EVENT0("audio", "MediaStreamAudioProcessor::ProcessAndConsumeData");
330 MediaStreamAudioBus
* process_bus
;
331 if (!capture_fifo_
->Consume(&process_bus
, capture_delay
))
334 // Use the process bus directly if audio processing is disabled.
335 MediaStreamAudioBus
* output_bus
= process_bus
;
337 if (audio_processing_
) {
338 output_bus
= output_bus_
.get();
339 *new_volume
= ProcessData(process_bus
->channel_ptrs(),
340 process_bus
->bus()->frames(), *capture_delay
,
341 volume
, key_pressed
, output_bus
->channel_ptrs());
344 // Swap channels before interleaving the data.
345 if (audio_mirroring_
&&
346 output_format_
.channel_layout() == media::CHANNEL_LAYOUT_STEREO
) {
347 // Swap the first and second channels.
348 output_bus
->bus()->SwapChannels(0, 1);
351 *processed_data
= output_bus
->bus();
356 void MediaStreamAudioProcessor::Stop() {
357 DCHECK(main_thread_checker_
.CalledOnValidThread());
363 if (aec_dump_message_filter_
.get()) {
364 aec_dump_message_filter_
->RemoveDelegate(this);
365 aec_dump_message_filter_
= NULL
;
368 if (!audio_processing_
.get())
371 audio_processing_
.get()->UpdateHistogramsOnCallEnd();
372 StopEchoCancellationDump(audio_processing_
.get());
374 if (playout_data_source_
) {
375 playout_data_source_
->RemovePlayoutSink(this);
376 playout_data_source_
= NULL
;
380 const media::AudioParameters
& MediaStreamAudioProcessor::InputFormat() const {
381 return input_format_
;
384 const media::AudioParameters
& MediaStreamAudioProcessor::OutputFormat() const {
385 return output_format_
;
388 void MediaStreamAudioProcessor::OnAecDumpFile(
389 const IPC::PlatformFileForTransit
& file_handle
) {
390 DCHECK(main_thread_checker_
.CalledOnValidThread());
392 base::File file
= IPC::PlatformFileForTransitToFile(file_handle
);
393 DCHECK(file
.IsValid());
395 if (audio_processing_
)
396 StartEchoCancellationDump(audio_processing_
.get(), file
.Pass());
401 void MediaStreamAudioProcessor::OnDisableAecDump() {
402 DCHECK(main_thread_checker_
.CalledOnValidThread());
403 if (audio_processing_
)
404 StopEchoCancellationDump(audio_processing_
.get());
407 void MediaStreamAudioProcessor::OnIpcClosing() {
408 DCHECK(main_thread_checker_
.CalledOnValidThread());
409 aec_dump_message_filter_
= NULL
;
412 void MediaStreamAudioProcessor::OnPlayoutData(media::AudioBus
* audio_bus
,
414 int audio_delay_milliseconds
) {
415 DCHECK(render_thread_checker_
.CalledOnValidThread());
416 DCHECK(audio_processing_
->echo_control_mobile()->is_enabled() ^
417 audio_processing_
->echo_cancellation()->is_enabled());
419 TRACE_EVENT0("audio", "MediaStreamAudioProcessor::OnPlayoutData");
420 DCHECK_LT(audio_delay_milliseconds
,
421 std::numeric_limits
<base::subtle::Atomic32
>::max());
422 base::subtle::Release_Store(&render_delay_ms_
, audio_delay_milliseconds
);
424 InitializeRenderFifoIfNeeded(sample_rate
, audio_bus
->channels(),
425 audio_bus
->frames());
428 *audio_bus
, base::TimeDelta::FromMilliseconds(audio_delay_milliseconds
));
429 MediaStreamAudioBus
* analysis_bus
;
430 base::TimeDelta audio_delay
;
431 while (render_fifo_
->Consume(&analysis_bus
, &audio_delay
)) {
432 // TODO(ajm): Should AnalyzeReverseStream() account for the |audio_delay|?
433 audio_processing_
->AnalyzeReverseStream(
434 analysis_bus
->channel_ptrs(),
435 analysis_bus
->bus()->frames(),
437 ChannelsToLayout(audio_bus
->channels()));
441 void MediaStreamAudioProcessor::OnPlayoutDataSourceChanged() {
442 DCHECK(main_thread_checker_
.CalledOnValidThread());
443 // There is no need to hold a lock here since the caller guarantees that
444 // there is no more OnPlayoutData() callback on the render thread.
445 render_thread_checker_
.DetachFromThread();
446 render_fifo_
.reset();
449 void MediaStreamAudioProcessor::GetStats(AudioProcessorStats
* stats
) {
450 stats
->typing_noise_detected
=
451 (base::subtle::Acquire_Load(&typing_detected_
) != false);
452 GetAecStats(audio_processing_
.get()->echo_cancellation(), stats
);
455 void MediaStreamAudioProcessor::InitializeAudioProcessingModule(
456 const blink::WebMediaConstraints
& constraints
, int effects
) {
457 DCHECK(main_thread_checker_
.CalledOnValidThread());
458 DCHECK(!audio_processing_
);
460 MediaAudioConstraints
audio_constraints(constraints
, effects
);
462 // Audio mirroring can be enabled even though audio processing is otherwise
464 audio_mirroring_
= audio_constraints
.GetProperty(
465 MediaAudioConstraints::kGoogAudioMirroring
);
468 // On iOS, VPIO provides built-in AGC and AEC.
469 const bool echo_cancellation
= false;
470 const bool goog_agc
= false;
472 const bool echo_cancellation
=
473 audio_constraints
.GetEchoCancellationProperty();
474 const bool goog_agc
= audio_constraints
.GetProperty(
475 MediaAudioConstraints::kGoogAutoGainControl
);
478 #if defined(OS_IOS) || defined(OS_ANDROID)
479 const bool goog_experimental_aec
= false;
480 const bool goog_typing_detection
= false;
482 const bool goog_experimental_aec
= audio_constraints
.GetProperty(
483 MediaAudioConstraints::kGoogExperimentalEchoCancellation
);
484 const bool goog_typing_detection
= audio_constraints
.GetProperty(
485 MediaAudioConstraints::kGoogTypingNoiseDetection
);
488 const bool goog_ns
= audio_constraints
.GetProperty(
489 MediaAudioConstraints::kGoogNoiseSuppression
);
490 const bool goog_experimental_ns
= audio_constraints
.GetProperty(
491 MediaAudioConstraints::kGoogExperimentalNoiseSuppression
);
492 const bool goog_beamforming
= IsBeamformingEnabled(audio_constraints
);
493 const bool goog_high_pass_filter
= audio_constraints
.GetProperty(
494 MediaAudioConstraints::kGoogHighpassFilter
);
495 // Return immediately if no goog constraint is enabled.
496 if (!echo_cancellation
&& !goog_experimental_aec
&& !goog_ns
&&
497 !goog_high_pass_filter
&& !goog_typing_detection
&&
498 !goog_agc
&& !goog_experimental_ns
&& !goog_beamforming
) {
499 RecordProcessingState(AUDIO_PROCESSING_DISABLED
);
503 // Experimental options provided at creation.
504 webrtc::Config config
;
505 if (goog_experimental_aec
)
506 config
.Set
<webrtc::ExtendedFilter
>(new webrtc::ExtendedFilter(true));
507 if (goog_experimental_ns
)
508 config
.Set
<webrtc::ExperimentalNs
>(new webrtc::ExperimentalNs(true));
509 if (IsDelayAgnosticAecEnabled())
510 config
.Set
<webrtc::DelayAgnostic
>(new webrtc::DelayAgnostic(true));
511 if (goog_beamforming
) {
512 ConfigureBeamforming(&config
,
513 audio_constraints
.GetPropertyAsString(
514 MediaAudioConstraints::kGoogArrayGeometry
));
517 // Create and configure the webrtc::AudioProcessing.
518 audio_processing_
.reset(webrtc::AudioProcessing::Create(config
));
520 // Enable the audio processing components.
521 if (echo_cancellation
) {
522 EnableEchoCancellation(audio_processing_
.get());
524 if (playout_data_source_
)
525 playout_data_source_
->AddPlayoutSink(this);
527 // Prepare for logging echo information. If there are data remaining in
528 // |echo_information_| we simply discard it.
529 echo_information_
.reset(new EchoInformation());
533 // The beamforming postfilter is effective at suppressing stationary noise,
534 // so reduce the single-channel NS aggressiveness when enabled.
535 const NoiseSuppression::Level ns_level
=
536 config
.Get
<webrtc::Beamforming
>().enabled
? NoiseSuppression::kLow
537 : NoiseSuppression::kHigh
;
539 EnableNoiseSuppression(audio_processing_
.get(), ns_level
);
542 if (goog_high_pass_filter
)
543 EnableHighPassFilter(audio_processing_
.get());
545 if (goog_typing_detection
) {
546 // TODO(xians): Remove this |typing_detector_| after the typing suppression
547 // is enabled by default.
548 typing_detector_
.reset(new webrtc::TypingDetection());
549 EnableTypingDetection(audio_processing_
.get(), typing_detector_
.get());
553 EnableAutomaticGainControl(audio_processing_
.get());
555 RecordProcessingState(AUDIO_PROCESSING_ENABLED
);
558 void MediaStreamAudioProcessor::InitializeCaptureFifo(
559 const media::AudioParameters
& input_format
) {
560 DCHECK(main_thread_checker_
.CalledOnValidThread());
561 DCHECK(input_format
.IsValid());
562 input_format_
= input_format
;
564 // TODO(ajm): For now, we assume fixed parameters for the output when audio
565 // processing is enabled, to match the previous behavior. We should either
566 // use the input parameters (in which case, audio processing will convert
567 // at output) or ideally, have a backchannel from the sink to know what
568 // format it would prefer.
569 #if defined(OS_ANDROID)
570 int audio_processing_sample_rate
= AudioProcessing::kSampleRate16kHz
;
572 int audio_processing_sample_rate
= AudioProcessing::kSampleRate48kHz
;
574 const int output_sample_rate
= audio_processing_
?
575 audio_processing_sample_rate
:
576 input_format
.sample_rate();
577 media::ChannelLayout output_channel_layout
= audio_processing_
?
578 media::GuessChannelLayout(kAudioProcessingNumberOfChannels
) :
579 input_format
.channel_layout();
581 // The output channels from the fifo is normally the same as input.
582 int fifo_output_channels
= input_format
.channels();
584 // Special case for if we have a keyboard mic channel on the input and no
585 // audio processing is used. We will then have the fifo strip away that
586 // channel. So we use stereo as output layout, and also change the output
587 // channels for the fifo.
588 if (input_format
.channel_layout() ==
589 media::CHANNEL_LAYOUT_STEREO_AND_KEYBOARD_MIC
&&
590 !audio_processing_
) {
591 output_channel_layout
= media::CHANNEL_LAYOUT_STEREO
;
592 fifo_output_channels
= ChannelLayoutToChannelCount(output_channel_layout
);
595 // webrtc::AudioProcessing requires a 10 ms chunk size. We use this native
596 // size when processing is enabled. When disabled we use the same size as
597 // the source if less than 10 ms.
599 // TODO(ajm): This conditional buffer size appears to be assuming knowledge of
600 // the sink based on the source parameters. PeerConnection sinks seem to want
601 // 10 ms chunks regardless, while WebAudio sinks want less, and we're assuming
602 // we can identify WebAudio sinks by the input chunk size. Less fragile would
603 // be to have the sink actually tell us how much it wants (as in the above
605 int processing_frames
= input_format
.sample_rate() / 100;
606 int output_frames
= output_sample_rate
/ 100;
607 if (!audio_processing_
&& input_format
.frames_per_buffer() < output_frames
) {
608 processing_frames
= input_format
.frames_per_buffer();
609 output_frames
= processing_frames
;
612 output_format_
= media::AudioParameters(
613 media::AudioParameters::AUDIO_PCM_LOW_LATENCY
,
614 output_channel_layout
,
620 new MediaStreamAudioFifo(input_format
.channels(),
621 fifo_output_channels
,
622 input_format
.frames_per_buffer(),
624 input_format
.sample_rate()));
626 if (audio_processing_
) {
627 output_bus_
.reset(new MediaStreamAudioBus(output_format_
.channels(),
632 void MediaStreamAudioProcessor::InitializeRenderFifoIfNeeded(
633 int sample_rate
, int number_of_channels
, int frames_per_buffer
) {
634 DCHECK(render_thread_checker_
.CalledOnValidThread());
635 if (render_fifo_
.get() &&
636 render_format_
.sample_rate() == sample_rate
&&
637 render_format_
.channels() == number_of_channels
&&
638 render_format_
.frames_per_buffer() == frames_per_buffer
) {
639 // Do nothing if the |render_fifo_| has been setup properly.
643 render_format_
= media::AudioParameters(
644 media::AudioParameters::AUDIO_PCM_LOW_LATENCY
,
645 media::GuessChannelLayout(number_of_channels
),
650 const int analysis_frames
= sample_rate
/ 100; // 10 ms chunks.
652 new MediaStreamAudioFifo(number_of_channels
,
659 int MediaStreamAudioProcessor::ProcessData(const float* const* process_ptrs
,
661 base::TimeDelta capture_delay
,
664 float* const* output_ptrs
) {
665 DCHECK(audio_processing_
);
666 DCHECK(capture_thread_checker_
.CalledOnValidThread());
668 TRACE_EVENT0("audio", "MediaStreamAudioProcessor::ProcessData");
670 base::subtle::Atomic32 render_delay_ms
=
671 base::subtle::Acquire_Load(&render_delay_ms_
);
672 int64 capture_delay_ms
= capture_delay
.InMilliseconds();
673 DCHECK_LT(capture_delay_ms
,
674 std::numeric_limits
<base::subtle::Atomic32
>::max());
675 int total_delay_ms
= capture_delay_ms
+ render_delay_ms
;
676 if (total_delay_ms
> 300) {
677 LOG(WARNING
) << "Large audio delay, capture delay: " << capture_delay_ms
678 << "ms; render delay: " << render_delay_ms
<< "ms";
681 webrtc::AudioProcessing
* ap
= audio_processing_
.get();
682 ap
->set_stream_delay_ms(total_delay_ms
);
684 DCHECK_LE(volume
, WebRtcAudioDeviceImpl::kMaxVolumeLevel
);
685 webrtc::GainControl
* agc
= ap
->gain_control();
686 int err
= agc
->set_stream_analog_level(volume
);
687 DCHECK_EQ(err
, 0) << "set_stream_analog_level() error: " << err
;
689 ap
->set_stream_key_pressed(key_pressed
);
691 err
= ap
->ProcessStream(process_ptrs
,
693 input_format_
.sample_rate(),
694 MapLayout(input_format_
.channel_layout()),
695 output_format_
.sample_rate(),
696 MapLayout(output_format_
.channel_layout()),
698 DCHECK_EQ(err
, 0) << "ProcessStream() error: " << err
;
700 if (typing_detector_
) {
701 webrtc::VoiceDetection
* vad
= ap
->voice_detection();
702 DCHECK(vad
->is_enabled());
703 bool detected
= typing_detector_
->Process(key_pressed
,
704 vad
->stream_has_voice());
705 base::subtle::Release_Store(&typing_detected_
, detected
);
708 if (echo_information_
) {
709 echo_information_
.get()->UpdateAecDelayStats(ap
->echo_cancellation());
712 // Return 0 if the volume hasn't been changed, and otherwise the new volume.
713 return (agc
->stream_analog_level() == volume
) ?
714 0 : agc
->stream_analog_level();
717 } // namespace content