1 /*
2 * Copyright (c) 2004 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11 #include "media/engine/webrtc_voice_engine.h"
12
13 #include <algorithm>
14 #include <atomic>
15 #include <functional>
16 #include <memory>
17 #include <string>
18 #include <utility>
19 #include <vector>
20
21 #include "absl/algorithm/container.h"
22 #include "absl/strings/match.h"
23 #include "api/audio/audio_frame_processor.h"
24 #include "api/audio_codecs/audio_codec_pair_id.h"
25 #include "api/call/audio_sink.h"
26 #include "api/field_trials_view.h"
27 #include "api/task_queue/pending_task_safety_flag.h"
28 #include "media/base/audio_source.h"
29 #include "media/base/media_constants.h"
30 #include "media/base/stream_params.h"
31 #include "media/engine/adm_helpers.h"
32 #include "media/engine/payload_type_mapper.h"
33 #include "media/engine/webrtc_media_engine.h"
34 #include "modules/async_audio_processing/async_audio_processing.h"
35 #include "modules/audio_device/audio_device_impl.h"
36 #include "modules/audio_mixer/audio_mixer_impl.h"
37 #include "modules/audio_processing/aec_dump/aec_dump_factory.h"
38 #include "modules/audio_processing/include/audio_processing.h"
39 #include "modules/rtp_rtcp/source/rtp_util.h"
40 #include "rtc_base/arraysize.h"
41 #include "rtc_base/byte_order.h"
42 #include "rtc_base/experiments/field_trial_parser.h"
43 #include "rtc_base/experiments/field_trial_units.h"
44 #include "rtc_base/experiments/struct_parameters_parser.h"
45 #include "rtc_base/helpers.h"
46 #include "rtc_base/ignore_wundef.h"
47 #include "rtc_base/logging.h"
48 #include "rtc_base/race_checker.h"
49 #include "rtc_base/strings/audio_format_to_string.h"
50 #include "rtc_base/strings/string_builder.h"
51 #include "rtc_base/strings/string_format.h"
52 #include "rtc_base/third_party/base64/base64.h"
53 #include "rtc_base/trace_event.h"
54 #include "system_wrappers/include/metrics.h"
55
56 #if WEBRTC_ENABLE_PROTOBUF
57 RTC_PUSH_IGNORING_WUNDEF()
58 #ifdef WEBRTC_ANDROID_PLATFORM_BUILD
59 #include "external/webrtc/webrtc/modules/audio_coding/audio_network_adaptor/config.pb.h"
60 #else
61 #include "modules/audio_coding/audio_network_adaptor/config.pb.h"
62 #endif
63 RTC_POP_IGNORING_WUNDEF()
64 #endif
65
66 namespace cricket {
67 namespace {
68
69 using ::webrtc::ParseRtpSsrc;
70
71 constexpr size_t kMaxUnsignaledRecvStreams = 4;
72
73 constexpr int kNackRtpHistoryMs = 5000;
74
75 const int kMinTelephoneEventCode = 0; // RFC4733 (Section 2.3.1)
76 const int kMaxTelephoneEventCode = 255;
77
78 const int kMinPayloadType = 0;
79 const int kMaxPayloadType = 127;
80
81 class ProxySink : public webrtc::AudioSinkInterface {
82 public:
ProxySink(AudioSinkInterface * sink)83 explicit ProxySink(AudioSinkInterface* sink) : sink_(sink) {
84 RTC_DCHECK(sink);
85 }
86
OnData(const Data & audio)87 void OnData(const Data& audio) override { sink_->OnData(audio); }
88
89 private:
90 webrtc::AudioSinkInterface* sink_;
91 };
92
ValidateStreamParams(const StreamParams & sp)93 bool ValidateStreamParams(const StreamParams& sp) {
94 if (sp.ssrcs.empty()) {
95 RTC_DLOG(LS_ERROR) << "No SSRCs in stream parameters: " << sp.ToString();
96 return false;
97 }
98 if (sp.ssrcs.size() > 1) {
99 RTC_DLOG(LS_ERROR) << "Multiple SSRCs in stream parameters: "
100 << sp.ToString();
101 return false;
102 }
103 return true;
104 }
105
106 // Dumps an AudioCodec in RFC 2327-ish format.
ToString(const AudioCodec & codec)107 std::string ToString(const AudioCodec& codec) {
108 rtc::StringBuilder ss;
109 ss << codec.name << "/" << codec.clockrate << "/" << codec.channels;
110 if (!codec.params.empty()) {
111 ss << " {";
112 for (const auto& param : codec.params) {
113 ss << " " << param.first << "=" << param.second;
114 }
115 ss << " }";
116 }
117 ss << " (" << codec.id << ")";
118 return ss.Release();
119 }
120
IsCodec(const AudioCodec & codec,const char * ref_name)121 bool IsCodec(const AudioCodec& codec, const char* ref_name) {
122 return absl::EqualsIgnoreCase(codec.name, ref_name);
123 }
124
FindCodec(const std::vector<AudioCodec> & codecs,const AudioCodec & codec,AudioCodec * found_codec,const webrtc::FieldTrialsView * field_trials)125 bool FindCodec(const std::vector<AudioCodec>& codecs,
126 const AudioCodec& codec,
127 AudioCodec* found_codec,
128 const webrtc::FieldTrialsView* field_trials) {
129 for (const AudioCodec& c : codecs) {
130 if (c.Matches(codec, field_trials)) {
131 if (found_codec != NULL) {
132 *found_codec = c;
133 }
134 return true;
135 }
136 }
137 return false;
138 }
139
VerifyUniquePayloadTypes(const std::vector<AudioCodec> & codecs)140 bool VerifyUniquePayloadTypes(const std::vector<AudioCodec>& codecs) {
141 if (codecs.empty()) {
142 return true;
143 }
144 std::vector<int> payload_types;
145 absl::c_transform(codecs, std::back_inserter(payload_types),
146 [](const AudioCodec& codec) { return codec.id; });
147 absl::c_sort(payload_types);
148 return absl::c_adjacent_find(payload_types) == payload_types.end();
149 }
150
GetAudioNetworkAdaptorConfig(const AudioOptions & options)151 absl::optional<std::string> GetAudioNetworkAdaptorConfig(
152 const AudioOptions& options) {
153 if (options.audio_network_adaptor && *options.audio_network_adaptor &&
154 options.audio_network_adaptor_config) {
155 // Turn on audio network adaptor only when `options_.audio_network_adaptor`
156 // equals true and `options_.audio_network_adaptor_config` has a value.
157 return options.audio_network_adaptor_config;
158 }
159 return absl::nullopt;
160 }
161
162 // Returns its smallest positive argument. If neither argument is positive,
163 // returns an arbitrary nonpositive value.
MinPositive(int a,int b)164 int MinPositive(int a, int b) {
165 if (a <= 0) {
166 return b;
167 }
168 if (b <= 0) {
169 return a;
170 }
171 return std::min(a, b);
172 }
173
174 // `max_send_bitrate_bps` is the bitrate from "b=" in SDP.
175 // `rtp_max_bitrate_bps` is the bitrate from RtpSender::SetParameters.
ComputeSendBitrate(int max_send_bitrate_bps,absl::optional<int> rtp_max_bitrate_bps,const webrtc::AudioCodecSpec & spec)176 absl::optional<int> ComputeSendBitrate(int max_send_bitrate_bps,
177 absl::optional<int> rtp_max_bitrate_bps,
178 const webrtc::AudioCodecSpec& spec) {
179 // If application-configured bitrate is set, take minimum of that and SDP
180 // bitrate.
181 const int bps = rtp_max_bitrate_bps
182 ? MinPositive(max_send_bitrate_bps, *rtp_max_bitrate_bps)
183 : max_send_bitrate_bps;
184 if (bps <= 0) {
185 return spec.info.default_bitrate_bps;
186 }
187
188 if (bps < spec.info.min_bitrate_bps) {
189 // If codec is not multi-rate and `bps` is less than the fixed bitrate then
190 // fail. If codec is not multi-rate and `bps` exceeds or equal the fixed
191 // bitrate then ignore.
192 RTC_LOG(LS_ERROR) << "Failed to set codec " << spec.format.name
193 << " to bitrate " << bps
194 << " bps"
195 ", requires at least "
196 << spec.info.min_bitrate_bps << " bps.";
197 return absl::nullopt;
198 }
199
200 if (spec.info.HasFixedBitrate()) {
201 return spec.info.default_bitrate_bps;
202 } else {
203 // If codec is multi-rate then just set the bitrate.
204 return std::min(bps, spec.info.max_bitrate_bps);
205 }
206 }
207
IsEnabled(const webrtc::FieldTrialsView & config,absl::string_view trial)208 bool IsEnabled(const webrtc::FieldTrialsView& config, absl::string_view trial) {
209 return absl::StartsWith(config.Lookup(trial), "Enabled");
210 }
211
212 struct AdaptivePtimeConfig {
213 bool enabled = false;
214 webrtc::DataRate min_payload_bitrate = webrtc::DataRate::KilobitsPerSec(16);
215 // Value is chosen to ensure FEC can be encoded, see LBRR_WB_MIN_RATE_BPS in
216 // libopus.
217 webrtc::DataRate min_encoder_bitrate = webrtc::DataRate::KilobitsPerSec(16);
218 bool use_slow_adaptation = true;
219
220 absl::optional<std::string> audio_network_adaptor_config;
221
Parsercricket::__anon564bdbe50111::AdaptivePtimeConfig222 std::unique_ptr<webrtc::StructParametersParser> Parser() {
223 return webrtc::StructParametersParser::Create( //
224 "enabled", &enabled, //
225 "min_payload_bitrate", &min_payload_bitrate, //
226 "min_encoder_bitrate", &min_encoder_bitrate, //
227 "use_slow_adaptation", &use_slow_adaptation);
228 }
229
AdaptivePtimeConfigcricket::__anon564bdbe50111::AdaptivePtimeConfig230 explicit AdaptivePtimeConfig(const webrtc::FieldTrialsView& trials) {
231 Parser()->Parse(trials.Lookup("WebRTC-Audio-AdaptivePtime"));
232 #if WEBRTC_ENABLE_PROTOBUF
233 webrtc::audio_network_adaptor::config::ControllerManager config;
234 auto* frame_length_controller =
235 config.add_controllers()->mutable_frame_length_controller_v2();
236 frame_length_controller->set_min_payload_bitrate_bps(
237 min_payload_bitrate.bps());
238 frame_length_controller->set_use_slow_adaptation(use_slow_adaptation);
239 config.add_controllers()->mutable_bitrate_controller();
240 audio_network_adaptor_config = config.SerializeAsString();
241 #endif
242 }
243 };
244
245 // TODO(tommi): Constructing a receive stream could be made simpler.
246 // Move some of this boiler plate code into the config structs themselves.
BuildReceiveStreamConfig(uint32_t remote_ssrc,uint32_t local_ssrc,bool use_transport_cc,bool use_nack,bool enable_non_sender_rtt,const std::vector<std::string> & stream_ids,const std::vector<webrtc::RtpExtension> & extensions,webrtc::Transport * rtcp_send_transport,const rtc::scoped_refptr<webrtc::AudioDecoderFactory> & decoder_factory,const std::map<int,webrtc::SdpAudioFormat> & decoder_map,absl::optional<webrtc::AudioCodecPairId> codec_pair_id,size_t jitter_buffer_max_packets,bool jitter_buffer_fast_accelerate,int jitter_buffer_min_delay_ms,rtc::scoped_refptr<webrtc::FrameDecryptorInterface> frame_decryptor,const webrtc::CryptoOptions & crypto_options,rtc::scoped_refptr<webrtc::FrameTransformerInterface> frame_transformer)247 webrtc::AudioReceiveStreamInterface::Config BuildReceiveStreamConfig(
248 uint32_t remote_ssrc,
249 uint32_t local_ssrc,
250 bool use_transport_cc,
251 bool use_nack,
252 bool enable_non_sender_rtt,
253 const std::vector<std::string>& stream_ids,
254 const std::vector<webrtc::RtpExtension>& extensions,
255 webrtc::Transport* rtcp_send_transport,
256 const rtc::scoped_refptr<webrtc::AudioDecoderFactory>& decoder_factory,
257 const std::map<int, webrtc::SdpAudioFormat>& decoder_map,
258 absl::optional<webrtc::AudioCodecPairId> codec_pair_id,
259 size_t jitter_buffer_max_packets,
260 bool jitter_buffer_fast_accelerate,
261 int jitter_buffer_min_delay_ms,
262 rtc::scoped_refptr<webrtc::FrameDecryptorInterface> frame_decryptor,
263 const webrtc::CryptoOptions& crypto_options,
264 rtc::scoped_refptr<webrtc::FrameTransformerInterface> frame_transformer) {
265 webrtc::AudioReceiveStreamInterface::Config config;
266 config.rtp.remote_ssrc = remote_ssrc;
267 config.rtp.local_ssrc = local_ssrc;
268 config.rtp.transport_cc = use_transport_cc;
269 config.rtp.nack.rtp_history_ms = use_nack ? kNackRtpHistoryMs : 0;
270 if (!stream_ids.empty()) {
271 config.sync_group = stream_ids[0];
272 }
273 config.rtp.extensions = extensions;
274 config.rtcp_send_transport = rtcp_send_transport;
275 config.enable_non_sender_rtt = enable_non_sender_rtt;
276 config.decoder_factory = decoder_factory;
277 config.decoder_map = decoder_map;
278 config.codec_pair_id = codec_pair_id;
279 config.jitter_buffer_max_packets = jitter_buffer_max_packets;
280 config.jitter_buffer_fast_accelerate = jitter_buffer_fast_accelerate;
281 config.jitter_buffer_min_delay_ms = jitter_buffer_min_delay_ms;
282 config.frame_decryptor = std::move(frame_decryptor);
283 config.crypto_options = crypto_options;
284 config.frame_transformer = std::move(frame_transformer);
285 return config;
286 }
287
288 } // namespace
289
WebRtcVoiceEngine(webrtc::TaskQueueFactory * task_queue_factory,webrtc::AudioDeviceModule * adm,const rtc::scoped_refptr<webrtc::AudioEncoderFactory> & encoder_factory,const rtc::scoped_refptr<webrtc::AudioDecoderFactory> & decoder_factory,rtc::scoped_refptr<webrtc::AudioMixer> audio_mixer,rtc::scoped_refptr<webrtc::AudioProcessing> audio_processing,webrtc::AudioFrameProcessor * audio_frame_processor,const webrtc::FieldTrialsView & trials)290 WebRtcVoiceEngine::WebRtcVoiceEngine(
291 webrtc::TaskQueueFactory* task_queue_factory,
292 webrtc::AudioDeviceModule* adm,
293 const rtc::scoped_refptr<webrtc::AudioEncoderFactory>& encoder_factory,
294 const rtc::scoped_refptr<webrtc::AudioDecoderFactory>& decoder_factory,
295 rtc::scoped_refptr<webrtc::AudioMixer> audio_mixer,
296 rtc::scoped_refptr<webrtc::AudioProcessing> audio_processing,
297 webrtc::AudioFrameProcessor* audio_frame_processor,
298 const webrtc::FieldTrialsView& trials)
299 : task_queue_factory_(task_queue_factory),
300 adm_(adm),
301 encoder_factory_(encoder_factory),
302 decoder_factory_(decoder_factory),
303 audio_mixer_(audio_mixer),
304 apm_(audio_processing),
305 audio_frame_processor_(audio_frame_processor),
306 minimized_remsampling_on_mobile_trial_enabled_(
307 IsEnabled(trials, "WebRTC-Audio-MinimizeResamplingOnMobile")) {
308 // This may be called from any thread, so detach thread checkers.
309 worker_thread_checker_.Detach();
310 signal_thread_checker_.Detach();
311 RTC_LOG(LS_INFO) << "WebRtcVoiceEngine::WebRtcVoiceEngine";
312 RTC_DCHECK(decoder_factory);
313 RTC_DCHECK(encoder_factory);
314 // The rest of our initialization will happen in Init.
315 }
316
~WebRtcVoiceEngine()317 WebRtcVoiceEngine::~WebRtcVoiceEngine() {
318 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
319 RTC_LOG(LS_INFO) << "WebRtcVoiceEngine::~WebRtcVoiceEngine";
320 if (initialized_) {
321 StopAecDump();
322
323 // Stop AudioDevice.
324 adm()->StopPlayout();
325 adm()->StopRecording();
326 adm()->RegisterAudioCallback(nullptr);
327 adm()->Terminate();
328 }
329 }
330
Init()331 void WebRtcVoiceEngine::Init() {
332 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
333 RTC_LOG(LS_INFO) << "WebRtcVoiceEngine::Init";
334
335 // TaskQueue expects to be created/destroyed on the same thread.
336 RTC_DCHECK(!low_priority_worker_queue_);
337 low_priority_worker_queue_.reset(
338 new rtc::TaskQueue(task_queue_factory_->CreateTaskQueue(
339 "rtc-low-prio", webrtc::TaskQueueFactory::Priority::LOW)));
340
341 // Load our audio codec lists.
342 RTC_LOG(LS_VERBOSE) << "Supported send codecs in order of preference:";
343 send_codecs_ = CollectCodecs(encoder_factory_->GetSupportedEncoders());
344 for (const AudioCodec& codec : send_codecs_) {
345 RTC_LOG(LS_VERBOSE) << ToString(codec);
346 }
347
348 RTC_LOG(LS_VERBOSE) << "Supported recv codecs in order of preference:";
349 recv_codecs_ = CollectCodecs(decoder_factory_->GetSupportedDecoders());
350 for (const AudioCodec& codec : recv_codecs_) {
351 RTC_LOG(LS_VERBOSE) << ToString(codec);
352 }
353
354 #if defined(WEBRTC_INCLUDE_INTERNAL_AUDIO_DEVICE)
355 // No ADM supplied? Create a default one.
356 if (!adm_) {
357 adm_ = webrtc::AudioDeviceModule::Create(
358 webrtc::AudioDeviceModule::kPlatformDefaultAudio, task_queue_factory_);
359 }
360 #endif // WEBRTC_INCLUDE_INTERNAL_AUDIO_DEVICE
361 RTC_CHECK(adm());
362 webrtc::adm_helpers::Init(adm());
363
364 // Set up AudioState.
365 {
366 webrtc::AudioState::Config config;
367 if (audio_mixer_) {
368 config.audio_mixer = audio_mixer_;
369 } else {
370 config.audio_mixer = webrtc::AudioMixerImpl::Create();
371 }
372 config.audio_processing = apm_;
373 config.audio_device_module = adm_;
374 if (audio_frame_processor_)
375 config.async_audio_processing_factory =
376 rtc::make_ref_counted<webrtc::AsyncAudioProcessing::Factory>(
377 *audio_frame_processor_, *task_queue_factory_);
378 audio_state_ = webrtc::AudioState::Create(config);
379 }
380
381 // Connect the ADM to our audio path.
382 adm()->RegisterAudioCallback(audio_state()->audio_transport());
383
384 // Set default engine options.
385 {
386 AudioOptions options;
387 options.echo_cancellation = true;
388 options.auto_gain_control = true;
389 #if defined(WEBRTC_IOS)
390 // On iOS, VPIO provides built-in NS.
391 options.noise_suppression = false;
392 #else
393 options.noise_suppression = true;
394 #endif
395 options.highpass_filter = true;
396 options.stereo_swapping = false;
397 options.audio_jitter_buffer_max_packets = 200;
398 options.audio_jitter_buffer_fast_accelerate = false;
399 options.audio_jitter_buffer_min_delay_ms = 0;
400 ApplyOptions(options);
401 }
402 initialized_ = true;
403 }
404
GetAudioState() const405 rtc::scoped_refptr<webrtc::AudioState> WebRtcVoiceEngine::GetAudioState()
406 const {
407 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
408 return audio_state_;
409 }
410
CreateMediaChannel(webrtc::Call * call,const MediaConfig & config,const AudioOptions & options,const webrtc::CryptoOptions & crypto_options)411 VoiceMediaChannel* WebRtcVoiceEngine::CreateMediaChannel(
412 webrtc::Call* call,
413 const MediaConfig& config,
414 const AudioOptions& options,
415 const webrtc::CryptoOptions& crypto_options) {
416 RTC_DCHECK_RUN_ON(call->worker_thread());
417 return new WebRtcVoiceMediaChannel(this, config, options, crypto_options,
418 call);
419 }
420
ApplyOptions(const AudioOptions & options_in)421 void WebRtcVoiceEngine::ApplyOptions(const AudioOptions& options_in) {
422 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
423 RTC_LOG(LS_INFO) << "WebRtcVoiceEngine::ApplyOptions: "
424 << options_in.ToString();
425 AudioOptions options = options_in; // The options are modified below.
426
427 // Set and adjust echo canceller options.
428 // Use desktop AEC by default, when not using hardware AEC.
429 bool use_mobile_software_aec = false;
430
431 #if defined(WEBRTC_IOS)
432 if (options.ios_force_software_aec_HACK &&
433 *options.ios_force_software_aec_HACK) {
434 // EC may be forced on for a device known to have non-functioning platform
435 // AEC.
436 options.echo_cancellation = true;
437 RTC_LOG(LS_WARNING)
438 << "Force software AEC on iOS. May conflict with platform AEC.";
439 } else {
440 // On iOS, VPIO provides built-in EC.
441 options.echo_cancellation = false;
442 RTC_LOG(LS_INFO) << "Always disable AEC on iOS. Use built-in instead.";
443 }
444 #elif defined(WEBRTC_ANDROID)
445 use_mobile_software_aec = true;
446 #endif
447
448 // Set and adjust gain control options.
449 #if defined(WEBRTC_IOS)
450 // On iOS, VPIO provides built-in AGC.
451 options.auto_gain_control = false;
452 RTC_LOG(LS_INFO) << "Always disable AGC on iOS. Use built-in instead.";
453 #endif
454
455 #if defined(WEBRTC_IOS) || defined(WEBRTC_ANDROID)
456 // Turn off the gain control if specified by the field trial.
457 // The purpose of the field trial is to reduce the amount of resampling
458 // performed inside the audio processing module on mobile platforms by
459 // whenever possible turning off the fixed AGC mode and the high-pass filter.
460 // (https://bugs.chromium.org/p/webrtc/issues/detail?id=6181).
461 if (minimized_remsampling_on_mobile_trial_enabled_) {
462 options.auto_gain_control = false;
463 RTC_LOG(LS_INFO) << "Disable AGC according to field trial.";
464 if (!(options.noise_suppression.value_or(false) ||
465 options.echo_cancellation.value_or(false))) {
466 // If possible, turn off the high-pass filter.
467 RTC_LOG(LS_INFO)
468 << "Disable high-pass filter in response to field trial.";
469 options.highpass_filter = false;
470 }
471 }
472 #endif
473
474 if (options.echo_cancellation) {
475 // Check if platform supports built-in EC. Currently only supported on
476 // Android and in combination with Java based audio layer.
477 // TODO(henrika): investigate possibility to support built-in EC also
478 // in combination with Open SL ES audio.
479 const bool built_in_aec = adm()->BuiltInAECIsAvailable();
480 if (built_in_aec) {
481 // Built-in EC exists on this device. Enable/Disable it according to the
482 // echo_cancellation audio option.
483 const bool enable_built_in_aec = *options.echo_cancellation;
484 if (adm()->EnableBuiltInAEC(enable_built_in_aec) == 0 &&
485 enable_built_in_aec) {
486 // Disable internal software EC if built-in EC is enabled,
487 // i.e., replace the software EC with the built-in EC.
488 options.echo_cancellation = false;
489 RTC_LOG(LS_INFO)
490 << "Disabling EC since built-in EC will be used instead";
491 }
492 }
493 }
494
495 if (options.auto_gain_control) {
496 bool built_in_agc_avaliable = adm()->BuiltInAGCIsAvailable();
497 if (built_in_agc_avaliable) {
498 if (adm()->EnableBuiltInAGC(*options.auto_gain_control) == 0 &&
499 *options.auto_gain_control) {
500 // Disable internal software AGC if built-in AGC is enabled,
501 // i.e., replace the software AGC with the built-in AGC.
502 options.auto_gain_control = false;
503 RTC_LOG(LS_INFO)
504 << "Disabling AGC since built-in AGC will be used instead";
505 }
506 }
507 }
508
509 if (options.noise_suppression) {
510 if (adm()->BuiltInNSIsAvailable()) {
511 bool builtin_ns = *options.noise_suppression;
512 if (adm()->EnableBuiltInNS(builtin_ns) == 0 && builtin_ns) {
513 // Disable internal software NS if built-in NS is enabled,
514 // i.e., replace the software NS with the built-in NS.
515 options.noise_suppression = false;
516 RTC_LOG(LS_INFO)
517 << "Disabling NS since built-in NS will be used instead";
518 }
519 }
520 }
521
522 if (options.stereo_swapping) {
523 audio_state()->SetStereoChannelSwapping(*options.stereo_swapping);
524 }
525
526 if (options.audio_jitter_buffer_max_packets) {
527 audio_jitter_buffer_max_packets_ =
528 std::max(20, *options.audio_jitter_buffer_max_packets);
529 }
530 if (options.audio_jitter_buffer_fast_accelerate) {
531 audio_jitter_buffer_fast_accelerate_ =
532 *options.audio_jitter_buffer_fast_accelerate;
533 }
534 if (options.audio_jitter_buffer_min_delay_ms) {
535 audio_jitter_buffer_min_delay_ms_ =
536 *options.audio_jitter_buffer_min_delay_ms;
537 }
538
539 webrtc::AudioProcessing* ap = apm();
540 if (!ap) {
541 return;
542 }
543
544 webrtc::AudioProcessing::Config apm_config = ap->GetConfig();
545
546 if (options.echo_cancellation) {
547 apm_config.echo_canceller.enabled = *options.echo_cancellation;
548 apm_config.echo_canceller.mobile_mode = use_mobile_software_aec;
549 }
550
551 if (options.auto_gain_control) {
552 const bool enabled = *options.auto_gain_control;
553 apm_config.gain_controller1.enabled = enabled;
554 #if defined(WEBRTC_IOS) || defined(WEBRTC_ANDROID)
555 apm_config.gain_controller1.mode =
556 apm_config.gain_controller1.kFixedDigital;
557 #else
558 apm_config.gain_controller1.mode =
559 apm_config.gain_controller1.kAdaptiveAnalog;
560 #endif
561 }
562
563 if (options.highpass_filter) {
564 apm_config.high_pass_filter.enabled = *options.highpass_filter;
565 }
566
567 if (options.noise_suppression) {
568 const bool enabled = *options.noise_suppression;
569 apm_config.noise_suppression.enabled = enabled;
570 apm_config.noise_suppression.level =
571 webrtc::AudioProcessing::Config::NoiseSuppression::Level::kHigh;
572 }
573
574 ap->ApplyConfig(apm_config);
575 }
576
send_codecs() const577 const std::vector<AudioCodec>& WebRtcVoiceEngine::send_codecs() const {
578 RTC_DCHECK(signal_thread_checker_.IsCurrent());
579 return send_codecs_;
580 }
581
recv_codecs() const582 const std::vector<AudioCodec>& WebRtcVoiceEngine::recv_codecs() const {
583 RTC_DCHECK(signal_thread_checker_.IsCurrent());
584 return recv_codecs_;
585 }
586
587 std::vector<webrtc::RtpHeaderExtensionCapability>
GetRtpHeaderExtensions() const588 WebRtcVoiceEngine::GetRtpHeaderExtensions() const {
589 RTC_DCHECK(signal_thread_checker_.IsCurrent());
590 std::vector<webrtc::RtpHeaderExtensionCapability> result;
591 int id = 1;
592 for (const auto& uri : {webrtc::RtpExtension::kAudioLevelUri,
593 webrtc::RtpExtension::kAbsSendTimeUri,
594 webrtc::RtpExtension::kTransportSequenceNumberUri,
595 webrtc::RtpExtension::kMidUri}) {
596 result.emplace_back(uri, id++, webrtc::RtpTransceiverDirection::kSendRecv);
597 }
598 return result;
599 }
600
StartAecDump(webrtc::FileWrapper file,int64_t max_size_bytes)601 bool WebRtcVoiceEngine::StartAecDump(webrtc::FileWrapper file,
602 int64_t max_size_bytes) {
603 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
604
605 webrtc::AudioProcessing* ap = apm();
606 if (!ap) {
607 RTC_LOG(LS_WARNING)
608 << "Attempting to start aecdump when no audio processing module is "
609 "present, hence no aecdump is started.";
610 return false;
611 }
612
613 return ap->CreateAndAttachAecDump(file.Release(), max_size_bytes,
614 low_priority_worker_queue_.get());
615 }
616
StopAecDump()617 void WebRtcVoiceEngine::StopAecDump() {
618 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
619 webrtc::AudioProcessing* ap = apm();
620 if (ap) {
621 ap->DetachAecDump();
622 } else {
623 RTC_LOG(LS_WARNING) << "Attempting to stop aecdump when no audio "
624 "processing module is present";
625 }
626 }
627
adm()628 webrtc::AudioDeviceModule* WebRtcVoiceEngine::adm() {
629 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
630 RTC_DCHECK(adm_);
631 return adm_.get();
632 }
633
apm() const634 webrtc::AudioProcessing* WebRtcVoiceEngine::apm() const {
635 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
636 return apm_.get();
637 }
638
audio_state()639 webrtc::AudioState* WebRtcVoiceEngine::audio_state() {
640 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
641 RTC_DCHECK(audio_state_);
642 return audio_state_.get();
643 }
644
CollectCodecs(const std::vector<webrtc::AudioCodecSpec> & specs) const645 std::vector<AudioCodec> WebRtcVoiceEngine::CollectCodecs(
646 const std::vector<webrtc::AudioCodecSpec>& specs) const {
647 PayloadTypeMapper mapper;
648 std::vector<AudioCodec> out;
649
650 // Only generate CN payload types for these clockrates:
651 std::map<int, bool, std::greater<int>> generate_cn = {
652 {8000, false}, {16000, false}, {32000, false}};
653 // Only generate telephone-event payload types for these clockrates:
654 std::map<int, bool, std::greater<int>> generate_dtmf = {
655 {8000, false}, {16000, false}, {32000, false}, {48000, false}};
656
657 auto map_format = [&mapper](const webrtc::SdpAudioFormat& format,
658 std::vector<AudioCodec>* out) {
659 absl::optional<AudioCodec> opt_codec = mapper.ToAudioCodec(format);
660 if (opt_codec) {
661 if (out) {
662 out->push_back(*opt_codec);
663 }
664 } else {
665 RTC_LOG(LS_ERROR) << "Unable to assign payload type to format: "
666 << rtc::ToString(format);
667 }
668
669 return opt_codec;
670 };
671
672 for (const auto& spec : specs) {
673 // We need to do some extra stuff before adding the main codecs to out.
674 absl::optional<AudioCodec> opt_codec = map_format(spec.format, nullptr);
675 if (opt_codec) {
676 AudioCodec& codec = *opt_codec;
677 if (spec.info.supports_network_adaption) {
678 codec.AddFeedbackParam(
679 FeedbackParam(kRtcpFbParamTransportCc, kParamValueEmpty));
680 }
681
682 if (spec.info.allow_comfort_noise) {
683 // Generate a CN entry if the decoder allows it and we support the
684 // clockrate.
685 auto cn = generate_cn.find(spec.format.clockrate_hz);
686 if (cn != generate_cn.end()) {
687 cn->second = true;
688 }
689 }
690
691 // Generate a telephone-event entry if we support the clockrate.
692 auto dtmf = generate_dtmf.find(spec.format.clockrate_hz);
693 if (dtmf != generate_dtmf.end()) {
694 dtmf->second = true;
695 }
696
697 out.push_back(codec);
698
699 if (codec.name == kOpusCodecName) {
700 std::string redFmtp =
701 rtc::ToString(codec.id) + "/" + rtc::ToString(codec.id);
702 map_format({kRedCodecName, 48000, 2, {{"", redFmtp}}}, &out);
703 }
704 }
705 }
706
707 // Add CN codecs after "proper" audio codecs.
708 for (const auto& cn : generate_cn) {
709 if (cn.second) {
710 map_format({kCnCodecName, cn.first, 1}, &out);
711 }
712 }
713
714 // Add telephone-event codecs last.
715 for (const auto& dtmf : generate_dtmf) {
716 if (dtmf.second) {
717 map_format({kDtmfCodecName, dtmf.first, 1}, &out);
718 }
719 }
720
721 return out;
722 }
723
724 class WebRtcVoiceMediaChannel::WebRtcAudioSendStream
725 : public AudioSource::Sink {
726 public:
WebRtcAudioSendStream(uint32_t ssrc,const std::string & mid,const std::string & c_name,const std::string track_id,const absl::optional<webrtc::AudioSendStream::Config::SendCodecSpec> & send_codec_spec,bool extmap_allow_mixed,const std::vector<webrtc::RtpExtension> & extensions,int max_send_bitrate_bps,int rtcp_report_interval_ms,const absl::optional<std::string> & audio_network_adaptor_config,webrtc::Call * call,webrtc::Transport * send_transport,const rtc::scoped_refptr<webrtc::AudioEncoderFactory> & encoder_factory,const absl::optional<webrtc::AudioCodecPairId> codec_pair_id,rtc::scoped_refptr<webrtc::FrameEncryptorInterface> frame_encryptor,const webrtc::CryptoOptions & crypto_options)727 WebRtcAudioSendStream(
728 uint32_t ssrc,
729 const std::string& mid,
730 const std::string& c_name,
731 const std::string track_id,
732 const absl::optional<webrtc::AudioSendStream::Config::SendCodecSpec>&
733 send_codec_spec,
734 bool extmap_allow_mixed,
735 const std::vector<webrtc::RtpExtension>& extensions,
736 int max_send_bitrate_bps,
737 int rtcp_report_interval_ms,
738 const absl::optional<std::string>& audio_network_adaptor_config,
739 webrtc::Call* call,
740 webrtc::Transport* send_transport,
741 const rtc::scoped_refptr<webrtc::AudioEncoderFactory>& encoder_factory,
742 const absl::optional<webrtc::AudioCodecPairId> codec_pair_id,
743 rtc::scoped_refptr<webrtc::FrameEncryptorInterface> frame_encryptor,
744 const webrtc::CryptoOptions& crypto_options)
745 : adaptive_ptime_config_(call->trials()),
746 call_(call),
747 config_(send_transport),
748 max_send_bitrate_bps_(max_send_bitrate_bps),
749 rtp_parameters_(CreateRtpParametersWithOneEncoding()) {
750 RTC_DCHECK(call);
751 RTC_DCHECK(encoder_factory);
752 config_.rtp.ssrc = ssrc;
753 config_.rtp.mid = mid;
754 config_.rtp.c_name = c_name;
755 config_.rtp.extmap_allow_mixed = extmap_allow_mixed;
756 config_.rtp.extensions = extensions;
757 config_.has_dscp =
758 rtp_parameters_.encodings[0].network_priority != webrtc::Priority::kLow;
759 config_.encoder_factory = encoder_factory;
760 config_.codec_pair_id = codec_pair_id;
761 config_.track_id = track_id;
762 config_.frame_encryptor = frame_encryptor;
763 config_.crypto_options = crypto_options;
764 config_.rtcp_report_interval_ms = rtcp_report_interval_ms;
765 rtp_parameters_.encodings[0].ssrc = ssrc;
766 rtp_parameters_.rtcp.cname = c_name;
767 rtp_parameters_.header_extensions = extensions;
768
769 audio_network_adaptor_config_from_options_ = audio_network_adaptor_config;
770 UpdateAudioNetworkAdaptorConfig();
771
772 if (send_codec_spec) {
773 UpdateSendCodecSpec(*send_codec_spec);
774 }
775
776 stream_ = call_->CreateAudioSendStream(config_);
777 }
778
779 WebRtcAudioSendStream() = delete;
780 WebRtcAudioSendStream(const WebRtcAudioSendStream&) = delete;
781 WebRtcAudioSendStream& operator=(const WebRtcAudioSendStream&) = delete;
782
~WebRtcAudioSendStream()783 ~WebRtcAudioSendStream() override {
784 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
785 ClearSource();
786 call_->DestroyAudioSendStream(stream_);
787 }
788
SetSendCodecSpec(const webrtc::AudioSendStream::Config::SendCodecSpec & send_codec_spec)789 void SetSendCodecSpec(
790 const webrtc::AudioSendStream::Config::SendCodecSpec& send_codec_spec) {
791 UpdateSendCodecSpec(send_codec_spec);
792 ReconfigureAudioSendStream(nullptr);
793 }
794
SetRtpExtensions(const std::vector<webrtc::RtpExtension> & extensions)795 void SetRtpExtensions(const std::vector<webrtc::RtpExtension>& extensions) {
796 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
797 config_.rtp.extensions = extensions;
798 rtp_parameters_.header_extensions = extensions;
799 ReconfigureAudioSendStream(nullptr);
800 }
801
SetExtmapAllowMixed(bool extmap_allow_mixed)802 void SetExtmapAllowMixed(bool extmap_allow_mixed) {
803 config_.rtp.extmap_allow_mixed = extmap_allow_mixed;
804 ReconfigureAudioSendStream(nullptr);
805 }
806
SetMid(const std::string & mid)807 void SetMid(const std::string& mid) {
808 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
809 if (config_.rtp.mid == mid) {
810 return;
811 }
812 config_.rtp.mid = mid;
813 ReconfigureAudioSendStream(nullptr);
814 }
815
SetFrameEncryptor(rtc::scoped_refptr<webrtc::FrameEncryptorInterface> frame_encryptor)816 void SetFrameEncryptor(
817 rtc::scoped_refptr<webrtc::FrameEncryptorInterface> frame_encryptor) {
818 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
819 config_.frame_encryptor = frame_encryptor;
820 ReconfigureAudioSendStream(nullptr);
821 }
822
SetAudioNetworkAdaptorConfig(const absl::optional<std::string> & audio_network_adaptor_config)823 void SetAudioNetworkAdaptorConfig(
824 const absl::optional<std::string>& audio_network_adaptor_config) {
825 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
826 if (audio_network_adaptor_config_from_options_ ==
827 audio_network_adaptor_config) {
828 return;
829 }
830 audio_network_adaptor_config_from_options_ = audio_network_adaptor_config;
831 UpdateAudioNetworkAdaptorConfig();
832 UpdateAllowedBitrateRange();
833 ReconfigureAudioSendStream(nullptr);
834 }
835
SetMaxSendBitrate(int bps)836 bool SetMaxSendBitrate(int bps) {
837 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
838 RTC_DCHECK(config_.send_codec_spec);
839 RTC_DCHECK(audio_codec_spec_);
840 auto send_rate = ComputeSendBitrate(
841 bps, rtp_parameters_.encodings[0].max_bitrate_bps, *audio_codec_spec_);
842
843 if (!send_rate) {
844 return false;
845 }
846
847 max_send_bitrate_bps_ = bps;
848
849 if (send_rate != config_.send_codec_spec->target_bitrate_bps) {
850 config_.send_codec_spec->target_bitrate_bps = send_rate;
851 ReconfigureAudioSendStream(nullptr);
852 }
853 return true;
854 }
855
SendTelephoneEvent(int payload_type,int payload_freq,int event,int duration_ms)856 bool SendTelephoneEvent(int payload_type,
857 int payload_freq,
858 int event,
859 int duration_ms) {
860 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
861 RTC_DCHECK(stream_);
862 return stream_->SendTelephoneEvent(payload_type, payload_freq, event,
863 duration_ms);
864 }
865
SetSend(bool send)866 void SetSend(bool send) {
867 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
868 send_ = send;
869 UpdateSendState();
870 }
871
SetMuted(bool muted)872 void SetMuted(bool muted) {
873 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
874 RTC_DCHECK(stream_);
875 stream_->SetMuted(muted);
876 muted_ = muted;
877 }
878
muted() const879 bool muted() const {
880 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
881 return muted_;
882 }
883
GetStats(bool has_remote_tracks) const884 webrtc::AudioSendStream::Stats GetStats(bool has_remote_tracks) const {
885 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
886 RTC_DCHECK(stream_);
887 return stream_->GetStats(has_remote_tracks);
888 }
889
890 // Starts the sending by setting ourselves as a sink to the AudioSource to
891 // get data callbacks.
892 // This method is called on the libjingle worker thread.
893 // TODO(xians): Make sure Start() is called only once.
SetSource(AudioSource * source)894 void SetSource(AudioSource* source) {
895 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
896 RTC_DCHECK(source);
897 if (source_) {
898 RTC_DCHECK(source_ == source);
899 return;
900 }
901 source->SetSink(this);
902 source_ = source;
903 UpdateSendState();
904 }
905
906 // Stops sending by setting the sink of the AudioSource to nullptr. No data
907 // callback will be received after this method.
908 // This method is called on the libjingle worker thread.
ClearSource()909 void ClearSource() {
910 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
911 if (source_) {
912 source_->SetSink(nullptr);
913 source_ = nullptr;
914 }
915 UpdateSendState();
916 }
917
918 // AudioSource::Sink implementation.
919 // This method is called on the audio thread.
OnData(const void * audio_data,int bits_per_sample,int sample_rate,size_t number_of_channels,size_t number_of_frames,absl::optional<int64_t> absolute_capture_timestamp_ms)920 void OnData(const void* audio_data,
921 int bits_per_sample,
922 int sample_rate,
923 size_t number_of_channels,
924 size_t number_of_frames,
925 absl::optional<int64_t> absolute_capture_timestamp_ms) override {
926 TRACE_EVENT_BEGIN2("webrtc", "WebRtcAudioSendStream::OnData", "sample_rate",
927 sample_rate, "number_of_frames", number_of_frames);
928 RTC_DCHECK_EQ(16, bits_per_sample);
929 RTC_CHECK_RUNS_SERIALIZED(&audio_capture_race_checker_);
930 RTC_DCHECK(stream_);
931 std::unique_ptr<webrtc::AudioFrame> audio_frame(new webrtc::AudioFrame());
932 audio_frame->UpdateFrame(
933 audio_frame->timestamp_, static_cast<const int16_t*>(audio_data),
934 number_of_frames, sample_rate, audio_frame->speech_type_,
935 audio_frame->vad_activity_, number_of_channels);
936 // TODO(bugs.webrtc.org/10739): add dcheck that
937 // `absolute_capture_timestamp_ms` always receives a value.
938 if (absolute_capture_timestamp_ms) {
939 audio_frame->set_absolute_capture_timestamp_ms(
940 *absolute_capture_timestamp_ms);
941 }
942 stream_->SendAudioData(std::move(audio_frame));
943 TRACE_EVENT_END1("webrtc", "WebRtcAudioSendStream::OnData",
944 "number_of_channels", number_of_channels);
945 }
946
947 // Callback from the `source_` when it is going away. In case Start() has
948 // never been called, this callback won't be triggered.
OnClose()949 void OnClose() override {
950 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
951 // Set `source_` to nullptr to make sure no more callback will get into
952 // the source.
953 source_ = nullptr;
954 UpdateSendState();
955 }
956
rtp_parameters() const957 const webrtc::RtpParameters& rtp_parameters() const {
958 return rtp_parameters_;
959 }
960
SetRtpParameters(const webrtc::RtpParameters & parameters,webrtc::SetParametersCallback callback)961 webrtc::RTCError SetRtpParameters(const webrtc::RtpParameters& parameters,
962 webrtc::SetParametersCallback callback) {
963 webrtc::RTCError error = CheckRtpParametersInvalidModificationAndValues(
964 rtp_parameters_, parameters);
965 if (!error.ok()) {
966 return webrtc::InvokeSetParametersCallback(callback, error);
967 }
968
969 absl::optional<int> send_rate;
970 if (audio_codec_spec_) {
971 send_rate = ComputeSendBitrate(max_send_bitrate_bps_,
972 parameters.encodings[0].max_bitrate_bps,
973 *audio_codec_spec_);
974 if (!send_rate) {
975 return webrtc::InvokeSetParametersCallback(
976 callback, webrtc::RTCError(webrtc::RTCErrorType::INTERNAL_ERROR));
977 }
978 }
979
980 const absl::optional<int> old_rtp_max_bitrate =
981 rtp_parameters_.encodings[0].max_bitrate_bps;
982 double old_priority = rtp_parameters_.encodings[0].bitrate_priority;
983 webrtc::Priority old_dscp = rtp_parameters_.encodings[0].network_priority;
984 bool old_adaptive_ptime = rtp_parameters_.encodings[0].adaptive_ptime;
985 rtp_parameters_ = parameters;
986 config_.bitrate_priority = rtp_parameters_.encodings[0].bitrate_priority;
987 config_.has_dscp = (rtp_parameters_.encodings[0].network_priority !=
988 webrtc::Priority::kLow);
989
990 bool reconfigure_send_stream =
991 (rtp_parameters_.encodings[0].max_bitrate_bps != old_rtp_max_bitrate) ||
992 (rtp_parameters_.encodings[0].bitrate_priority != old_priority) ||
993 (rtp_parameters_.encodings[0].network_priority != old_dscp) ||
994 (rtp_parameters_.encodings[0].adaptive_ptime != old_adaptive_ptime);
995 if (rtp_parameters_.encodings[0].max_bitrate_bps != old_rtp_max_bitrate) {
996 // Update the bitrate range.
997 if (send_rate) {
998 config_.send_codec_spec->target_bitrate_bps = send_rate;
999 }
1000 }
1001 if (reconfigure_send_stream) {
1002 // Changing adaptive_ptime may update the audio network adaptor config
1003 // used.
1004 UpdateAudioNetworkAdaptorConfig();
1005 UpdateAllowedBitrateRange();
1006 ReconfigureAudioSendStream(std::move(callback));
1007 } else {
1008 webrtc::InvokeSetParametersCallback(callback, webrtc::RTCError::OK());
1009 }
1010
1011 rtp_parameters_.rtcp.cname = config_.rtp.c_name;
1012 rtp_parameters_.rtcp.reduced_size = false;
1013
1014 // parameters.encodings[0].active could have changed.
1015 UpdateSendState();
1016 return webrtc::RTCError::OK();
1017 }
1018
SetEncoderToPacketizerFrameTransformer(rtc::scoped_refptr<webrtc::FrameTransformerInterface> frame_transformer)1019 void SetEncoderToPacketizerFrameTransformer(
1020 rtc::scoped_refptr<webrtc::FrameTransformerInterface> frame_transformer) {
1021 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
1022 config_.frame_transformer = std::move(frame_transformer);
1023 ReconfigureAudioSendStream(nullptr);
1024 }
1025
1026 private:
UpdateSendState()1027 void UpdateSendState() {
1028 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
1029 RTC_DCHECK(stream_);
1030 RTC_DCHECK_EQ(1UL, rtp_parameters_.encodings.size());
1031 if (send_ && source_ != nullptr && rtp_parameters_.encodings[0].active) {
1032 stream_->Start();
1033 } else { // !send || source_ = nullptr
1034 stream_->Stop();
1035 }
1036 }
1037
UpdateAllowedBitrateRange()1038 void UpdateAllowedBitrateRange() {
1039 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
1040 // The order of precedence, from lowest to highest is:
1041 // - a reasonable default of 32kbps min/max
1042 // - fixed target bitrate from codec spec
1043 // - lower min bitrate if adaptive ptime is enabled
1044 const int kDefaultBitrateBps = 32000;
1045 config_.min_bitrate_bps = kDefaultBitrateBps;
1046 config_.max_bitrate_bps = kDefaultBitrateBps;
1047
1048 if (config_.send_codec_spec &&
1049 config_.send_codec_spec->target_bitrate_bps) {
1050 config_.min_bitrate_bps = *config_.send_codec_spec->target_bitrate_bps;
1051 config_.max_bitrate_bps = *config_.send_codec_spec->target_bitrate_bps;
1052 }
1053
1054 if (rtp_parameters_.encodings[0].adaptive_ptime) {
1055 config_.min_bitrate_bps = std::min(
1056 config_.min_bitrate_bps,
1057 static_cast<int>(adaptive_ptime_config_.min_encoder_bitrate.bps()));
1058 }
1059 }
1060
UpdateSendCodecSpec(const webrtc::AudioSendStream::Config::SendCodecSpec & send_codec_spec)1061 void UpdateSendCodecSpec(
1062 const webrtc::AudioSendStream::Config::SendCodecSpec& send_codec_spec) {
1063 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
1064 config_.send_codec_spec = send_codec_spec;
1065 auto info =
1066 config_.encoder_factory->QueryAudioEncoder(send_codec_spec.format);
1067 RTC_DCHECK(info);
1068 // If a specific target bitrate has been set for the stream, use that as
1069 // the new default bitrate when computing send bitrate.
1070 if (send_codec_spec.target_bitrate_bps) {
1071 info->default_bitrate_bps = std::max(
1072 info->min_bitrate_bps,
1073 std::min(info->max_bitrate_bps, *send_codec_spec.target_bitrate_bps));
1074 }
1075
1076 audio_codec_spec_.emplace(
1077 webrtc::AudioCodecSpec{send_codec_spec.format, *info});
1078
1079 config_.send_codec_spec->target_bitrate_bps = ComputeSendBitrate(
1080 max_send_bitrate_bps_, rtp_parameters_.encodings[0].max_bitrate_bps,
1081 *audio_codec_spec_);
1082
1083 UpdateAllowedBitrateRange();
1084
1085 // Encoder will only use two channels if the stereo parameter is set.
1086 const auto& it = send_codec_spec.format.parameters.find("stereo");
1087 if (it != send_codec_spec.format.parameters.end() && it->second == "1") {
1088 num_encoded_channels_ = 2;
1089 } else {
1090 num_encoded_channels_ = 1;
1091 }
1092 }
1093
UpdateAudioNetworkAdaptorConfig()1094 void UpdateAudioNetworkAdaptorConfig() {
1095 if (adaptive_ptime_config_.enabled ||
1096 rtp_parameters_.encodings[0].adaptive_ptime) {
1097 config_.audio_network_adaptor_config =
1098 adaptive_ptime_config_.audio_network_adaptor_config;
1099 return;
1100 }
1101 config_.audio_network_adaptor_config =
1102 audio_network_adaptor_config_from_options_;
1103 }
1104
ReconfigureAudioSendStream(webrtc::SetParametersCallback callback)1105 void ReconfigureAudioSendStream(webrtc::SetParametersCallback callback) {
1106 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
1107 RTC_DCHECK(stream_);
1108 stream_->Reconfigure(config_, std::move(callback));
1109 }
1110
NumPreferredChannels() const1111 int NumPreferredChannels() const override { return num_encoded_channels_; }
1112
1113 const AdaptivePtimeConfig adaptive_ptime_config_;
1114 webrtc::SequenceChecker worker_thread_checker_;
1115 rtc::RaceChecker audio_capture_race_checker_;
1116 webrtc::Call* call_ = nullptr;
1117 webrtc::AudioSendStream::Config config_;
1118 // The stream is owned by WebRtcAudioSendStream and may be reallocated if
1119 // configuration changes.
1120 webrtc::AudioSendStream* stream_ = nullptr;
1121
1122 // Raw pointer to AudioSource owned by LocalAudioTrackHandler.
1123 // PeerConnection will make sure invalidating the pointer before the object
1124 // goes away.
1125 AudioSource* source_ = nullptr;
1126 bool send_ = false;
1127 bool muted_ = false;
1128 int max_send_bitrate_bps_;
1129 webrtc::RtpParameters rtp_parameters_;
1130 absl::optional<webrtc::AudioCodecSpec> audio_codec_spec_;
1131 // TODO(webrtc:11717): Remove this once audio_network_adaptor in AudioOptions
1132 // has been removed.
1133 absl::optional<std::string> audio_network_adaptor_config_from_options_;
1134 std::atomic<int> num_encoded_channels_{-1};
1135 };
1136
1137 class WebRtcVoiceMediaChannel::WebRtcAudioReceiveStream {
1138 public:
WebRtcAudioReceiveStream(webrtc::AudioReceiveStreamInterface::Config config,webrtc::Call * call)1139 WebRtcAudioReceiveStream(webrtc::AudioReceiveStreamInterface::Config config,
1140 webrtc::Call* call)
1141 : call_(call), stream_(call_->CreateAudioReceiveStream(config)) {
1142 RTC_DCHECK(call);
1143 RTC_DCHECK(stream_);
1144 }
1145
1146 WebRtcAudioReceiveStream() = delete;
1147 WebRtcAudioReceiveStream(const WebRtcAudioReceiveStream&) = delete;
1148 WebRtcAudioReceiveStream& operator=(const WebRtcAudioReceiveStream&) = delete;
1149
~WebRtcAudioReceiveStream()1150 ~WebRtcAudioReceiveStream() {
1151 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
1152 call_->DestroyAudioReceiveStream(stream_);
1153 }
1154
stream()1155 webrtc::AudioReceiveStreamInterface& stream() {
1156 RTC_DCHECK(stream_);
1157 return *stream_;
1158 }
1159
SetFrameDecryptor(rtc::scoped_refptr<webrtc::FrameDecryptorInterface> frame_decryptor)1160 void SetFrameDecryptor(
1161 rtc::scoped_refptr<webrtc::FrameDecryptorInterface> frame_decryptor) {
1162 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
1163 stream_->SetFrameDecryptor(std::move(frame_decryptor));
1164 }
1165
SetUseTransportCc(bool use_transport_cc,bool use_nack)1166 void SetUseTransportCc(bool use_transport_cc, bool use_nack) {
1167 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
1168 stream_->SetTransportCc(use_transport_cc);
1169 stream_->SetNackHistory(use_nack ? kNackRtpHistoryMs : 0);
1170 }
1171
SetNonSenderRttMeasurement(bool enabled)1172 void SetNonSenderRttMeasurement(bool enabled) {
1173 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
1174 stream_->SetNonSenderRttMeasurement(enabled);
1175 }
1176
SetRtpExtensions(const std::vector<webrtc::RtpExtension> & extensions)1177 void SetRtpExtensions(const std::vector<webrtc::RtpExtension>& extensions) {
1178 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
1179 stream_->SetRtpExtensions(extensions);
1180 }
1181
1182 // Set a new payload type -> decoder map.
SetDecoderMap(const std::map<int,webrtc::SdpAudioFormat> & decoder_map)1183 void SetDecoderMap(const std::map<int, webrtc::SdpAudioFormat>& decoder_map) {
1184 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
1185 stream_->SetDecoderMap(decoder_map);
1186 }
1187
GetStats(bool get_and_clear_legacy_stats) const1188 webrtc::AudioReceiveStreamInterface::Stats GetStats(
1189 bool get_and_clear_legacy_stats) const {
1190 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
1191 return stream_->GetStats(get_and_clear_legacy_stats);
1192 }
1193
SetRawAudioSink(std::unique_ptr<webrtc::AudioSinkInterface> sink)1194 void SetRawAudioSink(std::unique_ptr<webrtc::AudioSinkInterface> sink) {
1195 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
1196 // Need to update the stream's sink first; once raw_audio_sink_ is
1197 // reassigned, whatever was in there before is destroyed.
1198 stream_->SetSink(sink.get());
1199 raw_audio_sink_ = std::move(sink);
1200 }
1201
SetOutputVolume(double volume)1202 void SetOutputVolume(double volume) {
1203 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
1204 stream_->SetGain(volume);
1205 }
1206
SetPlayout(bool playout)1207 void SetPlayout(bool playout) {
1208 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
1209 if (playout) {
1210 stream_->Start();
1211 } else {
1212 stream_->Stop();
1213 }
1214 }
1215
SetBaseMinimumPlayoutDelayMs(int delay_ms)1216 bool SetBaseMinimumPlayoutDelayMs(int delay_ms) {
1217 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
1218 if (stream_->SetBaseMinimumPlayoutDelayMs(delay_ms))
1219 return true;
1220
1221 RTC_LOG(LS_ERROR) << "Failed to SetBaseMinimumPlayoutDelayMs"
1222 " on AudioReceiveStreamInterface on SSRC="
1223 << stream_->remote_ssrc()
1224 << " with delay_ms=" << delay_ms;
1225 return false;
1226 }
1227
GetBaseMinimumPlayoutDelayMs() const1228 int GetBaseMinimumPlayoutDelayMs() const {
1229 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
1230 return stream_->GetBaseMinimumPlayoutDelayMs();
1231 }
1232
GetSources()1233 std::vector<webrtc::RtpSource> GetSources() {
1234 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
1235 return stream_->GetSources();
1236 }
1237
GetRtpParameters() const1238 webrtc::RtpParameters GetRtpParameters() const {
1239 webrtc::RtpParameters rtp_parameters;
1240 rtp_parameters.encodings.emplace_back();
1241 rtp_parameters.encodings[0].ssrc = stream_->remote_ssrc();
1242 rtp_parameters.header_extensions = stream_->GetRtpExtensions();
1243 return rtp_parameters;
1244 }
1245
SetDepacketizerToDecoderFrameTransformer(rtc::scoped_refptr<webrtc::FrameTransformerInterface> frame_transformer)1246 void SetDepacketizerToDecoderFrameTransformer(
1247 rtc::scoped_refptr<webrtc::FrameTransformerInterface> frame_transformer) {
1248 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
1249 stream_->SetDepacketizerToDecoderFrameTransformer(frame_transformer);
1250 }
1251
1252 private:
1253 webrtc::SequenceChecker worker_thread_checker_;
1254 webrtc::Call* call_ = nullptr;
1255 webrtc::AudioReceiveStreamInterface* const stream_ = nullptr;
1256 std::unique_ptr<webrtc::AudioSinkInterface> raw_audio_sink_
1257 RTC_GUARDED_BY(worker_thread_checker_);
1258 };
1259
WebRtcVoiceMediaChannel(WebRtcVoiceEngine * engine,const MediaConfig & config,const AudioOptions & options,const webrtc::CryptoOptions & crypto_options,webrtc::Call * call)1260 WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel(
1261 WebRtcVoiceEngine* engine,
1262 const MediaConfig& config,
1263 const AudioOptions& options,
1264 const webrtc::CryptoOptions& crypto_options,
1265 webrtc::Call* call)
1266 : VoiceMediaChannel(call->network_thread(), config.enable_dscp),
1267 worker_thread_(call->worker_thread()),
1268 engine_(engine),
1269 call_(call),
1270 audio_config_(config.audio),
1271 crypto_options_(crypto_options) {
1272 network_thread_checker_.Detach();
1273 RTC_LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel";
1274 RTC_DCHECK(call);
1275 SetOptions(options);
1276 }
1277
~WebRtcVoiceMediaChannel()1278 WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel() {
1279 RTC_DCHECK_RUN_ON(worker_thread_);
1280 RTC_LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel";
1281 // TODO(solenberg): Should be able to delete the streams directly, without
1282 // going through RemoveNnStream(), once stream objects handle
1283 // all (de)configuration.
1284 while (!send_streams_.empty()) {
1285 RemoveSendStream(send_streams_.begin()->first);
1286 }
1287 while (!recv_streams_.empty()) {
1288 RemoveRecvStream(recv_streams_.begin()->first);
1289 }
1290 }
1291
SetSendParameters(const AudioSendParameters & params)1292 bool WebRtcVoiceMediaChannel::SetSendParameters(
1293 const AudioSendParameters& params) {
1294 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::SetSendParameters");
1295 RTC_DCHECK_RUN_ON(worker_thread_);
1296 RTC_LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendParameters: "
1297 << params.ToString();
1298 // TODO(pthatcher): Refactor this to be more clean now that we have
1299 // all the information at once.
1300
1301 if (!SetSendCodecs(params.codecs)) {
1302 return false;
1303 }
1304
1305 if (!ValidateRtpExtensions(params.extensions, send_rtp_extensions_)) {
1306 return false;
1307 }
1308
1309 if (ExtmapAllowMixed() != params.extmap_allow_mixed) {
1310 SetExtmapAllowMixed(params.extmap_allow_mixed);
1311 for (auto& it : send_streams_) {
1312 it.second->SetExtmapAllowMixed(params.extmap_allow_mixed);
1313 }
1314 }
1315
1316 std::vector<webrtc::RtpExtension> filtered_extensions = FilterRtpExtensions(
1317 params.extensions, webrtc::RtpExtension::IsSupportedForAudio, true,
1318 call_->trials());
1319 if (send_rtp_extensions_ != filtered_extensions) {
1320 send_rtp_extensions_.swap(filtered_extensions);
1321 for (auto& it : send_streams_) {
1322 it.second->SetRtpExtensions(send_rtp_extensions_);
1323 }
1324 }
1325 if (!params.mid.empty()) {
1326 mid_ = params.mid;
1327 for (auto& it : send_streams_) {
1328 it.second->SetMid(params.mid);
1329 }
1330 }
1331
1332 if (!SetMaxSendBitrate(params.max_bandwidth_bps)) {
1333 return false;
1334 }
1335 return SetOptions(params.options);
1336 }
1337
SetRecvParameters(const AudioRecvParameters & params)1338 bool WebRtcVoiceMediaChannel::SetRecvParameters(
1339 const AudioRecvParameters& params) {
1340 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::SetRecvParameters");
1341 RTC_DCHECK_RUN_ON(worker_thread_);
1342 RTC_LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetRecvParameters: "
1343 << params.ToString();
1344 // TODO(pthatcher): Refactor this to be more clean now that we have
1345 // all the information at once.
1346
1347 if (!SetRecvCodecs(params.codecs)) {
1348 return false;
1349 }
1350
1351 if (!ValidateRtpExtensions(params.extensions, recv_rtp_extensions_)) {
1352 return false;
1353 }
1354 std::vector<webrtc::RtpExtension> filtered_extensions = FilterRtpExtensions(
1355 params.extensions, webrtc::RtpExtension::IsSupportedForAudio, false,
1356 call_->trials());
1357 if (recv_rtp_extensions_ != filtered_extensions) {
1358 recv_rtp_extensions_.swap(filtered_extensions);
1359 for (auto& it : recv_streams_) {
1360 it.second->SetRtpExtensions(recv_rtp_extensions_);
1361 }
1362 }
1363 return true;
1364 }
1365
GetRtpSendParameters(uint32_t ssrc) const1366 webrtc::RtpParameters WebRtcVoiceMediaChannel::GetRtpSendParameters(
1367 uint32_t ssrc) const {
1368 RTC_DCHECK_RUN_ON(worker_thread_);
1369 auto it = send_streams_.find(ssrc);
1370 if (it == send_streams_.end()) {
1371 RTC_LOG(LS_WARNING) << "Attempting to get RTP send parameters for stream "
1372 "with ssrc "
1373 << ssrc << " which doesn't exist.";
1374 return webrtc::RtpParameters();
1375 }
1376
1377 webrtc::RtpParameters rtp_params = it->second->rtp_parameters();
1378 // Need to add the common list of codecs to the send stream-specific
1379 // RTP parameters.
1380 for (const AudioCodec& codec : send_codecs_) {
1381 rtp_params.codecs.push_back(codec.ToCodecParameters());
1382 }
1383 return rtp_params;
1384 }
1385
SetRtpSendParameters(uint32_t ssrc,const webrtc::RtpParameters & parameters,webrtc::SetParametersCallback callback)1386 webrtc::RTCError WebRtcVoiceMediaChannel::SetRtpSendParameters(
1387 uint32_t ssrc,
1388 const webrtc::RtpParameters& parameters,
1389 webrtc::SetParametersCallback callback) {
1390 RTC_DCHECK_RUN_ON(worker_thread_);
1391 auto it = send_streams_.find(ssrc);
1392 if (it == send_streams_.end()) {
1393 RTC_LOG(LS_WARNING) << "Attempting to set RTP send parameters for stream "
1394 "with ssrc "
1395 << ssrc << " which doesn't exist.";
1396 return webrtc::InvokeSetParametersCallback(
1397 callback, webrtc::RTCError(webrtc::RTCErrorType::INTERNAL_ERROR));
1398 }
1399
1400 // TODO(deadbeef): Handle setting parameters with a list of codecs in a
1401 // different order (which should change the send codec).
1402 webrtc::RtpParameters current_parameters = GetRtpSendParameters(ssrc);
1403 if (current_parameters.codecs != parameters.codecs) {
1404 RTC_DLOG(LS_ERROR) << "Using SetParameters to change the set of codecs "
1405 "is not currently supported.";
1406 return webrtc::InvokeSetParametersCallback(
1407 callback, webrtc::RTCError(webrtc::RTCErrorType::INTERNAL_ERROR));
1408 }
1409
1410 if (!parameters.encodings.empty()) {
1411 // Note that these values come from:
1412 // https://tools.ietf.org/html/draft-ietf-tsvwg-rtcweb-qos-16#section-5
1413 rtc::DiffServCodePoint new_dscp = rtc::DSCP_DEFAULT;
1414 switch (parameters.encodings[0].network_priority) {
1415 case webrtc::Priority::kVeryLow:
1416 new_dscp = rtc::DSCP_CS1;
1417 break;
1418 case webrtc::Priority::kLow:
1419 new_dscp = rtc::DSCP_DEFAULT;
1420 break;
1421 case webrtc::Priority::kMedium:
1422 new_dscp = rtc::DSCP_EF;
1423 break;
1424 case webrtc::Priority::kHigh:
1425 new_dscp = rtc::DSCP_EF;
1426 break;
1427 }
1428 SetPreferredDscp(new_dscp);
1429 }
1430
1431 // TODO(minyue): The following legacy actions go into
1432 // `WebRtcAudioSendStream::SetRtpParameters()` which is called at the end,
1433 // though there are two difference:
1434 // 1. `WebRtcVoiceMediaChannel::SetChannelSendParameters()` only calls
1435 // `SetSendCodec` while `WebRtcAudioSendStream::SetRtpParameters()` calls
1436 // `SetSendCodecs`. The outcome should be the same.
1437 // 2. AudioSendStream can be recreated.
1438
1439 // Codecs are handled at the WebRtcVoiceMediaChannel level.
1440 webrtc::RtpParameters reduced_params = parameters;
1441 reduced_params.codecs.clear();
1442 return it->second->SetRtpParameters(reduced_params, std::move(callback));
1443 }
1444
GetRtpReceiveParameters(uint32_t ssrc) const1445 webrtc::RtpParameters WebRtcVoiceMediaChannel::GetRtpReceiveParameters(
1446 uint32_t ssrc) const {
1447 RTC_DCHECK_RUN_ON(worker_thread_);
1448 webrtc::RtpParameters rtp_params;
1449 auto it = recv_streams_.find(ssrc);
1450 if (it == recv_streams_.end()) {
1451 RTC_LOG(LS_WARNING)
1452 << "Attempting to get RTP receive parameters for stream "
1453 "with ssrc "
1454 << ssrc << " which doesn't exist.";
1455 return webrtc::RtpParameters();
1456 }
1457 rtp_params = it->second->GetRtpParameters();
1458
1459 for (const AudioCodec& codec : recv_codecs_) {
1460 rtp_params.codecs.push_back(codec.ToCodecParameters());
1461 }
1462 return rtp_params;
1463 }
1464
GetDefaultRtpReceiveParameters() const1465 webrtc::RtpParameters WebRtcVoiceMediaChannel::GetDefaultRtpReceiveParameters()
1466 const {
1467 RTC_DCHECK_RUN_ON(worker_thread_);
1468 webrtc::RtpParameters rtp_params;
1469 if (!default_sink_) {
1470 // Getting parameters on a default, unsignaled audio receive stream but
1471 // because we've not configured to receive such a stream, `encodings` is
1472 // empty.
1473 return rtp_params;
1474 }
1475 rtp_params.encodings.emplace_back();
1476
1477 for (const AudioCodec& codec : recv_codecs_) {
1478 rtp_params.codecs.push_back(codec.ToCodecParameters());
1479 }
1480 return rtp_params;
1481 }
1482
SetOptions(const AudioOptions & options)1483 bool WebRtcVoiceMediaChannel::SetOptions(const AudioOptions& options) {
1484 RTC_DCHECK_RUN_ON(worker_thread_);
1485 RTC_LOG(LS_INFO) << "Setting voice channel options: " << options.ToString();
1486
1487 // We retain all of the existing options, and apply the given ones
1488 // on top. This means there is no way to "clear" options such that
1489 // they go back to the engine default.
1490 options_.SetAll(options);
1491 engine()->ApplyOptions(options_);
1492
1493 absl::optional<std::string> audio_network_adaptor_config =
1494 GetAudioNetworkAdaptorConfig(options_);
1495 for (auto& it : send_streams_) {
1496 it.second->SetAudioNetworkAdaptorConfig(audio_network_adaptor_config);
1497 }
1498
1499 RTC_LOG(LS_INFO) << "Set voice channel options. Current options: "
1500 << options_.ToString();
1501 return true;
1502 }
1503
SetRecvCodecs(const std::vector<AudioCodec> & codecs)1504 bool WebRtcVoiceMediaChannel::SetRecvCodecs(
1505 const std::vector<AudioCodec>& codecs) {
1506 RTC_DCHECK_RUN_ON(worker_thread_);
1507
1508 // Set the payload types to be used for incoming media.
1509 RTC_LOG(LS_INFO) << "Setting receive voice codecs.";
1510
1511 if (!VerifyUniquePayloadTypes(codecs)) {
1512 RTC_LOG(LS_ERROR) << "Codec payload types overlap.";
1513 return false;
1514 }
1515
1516 // Create a payload type -> SdpAudioFormat map with all the decoders. Fail
1517 // unless the factory claims to support all decoders.
1518 std::map<int, webrtc::SdpAudioFormat> decoder_map;
1519 for (const AudioCodec& codec : codecs) {
1520 // Log a warning if a codec's payload type is changing. This used to be
1521 // treated as an error. It's abnormal, but not really illegal.
1522 AudioCodec old_codec;
1523 if (FindCodec(recv_codecs_, codec, &old_codec, &call_->trials()) &&
1524 old_codec.id != codec.id) {
1525 RTC_LOG(LS_WARNING) << codec.name << " mapped to a second payload type ("
1526 << codec.id << ", was already mapped to "
1527 << old_codec.id << ")";
1528 }
1529 auto format = AudioCodecToSdpAudioFormat(codec);
1530 if (!IsCodec(codec, kCnCodecName) && !IsCodec(codec, kDtmfCodecName) &&
1531 !IsCodec(codec, kRedCodecName) &&
1532 !engine()->decoder_factory_->IsSupportedDecoder(format)) {
1533 RTC_LOG(LS_ERROR) << "Unsupported codec: " << rtc::ToString(format);
1534 return false;
1535 }
1536 // We allow adding new codecs but don't allow changing the payload type of
1537 // codecs that are already configured since we might already be receiving
1538 // packets with that payload type. See RFC3264, Section 8.3.2.
1539 // TODO(deadbeef): Also need to check for clashes with previously mapped
1540 // payload types, and not just currently mapped ones. For example, this
1541 // should be illegal:
1542 // 1. {100: opus/48000/2, 101: ISAC/16000}
1543 // 2. {100: opus/48000/2}
1544 // 3. {100: opus/48000/2, 101: ISAC/32000}
1545 // Though this check really should happen at a higher level, since this
1546 // conflict could happen between audio and video codecs.
1547 auto existing = decoder_map_.find(codec.id);
1548 if (existing != decoder_map_.end() && !existing->second.Matches(format)) {
1549 RTC_LOG(LS_ERROR) << "Attempting to use payload type " << codec.id
1550 << " for " << codec.name
1551 << ", but it is already used for "
1552 << existing->second.name;
1553 return false;
1554 }
1555 decoder_map.insert({codec.id, std::move(format)});
1556 }
1557
1558 if (decoder_map == decoder_map_) {
1559 // There's nothing new to configure.
1560 return true;
1561 }
1562
1563 bool playout_enabled = playout_;
1564 // Receive codecs can not be changed while playing. So we temporarily
1565 // pause playout.
1566 SetPlayout(false);
1567 RTC_DCHECK(!playout_);
1568
1569 decoder_map_ = std::move(decoder_map);
1570 for (auto& kv : recv_streams_) {
1571 kv.second->SetDecoderMap(decoder_map_);
1572 }
1573
1574 recv_codecs_ = codecs;
1575
1576 SetPlayout(playout_enabled);
1577 RTC_DCHECK_EQ(playout_, playout_enabled);
1578
1579 return true;
1580 }
1581
1582 // Utility function to check if RED codec and its parameters match a codec spec.
CheckRedParameters(const AudioCodec & red_codec,const webrtc::AudioSendStream::Config::SendCodecSpec & send_codec_spec)1583 bool CheckRedParameters(
1584 const AudioCodec& red_codec,
1585 const webrtc::AudioSendStream::Config::SendCodecSpec& send_codec_spec) {
1586 if (red_codec.clockrate != send_codec_spec.format.clockrate_hz ||
1587 red_codec.channels != send_codec_spec.format.num_channels) {
1588 return false;
1589 }
1590
1591 // Check the FMTP line for the empty parameter which should match
1592 // <primary codec>/<primary codec>[/...]
1593 auto red_parameters = red_codec.params.find("");
1594 if (red_parameters == red_codec.params.end()) {
1595 RTC_LOG(LS_WARNING) << "audio/RED missing fmtp parameters.";
1596 return false;
1597 }
1598 std::vector<absl::string_view> redundant_payloads =
1599 rtc::split(red_parameters->second, '/');
1600 // 32 is chosen as a maximum upper bound for consistency with the
1601 // red payload splitter.
1602 if (redundant_payloads.size() < 2 || redundant_payloads.size() > 32) {
1603 return false;
1604 }
1605 for (auto pt : redundant_payloads) {
1606 if (pt != rtc::ToString(send_codec_spec.payload_type)) {
1607 return false;
1608 }
1609 }
1610 return true;
1611 }
1612
1613 // Utility function called from SetSendParameters() to extract current send
1614 // codec settings from the given list of codecs (originally from SDP). Both send
1615 // and receive streams may be reconfigured based on the new settings.
SetSendCodecs(const std::vector<AudioCodec> & codecs)1616 bool WebRtcVoiceMediaChannel::SetSendCodecs(
1617 const std::vector<AudioCodec>& codecs) {
1618 RTC_DCHECK_RUN_ON(worker_thread_);
1619 dtmf_payload_type_ = absl::nullopt;
1620 dtmf_payload_freq_ = -1;
1621
1622 // Validate supplied codecs list.
1623 for (const AudioCodec& codec : codecs) {
1624 // TODO(solenberg): Validate more aspects of input - that payload types
1625 // don't overlap, remove redundant/unsupported codecs etc -
1626 // the same way it is done for RtpHeaderExtensions.
1627 if (codec.id < kMinPayloadType || codec.id > kMaxPayloadType) {
1628 RTC_LOG(LS_WARNING) << "Codec payload type out of range: "
1629 << ToString(codec);
1630 return false;
1631 }
1632 }
1633
1634 // Find PT of telephone-event codec with lowest clockrate, as a fallback, in
1635 // case we don't have a DTMF codec with a rate matching the send codec's, or
1636 // if this function returns early.
1637 std::vector<AudioCodec> dtmf_codecs;
1638 for (const AudioCodec& codec : codecs) {
1639 if (IsCodec(codec, kDtmfCodecName)) {
1640 dtmf_codecs.push_back(codec);
1641 if (!dtmf_payload_type_ || codec.clockrate < dtmf_payload_freq_) {
1642 dtmf_payload_type_ = codec.id;
1643 dtmf_payload_freq_ = codec.clockrate;
1644 }
1645 }
1646 }
1647
1648 // Scan through the list to figure out the codec to use for sending.
1649 absl::optional<webrtc::AudioSendStream::Config::SendCodecSpec>
1650 send_codec_spec;
1651 webrtc::BitrateConstraints bitrate_config;
1652 absl::optional<webrtc::AudioCodecInfo> voice_codec_info;
1653 size_t send_codec_position = 0;
1654 for (const AudioCodec& voice_codec : codecs) {
1655 if (!(IsCodec(voice_codec, kCnCodecName) ||
1656 IsCodec(voice_codec, kDtmfCodecName) ||
1657 IsCodec(voice_codec, kRedCodecName))) {
1658 webrtc::SdpAudioFormat format(voice_codec.name, voice_codec.clockrate,
1659 voice_codec.channels, voice_codec.params);
1660
1661 voice_codec_info = engine()->encoder_factory_->QueryAudioEncoder(format);
1662 if (!voice_codec_info) {
1663 RTC_LOG(LS_WARNING) << "Unknown codec " << ToString(voice_codec);
1664 continue;
1665 }
1666
1667 send_codec_spec = webrtc::AudioSendStream::Config::SendCodecSpec(
1668 voice_codec.id, format);
1669 if (voice_codec.bitrate > 0) {
1670 send_codec_spec->target_bitrate_bps = voice_codec.bitrate;
1671 }
1672 send_codec_spec->transport_cc_enabled = HasTransportCc(voice_codec);
1673 send_codec_spec->nack_enabled = HasNack(voice_codec);
1674 send_codec_spec->enable_non_sender_rtt = HasRrtr(voice_codec);
1675 bitrate_config = GetBitrateConfigForCodec(voice_codec);
1676 break;
1677 }
1678 send_codec_position++;
1679 }
1680
1681 if (!send_codec_spec) {
1682 return false;
1683 }
1684
1685 RTC_DCHECK(voice_codec_info);
1686 if (voice_codec_info->allow_comfort_noise) {
1687 // Loop through the codecs list again to find the CN codec.
1688 // TODO(solenberg): Break out into a separate function?
1689 for (const AudioCodec& cn_codec : codecs) {
1690 if (IsCodec(cn_codec, kCnCodecName) &&
1691 cn_codec.clockrate == send_codec_spec->format.clockrate_hz &&
1692 cn_codec.channels == voice_codec_info->num_channels) {
1693 if (cn_codec.channels != 1) {
1694 RTC_LOG(LS_WARNING)
1695 << "CN #channels " << cn_codec.channels << " not supported.";
1696 } else if (cn_codec.clockrate != 8000 && cn_codec.clockrate != 16000 &&
1697 cn_codec.clockrate != 32000) {
1698 RTC_LOG(LS_WARNING)
1699 << "CN frequency " << cn_codec.clockrate << " not supported.";
1700 } else {
1701 send_codec_spec->cng_payload_type = cn_codec.id;
1702 }
1703 break;
1704 }
1705 }
1706
1707 // Find the telephone-event PT exactly matching the preferred send codec.
1708 for (const AudioCodec& dtmf_codec : dtmf_codecs) {
1709 if (dtmf_codec.clockrate == send_codec_spec->format.clockrate_hz) {
1710 dtmf_payload_type_ = dtmf_codec.id;
1711 dtmf_payload_freq_ = dtmf_codec.clockrate;
1712 break;
1713 }
1714 }
1715 }
1716
1717 // Loop through the codecs to find the RED codec that matches opus
1718 // with respect to clockrate and number of channels.
1719 size_t red_codec_position = 0;
1720 for (const AudioCodec& red_codec : codecs) {
1721 if (red_codec_position < send_codec_position &&
1722 IsCodec(red_codec, kRedCodecName) &&
1723 CheckRedParameters(red_codec, *send_codec_spec)) {
1724 send_codec_spec->red_payload_type = red_codec.id;
1725 break;
1726 }
1727 red_codec_position++;
1728 }
1729
1730 if (send_codec_spec_ != send_codec_spec) {
1731 send_codec_spec_ = std::move(send_codec_spec);
1732 // Apply new settings to all streams.
1733 for (const auto& kv : send_streams_) {
1734 kv.second->SetSendCodecSpec(*send_codec_spec_);
1735 }
1736 } else {
1737 // If the codec isn't changing, set the start bitrate to -1 which means
1738 // "unchanged" so that BWE isn't affected.
1739 bitrate_config.start_bitrate_bps = -1;
1740 }
1741 call_->GetTransportControllerSend()->SetSdpBitrateParameters(bitrate_config);
1742
1743 // Check if the transport cc feedback or NACK status has changed on the
1744 // preferred send codec, and in that case reconfigure all receive streams.
1745 if (recv_transport_cc_enabled_ != send_codec_spec_->transport_cc_enabled ||
1746 recv_nack_enabled_ != send_codec_spec_->nack_enabled) {
1747 RTC_LOG(LS_INFO) << "Changing transport cc and NACK status on receive "
1748 "streams.";
1749 recv_transport_cc_enabled_ = send_codec_spec_->transport_cc_enabled;
1750 recv_nack_enabled_ = send_codec_spec_->nack_enabled;
1751 for (auto& kv : recv_streams_) {
1752 kv.second->SetUseTransportCc(recv_transport_cc_enabled_,
1753 recv_nack_enabled_);
1754 }
1755 }
1756
1757 // Check if the receive-side RTT status has changed on the preferred send
1758 // codec, in that case reconfigure all receive streams.
1759 if (enable_non_sender_rtt_ != send_codec_spec_->enable_non_sender_rtt) {
1760 RTC_LOG(LS_INFO) << "Changing receive-side RTT status on receive streams.";
1761 enable_non_sender_rtt_ = send_codec_spec_->enable_non_sender_rtt;
1762 for (auto& kv : recv_streams_) {
1763 kv.second->SetNonSenderRttMeasurement(enable_non_sender_rtt_);
1764 }
1765 }
1766
1767 send_codecs_ = codecs;
1768 return true;
1769 }
1770
SetPlayout(bool playout)1771 void WebRtcVoiceMediaChannel::SetPlayout(bool playout) {
1772 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::SetPlayout");
1773 RTC_DCHECK_RUN_ON(worker_thread_);
1774 if (playout_ == playout) {
1775 return;
1776 }
1777
1778 for (const auto& kv : recv_streams_) {
1779 kv.second->SetPlayout(playout);
1780 }
1781 playout_ = playout;
1782 }
1783
SetSend(bool send)1784 void WebRtcVoiceMediaChannel::SetSend(bool send) {
1785 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::SetSend");
1786 if (send_ == send) {
1787 return;
1788 }
1789
1790 // Apply channel specific options.
1791 if (send) {
1792 engine()->ApplyOptions(options_);
1793
1794 // Initialize the ADM for recording (this may take time on some platforms,
1795 // e.g. Android).
1796 if (options_.init_recording_on_send.value_or(true) &&
1797 // InitRecording() may return an error if the ADM is already recording.
1798 !engine()->adm()->RecordingIsInitialized() &&
1799 !engine()->adm()->Recording()) {
1800 if (engine()->adm()->InitRecording() != 0) {
1801 RTC_LOG(LS_WARNING) << "Failed to initialize recording";
1802 }
1803 }
1804 }
1805
1806 // Change the settings on each send channel.
1807 for (auto& kv : send_streams_) {
1808 kv.second->SetSend(send);
1809 }
1810
1811 send_ = send;
1812 }
1813
SetAudioSend(uint32_t ssrc,bool enable,const AudioOptions * options,AudioSource * source)1814 bool WebRtcVoiceMediaChannel::SetAudioSend(uint32_t ssrc,
1815 bool enable,
1816 const AudioOptions* options,
1817 AudioSource* source) {
1818 RTC_DCHECK_RUN_ON(worker_thread_);
1819 // TODO(solenberg): The state change should be fully rolled back if any one of
1820 // these calls fail.
1821 if (!SetLocalSource(ssrc, source)) {
1822 return false;
1823 }
1824 if (!MuteStream(ssrc, !enable)) {
1825 return false;
1826 }
1827 if (enable && options) {
1828 return SetOptions(*options);
1829 }
1830 return true;
1831 }
1832
AddSendStream(const StreamParams & sp)1833 bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) {
1834 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::AddSendStream");
1835 RTC_DCHECK_RUN_ON(worker_thread_);
1836 RTC_LOG(LS_INFO) << "AddSendStream: " << sp.ToString();
1837
1838 uint32_t ssrc = sp.first_ssrc();
1839 RTC_DCHECK(0 != ssrc);
1840
1841 if (send_streams_.find(ssrc) != send_streams_.end()) {
1842 RTC_LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
1843 return false;
1844 }
1845
1846 absl::optional<std::string> audio_network_adaptor_config =
1847 GetAudioNetworkAdaptorConfig(options_);
1848 WebRtcAudioSendStream* stream = new WebRtcAudioSendStream(
1849 ssrc, mid_, sp.cname, sp.id, send_codec_spec_, ExtmapAllowMixed(),
1850 send_rtp_extensions_, max_send_bitrate_bps_,
1851 audio_config_.rtcp_report_interval_ms, audio_network_adaptor_config,
1852 call_, this, engine()->encoder_factory_, codec_pair_id_, nullptr,
1853 crypto_options_);
1854 send_streams_.insert(std::make_pair(ssrc, stream));
1855
1856 // At this point the stream's local SSRC has been updated. If it is the first
1857 // send stream, make sure that all the receive streams are updated with the
1858 // same SSRC in order to send receiver reports.
1859 if (send_streams_.size() == 1) {
1860 receiver_reports_ssrc_ = ssrc;
1861 for (auto& kv : recv_streams_) {
1862 call_->OnLocalSsrcUpdated(kv.second->stream(), ssrc);
1863 }
1864 }
1865
1866 send_streams_[ssrc]->SetSend(send_);
1867 return true;
1868 }
1869
RemoveSendStream(uint32_t ssrc)1870 bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32_t ssrc) {
1871 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::RemoveSendStream");
1872 RTC_DCHECK_RUN_ON(worker_thread_);
1873 RTC_LOG(LS_INFO) << "RemoveSendStream: " << ssrc;
1874
1875 auto it = send_streams_.find(ssrc);
1876 if (it == send_streams_.end()) {
1877 RTC_LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
1878 << " which doesn't exist.";
1879 return false;
1880 }
1881
1882 it->second->SetSend(false);
1883
1884 // TODO(solenberg): If we're removing the receiver_reports_ssrc_ stream, find
1885 // the first active send stream and use that instead, reassociating receive
1886 // streams.
1887
1888 delete it->second;
1889 send_streams_.erase(it);
1890 if (send_streams_.empty()) {
1891 SetSend(false);
1892 }
1893 return true;
1894 }
1895
AddRecvStream(const StreamParams & sp)1896 bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
1897 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::AddRecvStream");
1898 RTC_DCHECK_RUN_ON(worker_thread_);
1899 RTC_LOG(LS_INFO) << "AddRecvStream: " << sp.ToString();
1900
1901 if (!sp.has_ssrcs()) {
1902 // This is a StreamParam with unsignaled SSRCs. Store it, so it can be used
1903 // later when we know the SSRCs on the first packet arrival.
1904 unsignaled_stream_params_ = sp;
1905 return true;
1906 }
1907
1908 if (!ValidateStreamParams(sp)) {
1909 return false;
1910 }
1911
1912 const uint32_t ssrc = sp.first_ssrc();
1913
1914 // If this stream was previously received unsignaled, we promote it, possibly
1915 // updating the sync group if stream ids have changed.
1916 if (MaybeDeregisterUnsignaledRecvStream(ssrc)) {
1917 auto stream_ids = sp.stream_ids();
1918 std::string sync_group = stream_ids.empty() ? std::string() : stream_ids[0];
1919 call_->OnUpdateSyncGroup(recv_streams_[ssrc]->stream(),
1920 std::move(sync_group));
1921 return true;
1922 }
1923
1924 if (recv_streams_.find(ssrc) != recv_streams_.end()) {
1925 RTC_LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
1926 return false;
1927 }
1928
1929 // Create a new channel for receiving audio data.
1930 auto config = BuildReceiveStreamConfig(
1931 ssrc, receiver_reports_ssrc_, recv_transport_cc_enabled_,
1932 recv_nack_enabled_, enable_non_sender_rtt_, sp.stream_ids(),
1933 recv_rtp_extensions_, this, engine()->decoder_factory_, decoder_map_,
1934 codec_pair_id_, engine()->audio_jitter_buffer_max_packets_,
1935 engine()->audio_jitter_buffer_fast_accelerate_,
1936 engine()->audio_jitter_buffer_min_delay_ms_, unsignaled_frame_decryptor_,
1937 crypto_options_, unsignaled_frame_transformer_);
1938
1939 recv_streams_.insert(std::make_pair(
1940 ssrc, new WebRtcAudioReceiveStream(std::move(config), call_)));
1941 recv_streams_[ssrc]->SetPlayout(playout_);
1942
1943 return true;
1944 }
1945
RemoveRecvStream(uint32_t ssrc)1946 bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32_t ssrc) {
1947 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::RemoveRecvStream");
1948 RTC_DCHECK_RUN_ON(worker_thread_);
1949 RTC_LOG(LS_INFO) << "RemoveRecvStream: " << ssrc;
1950
1951 const auto it = recv_streams_.find(ssrc);
1952 if (it == recv_streams_.end()) {
1953 RTC_LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
1954 << " which doesn't exist.";
1955 return false;
1956 }
1957
1958 MaybeDeregisterUnsignaledRecvStream(ssrc);
1959
1960 it->second->SetRawAudioSink(nullptr);
1961 delete it->second;
1962 recv_streams_.erase(it);
1963 return true;
1964 }
1965
ResetUnsignaledRecvStream()1966 void WebRtcVoiceMediaChannel::ResetUnsignaledRecvStream() {
1967 RTC_DCHECK_RUN_ON(worker_thread_);
1968 RTC_LOG(LS_INFO) << "ResetUnsignaledRecvStream.";
1969 unsignaled_stream_params_ = StreamParams();
1970 // Create a copy since RemoveRecvStream will modify `unsignaled_recv_ssrcs_`.
1971 std::vector<uint32_t> to_remove = unsignaled_recv_ssrcs_;
1972 for (uint32_t ssrc : to_remove) {
1973 RemoveRecvStream(ssrc);
1974 }
1975 }
1976
1977 // Not implemented.
1978 // TODO(https://crbug.com/webrtc/12676): Implement a fix for the unsignalled
1979 // SSRC race that can happen when an m= section goes from receiving to not
1980 // receiving.
OnDemuxerCriteriaUpdatePending()1981 void WebRtcVoiceMediaChannel::OnDemuxerCriteriaUpdatePending() {}
OnDemuxerCriteriaUpdateComplete()1982 void WebRtcVoiceMediaChannel::OnDemuxerCriteriaUpdateComplete() {}
1983
SetLocalSource(uint32_t ssrc,AudioSource * source)1984 bool WebRtcVoiceMediaChannel::SetLocalSource(uint32_t ssrc,
1985 AudioSource* source) {
1986 auto it = send_streams_.find(ssrc);
1987 if (it == send_streams_.end()) {
1988 if (source) {
1989 // Return an error if trying to set a valid source with an invalid ssrc.
1990 RTC_LOG(LS_ERROR) << "SetLocalSource failed with ssrc " << ssrc;
1991 return false;
1992 }
1993
1994 // The channel likely has gone away, do nothing.
1995 return true;
1996 }
1997
1998 if (source) {
1999 it->second->SetSource(source);
2000 } else {
2001 it->second->ClearSource();
2002 }
2003
2004 return true;
2005 }
2006
SetOutputVolume(uint32_t ssrc,double volume)2007 bool WebRtcVoiceMediaChannel::SetOutputVolume(uint32_t ssrc, double volume) {
2008 RTC_DCHECK_RUN_ON(worker_thread_);
2009 RTC_LOG(LS_INFO) << rtc::StringFormat("WRVMC::%s({ssrc=%u}, {volume=%.2f})",
2010 __func__, ssrc, volume);
2011 const auto it = recv_streams_.find(ssrc);
2012 if (it == recv_streams_.end()) {
2013 RTC_LOG(LS_WARNING) << rtc::StringFormat(
2014 "WRVMC::%s => (WARNING: no receive stream for SSRC %u)", __func__,
2015 ssrc);
2016 return false;
2017 }
2018 it->second->SetOutputVolume(volume);
2019 RTC_LOG(LS_INFO) << rtc::StringFormat(
2020 "WRVMC::%s => (stream with SSRC %u now uses volume %.2f)", __func__, ssrc,
2021 volume);
2022 return true;
2023 }
2024
SetDefaultOutputVolume(double volume)2025 bool WebRtcVoiceMediaChannel::SetDefaultOutputVolume(double volume) {
2026 RTC_DCHECK_RUN_ON(worker_thread_);
2027 default_recv_volume_ = volume;
2028 for (uint32_t ssrc : unsignaled_recv_ssrcs_) {
2029 const auto it = recv_streams_.find(ssrc);
2030 if (it == recv_streams_.end()) {
2031 RTC_LOG(LS_WARNING) << "SetDefaultOutputVolume: no recv stream " << ssrc;
2032 return false;
2033 }
2034 it->second->SetOutputVolume(volume);
2035 RTC_LOG(LS_INFO) << "SetDefaultOutputVolume() to " << volume
2036 << " for recv stream with ssrc " << ssrc;
2037 }
2038 return true;
2039 }
2040
SetBaseMinimumPlayoutDelayMs(uint32_t ssrc,int delay_ms)2041 bool WebRtcVoiceMediaChannel::SetBaseMinimumPlayoutDelayMs(uint32_t ssrc,
2042 int delay_ms) {
2043 RTC_DCHECK_RUN_ON(worker_thread_);
2044 std::vector<uint32_t> ssrcs(1, ssrc);
2045 // SSRC of 0 represents the default receive stream.
2046 if (ssrc == 0) {
2047 default_recv_base_minimum_delay_ms_ = delay_ms;
2048 ssrcs = unsignaled_recv_ssrcs_;
2049 }
2050 for (uint32_t ssrc : ssrcs) {
2051 const auto it = recv_streams_.find(ssrc);
2052 if (it == recv_streams_.end()) {
2053 RTC_LOG(LS_WARNING) << "SetBaseMinimumPlayoutDelayMs: no recv stream "
2054 << ssrc;
2055 return false;
2056 }
2057 it->second->SetBaseMinimumPlayoutDelayMs(delay_ms);
2058 RTC_LOG(LS_INFO) << "SetBaseMinimumPlayoutDelayMs() to " << delay_ms
2059 << " for recv stream with ssrc " << ssrc;
2060 }
2061 return true;
2062 }
2063
GetBaseMinimumPlayoutDelayMs(uint32_t ssrc) const2064 absl::optional<int> WebRtcVoiceMediaChannel::GetBaseMinimumPlayoutDelayMs(
2065 uint32_t ssrc) const {
2066 // SSRC of 0 represents the default receive stream.
2067 if (ssrc == 0) {
2068 return default_recv_base_minimum_delay_ms_;
2069 }
2070
2071 const auto it = recv_streams_.find(ssrc);
2072
2073 if (it != recv_streams_.end()) {
2074 return it->second->GetBaseMinimumPlayoutDelayMs();
2075 }
2076 return absl::nullopt;
2077 }
2078
CanInsertDtmf()2079 bool WebRtcVoiceMediaChannel::CanInsertDtmf() {
2080 return dtmf_payload_type_.has_value() && send_;
2081 }
2082
SetFrameDecryptor(uint32_t ssrc,rtc::scoped_refptr<webrtc::FrameDecryptorInterface> frame_decryptor)2083 void WebRtcVoiceMediaChannel::SetFrameDecryptor(
2084 uint32_t ssrc,
2085 rtc::scoped_refptr<webrtc::FrameDecryptorInterface> frame_decryptor) {
2086 RTC_DCHECK_RUN_ON(worker_thread_);
2087 auto matching_stream = recv_streams_.find(ssrc);
2088 if (matching_stream != recv_streams_.end()) {
2089 matching_stream->second->SetFrameDecryptor(frame_decryptor);
2090 }
2091 // Handle unsignaled frame decryptors.
2092 if (ssrc == 0) {
2093 unsignaled_frame_decryptor_ = frame_decryptor;
2094 }
2095 }
2096
SetFrameEncryptor(uint32_t ssrc,rtc::scoped_refptr<webrtc::FrameEncryptorInterface> frame_encryptor)2097 void WebRtcVoiceMediaChannel::SetFrameEncryptor(
2098 uint32_t ssrc,
2099 rtc::scoped_refptr<webrtc::FrameEncryptorInterface> frame_encryptor) {
2100 RTC_DCHECK_RUN_ON(worker_thread_);
2101 auto matching_stream = send_streams_.find(ssrc);
2102 if (matching_stream != send_streams_.end()) {
2103 matching_stream->second->SetFrameEncryptor(frame_encryptor);
2104 }
2105 }
2106
InsertDtmf(uint32_t ssrc,int event,int duration)2107 bool WebRtcVoiceMediaChannel::InsertDtmf(uint32_t ssrc,
2108 int event,
2109 int duration) {
2110 RTC_DCHECK_RUN_ON(worker_thread_);
2111 RTC_LOG(LS_INFO) << "WebRtcVoiceMediaChannel::InsertDtmf";
2112 if (!CanInsertDtmf()) {
2113 return false;
2114 }
2115
2116 // Figure out which WebRtcAudioSendStream to send the event on.
2117 auto it = ssrc != 0 ? send_streams_.find(ssrc) : send_streams_.begin();
2118 if (it == send_streams_.end()) {
2119 RTC_LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
2120 return false;
2121 }
2122 if (event < kMinTelephoneEventCode || event > kMaxTelephoneEventCode) {
2123 RTC_LOG(LS_WARNING) << "DTMF event code " << event << " out of range.";
2124 return false;
2125 }
2126 RTC_DCHECK_NE(-1, dtmf_payload_freq_);
2127 return it->second->SendTelephoneEvent(*dtmf_payload_type_, dtmf_payload_freq_,
2128 event, duration);
2129 }
2130
OnPacketReceived(rtc::CopyOnWriteBuffer packet,int64_t packet_time_us)2131 void WebRtcVoiceMediaChannel::OnPacketReceived(rtc::CopyOnWriteBuffer packet,
2132 int64_t packet_time_us) {
2133 RTC_DCHECK_RUN_ON(&network_thread_checker_);
2134 // TODO(bugs.webrtc.org/11993): This code is very similar to what
2135 // WebRtcVideoChannel::OnPacketReceived does. For maintainability and
2136 // consistency it would be good to move the interaction with call_->Receiver()
2137 // to a common implementation and provide a callback on the worker thread
2138 // for the exception case (DELIVERY_UNKNOWN_SSRC) and how retry is attempted.
2139 worker_thread_->PostTask(SafeTask(task_safety_.flag(), [this, packet,
2140 packet_time_us] {
2141 RTC_DCHECK_RUN_ON(worker_thread_);
2142
2143 webrtc::PacketReceiver::DeliveryStatus delivery_result =
2144 call_->Receiver()->DeliverPacket(webrtc::MediaType::AUDIO, packet,
2145 packet_time_us);
2146
2147 if (delivery_result != webrtc::PacketReceiver::DELIVERY_UNKNOWN_SSRC) {
2148 return;
2149 }
2150
2151 // Create an unsignaled receive stream for this previously not received
2152 // ssrc. If there already is N unsignaled receive streams, delete the
2153 // oldest. See: https://bugs.chromium.org/p/webrtc/issues/detail?id=5208
2154 uint32_t ssrc = ParseRtpSsrc(packet);
2155 RTC_DCHECK(!absl::c_linear_search(unsignaled_recv_ssrcs_, ssrc));
2156
2157 // Add new stream.
2158 StreamParams sp = unsignaled_stream_params_;
2159 sp.ssrcs.push_back(ssrc);
2160 RTC_LOG(LS_INFO) << "Creating unsignaled receive stream for SSRC=" << ssrc;
2161 if (!AddRecvStream(sp)) {
2162 RTC_LOG(LS_WARNING) << "Could not create unsignaled receive stream.";
2163 return;
2164 }
2165 unsignaled_recv_ssrcs_.push_back(ssrc);
2166 RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.NumOfUnsignaledStreams",
2167 unsignaled_recv_ssrcs_.size(), 1, 100, 101);
2168
2169 // Remove oldest unsignaled stream, if we have too many.
2170 if (unsignaled_recv_ssrcs_.size() > kMaxUnsignaledRecvStreams) {
2171 uint32_t remove_ssrc = unsignaled_recv_ssrcs_.front();
2172 RTC_DLOG(LS_INFO) << "Removing unsignaled receive stream with SSRC="
2173 << remove_ssrc;
2174 RemoveRecvStream(remove_ssrc);
2175 }
2176 RTC_DCHECK_GE(kMaxUnsignaledRecvStreams, unsignaled_recv_ssrcs_.size());
2177
2178 SetOutputVolume(ssrc, default_recv_volume_);
2179 SetBaseMinimumPlayoutDelayMs(ssrc, default_recv_base_minimum_delay_ms_);
2180
2181 // The default sink can only be attached to one stream at a time, so we hook
2182 // it up to the *latest* unsignaled stream we've seen, in order to support
2183 // the case where the SSRC of one unsignaled stream changes.
2184 if (default_sink_) {
2185 for (uint32_t drop_ssrc : unsignaled_recv_ssrcs_) {
2186 auto it = recv_streams_.find(drop_ssrc);
2187 it->second->SetRawAudioSink(nullptr);
2188 }
2189 std::unique_ptr<webrtc::AudioSinkInterface> proxy_sink(
2190 new ProxySink(default_sink_.get()));
2191 SetRawAudioSink(ssrc, std::move(proxy_sink));
2192 }
2193
2194 delivery_result = call_->Receiver()->DeliverPacket(webrtc::MediaType::AUDIO,
2195 packet, packet_time_us);
2196 RTC_DCHECK_NE(webrtc::PacketReceiver::DELIVERY_UNKNOWN_SSRC,
2197 delivery_result);
2198 }));
2199 }
2200
OnPacketSent(const rtc::SentPacket & sent_packet)2201 void WebRtcVoiceMediaChannel::OnPacketSent(const rtc::SentPacket& sent_packet) {
2202 RTC_DCHECK_RUN_ON(&network_thread_checker_);
2203 // TODO(tommi): We shouldn't need to go through call_ to deliver this
2204 // notification. We should already have direct access to
2205 // video_send_delay_stats_ and transport_send_ptr_ via `stream_`.
2206 // So we should be able to remove OnSentPacket from Call and handle this per
2207 // channel instead. At the moment Call::OnSentPacket calls OnSentPacket for
2208 // the video stats, which we should be able to skip.
2209 call_->OnSentPacket(sent_packet);
2210 }
2211
OnNetworkRouteChanged(absl::string_view transport_name,const rtc::NetworkRoute & network_route)2212 void WebRtcVoiceMediaChannel::OnNetworkRouteChanged(
2213 absl::string_view transport_name,
2214 const rtc::NetworkRoute& network_route) {
2215 RTC_DCHECK_RUN_ON(&network_thread_checker_);
2216
2217 call_->OnAudioTransportOverheadChanged(network_route.packet_overhead);
2218
2219 worker_thread_->PostTask(SafeTask(
2220 task_safety_.flag(),
2221 [this, name = std::string(transport_name), route = network_route] {
2222 RTC_DCHECK_RUN_ON(worker_thread_);
2223 call_->GetTransportControllerSend()->OnNetworkRouteChanged(name, route);
2224 }));
2225 }
2226
MuteStream(uint32_t ssrc,bool muted)2227 bool WebRtcVoiceMediaChannel::MuteStream(uint32_t ssrc, bool muted) {
2228 RTC_DCHECK_RUN_ON(worker_thread_);
2229 const auto it = send_streams_.find(ssrc);
2230 if (it == send_streams_.end()) {
2231 RTC_LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
2232 return false;
2233 }
2234 it->second->SetMuted(muted);
2235
2236 // TODO(solenberg):
2237 // We set the AGC to mute state only when all the channels are muted.
2238 // This implementation is not ideal, instead we should signal the AGC when
2239 // the mic channel is muted/unmuted. We can't do it today because there
2240 // is no good way to know which stream is mapping to the mic channel.
2241 bool all_muted = muted;
2242 for (const auto& kv : send_streams_) {
2243 all_muted = all_muted && kv.second->muted();
2244 }
2245 webrtc::AudioProcessing* ap = engine()->apm();
2246 if (ap) {
2247 ap->set_output_will_be_muted(all_muted);
2248 }
2249
2250 return true;
2251 }
2252
SetMaxSendBitrate(int bps)2253 bool WebRtcVoiceMediaChannel::SetMaxSendBitrate(int bps) {
2254 RTC_LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetMaxSendBitrate.";
2255 max_send_bitrate_bps_ = bps;
2256 bool success = true;
2257 for (const auto& kv : send_streams_) {
2258 if (!kv.second->SetMaxSendBitrate(max_send_bitrate_bps_)) {
2259 success = false;
2260 }
2261 }
2262 return success;
2263 }
2264
OnReadyToSend(bool ready)2265 void WebRtcVoiceMediaChannel::OnReadyToSend(bool ready) {
2266 RTC_DCHECK_RUN_ON(&network_thread_checker_);
2267 RTC_LOG(LS_VERBOSE) << "OnReadyToSend: " << (ready ? "Ready." : "Not ready.");
2268 call_->SignalChannelNetworkState(
2269 webrtc::MediaType::AUDIO,
2270 ready ? webrtc::kNetworkUp : webrtc::kNetworkDown);
2271 }
2272
GetStats(VoiceMediaInfo * info,bool get_and_clear_legacy_stats)2273 bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info,
2274 bool get_and_clear_legacy_stats) {
2275 TRACE_EVENT0("webrtc", "WebRtcVoiceMediaChannel::GetStats");
2276 RTC_DCHECK_RUN_ON(worker_thread_);
2277 RTC_DCHECK(info);
2278
2279 // Get SSRC and stats for each sender.
2280 RTC_DCHECK_EQ(info->senders.size(), 0U);
2281 for (const auto& stream : send_streams_) {
2282 webrtc::AudioSendStream::Stats stats =
2283 stream.second->GetStats(recv_streams_.size() > 0);
2284 VoiceSenderInfo sinfo;
2285 sinfo.add_ssrc(stats.local_ssrc);
2286 sinfo.payload_bytes_sent = stats.payload_bytes_sent;
2287 sinfo.header_and_padding_bytes_sent = stats.header_and_padding_bytes_sent;
2288 sinfo.retransmitted_bytes_sent = stats.retransmitted_bytes_sent;
2289 sinfo.packets_sent = stats.packets_sent;
2290 sinfo.total_packet_send_delay = stats.total_packet_send_delay;
2291 sinfo.retransmitted_packets_sent = stats.retransmitted_packets_sent;
2292 sinfo.packets_lost = stats.packets_lost;
2293 sinfo.fraction_lost = stats.fraction_lost;
2294 sinfo.nacks_rcvd = stats.nacks_rcvd;
2295 sinfo.target_bitrate = stats.target_bitrate_bps;
2296 sinfo.codec_name = stats.codec_name;
2297 sinfo.codec_payload_type = stats.codec_payload_type;
2298 sinfo.jitter_ms = stats.jitter_ms;
2299 sinfo.rtt_ms = stats.rtt_ms;
2300 sinfo.audio_level = stats.audio_level;
2301 sinfo.total_input_energy = stats.total_input_energy;
2302 sinfo.total_input_duration = stats.total_input_duration;
2303 sinfo.ana_statistics = stats.ana_statistics;
2304 sinfo.apm_statistics = stats.apm_statistics;
2305 sinfo.report_block_datas = std::move(stats.report_block_datas);
2306
2307 auto encodings = stream.second->rtp_parameters().encodings;
2308 if (!encodings.empty()) {
2309 sinfo.active = encodings[0].active;
2310 }
2311
2312 info->senders.push_back(sinfo);
2313 }
2314
2315 // Get SSRC and stats for each receiver.
2316 RTC_DCHECK_EQ(info->receivers.size(), 0U);
2317 for (const auto& stream : recv_streams_) {
2318 uint32_t ssrc = stream.first;
2319 // When SSRCs are unsignaled, there's only one audio MediaStreamTrack, but
2320 // multiple RTP streams can be received over time (if the SSRC changes for
2321 // whatever reason). We only want the RTCMediaStreamTrackStats to represent
2322 // the stats for the most recent stream (the one whose audio is actually
2323 // routed to the MediaStreamTrack), so here we ignore any unsignaled SSRCs
2324 // except for the most recent one (last in the vector). This is somewhat of
2325 // a hack, and means you don't get *any* stats for these inactive streams,
2326 // but it's slightly better than the previous behavior, which was "highest
2327 // SSRC wins".
2328 // See: https://bugs.chromium.org/p/webrtc/issues/detail?id=8158
2329 if (!unsignaled_recv_ssrcs_.empty()) {
2330 auto end_it = --unsignaled_recv_ssrcs_.end();
2331 if (absl::linear_search(unsignaled_recv_ssrcs_.begin(), end_it, ssrc)) {
2332 continue;
2333 }
2334 }
2335 webrtc::AudioReceiveStreamInterface::Stats stats =
2336 stream.second->GetStats(get_and_clear_legacy_stats);
2337 VoiceReceiverInfo rinfo;
2338 rinfo.add_ssrc(stats.remote_ssrc);
2339 rinfo.payload_bytes_rcvd = stats.payload_bytes_rcvd;
2340 rinfo.header_and_padding_bytes_rcvd = stats.header_and_padding_bytes_rcvd;
2341 rinfo.packets_rcvd = stats.packets_rcvd;
2342 rinfo.fec_packets_received = stats.fec_packets_received;
2343 rinfo.fec_packets_discarded = stats.fec_packets_discarded;
2344 rinfo.packets_lost = stats.packets_lost;
2345 rinfo.packets_discarded = stats.packets_discarded;
2346 rinfo.codec_name = stats.codec_name;
2347 rinfo.codec_payload_type = stats.codec_payload_type;
2348 rinfo.jitter_ms = stats.jitter_ms;
2349 rinfo.jitter_buffer_ms = stats.jitter_buffer_ms;
2350 rinfo.jitter_buffer_preferred_ms = stats.jitter_buffer_preferred_ms;
2351 rinfo.delay_estimate_ms = stats.delay_estimate_ms;
2352 rinfo.audio_level = stats.audio_level;
2353 rinfo.total_output_energy = stats.total_output_energy;
2354 rinfo.total_samples_received = stats.total_samples_received;
2355 rinfo.total_output_duration = stats.total_output_duration;
2356 rinfo.concealed_samples = stats.concealed_samples;
2357 rinfo.silent_concealed_samples = stats.silent_concealed_samples;
2358 rinfo.concealment_events = stats.concealment_events;
2359 rinfo.jitter_buffer_delay_seconds = stats.jitter_buffer_delay_seconds;
2360 rinfo.jitter_buffer_emitted_count = stats.jitter_buffer_emitted_count;
2361 rinfo.jitter_buffer_target_delay_seconds =
2362 stats.jitter_buffer_target_delay_seconds;
2363 rinfo.jitter_buffer_minimum_delay_seconds =
2364 stats.jitter_buffer_minimum_delay_seconds;
2365 rinfo.inserted_samples_for_deceleration =
2366 stats.inserted_samples_for_deceleration;
2367 rinfo.removed_samples_for_acceleration =
2368 stats.removed_samples_for_acceleration;
2369 rinfo.expand_rate = stats.expand_rate;
2370 rinfo.speech_expand_rate = stats.speech_expand_rate;
2371 rinfo.secondary_decoded_rate = stats.secondary_decoded_rate;
2372 rinfo.secondary_discarded_rate = stats.secondary_discarded_rate;
2373 rinfo.accelerate_rate = stats.accelerate_rate;
2374 rinfo.preemptive_expand_rate = stats.preemptive_expand_rate;
2375 rinfo.delayed_packet_outage_samples = stats.delayed_packet_outage_samples;
2376 rinfo.decoding_calls_to_silence_generator =
2377 stats.decoding_calls_to_silence_generator;
2378 rinfo.decoding_calls_to_neteq = stats.decoding_calls_to_neteq;
2379 rinfo.decoding_normal = stats.decoding_normal;
2380 rinfo.decoding_plc = stats.decoding_plc;
2381 rinfo.decoding_codec_plc = stats.decoding_codec_plc;
2382 rinfo.decoding_cng = stats.decoding_cng;
2383 rinfo.decoding_plc_cng = stats.decoding_plc_cng;
2384 rinfo.decoding_muted_output = stats.decoding_muted_output;
2385 rinfo.capture_start_ntp_time_ms = stats.capture_start_ntp_time_ms;
2386 rinfo.last_packet_received_timestamp_ms =
2387 stats.last_packet_received_timestamp_ms;
2388 rinfo.estimated_playout_ntp_timestamp_ms =
2389 stats.estimated_playout_ntp_timestamp_ms;
2390 rinfo.jitter_buffer_flushes = stats.jitter_buffer_flushes;
2391 rinfo.relative_packet_arrival_delay_seconds =
2392 stats.relative_packet_arrival_delay_seconds;
2393 rinfo.interruption_count = stats.interruption_count;
2394 rinfo.total_interruption_duration_ms = stats.total_interruption_duration_ms;
2395 rinfo.last_sender_report_timestamp_ms =
2396 stats.last_sender_report_timestamp_ms;
2397 rinfo.last_sender_report_remote_timestamp_ms =
2398 stats.last_sender_report_remote_timestamp_ms;
2399 rinfo.sender_reports_packets_sent = stats.sender_reports_packets_sent;
2400 rinfo.sender_reports_bytes_sent = stats.sender_reports_bytes_sent;
2401 rinfo.sender_reports_reports_count = stats.sender_reports_reports_count;
2402 rinfo.round_trip_time = stats.round_trip_time;
2403 rinfo.round_trip_time_measurements = stats.round_trip_time_measurements;
2404 rinfo.total_round_trip_time = stats.total_round_trip_time;
2405
2406 if (recv_nack_enabled_) {
2407 rinfo.nacks_sent = stats.nacks_sent;
2408 }
2409
2410 info->receivers.push_back(rinfo);
2411 }
2412
2413 // Get codec info
2414 for (const AudioCodec& codec : send_codecs_) {
2415 webrtc::RtpCodecParameters codec_params = codec.ToCodecParameters();
2416 info->send_codecs.insert(
2417 std::make_pair(codec_params.payload_type, std::move(codec_params)));
2418 }
2419 for (const AudioCodec& codec : recv_codecs_) {
2420 webrtc::RtpCodecParameters codec_params = codec.ToCodecParameters();
2421 info->receive_codecs.insert(
2422 std::make_pair(codec_params.payload_type, std::move(codec_params)));
2423 }
2424 info->device_underrun_count = engine_->adm()->GetPlayoutUnderrunCount();
2425
2426 return true;
2427 }
2428
SetRawAudioSink(uint32_t ssrc,std::unique_ptr<webrtc::AudioSinkInterface> sink)2429 void WebRtcVoiceMediaChannel::SetRawAudioSink(
2430 uint32_t ssrc,
2431 std::unique_ptr<webrtc::AudioSinkInterface> sink) {
2432 RTC_DCHECK_RUN_ON(worker_thread_);
2433 RTC_LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::SetRawAudioSink: ssrc:"
2434 << ssrc << " " << (sink ? "(ptr)" : "NULL");
2435 const auto it = recv_streams_.find(ssrc);
2436 if (it == recv_streams_.end()) {
2437 RTC_LOG(LS_WARNING) << "SetRawAudioSink: no recv stream " << ssrc;
2438 return;
2439 }
2440 it->second->SetRawAudioSink(std::move(sink));
2441 }
2442
SetDefaultRawAudioSink(std::unique_ptr<webrtc::AudioSinkInterface> sink)2443 void WebRtcVoiceMediaChannel::SetDefaultRawAudioSink(
2444 std::unique_ptr<webrtc::AudioSinkInterface> sink) {
2445 RTC_DCHECK_RUN_ON(worker_thread_);
2446 RTC_LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::SetDefaultRawAudioSink:";
2447 if (!unsignaled_recv_ssrcs_.empty()) {
2448 std::unique_ptr<webrtc::AudioSinkInterface> proxy_sink(
2449 sink ? new ProxySink(sink.get()) : nullptr);
2450 SetRawAudioSink(unsignaled_recv_ssrcs_.back(), std::move(proxy_sink));
2451 }
2452 default_sink_ = std::move(sink);
2453 }
2454
GetSources(uint32_t ssrc) const2455 std::vector<webrtc::RtpSource> WebRtcVoiceMediaChannel::GetSources(
2456 uint32_t ssrc) const {
2457 auto it = recv_streams_.find(ssrc);
2458 if (it == recv_streams_.end()) {
2459 RTC_LOG(LS_ERROR) << "Attempting to get contributing sources for SSRC:"
2460 << ssrc << " which doesn't exist.";
2461 return std::vector<webrtc::RtpSource>();
2462 }
2463 return it->second->GetSources();
2464 }
2465
SetEncoderToPacketizerFrameTransformer(uint32_t ssrc,rtc::scoped_refptr<webrtc::FrameTransformerInterface> frame_transformer)2466 void WebRtcVoiceMediaChannel::SetEncoderToPacketizerFrameTransformer(
2467 uint32_t ssrc,
2468 rtc::scoped_refptr<webrtc::FrameTransformerInterface> frame_transformer) {
2469 RTC_DCHECK_RUN_ON(worker_thread_);
2470 auto matching_stream = send_streams_.find(ssrc);
2471 if (matching_stream == send_streams_.end()) {
2472 RTC_LOG(LS_INFO) << "Attempting to set frame transformer for SSRC:" << ssrc
2473 << " which doesn't exist.";
2474 return;
2475 }
2476 matching_stream->second->SetEncoderToPacketizerFrameTransformer(
2477 std::move(frame_transformer));
2478 }
2479
SetDepacketizerToDecoderFrameTransformer(uint32_t ssrc,rtc::scoped_refptr<webrtc::FrameTransformerInterface> frame_transformer)2480 void WebRtcVoiceMediaChannel::SetDepacketizerToDecoderFrameTransformer(
2481 uint32_t ssrc,
2482 rtc::scoped_refptr<webrtc::FrameTransformerInterface> frame_transformer) {
2483 RTC_DCHECK_RUN_ON(worker_thread_);
2484 if (ssrc == 0) {
2485 // If the receiver is unsignaled, save the frame transformer and set it when
2486 // the stream is associated with an ssrc.
2487 unsignaled_frame_transformer_ = std::move(frame_transformer);
2488 return;
2489 }
2490
2491 auto matching_stream = recv_streams_.find(ssrc);
2492 if (matching_stream == recv_streams_.end()) {
2493 RTC_LOG(LS_INFO) << "Attempting to set frame transformer for SSRC:" << ssrc
2494 << " which doesn't exist.";
2495 return;
2496 }
2497 matching_stream->second->SetDepacketizerToDecoderFrameTransformer(
2498 std::move(frame_transformer));
2499 }
2500
SendRtp(const uint8_t * data,size_t len,const webrtc::PacketOptions & options)2501 bool WebRtcVoiceMediaChannel::SendRtp(const uint8_t* data,
2502 size_t len,
2503 const webrtc::PacketOptions& options) {
2504 MediaChannel::SendRtp(data, len, options);
2505 return true;
2506 }
2507
SendRtcp(const uint8_t * data,size_t len)2508 bool WebRtcVoiceMediaChannel::SendRtcp(const uint8_t* data, size_t len) {
2509 MediaChannel::SendRtcp(data, len);
2510 return true;
2511 }
2512
MaybeDeregisterUnsignaledRecvStream(uint32_t ssrc)2513 bool WebRtcVoiceMediaChannel::MaybeDeregisterUnsignaledRecvStream(
2514 uint32_t ssrc) {
2515 RTC_DCHECK_RUN_ON(worker_thread_);
2516 auto it = absl::c_find(unsignaled_recv_ssrcs_, ssrc);
2517 if (it != unsignaled_recv_ssrcs_.end()) {
2518 unsignaled_recv_ssrcs_.erase(it);
2519 return true;
2520 }
2521 return false;
2522 }
2523 } // namespace cricket
2524