1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/renderer/media/webrtc_audio_capturer.h"
#include "base/bind.h"
#include "base/logging.h"
#include "base/metrics/histogram.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "content/child/child_process.h"
#include "content/renderer/media/audio_device_factory.h"
#include "content/renderer/media/media_stream_audio_processor.h"
#include "content/renderer/media/media_stream_audio_processor_options.h"
#include "content/renderer/media/webrtc_audio_device_impl.h"
#include "content/renderer/media/webrtc_local_audio_track.h"
#include "content/renderer/media/webrtc_logging.h"
#include "media/audio/sample_rates.h"
namespace content {
namespace {
// Supported hardware sample rates for input and output sides.
#if defined(OS_WIN) || defined(OS_MACOSX)
// media::GetAudioInputHardwareSampleRate() asks the audio layer
// for its current sample rate (set by the user) on Windows and Mac OS X.
// The listed rates below adds restrictions and WebRtcAudioDeviceImpl::Init()
// will fail if the user selects any rate outside these ranges.
const int kValidInputRates[] = {96000, 48000, 44100, 32000, 16000, 8000};
#elif defined(OS_LINUX) || defined(OS_OPENBSD)
const int kValidInputRates[] = {48000, 44100};
#elif defined(OS_ANDROID)
const int kValidInputRates[] = {48000, 44100};
#else
const int kValidInputRates[] = {44100};
#endif
} // namespace
// Reference counted container of WebRtcLocalAudioTrack delegate.
// TODO(xians): Switch to MediaStreamAudioSinkOwner.
class WebRtcAudioCapturer::TrackOwner
: public base::RefCountedThreadSafe<WebRtcAudioCapturer::TrackOwner> {
public:
explicit TrackOwner(WebRtcLocalAudioTrack* track)
: delegate_(track) {}
void Capture(const int16* audio_data,
base::TimeDelta delay,
double volume,
bool key_pressed,
bool need_audio_processing) {
base::AutoLock lock(lock_);
if (delegate_) {
delegate_->Capture(audio_data,
delay,
volume,
key_pressed,
need_audio_processing);
}
}
void OnSetFormat(const media::AudioParameters& params) {
base::AutoLock lock(lock_);
if (delegate_)
delegate_->OnSetFormat(params);
}
void Reset() {
base::AutoLock lock(lock_);
delegate_ = NULL;
}
void Stop() {
base::AutoLock lock(lock_);
DCHECK(delegate_);
// This can be reentrant so reset |delegate_| before calling out.
WebRtcLocalAudioTrack* temp = delegate_;
delegate_ = NULL;
temp->Stop();
}
// Wrapper which allows to use std::find_if() when adding and removing
// sinks to/from the list.
struct TrackWrapper {
TrackWrapper(WebRtcLocalAudioTrack* track) : track_(track) {}
bool operator()(
const scoped_refptr<WebRtcAudioCapturer::TrackOwner>& owner) const {
return owner->IsEqual(track_);
}
WebRtcLocalAudioTrack* track_;
};
protected:
virtual ~TrackOwner() {}
private:
friend class base::RefCountedThreadSafe<WebRtcAudioCapturer::TrackOwner>;
bool IsEqual(const WebRtcLocalAudioTrack* other) const {
base::AutoLock lock(lock_);
return (other == delegate_);
}
// Do NOT reference count the |delegate_| to avoid cyclic reference counting.
WebRtcLocalAudioTrack* delegate_;
mutable base::Lock lock_;
DISALLOW_COPY_AND_ASSIGN(TrackOwner);
};
// static
scoped_refptr<WebRtcAudioCapturer> WebRtcAudioCapturer::CreateCapturer(
int render_view_id, const StreamDeviceInfo& device_info,
const blink::WebMediaConstraints& constraints,
WebRtcAudioDeviceImpl* audio_device) {
scoped_refptr<WebRtcAudioCapturer> capturer = new WebRtcAudioCapturer(
render_view_id, device_info, constraints, audio_device);
if (capturer->Initialize())
return capturer;
return NULL;
}
bool WebRtcAudioCapturer::Initialize() {
DCHECK(thread_checker_.CalledOnValidThread());
DVLOG(1) << "WebRtcAudioCapturer::Initialize()";
WebRtcLogMessage(base::StringPrintf(
"WAC::Initialize. render_view_id=%d"
", channel_layout=%d, sample_rate=%d, buffer_size=%d"
", session_id=%d, paired_output_sample_rate=%d"
", paired_output_frames_per_buffer=%d, effects=%d. ",
render_view_id_,
device_info_.device.input.channel_layout,
device_info_.device.input.sample_rate,
device_info_.device.input.frames_per_buffer,
device_info_.session_id,
device_info_.device.matched_output.sample_rate,
device_info_.device.matched_output.frames_per_buffer,
device_info_.device.input.effects));
if (render_view_id_ == -1) {
// Return true here to allow injecting a new source via
// SetCapturerSourceForTesting() at a later state.
return true;
}
media::ChannelLayout channel_layout = static_cast<media::ChannelLayout>(
device_info_.device.input.channel_layout);
DVLOG(1) << "Audio input hardware channel layout: " << channel_layout;
UMA_HISTOGRAM_ENUMERATION("WebRTC.AudioInputChannelLayout",
channel_layout, media::CHANNEL_LAYOUT_MAX);
// Verify that the reported input channel configuration is supported.
if (channel_layout != media::CHANNEL_LAYOUT_MONO &&
channel_layout != media::CHANNEL_LAYOUT_STEREO) {
DLOG(ERROR) << channel_layout
<< " is not a supported input channel configuration.";
return false;
}
DVLOG(1) << "Audio input hardware sample rate: "
<< device_info_.device.input.sample_rate;
media::AudioSampleRate asr = media::AsAudioSampleRate(
device_info_.device.input.sample_rate);
if (asr != media::kUnexpectedAudioSampleRate) {
UMA_HISTOGRAM_ENUMERATION(
"WebRTC.AudioInputSampleRate", asr, media::kUnexpectedAudioSampleRate);
} else {
UMA_HISTOGRAM_COUNTS("WebRTC.AudioInputSampleRateUnexpected",
device_info_.device.input.sample_rate);
}
// Verify that the reported input hardware sample rate is supported
// on the current platform.
if (std::find(&kValidInputRates[0],
&kValidInputRates[0] + arraysize(kValidInputRates),
device_info_.device.input.sample_rate) ==
&kValidInputRates[arraysize(kValidInputRates)]) {
DLOG(ERROR) << device_info_.device.input.sample_rate
<< " is not a supported input rate.";
return false;
}
// Create and configure the default audio capturing source.
SetCapturerSource(AudioDeviceFactory::NewInputDevice(render_view_id_),
channel_layout,
static_cast<float>(device_info_.device.input.sample_rate),
device_info_.device.input.effects,
constraints_);
// Add the capturer to the WebRtcAudioDeviceImpl since it needs some hardware
// information from the capturer.
if (audio_device_)
audio_device_->AddAudioCapturer(this);
return true;
}
WebRtcAudioCapturer::WebRtcAudioCapturer(
int render_view_id,
const StreamDeviceInfo& device_info,
const blink::WebMediaConstraints& constraints,
WebRtcAudioDeviceImpl* audio_device)
: constraints_(constraints),
running_(false),
render_view_id_(render_view_id),
device_info_(device_info),
volume_(0),
peer_connection_mode_(false),
key_pressed_(false),
need_audio_processing_(false),
audio_device_(audio_device) {
DVLOG(1) << "WebRtcAudioCapturer::WebRtcAudioCapturer()";
}
WebRtcAudioCapturer::~WebRtcAudioCapturer() {
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK(tracks_.IsEmpty());
DCHECK(!running_);
DVLOG(1) << "WebRtcAudioCapturer::~WebRtcAudioCapturer()";
}
void WebRtcAudioCapturer::AddTrack(WebRtcLocalAudioTrack* track) {
DCHECK(track);
DVLOG(1) << "WebRtcAudioCapturer::AddTrack()";
{
base::AutoLock auto_lock(lock_);
// Verify that |track| is not already added to the list.
DCHECK(!tracks_.Contains(TrackOwner::TrackWrapper(track)));
// Add with a tag, so we remember to call OnSetFormat() on the new
// track.
scoped_refptr<TrackOwner> track_owner(new TrackOwner(track));
tracks_.AddAndTag(track_owner);
}
// Start the source if the first audio track is connected to the capturer.
// Start() will do nothing if the capturer has already been started.
Start();
}
void WebRtcAudioCapturer::RemoveTrack(WebRtcLocalAudioTrack* track) {
DCHECK(thread_checker_.CalledOnValidThread());
base::AutoLock auto_lock(lock_);
scoped_refptr<TrackOwner> removed_item =
tracks_.Remove(TrackOwner::TrackWrapper(track));
// Clear the delegate to ensure that no more capture callbacks will
// be sent to this sink. Also avoids a possible crash which can happen
// if this method is called while capturing is active.
if (removed_item.get())
removed_item->Reset();
}
void WebRtcAudioCapturer::SetCapturerSource(
const scoped_refptr<media::AudioCapturerSource>& source,
media::ChannelLayout channel_layout,
float sample_rate,
int effects,
const blink::WebMediaConstraints& constraints) {
DCHECK(thread_checker_.CalledOnValidThread());
DVLOG(1) << "SetCapturerSource(channel_layout=" << channel_layout << ","
<< "sample_rate=" << sample_rate << ")";
scoped_refptr<media::AudioCapturerSource> old_source;
bool restart_source = false;
{
base::AutoLock auto_lock(lock_);
if (source_.get() == source.get())
return;
source_.swap(old_source);
source_ = source;
// Reset the flag to allow starting the new source.
restart_source = running_;
running_ = false;
}
DVLOG(1) << "Switching to a new capture source.";
if (old_source.get())
old_source->Stop();
// Dispatch the new parameters both to the sink(s) and to the new source,
// also apply the new |constraints|.
// The idea is to get rid of any dependency of the microphone parameters
// which would normally be used by default.
// bits_per_sample is always 16 for now.
int buffer_size = GetBufferSize(sample_rate);
media::AudioParameters params(media::AudioParameters::AUDIO_PCM_LOW_LATENCY,
channel_layout, 0, sample_rate,
16, buffer_size, effects);
scoped_refptr<MediaStreamAudioProcessor> new_audio_processor(
new MediaStreamAudioProcessor(params, constraints, effects));
{
base::AutoLock auto_lock(lock_);
audio_processor_ = new_audio_processor;
need_audio_processing_ = NeedsAudioProcessing(constraints, effects);
// Notify all tracks about the new format.
tracks_.TagAll();
}
if (source.get())
source->Initialize(params, this, session_id());
if (restart_source)
Start();
}
void WebRtcAudioCapturer::EnablePeerConnectionMode() {
DCHECK(thread_checker_.CalledOnValidThread());
DVLOG(1) << "EnablePeerConnectionMode";
// Do nothing if the peer connection mode has been enabled.
if (peer_connection_mode_)
return;
peer_connection_mode_ = true;
int render_view_id = -1;
media::AudioParameters input_params;
{
base::AutoLock auto_lock(lock_);
// Simply return if there is no existing source or the |render_view_id_| is
// not valid.
if (!source_.get() || render_view_id_== -1)
return;
render_view_id = render_view_id_;
input_params = audio_processor_->InputFormat();
}
// Do nothing if the current buffer size is the WebRtc native buffer size.
if (GetBufferSize(input_params.sample_rate()) ==
input_params.frames_per_buffer()) {
return;
}
// Create a new audio stream as source which will open the hardware using
// WebRtc native buffer size.
SetCapturerSource(AudioDeviceFactory::NewInputDevice(render_view_id),
input_params.channel_layout(),
static_cast<float>(input_params.sample_rate()),
input_params.effects(),
constraints_);
}
void WebRtcAudioCapturer::Start() {
DVLOG(1) << "WebRtcAudioCapturer::Start()";
base::AutoLock auto_lock(lock_);
if (running_ || !source_)
return;
// Start the data source, i.e., start capturing data from the current source.
// We need to set the AGC control before starting the stream.
source_->SetAutomaticGainControl(true);
source_->Start();
running_ = true;
}
void WebRtcAudioCapturer::Stop() {
DVLOG(1) << "WebRtcAudioCapturer::Stop()";
scoped_refptr<media::AudioCapturerSource> source;
TrackList::ItemList tracks;
{
base::AutoLock auto_lock(lock_);
if (!running_)
return;
source = source_;
tracks = tracks_.Items();
tracks_.Clear();
running_ = false;
}
// Remove the capturer object from the WebRtcAudioDeviceImpl.
if (audio_device_)
audio_device_->RemoveAudioCapturer(this);
for (TrackList::ItemList::const_iterator it = tracks.begin();
it != tracks.end();
++it) {
(*it)->Stop();
}
if (source.get())
source->Stop();
}
void WebRtcAudioCapturer::SetVolume(int volume) {
DVLOG(1) << "WebRtcAudioCapturer::SetVolume()";
DCHECK_LE(volume, MaxVolume());
double normalized_volume = static_cast<double>(volume) / MaxVolume();
base::AutoLock auto_lock(lock_);
if (source_.get())
source_->SetVolume(normalized_volume);
}
int WebRtcAudioCapturer::Volume() const {
base::AutoLock auto_lock(lock_);
return volume_;
}
int WebRtcAudioCapturer::MaxVolume() const {
return WebRtcAudioDeviceImpl::kMaxVolumeLevel;
}
void WebRtcAudioCapturer::Capture(media::AudioBus* audio_source,
int audio_delay_milliseconds,
double volume,
bool key_pressed) {
// This callback is driven by AudioInputDevice::AudioThreadCallback if
// |source_| is AudioInputDevice, otherwise it is driven by client's
// CaptureCallback.
#if defined(OS_WIN) || defined(OS_MACOSX)
DCHECK_LE(volume, 1.0);
#elif defined(OS_LINUX) || defined(OS_OPENBSD)
// We have a special situation on Linux where the microphone volume can be
// "higher than maximum". The input volume slider in the sound preference
// allows the user to set a scaling that is higher than 100%. It means that
// even if the reported maximum levels is N, the actual microphone level can
// go up to 1.5x*N and that corresponds to a normalized |volume| of 1.5x.
DCHECK_LE(volume, 1.6);
#endif
TrackList::ItemList tracks;
TrackList::ItemList tracks_to_notify_format;
int current_volume = 0;
base::TimeDelta audio_delay;
scoped_refptr<MediaStreamAudioProcessor> audio_processor;
bool need_audio_processing = true;
{
base::AutoLock auto_lock(lock_);
if (!running_)
return;
// Map internal volume range of [0.0, 1.0] into [0, 255] used by the
// webrtc::VoiceEngine. webrtc::VoiceEngine will handle the case when the
// volume is higher than 255.
volume_ = static_cast<int>((volume * MaxVolume()) + 0.5);
current_volume = volume_;
audio_delay = base::TimeDelta::FromMilliseconds(audio_delay_milliseconds);
audio_delay_ = audio_delay;
key_pressed_ = key_pressed;
tracks = tracks_.Items();
tracks_.RetrieveAndClearTags(&tracks_to_notify_format);
audio_processor = audio_processor_;
// Set the flag to turn on the audio processing in PeerConnection level.
// Note that, we turn off the audio processing in PeerConnection if the
// processor has already processed the data.
need_audio_processing = need_audio_processing_ ?
!audio_processor->has_audio_processing() : false;
}
DCHECK(audio_processor->InputFormat().IsValid());
DCHECK_EQ(audio_source->channels(),
audio_processor->InputFormat().channels());
DCHECK_EQ(audio_source->frames(),
audio_processor->InputFormat().frames_per_buffer());
// Notify the tracks on when the format changes. This will do nothing if
// |tracks_to_notify_format| is empty.
media::AudioParameters output_params = audio_processor_->OutputFormat();
for (TrackList::ItemList::const_iterator it = tracks_to_notify_format.begin();
it != tracks_to_notify_format.end(); ++it) {
(*it)->OnSetFormat(output_params);
}
// Push the data to the processor for processing.
audio_processor->PushCaptureData(audio_source);
// Process and consume the data in the processor until there is not enough
// data in the processor.
int16* output = NULL;
while (audio_processor->ProcessAndConsumeData(
audio_delay, current_volume, key_pressed, &output)) {
// Feed the post-processed data to the tracks.
for (TrackList::ItemList::const_iterator it = tracks.begin();
it != tracks.end(); ++it) {
(*it)->Capture(output, audio_delay, current_volume, key_pressed,
need_audio_processing);
}
// TODO(xians): Apply the new volume after AGC is working with the
// MediaStreamAudioProcessor.
}
}
void WebRtcAudioCapturer::OnCaptureError() {
NOTIMPLEMENTED();
}
media::AudioParameters WebRtcAudioCapturer::source_audio_parameters() const {
base::AutoLock auto_lock(lock_);
return audio_processor_ ?
audio_processor_->InputFormat() : media::AudioParameters();
}
bool WebRtcAudioCapturer::GetPairedOutputParameters(
int* session_id,
int* output_sample_rate,
int* output_frames_per_buffer) const {
// Don't set output parameters unless all of them are valid.
if (device_info_.session_id <= 0 ||
!device_info_.device.matched_output.sample_rate ||
!device_info_.device.matched_output.frames_per_buffer)
return false;
*session_id = device_info_.session_id;
*output_sample_rate = device_info_.device.matched_output.sample_rate;
*output_frames_per_buffer =
device_info_.device.matched_output.frames_per_buffer;
return true;
}
int WebRtcAudioCapturer::GetBufferSize(int sample_rate) const {
DCHECK(thread_checker_.CalledOnValidThread());
#if defined(OS_ANDROID)
// TODO(henrika): Tune and adjust buffer size on Android.
return (2 * sample_rate / 100);
#endif
// PeerConnection is running at a buffer size of 10ms data. A multiple of
// 10ms as the buffer size can give the best performance to PeerConnection.
int peer_connection_buffer_size = sample_rate / 100;
// Use the native hardware buffer size in non peer connection mode when the
// platform is using a native buffer size smaller than the PeerConnection
// buffer size.
int hardware_buffer_size = device_info_.device.input.frames_per_buffer;
if (!peer_connection_mode_ && hardware_buffer_size &&
hardware_buffer_size <= peer_connection_buffer_size) {
return hardware_buffer_size;
}
return (sample_rate / 100);
}
void WebRtcAudioCapturer::GetAudioProcessingParams(
base::TimeDelta* delay, int* volume, bool* key_pressed) {
base::AutoLock auto_lock(lock_);
*delay = audio_delay_;
*volume = volume_;
*key_pressed = key_pressed_;
}
void WebRtcAudioCapturer::FeedRenderDataToAudioProcessor(
const int16* render_audio,
int sample_rate,
int number_of_channels,
int number_of_frames,
base::TimeDelta render_delay) {
scoped_refptr<MediaStreamAudioProcessor> audio_processor;
{
base::AutoLock auto_lock(lock_);
if (!running_)
return;
audio_processor = audio_processor_;
}
audio_processor->PushRenderData(render_audio, sample_rate,
number_of_channels,
number_of_frames,
render_delay);
}
void WebRtcAudioCapturer::SetCapturerSourceForTesting(
const scoped_refptr<media::AudioCapturerSource>& source,
media::AudioParameters params) {
// Create a new audio stream as source which uses the new source.
SetCapturerSource(source, params.channel_layout(),
static_cast<float>(params.sample_rate()),
params.effects(),
constraints_);
}
} // namespace content
|