1 /*
2 * Copyright (c) 2013 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 <string.h>
12 #include <algorithm>
13 #include <map>
14 #include <memory>
15 #include <set>
16 #include <utility>
17 #include <vector>
18
19 #include "api/optional.h"
20 #include "audio/audio_receive_stream.h"
21 #include "audio/audio_send_stream.h"
22 #include "audio/audio_state.h"
23 #include "audio/scoped_voe_interface.h"
24 #include "audio/time_interval.h"
25 #include "call/bitrate_allocator.h"
26 #include "call/call.h"
27 #include "call/flexfec_receive_stream_impl.h"
28 #include "call/rtp_stream_receiver_controller.h"
29 #include "call/rtp_transport_controller_send.h"
30 #include "logging/rtc_event_log/events/rtc_event_audio_receive_stream_config.h"
31 #include "logging/rtc_event_log/events/rtc_event_audio_send_stream_config.h"
32 #include "logging/rtc_event_log/events/rtc_event_rtcp_packet_incoming.h"
33 #include "logging/rtc_event_log/events/rtc_event_rtp_packet_incoming.h"
34 #include "logging/rtc_event_log/events/rtc_event_video_receive_stream_config.h"
35 #include "logging/rtc_event_log/events/rtc_event_video_send_stream_config.h"
36 #include "logging/rtc_event_log/rtc_event_log.h"
37 #include "logging/rtc_event_log/rtc_stream_config.h"
38 #include "modules/bitrate_controller/include/bitrate_controller.h"
39 #include "modules/congestion_controller/include/receive_side_congestion_controller.h"
40 #include "modules/rtp_rtcp/include/flexfec_receiver.h"
41 #include "modules/rtp_rtcp/include/rtp_header_extension_map.h"
42 #include "modules/rtp_rtcp/include/rtp_header_parser.h"
43 #include "modules/rtp_rtcp/source/byte_io.h"
44 #include "modules/rtp_rtcp/source/rtp_packet_received.h"
45 #include "modules/utility/include/process_thread.h"
46 #include "rtc_base/basictypes.h"
47 #include "rtc_base/checks.h"
48 #include "rtc_base/constructormagic.h"
49 #include "rtc_base/location.h"
50 #include "rtc_base/logging.h"
51 #include "rtc_base/ptr_util.h"
52 #include "rtc_base/sequenced_task_checker.h"
53 #include "rtc_base/task_queue.h"
54 #include "rtc_base/thread_annotations.h"
55 #include "rtc_base/trace_event.h"
56 #include "system_wrappers/include/clock.h"
57 #include "system_wrappers/include/cpu_info.h"
58 #include "system_wrappers/include/metrics.h"
59 #include "system_wrappers/include/rw_lock_wrapper.h"
60 #include "video/call_stats.h"
61 #include "video/send_delay_stats.h"
62 #include "video/stats_counter.h"
63 #include "video/video_receive_stream.h"
64 #include "video/video_send_stream.h"
65
66 namespace webrtc {
67
68 namespace {
69
70 // TODO(nisse): This really begs for a shared context struct.
UseSendSideBwe(const std::vector<RtpExtension> & extensions,bool transport_cc)71 bool UseSendSideBwe(const std::vector<RtpExtension>& extensions,
72 bool transport_cc) {
73 if (!transport_cc)
74 return false;
75 for (const auto& extension : extensions) {
76 if (extension.uri == RtpExtension::kTransportSequenceNumberUri)
77 return true;
78 }
79 return false;
80 }
81
UseSendSideBwe(const VideoReceiveStream::Config & config)82 bool UseSendSideBwe(const VideoReceiveStream::Config& config) {
83 return UseSendSideBwe(config.rtp.extensions, config.rtp.transport_cc);
84 }
85
UseSendSideBwe(const AudioReceiveStream::Config & config)86 bool UseSendSideBwe(const AudioReceiveStream::Config& config) {
87 return UseSendSideBwe(config.rtp.extensions, config.rtp.transport_cc);
88 }
89
UseSendSideBwe(const FlexfecReceiveStream::Config & config)90 bool UseSendSideBwe(const FlexfecReceiveStream::Config& config) {
91 return UseSendSideBwe(config.rtp_header_extensions, config.transport_cc);
92 }
93
FindKeyByValue(const std::map<int,int> & m,int v)94 const int* FindKeyByValue(const std::map<int, int>& m, int v) {
95 for (const auto& kv : m) {
96 if (kv.second == v)
97 return &kv.first;
98 }
99 return nullptr;
100 }
101
CreateRtcLogStreamConfig(const VideoReceiveStream::Config & config)102 std::unique_ptr<rtclog::StreamConfig> CreateRtcLogStreamConfig(
103 const VideoReceiveStream::Config& config) {
104 auto rtclog_config = rtc::MakeUnique<rtclog::StreamConfig>();
105 rtclog_config->remote_ssrc = config.rtp.remote_ssrc;
106 rtclog_config->local_ssrc = config.rtp.local_ssrc;
107 rtclog_config->rtx_ssrc = config.rtp.rtx_ssrc;
108 rtclog_config->rtcp_mode = config.rtp.rtcp_mode;
109 rtclog_config->remb = config.rtp.remb;
110 rtclog_config->rtp_extensions = config.rtp.extensions;
111
112 for (const auto& d : config.decoders) {
113 const int* search =
114 FindKeyByValue(config.rtp.rtx_associated_payload_types, d.payload_type);
115 rtclog_config->codecs.emplace_back(d.payload_name, d.payload_type,
116 search ? *search : 0);
117 }
118 return rtclog_config;
119 }
120
CreateRtcLogStreamConfig(const VideoSendStream::Config & config,size_t ssrc_index)121 std::unique_ptr<rtclog::StreamConfig> CreateRtcLogStreamConfig(
122 const VideoSendStream::Config& config,
123 size_t ssrc_index) {
124 auto rtclog_config = rtc::MakeUnique<rtclog::StreamConfig>();
125 rtclog_config->local_ssrc = config.rtp.ssrcs[ssrc_index];
126 if (ssrc_index < config.rtp.rtx.ssrcs.size()) {
127 rtclog_config->rtx_ssrc = config.rtp.rtx.ssrcs[ssrc_index];
128 }
129 rtclog_config->rtcp_mode = config.rtp.rtcp_mode;
130 rtclog_config->rtp_extensions = config.rtp.extensions;
131
132 rtclog_config->codecs.emplace_back(config.encoder_settings.payload_name,
133 config.encoder_settings.payload_type,
134 config.rtp.rtx.payload_type);
135 return rtclog_config;
136 }
137
CreateRtcLogStreamConfig(const AudioReceiveStream::Config & config)138 std::unique_ptr<rtclog::StreamConfig> CreateRtcLogStreamConfig(
139 const AudioReceiveStream::Config& config) {
140 auto rtclog_config = rtc::MakeUnique<rtclog::StreamConfig>();
141 rtclog_config->remote_ssrc = config.rtp.remote_ssrc;
142 rtclog_config->local_ssrc = config.rtp.local_ssrc;
143 rtclog_config->rtp_extensions = config.rtp.extensions;
144 return rtclog_config;
145 }
146
CreateRtcLogStreamConfig(const AudioSendStream::Config & config)147 std::unique_ptr<rtclog::StreamConfig> CreateRtcLogStreamConfig(
148 const AudioSendStream::Config& config) {
149 auto rtclog_config = rtc::MakeUnique<rtclog::StreamConfig>();
150 rtclog_config->local_ssrc = config.rtp.ssrc;
151 rtclog_config->rtp_extensions = config.rtp.extensions;
152 if (config.send_codec_spec) {
153 rtclog_config->codecs.emplace_back(config.send_codec_spec->format.name,
154 config.send_codec_spec->payload_type, 0);
155 }
156 return rtclog_config;
157 }
158
159 } // namespace
160
161 namespace internal {
162
163 class Call : public webrtc::Call,
164 public PacketReceiver,
165 public RecoveredPacketReceiver,
166 public SendSideCongestionController::Observer,
167 public BitrateAllocator::LimitObserver {
168 public:
169 Call(const Call::Config& config,
170 std::unique_ptr<RtpTransportControllerSendInterface> transport_send);
171 virtual ~Call();
172
173 // Implements webrtc::Call.
174 PacketReceiver* Receiver() override;
175
176 webrtc::AudioSendStream* CreateAudioSendStream(
177 const webrtc::AudioSendStream::Config& config) override;
178 void DestroyAudioSendStream(webrtc::AudioSendStream* send_stream) override;
179
180 webrtc::AudioReceiveStream* CreateAudioReceiveStream(
181 const webrtc::AudioReceiveStream::Config& config) override;
182 void DestroyAudioReceiveStream(
183 webrtc::AudioReceiveStream* receive_stream) override;
184
185 webrtc::VideoSendStream* CreateVideoSendStream(
186 webrtc::VideoSendStream::Config config,
187 VideoEncoderConfig encoder_config) override;
188 void DestroyVideoSendStream(webrtc::VideoSendStream* send_stream) override;
189
190 webrtc::VideoReceiveStream* CreateVideoReceiveStream(
191 webrtc::VideoReceiveStream::Config configuration) override;
192 void DestroyVideoReceiveStream(
193 webrtc::VideoReceiveStream* receive_stream) override;
194
195 FlexfecReceiveStream* CreateFlexfecReceiveStream(
196 const FlexfecReceiveStream::Config& config) override;
197 void DestroyFlexfecReceiveStream(
198 FlexfecReceiveStream* receive_stream) override;
199
200 Stats GetStats() const override;
201
202 // Implements PacketReceiver.
203 DeliveryStatus DeliverPacket(MediaType media_type,
204 const uint8_t* packet,
205 size_t length,
206 const PacketTime& packet_time) override;
207
208 // Implements RecoveredPacketReceiver.
209 void OnRecoveredPacket(const uint8_t* packet, size_t length) override;
210
211 void SetBitrateConfig(
212 const webrtc::Call::Config::BitrateConfig& bitrate_config) override;
213
214 void SetBitrateConfigMask(
215 const webrtc::Call::Config::BitrateConfigMask& bitrate_config) override;
216
217 void SetBitrateAllocationStrategy(
218 std::unique_ptr<rtc::BitrateAllocationStrategy>
219 bitrate_allocation_strategy) override;
220
221 void SignalChannelNetworkState(MediaType media, NetworkState state) override;
222
223 void OnTransportOverheadChanged(MediaType media,
224 int transport_overhead_per_packet) override;
225
226 void OnNetworkRouteChanged(const std::string& transport_name,
227 const rtc::NetworkRoute& network_route) override;
228
229 void OnSentPacket(const rtc::SentPacket& sent_packet) override;
230
231 // Implements BitrateObserver.
232 void OnNetworkChanged(uint32_t bitrate_bps,
233 uint8_t fraction_loss,
234 int64_t rtt_ms,
235 int64_t probing_interval_ms) override;
236
237 // Implements BitrateAllocator::LimitObserver.
238 void OnAllocationLimitsChanged(uint32_t min_send_bitrate_bps,
239 uint32_t max_padding_bitrate_bps) override;
240
voice_engine()241 VoiceEngine* voice_engine() override {
242 internal::AudioState* audio_state =
243 static_cast<internal::AudioState*>(config_.audio_state.get());
244 if (audio_state)
245 return audio_state->voice_engine();
246 else
247 return nullptr;
248 }
249
250 private:
251 DeliveryStatus DeliverRtcp(MediaType media_type, const uint8_t* packet,
252 size_t length);
253 DeliveryStatus DeliverRtp(MediaType media_type,
254 const uint8_t* packet,
255 size_t length,
256 const PacketTime& packet_time);
257 void ConfigureSync(const std::string& sync_group)
258 RTC_EXCLUSIVE_LOCKS_REQUIRED(receive_crit_);
259
260 void NotifyBweOfReceivedPacket(const RtpPacketReceived& packet,
261 MediaType media_type)
262 RTC_SHARED_LOCKS_REQUIRED(receive_crit_);
263
264 void UpdateSendHistograms(int64_t first_sent_packet_ms)
265 RTC_EXCLUSIVE_LOCKS_REQUIRED(&bitrate_crit_);
266 void UpdateReceiveHistograms();
267 void UpdateHistograms();
268 void UpdateAggregateNetworkState();
269
270 // Applies update to the BitrateConfig cached in |config_|, restarting
271 // bandwidth estimation from |new_start| if set.
272 void UpdateCurrentBitrateConfig(const rtc::Optional<int>& new_start);
273
274 Clock* const clock_;
275
276 const int num_cpu_cores_;
277 const std::unique_ptr<ProcessThread> module_process_thread_;
278 const std::unique_ptr<ProcessThread> pacer_thread_;
279 const std::unique_ptr<CallStats> call_stats_;
280 const std::unique_ptr<BitrateAllocator> bitrate_allocator_;
281 Call::Config config_;
282 rtc::SequencedTaskChecker configuration_sequence_checker_;
283
284 NetworkState audio_network_state_;
285 NetworkState video_network_state_;
286
287 std::unique_ptr<RWLockWrapper> receive_crit_;
288 // Audio, Video, and FlexFEC receive streams are owned by the client that
289 // creates them.
290 std::set<AudioReceiveStream*> audio_receive_streams_
291 RTC_GUARDED_BY(receive_crit_);
292 std::set<VideoReceiveStream*> video_receive_streams_
293 RTC_GUARDED_BY(receive_crit_);
294
295 std::map<std::string, AudioReceiveStream*> sync_stream_mapping_
296 RTC_GUARDED_BY(receive_crit_);
297
298 // TODO(nisse): Should eventually be injected at creation,
299 // with a single object in the bundled case.
300 RtpStreamReceiverController audio_receiver_controller_;
301 RtpStreamReceiverController video_receiver_controller_;
302
303 // This extra map is used for receive processing which is
304 // independent of media type.
305
306 // TODO(nisse): In the RTP transport refactoring, we should have a
307 // single mapping from ssrc to a more abstract receive stream, with
308 // accessor methods for all configuration we need at this level.
309 struct ReceiveRtpConfig {
310 ReceiveRtpConfig() = default; // Needed by std::map
ReceiveRtpConfigwebrtc::internal::Call::ReceiveRtpConfig311 ReceiveRtpConfig(const std::vector<RtpExtension>& extensions,
312 bool use_send_side_bwe)
313 : extensions(extensions), use_send_side_bwe(use_send_side_bwe) {}
314
315 // Registered RTP header extensions for each stream. Note that RTP header
316 // extensions are negotiated per track ("m= line") in the SDP, but we have
317 // no notion of tracks at the Call level. We therefore store the RTP header
318 // extensions per SSRC instead, which leads to some storage overhead.
319 RtpHeaderExtensionMap extensions;
320 // Set if both RTP extension the RTCP feedback message needed for
321 // send side BWE are negotiated.
322 bool use_send_side_bwe = false;
323 };
324 std::map<uint32_t, ReceiveRtpConfig> receive_rtp_config_
325 RTC_GUARDED_BY(receive_crit_);
326
327 std::unique_ptr<RWLockWrapper> send_crit_;
328 // Audio and Video send streams are owned by the client that creates them.
329 std::map<uint32_t, AudioSendStream*> audio_send_ssrcs_
330 RTC_GUARDED_BY(send_crit_);
331 std::map<uint32_t, VideoSendStream*> video_send_ssrcs_
332 RTC_GUARDED_BY(send_crit_);
333 std::set<VideoSendStream*> video_send_streams_ RTC_GUARDED_BY(send_crit_);
334
335 using RtpStateMap = std::map<uint32_t, RtpState>;
336 RtpStateMap suspended_audio_send_ssrcs_
337 RTC_GUARDED_BY(configuration_sequence_checker_);
338 RtpStateMap suspended_video_send_ssrcs_
339 RTC_GUARDED_BY(configuration_sequence_checker_);
340
341 using RtpPayloadStateMap = std::map<uint32_t, RtpPayloadState>;
342 RtpPayloadStateMap suspended_video_payload_states_
343 RTC_GUARDED_BY(configuration_sequence_checker_);
344
345 webrtc::RtcEventLog* event_log_;
346
347 // The following members are only accessed (exclusively) from one thread and
348 // from the destructor, and therefore doesn't need any explicit
349 // synchronization.
350 RateCounter received_bytes_per_second_counter_;
351 RateCounter received_audio_bytes_per_second_counter_;
352 RateCounter received_video_bytes_per_second_counter_;
353 RateCounter received_rtcp_bytes_per_second_counter_;
354 rtc::Optional<int64_t> first_received_rtp_audio_ms_;
355 rtc::Optional<int64_t> last_received_rtp_audio_ms_;
356 rtc::Optional<int64_t> first_received_rtp_video_ms_;
357 rtc::Optional<int64_t> last_received_rtp_video_ms_;
358 TimeInterval sent_rtp_audio_timer_ms_;
359
360 // TODO(holmer): Remove this lock once BitrateController no longer calls
361 // OnNetworkChanged from multiple threads.
362 rtc::CriticalSection bitrate_crit_;
363 uint32_t min_allocated_send_bitrate_bps_ RTC_GUARDED_BY(&bitrate_crit_);
364 uint32_t configured_max_padding_bitrate_bps_ RTC_GUARDED_BY(&bitrate_crit_);
365 AvgCounter estimated_send_bitrate_kbps_counter_
366 RTC_GUARDED_BY(&bitrate_crit_);
367 AvgCounter pacer_bitrate_kbps_counter_ RTC_GUARDED_BY(&bitrate_crit_);
368
369 std::map<std::string, rtc::NetworkRoute> network_routes_;
370
371 std::unique_ptr<RtpTransportControllerSendInterface> transport_send_;
372 ReceiveSideCongestionController receive_side_cc_;
373 const std::unique_ptr<SendDelayStats> video_send_delay_stats_;
374 const int64_t start_ms_;
375 // TODO(perkj): |worker_queue_| is supposed to replace
376 // |module_process_thread_|.
377 // |worker_queue| is defined last to ensure all pending tasks are cancelled
378 // and deleted before any other members.
379 rtc::TaskQueue worker_queue_;
380
381 // The config mask set by SetBitrateConfigMask.
382 // 0 <= min <= start <= max
383 Config::BitrateConfigMask bitrate_config_mask_;
384
385 // The config set by SetBitrateConfig.
386 // min >= 0, start != 0, max == -1 || max > 0
387 Config::BitrateConfig base_bitrate_config_;
388
389 RTC_DISALLOW_COPY_AND_ASSIGN(Call);
390 };
391 } // namespace internal
392
ToString(int64_t time_ms) const393 std::string Call::Stats::ToString(int64_t time_ms) const {
394 std::stringstream ss;
395 ss << "Call stats: " << time_ms << ", {";
396 ss << "send_bw_bps: " << send_bandwidth_bps << ", ";
397 ss << "recv_bw_bps: " << recv_bandwidth_bps << ", ";
398 ss << "max_pad_bps: " << max_padding_bitrate_bps << ", ";
399 ss << "pacer_delay_ms: " << pacer_delay_ms << ", ";
400 ss << "rtt_ms: " << rtt_ms;
401 ss << '}';
402 return ss.str();
403 }
404
Create(const Call::Config & config)405 Call* Call::Create(const Call::Config& config) {
406 return new internal::Call(config,
407 rtc::MakeUnique<RtpTransportControllerSend>(
408 Clock::GetRealTimeClock(), config.event_log));
409 }
410
Create(const Call::Config & config,std::unique_ptr<RtpTransportControllerSendInterface> transport_send)411 Call* Call::Create(
412 const Call::Config& config,
413 std::unique_ptr<RtpTransportControllerSendInterface> transport_send) {
414 return new internal::Call(config, std::move(transport_send));
415 }
416
417 namespace internal {
418
Call(const Call::Config & config,std::unique_ptr<RtpTransportControllerSendInterface> transport_send)419 Call::Call(const Call::Config& config,
420 std::unique_ptr<RtpTransportControllerSendInterface> transport_send)
421 : clock_(Clock::GetRealTimeClock()),
422 num_cpu_cores_(CpuInfo::DetectNumberOfCores()),
423 module_process_thread_(ProcessThread::Create("ModuleProcessThread")),
424 pacer_thread_(ProcessThread::Create("PacerThread")),
425 call_stats_(new CallStats(clock_)),
426 bitrate_allocator_(new BitrateAllocator(this)),
427 config_(config),
428 audio_network_state_(kNetworkDown),
429 video_network_state_(kNetworkDown),
430 receive_crit_(RWLockWrapper::CreateRWLock()),
431 send_crit_(RWLockWrapper::CreateRWLock()),
432 event_log_(config.event_log),
433 received_bytes_per_second_counter_(clock_, nullptr, true),
434 received_audio_bytes_per_second_counter_(clock_, nullptr, true),
435 received_video_bytes_per_second_counter_(clock_, nullptr, true),
436 received_rtcp_bytes_per_second_counter_(clock_, nullptr, true),
437 min_allocated_send_bitrate_bps_(0),
438 configured_max_padding_bitrate_bps_(0),
439 estimated_send_bitrate_kbps_counter_(clock_, nullptr, true),
440 pacer_bitrate_kbps_counter_(clock_, nullptr, true),
441 receive_side_cc_(clock_, transport_send->packet_router()),
442 video_send_delay_stats_(new SendDelayStats(clock_)),
443 start_ms_(clock_->TimeInMilliseconds()),
444 worker_queue_("call_worker_queue"),
445 base_bitrate_config_(config.bitrate_config) {
446 RTC_DCHECK(config.event_log != nullptr);
447 RTC_DCHECK_GE(config.bitrate_config.min_bitrate_bps, 0);
448 RTC_DCHECK_GE(config.bitrate_config.start_bitrate_bps,
449 config.bitrate_config.min_bitrate_bps);
450 if (config.bitrate_config.max_bitrate_bps != -1) {
451 RTC_DCHECK_GE(config.bitrate_config.max_bitrate_bps,
452 config.bitrate_config.start_bitrate_bps);
453 }
454 transport_send->send_side_cc()->RegisterNetworkObserver(this);
455 transport_send_ = std::move(transport_send);
456 transport_send_->send_side_cc()->SignalNetworkState(kNetworkDown);
457 transport_send_->send_side_cc()->SetBweBitrates(
458 config_.bitrate_config.min_bitrate_bps,
459 config_.bitrate_config.start_bitrate_bps,
460 config_.bitrate_config.max_bitrate_bps);
461 call_stats_->RegisterStatsObserver(&receive_side_cc_);
462 call_stats_->RegisterStatsObserver(transport_send_->send_side_cc());
463
464 // We have to attach the pacer to the pacer thread before starting the
465 // module process thread to avoid a race accessing the process thread
466 // both from the process thread and the pacer thread.
467 pacer_thread_->RegisterModule(transport_send_->pacer(), RTC_FROM_HERE);
468 pacer_thread_->RegisterModule(
469 receive_side_cc_.GetRemoteBitrateEstimator(true), RTC_FROM_HERE);
470 pacer_thread_->Start();
471
472 module_process_thread_->RegisterModule(call_stats_.get(), RTC_FROM_HERE);
473 module_process_thread_->RegisterModule(&receive_side_cc_, RTC_FROM_HERE);
474 module_process_thread_->RegisterModule(transport_send_->send_side_cc(),
475 RTC_FROM_HERE);
476 module_process_thread_->Start();
477 }
478
~Call()479 Call::~Call() {
480 RTC_DCHECK_CALLED_SEQUENTIALLY(&configuration_sequence_checker_);
481
482 RTC_CHECK(audio_send_ssrcs_.empty());
483 RTC_CHECK(video_send_ssrcs_.empty());
484 RTC_CHECK(video_send_streams_.empty());
485 RTC_CHECK(audio_receive_streams_.empty());
486 RTC_CHECK(video_receive_streams_.empty());
487
488 // The send-side congestion controller must be de-registered prior to
489 // the pacer thread being stopped to avoid a race when accessing the
490 // pacer thread object on the module process thread at the same time as
491 // the pacer thread is stopped.
492 module_process_thread_->DeRegisterModule(transport_send_->send_side_cc());
493 pacer_thread_->Stop();
494 pacer_thread_->DeRegisterModule(transport_send_->pacer());
495 pacer_thread_->DeRegisterModule(
496 receive_side_cc_.GetRemoteBitrateEstimator(true));
497 module_process_thread_->DeRegisterModule(&receive_side_cc_);
498 module_process_thread_->DeRegisterModule(call_stats_.get());
499 module_process_thread_->Stop();
500 call_stats_->DeregisterStatsObserver(&receive_side_cc_);
501 call_stats_->DeregisterStatsObserver(transport_send_->send_side_cc());
502
503 int64_t first_sent_packet_ms =
504 transport_send_->send_side_cc()->GetFirstPacketTimeMs();
505 // Only update histograms after process threads have been shut down, so that
506 // they won't try to concurrently update stats.
507 {
508 rtc::CritScope lock(&bitrate_crit_);
509 UpdateSendHistograms(first_sent_packet_ms);
510 }
511 UpdateReceiveHistograms();
512 UpdateHistograms();
513 }
514
UpdateHistograms()515 void Call::UpdateHistograms() {
516 RTC_HISTOGRAM_COUNTS_100000(
517 "WebRTC.Call.LifetimeInSeconds",
518 (clock_->TimeInMilliseconds() - start_ms_) / 1000);
519 }
520
UpdateSendHistograms(int64_t first_sent_packet_ms)521 void Call::UpdateSendHistograms(int64_t first_sent_packet_ms) {
522 if (first_sent_packet_ms == -1)
523 return;
524 if (!sent_rtp_audio_timer_ms_.Empty()) {
525 RTC_HISTOGRAM_COUNTS_100000(
526 "WebRTC.Call.TimeSendingAudioRtpPacketsInSeconds",
527 sent_rtp_audio_timer_ms_.Length() / 1000);
528 }
529 int64_t elapsed_sec =
530 (clock_->TimeInMilliseconds() - first_sent_packet_ms) / 1000;
531 if (elapsed_sec < metrics::kMinRunTimeInSeconds)
532 return;
533 const int kMinRequiredPeriodicSamples = 5;
534 AggregatedStats send_bitrate_stats =
535 estimated_send_bitrate_kbps_counter_.ProcessAndGetStats();
536 if (send_bitrate_stats.num_samples > kMinRequiredPeriodicSamples) {
537 RTC_HISTOGRAM_COUNTS_100000("WebRTC.Call.EstimatedSendBitrateInKbps",
538 send_bitrate_stats.average);
539 RTC_LOG(LS_INFO) << "WebRTC.Call.EstimatedSendBitrateInKbps, "
540 << send_bitrate_stats.ToString();
541 }
542 AggregatedStats pacer_bitrate_stats =
543 pacer_bitrate_kbps_counter_.ProcessAndGetStats();
544 if (pacer_bitrate_stats.num_samples > kMinRequiredPeriodicSamples) {
545 RTC_HISTOGRAM_COUNTS_100000("WebRTC.Call.PacerBitrateInKbps",
546 pacer_bitrate_stats.average);
547 RTC_LOG(LS_INFO) << "WebRTC.Call.PacerBitrateInKbps, "
548 << pacer_bitrate_stats.ToString();
549 }
550 }
551
UpdateReceiveHistograms()552 void Call::UpdateReceiveHistograms() {
553 if (first_received_rtp_audio_ms_) {
554 RTC_HISTOGRAM_COUNTS_100000(
555 "WebRTC.Call.TimeReceivingAudioRtpPacketsInSeconds",
556 (*last_received_rtp_audio_ms_ - *first_received_rtp_audio_ms_) / 1000);
557 }
558 if (first_received_rtp_video_ms_) {
559 RTC_HISTOGRAM_COUNTS_100000(
560 "WebRTC.Call.TimeReceivingVideoRtpPacketsInSeconds",
561 (*last_received_rtp_video_ms_ - *first_received_rtp_video_ms_) / 1000);
562 }
563 const int kMinRequiredPeriodicSamples = 5;
564 AggregatedStats video_bytes_per_sec =
565 received_video_bytes_per_second_counter_.GetStats();
566 if (video_bytes_per_sec.num_samples > kMinRequiredPeriodicSamples) {
567 RTC_HISTOGRAM_COUNTS_100000("WebRTC.Call.VideoBitrateReceivedInKbps",
568 video_bytes_per_sec.average * 8 / 1000);
569 RTC_LOG(LS_INFO) << "WebRTC.Call.VideoBitrateReceivedInBps, "
570 << video_bytes_per_sec.ToStringWithMultiplier(8);
571 }
572 AggregatedStats audio_bytes_per_sec =
573 received_audio_bytes_per_second_counter_.GetStats();
574 if (audio_bytes_per_sec.num_samples > kMinRequiredPeriodicSamples) {
575 RTC_HISTOGRAM_COUNTS_100000("WebRTC.Call.AudioBitrateReceivedInKbps",
576 audio_bytes_per_sec.average * 8 / 1000);
577 RTC_LOG(LS_INFO) << "WebRTC.Call.AudioBitrateReceivedInBps, "
578 << audio_bytes_per_sec.ToStringWithMultiplier(8);
579 }
580 AggregatedStats rtcp_bytes_per_sec =
581 received_rtcp_bytes_per_second_counter_.GetStats();
582 if (rtcp_bytes_per_sec.num_samples > kMinRequiredPeriodicSamples) {
583 RTC_HISTOGRAM_COUNTS_100000("WebRTC.Call.RtcpBitrateReceivedInBps",
584 rtcp_bytes_per_sec.average * 8);
585 RTC_LOG(LS_INFO) << "WebRTC.Call.RtcpBitrateReceivedInBps, "
586 << rtcp_bytes_per_sec.ToStringWithMultiplier(8);
587 }
588 AggregatedStats recv_bytes_per_sec =
589 received_bytes_per_second_counter_.GetStats();
590 if (recv_bytes_per_sec.num_samples > kMinRequiredPeriodicSamples) {
591 RTC_HISTOGRAM_COUNTS_100000("WebRTC.Call.BitrateReceivedInKbps",
592 recv_bytes_per_sec.average * 8 / 1000);
593 RTC_LOG(LS_INFO) << "WebRTC.Call.BitrateReceivedInBps, "
594 << recv_bytes_per_sec.ToStringWithMultiplier(8);
595 }
596 }
597
Receiver()598 PacketReceiver* Call::Receiver() {
599 //Mozilla: Called from STS thread while delivering packets
600 //RTC_DCHECK_CALLED_SEQUENTIALLY(&configuration_sequence_checker_);
601 return this;
602 }
603
CreateAudioSendStream(const webrtc::AudioSendStream::Config & config)604 webrtc::AudioSendStream* Call::CreateAudioSendStream(
605 const webrtc::AudioSendStream::Config& config) {
606 TRACE_EVENT0("webrtc", "Call::CreateAudioSendStream");
607 RTC_DCHECK_CALLED_SEQUENTIALLY(&configuration_sequence_checker_);
608 event_log_->Log(rtc::MakeUnique<RtcEventAudioSendStreamConfig>(
609 CreateRtcLogStreamConfig(config)));
610
611 rtc::Optional<RtpState> suspended_rtp_state;
612 {
613 const auto& iter = suspended_audio_send_ssrcs_.find(config.rtp.ssrc);
614 if (iter != suspended_audio_send_ssrcs_.end()) {
615 suspended_rtp_state.emplace(iter->second);
616 }
617 }
618
619 AudioSendStream* send_stream = new AudioSendStream(
620 config, config_.audio_state, &worker_queue_, transport_send_.get(),
621 bitrate_allocator_.get(), event_log_, call_stats_->rtcp_rtt_stats(),
622 suspended_rtp_state);
623 {
624 WriteLockScoped write_lock(*send_crit_);
625 RTC_DCHECK(audio_send_ssrcs_.find(config.rtp.ssrc) ==
626 audio_send_ssrcs_.end());
627 audio_send_ssrcs_[config.rtp.ssrc] = send_stream;
628 }
629 {
630 ReadLockScoped read_lock(*receive_crit_);
631 for (AudioReceiveStream* stream : audio_receive_streams_) {
632 if (stream->config().rtp.local_ssrc == config.rtp.ssrc) {
633 stream->AssociateSendStream(send_stream);
634 }
635 }
636 }
637 send_stream->SignalNetworkState(audio_network_state_);
638 UpdateAggregateNetworkState();
639 return send_stream;
640 }
641
DestroyAudioSendStream(webrtc::AudioSendStream * send_stream)642 void Call::DestroyAudioSendStream(webrtc::AudioSendStream* send_stream) {
643 TRACE_EVENT0("webrtc", "Call::DestroyAudioSendStream");
644 RTC_DCHECK_CALLED_SEQUENTIALLY(&configuration_sequence_checker_);
645 RTC_DCHECK(send_stream != nullptr);
646
647 send_stream->Stop();
648
649 const uint32_t ssrc = send_stream->GetConfig().rtp.ssrc;
650 webrtc::internal::AudioSendStream* audio_send_stream =
651 static_cast<webrtc::internal::AudioSendStream*>(send_stream);
652 suspended_audio_send_ssrcs_[ssrc] = audio_send_stream->GetRtpState();
653 {
654 WriteLockScoped write_lock(*send_crit_);
655 size_t num_deleted = audio_send_ssrcs_.erase(ssrc);
656 RTC_DCHECK_EQ(1, num_deleted);
657 }
658 {
659 ReadLockScoped read_lock(*receive_crit_);
660 for (AudioReceiveStream* stream : audio_receive_streams_) {
661 if (stream->config().rtp.local_ssrc == ssrc) {
662 stream->AssociateSendStream(nullptr);
663 }
664 }
665 }
666 UpdateAggregateNetworkState();
667 sent_rtp_audio_timer_ms_.Extend(audio_send_stream->GetActiveLifetime());
668 delete send_stream;
669 }
670
CreateAudioReceiveStream(const webrtc::AudioReceiveStream::Config & config)671 webrtc::AudioReceiveStream* Call::CreateAudioReceiveStream(
672 const webrtc::AudioReceiveStream::Config& config) {
673 TRACE_EVENT0("webrtc", "Call::CreateAudioReceiveStream");
674 RTC_DCHECK_CALLED_SEQUENTIALLY(&configuration_sequence_checker_);
675 event_log_->Log(rtc::MakeUnique<RtcEventAudioReceiveStreamConfig>(
676 CreateRtcLogStreamConfig(config)));
677 AudioReceiveStream* receive_stream = new AudioReceiveStream(
678 &audio_receiver_controller_, transport_send_->packet_router(), config,
679 config_.audio_state, event_log_);
680 {
681 WriteLockScoped write_lock(*receive_crit_);
682 receive_rtp_config_[config.rtp.remote_ssrc] =
683 ReceiveRtpConfig(config.rtp.extensions, UseSendSideBwe(config));
684 audio_receive_streams_.insert(receive_stream);
685
686 ConfigureSync(config.sync_group);
687 }
688 {
689 ReadLockScoped read_lock(*send_crit_);
690 auto it = audio_send_ssrcs_.find(config.rtp.local_ssrc);
691 if (it != audio_send_ssrcs_.end()) {
692 receive_stream->AssociateSendStream(it->second);
693 }
694 }
695 receive_stream->SignalNetworkState(audio_network_state_);
696 UpdateAggregateNetworkState();
697 return receive_stream;
698 }
699
DestroyAudioReceiveStream(webrtc::AudioReceiveStream * receive_stream)700 void Call::DestroyAudioReceiveStream(
701 webrtc::AudioReceiveStream* receive_stream) {
702 TRACE_EVENT0("webrtc", "Call::DestroyAudioReceiveStream");
703 RTC_DCHECK_CALLED_SEQUENTIALLY(&configuration_sequence_checker_);
704 RTC_DCHECK(receive_stream != nullptr);
705 webrtc::internal::AudioReceiveStream* audio_receive_stream =
706 static_cast<webrtc::internal::AudioReceiveStream*>(receive_stream);
707 {
708 WriteLockScoped write_lock(*receive_crit_);
709 const AudioReceiveStream::Config& config = audio_receive_stream->config();
710 uint32_t ssrc = config.rtp.remote_ssrc;
711 receive_side_cc_.GetRemoteBitrateEstimator(UseSendSideBwe(config))
712 ->RemoveStream(ssrc);
713 audio_receive_streams_.erase(audio_receive_stream);
714 const std::string& sync_group = audio_receive_stream->config().sync_group;
715 const auto it = sync_stream_mapping_.find(sync_group);
716 if (it != sync_stream_mapping_.end() &&
717 it->second == audio_receive_stream) {
718 sync_stream_mapping_.erase(it);
719 ConfigureSync(sync_group);
720 }
721 receive_rtp_config_.erase(ssrc);
722 }
723 UpdateAggregateNetworkState();
724 delete audio_receive_stream;
725 }
726
CreateVideoSendStream(webrtc::VideoSendStream::Config config,VideoEncoderConfig encoder_config)727 webrtc::VideoSendStream* Call::CreateVideoSendStream(
728 webrtc::VideoSendStream::Config config,
729 VideoEncoderConfig encoder_config) {
730 TRACE_EVENT0("webrtc", "Call::CreateVideoSendStream");
731 RTC_DCHECK_CALLED_SEQUENTIALLY(&configuration_sequence_checker_);
732
733 video_send_delay_stats_->AddSsrcs(config);
734 for (size_t ssrc_index = 0; ssrc_index < config.rtp.ssrcs.size();
735 ++ssrc_index) {
736 event_log_->Log(rtc::MakeUnique<RtcEventVideoSendStreamConfig>(
737 CreateRtcLogStreamConfig(config, ssrc_index)));
738 }
739
740 // TODO(mflodman): Base the start bitrate on a current bandwidth estimate, if
741 // the call has already started.
742 // Copy ssrcs from |config| since |config| is moved.
743 std::vector<uint32_t> ssrcs = config.rtp.ssrcs;
744 VideoSendStream* send_stream = new VideoSendStream(
745 num_cpu_cores_, module_process_thread_.get(), &worker_queue_,
746 call_stats_.get(), transport_send_.get(), bitrate_allocator_.get(),
747 video_send_delay_stats_.get(), event_log_, std::move(config),
748 std::move(encoder_config), suspended_video_send_ssrcs_,
749 suspended_video_payload_states_);
750
751 {
752 WriteLockScoped write_lock(*send_crit_);
753 for (uint32_t ssrc : ssrcs) {
754 RTC_DCHECK(video_send_ssrcs_.find(ssrc) == video_send_ssrcs_.end());
755 video_send_ssrcs_[ssrc] = send_stream;
756 }
757 video_send_streams_.insert(send_stream);
758 }
759 send_stream->SignalNetworkState(video_network_state_);
760 UpdateAggregateNetworkState();
761
762 return send_stream;
763 }
764
DestroyVideoSendStream(webrtc::VideoSendStream * send_stream)765 void Call::DestroyVideoSendStream(webrtc::VideoSendStream* send_stream) {
766 TRACE_EVENT0("webrtc", "Call::DestroyVideoSendStream");
767 RTC_DCHECK(send_stream != nullptr);
768 RTC_DCHECK_CALLED_SEQUENTIALLY(&configuration_sequence_checker_);
769
770 send_stream->Stop();
771
772 VideoSendStream* send_stream_impl = nullptr;
773 {
774 WriteLockScoped write_lock(*send_crit_);
775 auto it = video_send_ssrcs_.begin();
776 while (it != video_send_ssrcs_.end()) {
777 if (it->second == static_cast<VideoSendStream*>(send_stream)) {
778 send_stream_impl = it->second;
779 video_send_ssrcs_.erase(it++);
780 } else {
781 ++it;
782 }
783 }
784 video_send_streams_.erase(send_stream_impl);
785 }
786 RTC_CHECK(send_stream_impl != nullptr);
787
788 VideoSendStream::RtpStateMap rtp_states;
789 VideoSendStream::RtpPayloadStateMap rtp_payload_states;
790 send_stream_impl->StopPermanentlyAndGetRtpStates(&rtp_states,
791 &rtp_payload_states);
792 for (const auto& kv : rtp_states) {
793 suspended_video_send_ssrcs_[kv.first] = kv.second;
794 }
795 for (const auto& kv : rtp_payload_states) {
796 suspended_video_payload_states_[kv.first] = kv.second;
797 }
798
799 UpdateAggregateNetworkState();
800 delete send_stream_impl;
801 }
802
CreateVideoReceiveStream(webrtc::VideoReceiveStream::Config configuration)803 webrtc::VideoReceiveStream* Call::CreateVideoReceiveStream(
804 webrtc::VideoReceiveStream::Config configuration) {
805 TRACE_EVENT0("webrtc", "Call::CreateVideoReceiveStream");
806 RTC_DCHECK_CALLED_SEQUENTIALLY(&configuration_sequence_checker_);
807
808 VideoReceiveStream* receive_stream = new VideoReceiveStream(
809 &video_receiver_controller_, num_cpu_cores_,
810 transport_send_->packet_router(), std::move(configuration),
811 module_process_thread_.get(), call_stats_.get());
812
813 const webrtc::VideoReceiveStream::Config& config = receive_stream->config();
814 ReceiveRtpConfig receive_config(config.rtp.extensions,
815 UseSendSideBwe(config));
816 {
817 WriteLockScoped write_lock(*receive_crit_);
818 if (config.rtp.rtx_ssrc) {
819 // We record identical config for the rtx stream as for the main
820 // stream. Since the transport_send_cc negotiation is per payload
821 // type, we may get an incorrect value for the rtx stream, but
822 // that is unlikely to matter in practice.
823 receive_rtp_config_[config.rtp.rtx_ssrc] = receive_config;
824 }
825 receive_rtp_config_[config.rtp.remote_ssrc] = receive_config;
826 video_receive_streams_.insert(receive_stream);
827 ConfigureSync(config.sync_group);
828 }
829 receive_stream->SignalNetworkState(video_network_state_);
830 UpdateAggregateNetworkState();
831 event_log_->Log(rtc::MakeUnique<RtcEventVideoReceiveStreamConfig>(
832 CreateRtcLogStreamConfig(config)));
833 return receive_stream;
834 }
835
DestroyVideoReceiveStream(webrtc::VideoReceiveStream * receive_stream)836 void Call::DestroyVideoReceiveStream(
837 webrtc::VideoReceiveStream* receive_stream) {
838 TRACE_EVENT0("webrtc", "Call::DestroyVideoReceiveStream");
839 RTC_DCHECK_CALLED_SEQUENTIALLY(&configuration_sequence_checker_);
840 RTC_DCHECK(receive_stream != nullptr);
841 VideoReceiveStream* receive_stream_impl =
842 static_cast<VideoReceiveStream*>(receive_stream);
843 const VideoReceiveStream::Config& config = receive_stream_impl->config();
844 {
845 WriteLockScoped write_lock(*receive_crit_);
846 // Remove all ssrcs pointing to a receive stream. As RTX retransmits on a
847 // separate SSRC there can be either one or two.
848 receive_rtp_config_.erase(config.rtp.remote_ssrc);
849 if (config.rtp.rtx_ssrc) {
850 receive_rtp_config_.erase(config.rtp.rtx_ssrc);
851 }
852 video_receive_streams_.erase(receive_stream_impl);
853 ConfigureSync(config.sync_group);
854 }
855
856 receive_side_cc_.GetRemoteBitrateEstimator(UseSendSideBwe(config))
857 ->RemoveStream(config.rtp.remote_ssrc);
858
859 UpdateAggregateNetworkState();
860 delete receive_stream_impl;
861 }
862
CreateFlexfecReceiveStream(const FlexfecReceiveStream::Config & config)863 FlexfecReceiveStream* Call::CreateFlexfecReceiveStream(
864 const FlexfecReceiveStream::Config& config) {
865 TRACE_EVENT0("webrtc", "Call::CreateFlexfecReceiveStream");
866 RTC_DCHECK_CALLED_SEQUENTIALLY(&configuration_sequence_checker_);
867
868 RecoveredPacketReceiver* recovered_packet_receiver = this;
869
870 FlexfecReceiveStreamImpl* receive_stream;
871 {
872 WriteLockScoped write_lock(*receive_crit_);
873 // Unlike the video and audio receive streams,
874 // FlexfecReceiveStream implements RtpPacketSinkInterface itself,
875 // and hence its constructor passes its |this| pointer to
876 // video_receiver_controller_->CreateStream(). Calling the
877 // constructor while holding |receive_crit_| ensures that we don't
878 // call OnRtpPacket until the constructor is finished and the
879 // object is in a valid state.
880 // TODO(nisse): Fix constructor so that it can be moved outside of
881 // this locked scope.
882 receive_stream = new FlexfecReceiveStreamImpl(
883 &video_receiver_controller_, config, recovered_packet_receiver,
884 call_stats_->rtcp_rtt_stats(), module_process_thread_.get());
885
886 RTC_DCHECK(receive_rtp_config_.find(config.remote_ssrc) ==
887 receive_rtp_config_.end());
888 receive_rtp_config_[config.remote_ssrc] =
889 ReceiveRtpConfig(config.rtp_header_extensions, UseSendSideBwe(config));
890 }
891
892 // TODO(brandtr): Store config in RtcEventLog here.
893
894 return receive_stream;
895 }
896
DestroyFlexfecReceiveStream(FlexfecReceiveStream * receive_stream)897 void Call::DestroyFlexfecReceiveStream(FlexfecReceiveStream* receive_stream) {
898 TRACE_EVENT0("webrtc", "Call::DestroyFlexfecReceiveStream");
899 RTC_DCHECK_CALLED_SEQUENTIALLY(&configuration_sequence_checker_);
900
901 RTC_DCHECK(receive_stream != nullptr);
902 {
903 WriteLockScoped write_lock(*receive_crit_);
904
905 const FlexfecReceiveStream::Config& config = receive_stream->GetConfig();
906 uint32_t ssrc = config.remote_ssrc;
907 receive_rtp_config_.erase(ssrc);
908
909 // Remove all SSRCs pointing to the FlexfecReceiveStreamImpl to be
910 // destroyed.
911 receive_side_cc_.GetRemoteBitrateEstimator(UseSendSideBwe(config))
912 ->RemoveStream(ssrc);
913 }
914
915 delete receive_stream;
916 }
917
GetStats() const918 Call::Stats Call::GetStats() const {
919 // TODO(solenberg): Some test cases in EndToEndTest use this from a different
920 // thread. Re-enable once that is fixed.
921 // RTC_DCHECK_CALLED_SEQUENTIALLY(&configuration_sequence_checker_);
922 Stats stats;
923 // Fetch available send/receive bitrates.
924 uint32_t send_bandwidth = 0;
925 transport_send_->send_side_cc()->AvailableBandwidth(&send_bandwidth);
926 std::vector<unsigned int> ssrcs;
927 uint32_t recv_bandwidth = 0;
928 receive_side_cc_.GetRemoteBitrateEstimator(false)->LatestEstimate(
929 &ssrcs, &recv_bandwidth);
930 stats.send_bandwidth_bps = send_bandwidth;
931 stats.recv_bandwidth_bps = recv_bandwidth;
932 stats.pacer_delay_ms =
933 transport_send_->send_side_cc()->GetPacerQueuingDelayMs();
934 stats.rtt_ms = call_stats_->rtcp_rtt_stats()->LastProcessedRtt();
935 {
936 rtc::CritScope cs(&bitrate_crit_);
937 stats.max_padding_bitrate_bps = configured_max_padding_bitrate_bps_;
938 }
939 return stats;
940 }
941
SetBitrateConfig(const webrtc::Call::Config::BitrateConfig & bitrate_config)942 void Call::SetBitrateConfig(
943 const webrtc::Call::Config::BitrateConfig& bitrate_config) {
944 TRACE_EVENT0("webrtc", "Call::SetBitrateConfig");
945 RTC_DCHECK_CALLED_SEQUENTIALLY(&configuration_sequence_checker_);
946 RTC_DCHECK_GE(bitrate_config.min_bitrate_bps, 0);
947 RTC_DCHECK_NE(bitrate_config.start_bitrate_bps, 0);
948 if (bitrate_config.max_bitrate_bps != -1) {
949 RTC_DCHECK_GT(bitrate_config.max_bitrate_bps, 0);
950 }
951
952 rtc::Optional<int> new_start;
953 // Only update the "start" bitrate if it's set, and different from the old
954 // value. In practice, this value comes from the x-google-start-bitrate codec
955 // parameter in SDP, and setting the same remote description twice shouldn't
956 // restart bandwidth estimation.
957 if (bitrate_config.start_bitrate_bps != -1 &&
958 bitrate_config.start_bitrate_bps !=
959 base_bitrate_config_.start_bitrate_bps) {
960 new_start.emplace(bitrate_config.start_bitrate_bps);
961 }
962 base_bitrate_config_ = bitrate_config;
963 UpdateCurrentBitrateConfig(new_start);
964 }
965
SetBitrateConfigMask(const webrtc::Call::Config::BitrateConfigMask & mask)966 void Call::SetBitrateConfigMask(
967 const webrtc::Call::Config::BitrateConfigMask& mask) {
968 TRACE_EVENT0("webrtc", "Call::SetBitrateConfigMask");
969 RTC_DCHECK_CALLED_SEQUENTIALLY(&configuration_sequence_checker_);
970
971 bitrate_config_mask_ = mask;
972 UpdateCurrentBitrateConfig(mask.start_bitrate_bps);
973 }
974
UpdateCurrentBitrateConfig(const rtc::Optional<int> & new_start)975 void Call::UpdateCurrentBitrateConfig(const rtc::Optional<int>& new_start) {
976 Config::BitrateConfig updated;
977 updated.min_bitrate_bps =
978 std::max(bitrate_config_mask_.min_bitrate_bps.value_or(0),
979 base_bitrate_config_.min_bitrate_bps);
980
981 updated.max_bitrate_bps =
982 MinPositive(bitrate_config_mask_.max_bitrate_bps.value_or(-1),
983 base_bitrate_config_.max_bitrate_bps);
984
985 // If the combined min ends up greater than the combined max, the max takes
986 // priority.
987 if (updated.max_bitrate_bps != -1 &&
988 updated.min_bitrate_bps > updated.max_bitrate_bps) {
989 updated.min_bitrate_bps = updated.max_bitrate_bps;
990 }
991
992 // If there is nothing to update (min/max unchanged, no new bandwidth
993 // estimation start value), return early.
994 if (updated.min_bitrate_bps == config_.bitrate_config.min_bitrate_bps &&
995 updated.max_bitrate_bps == config_.bitrate_config.max_bitrate_bps &&
996 !new_start) {
997 RTC_LOG(LS_VERBOSE) << "WebRTC.Call.UpdateCurrentBitrateConfig: "
998 << "nothing to update";
999 return;
1000 }
1001
1002 if (new_start) {
1003 // Clamp start by min and max.
1004 updated.start_bitrate_bps = MinPositive(
1005 std::max(*new_start, updated.min_bitrate_bps), updated.max_bitrate_bps);
1006 } else {
1007 updated.start_bitrate_bps = -1;
1008 }
1009
1010 RTC_LOG(INFO) << "WebRTC.Call.UpdateCurrentBitrateConfig: "
1011 << "calling SetBweBitrates with args ("
1012 << updated.min_bitrate_bps << ", " << updated.start_bitrate_bps
1013 << ", " << updated.max_bitrate_bps << ")";
1014 transport_send_->send_side_cc()->SetBweBitrates(updated.min_bitrate_bps,
1015 updated.start_bitrate_bps,
1016 updated.max_bitrate_bps);
1017 if (!new_start) {
1018 updated.start_bitrate_bps = config_.bitrate_config.start_bitrate_bps;
1019 }
1020 config_.bitrate_config = updated;
1021 }
1022
SetBitrateAllocationStrategy(std::unique_ptr<rtc::BitrateAllocationStrategy> bitrate_allocation_strategy)1023 void Call::SetBitrateAllocationStrategy(
1024 std::unique_ptr<rtc::BitrateAllocationStrategy>
1025 bitrate_allocation_strategy) {
1026 if (!worker_queue_.IsCurrent()) {
1027 rtc::BitrateAllocationStrategy* strategy_raw =
1028 bitrate_allocation_strategy.release();
1029 auto functor = [this, strategy_raw]() {
1030 SetBitrateAllocationStrategy(
1031 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
1032 };
1033 worker_queue_.PostTask([functor] { functor(); });
1034 return;
1035 }
1036 RTC_DCHECK_RUN_ON(&worker_queue_);
1037 bitrate_allocator_->SetBitrateAllocationStrategy(
1038 std::move(bitrate_allocation_strategy));
1039 }
1040
SignalChannelNetworkState(MediaType media,NetworkState state)1041 void Call::SignalChannelNetworkState(MediaType media, NetworkState state) {
1042 RTC_DCHECK_CALLED_SEQUENTIALLY(&configuration_sequence_checker_);
1043 switch (media) {
1044 case MediaType::AUDIO:
1045 audio_network_state_ = state;
1046 break;
1047 case MediaType::VIDEO:
1048 video_network_state_ = state;
1049 break;
1050 case MediaType::ANY:
1051 case MediaType::DATA:
1052 RTC_NOTREACHED();
1053 break;
1054 }
1055
1056 UpdateAggregateNetworkState();
1057 {
1058 ReadLockScoped read_lock(*send_crit_);
1059 for (auto& kv : audio_send_ssrcs_) {
1060 kv.second->SignalNetworkState(audio_network_state_);
1061 }
1062 for (auto& kv : video_send_ssrcs_) {
1063 kv.second->SignalNetworkState(video_network_state_);
1064 }
1065 }
1066 {
1067 ReadLockScoped read_lock(*receive_crit_);
1068 for (AudioReceiveStream* audio_receive_stream : audio_receive_streams_) {
1069 audio_receive_stream->SignalNetworkState(audio_network_state_);
1070 }
1071 for (VideoReceiveStream* video_receive_stream : video_receive_streams_) {
1072 video_receive_stream->SignalNetworkState(video_network_state_);
1073 }
1074 }
1075 }
1076
OnTransportOverheadChanged(MediaType media,int transport_overhead_per_packet)1077 void Call::OnTransportOverheadChanged(MediaType media,
1078 int transport_overhead_per_packet) {
1079 switch (media) {
1080 case MediaType::AUDIO: {
1081 ReadLockScoped read_lock(*send_crit_);
1082 for (auto& kv : audio_send_ssrcs_) {
1083 kv.second->SetTransportOverhead(transport_overhead_per_packet);
1084 }
1085 break;
1086 }
1087 case MediaType::VIDEO: {
1088 ReadLockScoped read_lock(*send_crit_);
1089 for (auto& kv : video_send_ssrcs_) {
1090 kv.second->SetTransportOverhead(transport_overhead_per_packet);
1091 }
1092 break;
1093 }
1094 case MediaType::ANY:
1095 case MediaType::DATA:
1096 RTC_NOTREACHED();
1097 break;
1098 }
1099 }
1100
1101 // TODO(honghaiz): Add tests for this method.
OnNetworkRouteChanged(const std::string & transport_name,const rtc::NetworkRoute & network_route)1102 void Call::OnNetworkRouteChanged(const std::string& transport_name,
1103 const rtc::NetworkRoute& network_route) {
1104 RTC_DCHECK_CALLED_SEQUENTIALLY(&configuration_sequence_checker_);
1105 // Check if the network route is connected.
1106 if (!network_route.connected) {
1107 RTC_LOG(LS_INFO) << "Transport " << transport_name << " is disconnected";
1108 // TODO(honghaiz): Perhaps handle this in SignalChannelNetworkState and
1109 // consider merging these two methods.
1110 return;
1111 }
1112
1113 // Check whether the network route has changed on each transport.
1114 auto result =
1115 network_routes_.insert(std::make_pair(transport_name, network_route));
1116 auto kv = result.first;
1117 bool inserted = result.second;
1118 if (inserted) {
1119 // No need to reset BWE if this is the first time the network connects.
1120 return;
1121 }
1122 if (kv->second != network_route) {
1123 kv->second = network_route;
1124 RTC_LOG(LS_INFO)
1125 << "Network route changed on transport " << transport_name
1126 << ": new local network id " << network_route.local_network_id
1127 << " new remote network id " << network_route.remote_network_id
1128 << " Reset bitrates to min: " << config_.bitrate_config.min_bitrate_bps
1129 << " bps, start: " << config_.bitrate_config.start_bitrate_bps
1130 << " bps, max: " << config_.bitrate_config.start_bitrate_bps
1131 << " bps.";
1132 RTC_DCHECK_GT(config_.bitrate_config.start_bitrate_bps, 0);
1133 transport_send_->send_side_cc()->OnNetworkRouteChanged(
1134 network_route, config_.bitrate_config.start_bitrate_bps,
1135 config_.bitrate_config.min_bitrate_bps,
1136 config_.bitrate_config.max_bitrate_bps);
1137 }
1138 }
1139
UpdateAggregateNetworkState()1140 void Call::UpdateAggregateNetworkState() {
1141 RTC_DCHECK_CALLED_SEQUENTIALLY(&configuration_sequence_checker_);
1142
1143 bool have_audio = false;
1144 bool have_video = false;
1145 {
1146 ReadLockScoped read_lock(*send_crit_);
1147 if (audio_send_ssrcs_.size() > 0)
1148 have_audio = true;
1149 if (video_send_ssrcs_.size() > 0)
1150 have_video = true;
1151 }
1152 {
1153 ReadLockScoped read_lock(*receive_crit_);
1154 if (audio_receive_streams_.size() > 0)
1155 have_audio = true;
1156 if (video_receive_streams_.size() > 0)
1157 have_video = true;
1158 }
1159
1160 NetworkState aggregate_state = kNetworkDown;
1161 if ((have_video && video_network_state_ == kNetworkUp) ||
1162 (have_audio && audio_network_state_ == kNetworkUp)) {
1163 aggregate_state = kNetworkUp;
1164 }
1165
1166 RTC_LOG(LS_INFO) << "UpdateAggregateNetworkState: aggregate_state="
1167 << (aggregate_state == kNetworkUp ? "up" : "down");
1168
1169 transport_send_->send_side_cc()->SignalNetworkState(aggregate_state);
1170 }
1171
OnSentPacket(const rtc::SentPacket & sent_packet)1172 void Call::OnSentPacket(const rtc::SentPacket& sent_packet) {
1173 video_send_delay_stats_->OnSentPacket(sent_packet.packet_id,
1174 clock_->TimeInMilliseconds());
1175 transport_send_->send_side_cc()->OnSentPacket(sent_packet);
1176 }
1177
OnNetworkChanged(uint32_t target_bitrate_bps,uint8_t fraction_loss,int64_t rtt_ms,int64_t probing_interval_ms)1178 void Call::OnNetworkChanged(uint32_t target_bitrate_bps,
1179 uint8_t fraction_loss,
1180 int64_t rtt_ms,
1181 int64_t probing_interval_ms) {
1182 // TODO(perkj): Consider making sure CongestionController operates on
1183 // |worker_queue_|.
1184 if (!worker_queue_.IsCurrent()) {
1185 worker_queue_.PostTask(
1186 [this, target_bitrate_bps, fraction_loss, rtt_ms, probing_interval_ms] {
1187 OnNetworkChanged(target_bitrate_bps, fraction_loss, rtt_ms,
1188 probing_interval_ms);
1189 });
1190 return;
1191 }
1192 RTC_DCHECK_RUN_ON(&worker_queue_);
1193 // For controlling the rate of feedback messages.
1194 receive_side_cc_.OnBitrateChanged(target_bitrate_bps);
1195 bitrate_allocator_->OnNetworkChanged(target_bitrate_bps, fraction_loss,
1196 rtt_ms, probing_interval_ms);
1197
1198 // Ignore updates if bitrate is zero (the aggregate network state is down).
1199 if (target_bitrate_bps == 0) {
1200 rtc::CritScope lock(&bitrate_crit_);
1201 estimated_send_bitrate_kbps_counter_.ProcessAndPause();
1202 pacer_bitrate_kbps_counter_.ProcessAndPause();
1203 return;
1204 }
1205
1206 bool sending_video;
1207 {
1208 ReadLockScoped read_lock(*send_crit_);
1209 sending_video = !video_send_streams_.empty();
1210 }
1211
1212 rtc::CritScope lock(&bitrate_crit_);
1213 if (!sending_video) {
1214 // Do not update the stats if we are not sending video.
1215 estimated_send_bitrate_kbps_counter_.ProcessAndPause();
1216 pacer_bitrate_kbps_counter_.ProcessAndPause();
1217 return;
1218 }
1219 estimated_send_bitrate_kbps_counter_.Add(target_bitrate_bps / 1000);
1220 // Pacer bitrate may be higher than bitrate estimate if enforcing min bitrate.
1221 uint32_t pacer_bitrate_bps =
1222 std::max(target_bitrate_bps, min_allocated_send_bitrate_bps_);
1223 pacer_bitrate_kbps_counter_.Add(pacer_bitrate_bps / 1000);
1224 }
1225
OnAllocationLimitsChanged(uint32_t min_send_bitrate_bps,uint32_t max_padding_bitrate_bps)1226 void Call::OnAllocationLimitsChanged(uint32_t min_send_bitrate_bps,
1227 uint32_t max_padding_bitrate_bps) {
1228 transport_send_->SetAllocatedSendBitrateLimits(min_send_bitrate_bps,
1229 max_padding_bitrate_bps);
1230 rtc::CritScope lock(&bitrate_crit_);
1231 min_allocated_send_bitrate_bps_ = min_send_bitrate_bps;
1232 configured_max_padding_bitrate_bps_ = max_padding_bitrate_bps;
1233 }
1234
ConfigureSync(const std::string & sync_group)1235 void Call::ConfigureSync(const std::string& sync_group) {
1236 // Set sync only if there was no previous one.
1237 if (sync_group.empty())
1238 return;
1239
1240 AudioReceiveStream* sync_audio_stream = nullptr;
1241 // Find existing audio stream.
1242 const auto it = sync_stream_mapping_.find(sync_group);
1243 if (it != sync_stream_mapping_.end()) {
1244 sync_audio_stream = it->second;
1245 } else {
1246 // No configured audio stream, see if we can find one.
1247 for (AudioReceiveStream* stream : audio_receive_streams_) {
1248 if (stream->config().sync_group == sync_group) {
1249 if (sync_audio_stream != nullptr) {
1250 RTC_LOG(LS_WARNING)
1251 << "Attempting to sync more than one audio stream "
1252 "within the same sync group. This is not "
1253 "supported in the current implementation.";
1254 break;
1255 }
1256 sync_audio_stream = stream;
1257 }
1258 }
1259 }
1260 if (sync_audio_stream)
1261 sync_stream_mapping_[sync_group] = sync_audio_stream;
1262 size_t num_synced_streams = 0;
1263 for (VideoReceiveStream* video_stream : video_receive_streams_) {
1264 if (video_stream->config().sync_group != sync_group)
1265 continue;
1266 ++num_synced_streams;
1267 if (num_synced_streams > 1) {
1268 // TODO(pbos): Support synchronizing more than one A/V pair.
1269 // https://code.google.com/p/webrtc/issues/detail?id=4762
1270 RTC_LOG(LS_WARNING)
1271 << "Attempting to sync more than one audio/video pair "
1272 "within the same sync group. This is not supported in "
1273 "the current implementation.";
1274 }
1275 // Only sync the first A/V pair within this sync group.
1276 if (num_synced_streams == 1) {
1277 // sync_audio_stream may be null and that's ok.
1278 video_stream->SetSync(sync_audio_stream);
1279 } else {
1280 video_stream->SetSync(nullptr);
1281 }
1282 }
1283 }
1284
DeliverRtcp(MediaType media_type,const uint8_t * packet,size_t length)1285 PacketReceiver::DeliveryStatus Call::DeliverRtcp(MediaType media_type,
1286 const uint8_t* packet,
1287 size_t length) {
1288 TRACE_EVENT0("webrtc", "Call::DeliverRtcp");
1289 // TODO(pbos): Make sure it's a valid packet.
1290 // Return DELIVERY_UNKNOWN_SSRC if it can be determined that
1291 // there's no receiver of the packet.
1292 if (received_bytes_per_second_counter_.HasSample()) {
1293 // First RTP packet has been received.
1294 received_bytes_per_second_counter_.Add(static_cast<int>(length));
1295 received_rtcp_bytes_per_second_counter_.Add(static_cast<int>(length));
1296 }
1297 bool rtcp_delivered = false;
1298 if (media_type == MediaType::ANY || media_type == MediaType::VIDEO) {
1299 ReadLockScoped read_lock(*receive_crit_);
1300 for (VideoReceiveStream* stream : video_receive_streams_) {
1301 if (stream->DeliverRtcp(packet, length))
1302 rtcp_delivered = true;
1303 }
1304 }
1305 if (media_type == MediaType::ANY || media_type == MediaType::AUDIO) {
1306 ReadLockScoped read_lock(*receive_crit_);
1307 for (AudioReceiveStream* stream : audio_receive_streams_) {
1308 if (stream->DeliverRtcp(packet, length))
1309 rtcp_delivered = true;
1310 }
1311 }
1312 if (media_type == MediaType::ANY || media_type == MediaType::VIDEO) {
1313 ReadLockScoped read_lock(*send_crit_);
1314 for (VideoSendStream* stream : video_send_streams_) {
1315 if (stream->DeliverRtcp(packet, length))
1316 rtcp_delivered = true;
1317 }
1318 }
1319 if (media_type == MediaType::ANY || media_type == MediaType::AUDIO) {
1320 ReadLockScoped read_lock(*send_crit_);
1321 for (auto& kv : audio_send_ssrcs_) {
1322 if (kv.second->DeliverRtcp(packet, length))
1323 rtcp_delivered = true;
1324 }
1325 }
1326
1327 if (rtcp_delivered) {
1328 event_log_->Log(rtc::MakeUnique<RtcEventRtcpPacketIncoming>(
1329 rtc::MakeArrayView(packet, length)));
1330 }
1331
1332 return rtcp_delivered ? DELIVERY_OK : DELIVERY_PACKET_ERROR;
1333 }
1334
DeliverRtp(MediaType media_type,const uint8_t * packet,size_t length,const PacketTime & packet_time)1335 PacketReceiver::DeliveryStatus Call::DeliverRtp(MediaType media_type,
1336 const uint8_t* packet,
1337 size_t length,
1338 const PacketTime& packet_time) {
1339 TRACE_EVENT0("webrtc", "Call::DeliverRtp");
1340
1341 RtpPacketReceived parsed_packet;
1342 if (!parsed_packet.Parse(packet, length))
1343 return DELIVERY_PACKET_ERROR;
1344
1345 if (packet_time.timestamp != -1) {
1346 parsed_packet.set_arrival_time_ms((packet_time.timestamp + 500) / 1000);
1347 } else {
1348 parsed_packet.set_arrival_time_ms(clock_->TimeInMilliseconds());
1349 }
1350
1351 // We might get RTP keep-alive packets in accordance with RFC6263 section 4.6.
1352 // These are empty (zero length payload) RTP packets with an unsignaled
1353 // payload type.
1354 const bool is_keep_alive_packet = parsed_packet.payload_size() == 0;
1355
1356 RTC_DCHECK(media_type == MediaType::AUDIO || media_type == MediaType::VIDEO ||
1357 is_keep_alive_packet);
1358
1359 ReadLockScoped read_lock(*receive_crit_);
1360 auto it = receive_rtp_config_.find(parsed_packet.Ssrc());
1361 if (it == receive_rtp_config_.end()) {
1362 RTC_LOG(LS_ERROR) << "receive_rtp_config_ lookup failed for ssrc "
1363 << parsed_packet.Ssrc();
1364 // Destruction of the receive stream, including deregistering from the
1365 // RtpDemuxer, is not protected by the |receive_crit_| lock. But
1366 // deregistering in the |receive_rtp_config_| map is protected by that lock.
1367 // So by not passing the packet on to demuxing in this case, we prevent
1368 // incoming packets to be passed on via the demuxer to a receive stream
1369 // which is being torned down.
1370 return DELIVERY_UNKNOWN_SSRC;
1371 }
1372 parsed_packet.IdentifyExtensions(it->second.extensions);
1373
1374 NotifyBweOfReceivedPacket(parsed_packet, media_type);
1375
1376 if (media_type == MediaType::AUDIO) {
1377 if (audio_receiver_controller_.OnRtpPacket(parsed_packet)) {
1378 received_bytes_per_second_counter_.Add(static_cast<int>(length));
1379 received_audio_bytes_per_second_counter_.Add(static_cast<int>(length));
1380 event_log_->Log(
1381 rtc::MakeUnique<RtcEventRtpPacketIncoming>(parsed_packet));
1382 const int64_t arrival_time_ms = parsed_packet.arrival_time_ms();
1383 if (!first_received_rtp_audio_ms_) {
1384 first_received_rtp_audio_ms_.emplace(arrival_time_ms);
1385 }
1386 last_received_rtp_audio_ms_.emplace(arrival_time_ms);
1387 return DELIVERY_OK;
1388 }
1389 } else if (media_type == MediaType::VIDEO) {
1390 if (video_receiver_controller_.OnRtpPacket(parsed_packet)) {
1391 received_bytes_per_second_counter_.Add(static_cast<int>(length));
1392 received_video_bytes_per_second_counter_.Add(static_cast<int>(length));
1393 event_log_->Log(
1394 rtc::MakeUnique<RtcEventRtpPacketIncoming>(parsed_packet));
1395 const int64_t arrival_time_ms = parsed_packet.arrival_time_ms();
1396 if (!first_received_rtp_video_ms_) {
1397 first_received_rtp_video_ms_.emplace(arrival_time_ms);
1398 }
1399 last_received_rtp_video_ms_.emplace(arrival_time_ms);
1400 return DELIVERY_OK;
1401 }
1402 }
1403 return DELIVERY_UNKNOWN_SSRC;
1404 }
1405
DeliverPacket(MediaType media_type,const uint8_t * packet,size_t length,const PacketTime & packet_time)1406 PacketReceiver::DeliveryStatus Call::DeliverPacket(
1407 MediaType media_type,
1408 const uint8_t* packet,
1409 size_t length,
1410 const PacketTime& packet_time) {
1411 //Mozilla: Called from STS thread while delivering packets
1412 //RTC_DCHECK_CALLED_SEQUENTIALLY(&configuration_sequence_checker_);
1413 if (RtpHeaderParser::IsRtcp(packet, length))
1414 return DeliverRtcp(media_type, packet, length);
1415
1416 return DeliverRtp(media_type, packet, length, packet_time);
1417 }
1418
OnRecoveredPacket(const uint8_t * packet,size_t length)1419 void Call::OnRecoveredPacket(const uint8_t* packet, size_t length) {
1420 RtpPacketReceived parsed_packet;
1421 if (!parsed_packet.Parse(packet, length))
1422 return;
1423
1424 parsed_packet.set_recovered(true);
1425
1426 ReadLockScoped read_lock(*receive_crit_);
1427 auto it = receive_rtp_config_.find(parsed_packet.Ssrc());
1428 if (it == receive_rtp_config_.end()) {
1429 RTC_LOG(LS_ERROR) << "receive_rtp_config_ lookup failed for ssrc "
1430 << parsed_packet.Ssrc();
1431 // Destruction of the receive stream, including deregistering from the
1432 // RtpDemuxer, is not protected by the |receive_crit_| lock. But
1433 // deregistering in the |receive_rtp_config_| map is protected by that lock.
1434 // So by not passing the packet on to demuxing in this case, we prevent
1435 // incoming packets to be passed on via the demuxer to a receive stream
1436 // which is being torned down.
1437 return;
1438 }
1439 parsed_packet.IdentifyExtensions(it->second.extensions);
1440
1441 // TODO(brandtr): Update here when we support protecting audio packets too.
1442 video_receiver_controller_.OnRtpPacket(parsed_packet);
1443 }
1444
NotifyBweOfReceivedPacket(const RtpPacketReceived & packet,MediaType media_type)1445 void Call::NotifyBweOfReceivedPacket(const RtpPacketReceived& packet,
1446 MediaType media_type) {
1447 auto it = receive_rtp_config_.find(packet.Ssrc());
1448 bool use_send_side_bwe =
1449 (it != receive_rtp_config_.end()) && it->second.use_send_side_bwe;
1450
1451 RTPHeader header;
1452 packet.GetHeader(&header);
1453
1454 if (!use_send_side_bwe && header.extension.hasTransportSequenceNumber) {
1455 // Inconsistent configuration of send side BWE. Do nothing.
1456 // TODO(nisse): Without this check, we may produce RTCP feedback
1457 // packets even when not negotiated. But it would be cleaner to
1458 // move the check down to RTCPSender::SendFeedbackPacket, which
1459 // would also help the PacketRouter to select an appropriate rtp
1460 // module in the case that some, but not all, have RTCP feedback
1461 // enabled.
1462 return;
1463 }
1464 // For audio, we only support send side BWE.
1465 if (media_type == MediaType::VIDEO ||
1466 (use_send_side_bwe && header.extension.hasTransportSequenceNumber)) {
1467 receive_side_cc_.OnReceivedPacket(
1468 packet.arrival_time_ms(), packet.payload_size() + packet.padding_size(),
1469 header);
1470 }
1471 }
1472
1473 } // namespace internal
1474
1475 } // namespace webrtc
1476