You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1373 lines
52 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  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. #include "call/call.h"
  11. #include <string.h>
  12. #include <algorithm>
  13. #include <map>
  14. #include <memory>
  15. #include <set>
  16. #include <utility>
  17. #include <vector>
  18. #include "absl/types/optional.h"
  19. #include "api/rtc_event_log/rtc_event_log.h"
  20. #include "api/transport/network_control.h"
  21. #include "audio/audio_receive_stream.h"
  22. #include "audio/audio_send_stream.h"
  23. #include "audio/audio_state.h"
  24. #include "call/bitrate_allocator.h"
  25. #include "call/flexfec_receive_stream_impl.h"
  26. #include "call/receive_time_calculator.h"
  27. #include "call/rtp_stream_receiver_controller.h"
  28. #include "call/rtp_transport_controller_send.h"
  29. #include "logging/rtc_event_log/events/rtc_event_audio_receive_stream_config.h"
  30. #include "logging/rtc_event_log/events/rtc_event_rtcp_packet_incoming.h"
  31. #include "logging/rtc_event_log/events/rtc_event_rtp_packet_incoming.h"
  32. #include "logging/rtc_event_log/events/rtc_event_video_receive_stream_config.h"
  33. #include "logging/rtc_event_log/events/rtc_event_video_send_stream_config.h"
  34. #include "logging/rtc_event_log/rtc_stream_config.h"
  35. #include "modules/congestion_controller/include/receive_side_congestion_controller.h"
  36. #include "modules/rtp_rtcp/include/flexfec_receiver.h"
  37. #include "modules/rtp_rtcp/include/rtp_header_extension_map.h"
  38. #include "modules/rtp_rtcp/source/byte_io.h"
  39. #include "modules/rtp_rtcp/source/rtp_packet_received.h"
  40. #include "modules/rtp_rtcp/source/rtp_utility.h"
  41. #include "modules/utility/include/process_thread.h"
  42. #include "modules/video_coding/fec_controller_default.h"
  43. #include "rtc_base/checks.h"
  44. #include "rtc_base/constructor_magic.h"
  45. #include "rtc_base/location.h"
  46. #include "rtc_base/logging.h"
  47. #include "rtc_base/strings/string_builder.h"
  48. #include "rtc_base/synchronization/rw_lock_wrapper.h"
  49. #include "rtc_base/synchronization/sequence_checker.h"
  50. #include "rtc_base/thread_annotations.h"
  51. #include "rtc_base/time_utils.h"
  52. #include "rtc_base/trace_event.h"
  53. #include "system_wrappers/include/clock.h"
  54. #include "system_wrappers/include/cpu_info.h"
  55. #include "system_wrappers/include/field_trial.h"
  56. #include "system_wrappers/include/metrics.h"
  57. #include "video/call_stats.h"
  58. #include "video/send_delay_stats.h"
  59. #include "video/stats_counter.h"
  60. #include "video/video_receive_stream.h"
  61. #include "video/video_send_stream.h"
  62. namespace webrtc {
  63. namespace {
  64. bool SendPeriodicFeedback(const std::vector<RtpExtension>& extensions) {
  65. for (const auto& extension : extensions) {
  66. if (extension.uri == RtpExtension::kTransportSequenceNumberV2Uri)
  67. return false;
  68. }
  69. return true;
  70. }
  71. // TODO(nisse): This really begs for a shared context struct.
  72. bool UseSendSideBwe(const std::vector<RtpExtension>& extensions,
  73. bool transport_cc) {
  74. if (!transport_cc)
  75. return false;
  76. for (const auto& extension : extensions) {
  77. if (extension.uri == RtpExtension::kTransportSequenceNumberUri ||
  78. extension.uri == RtpExtension::kTransportSequenceNumberV2Uri)
  79. return true;
  80. }
  81. return false;
  82. }
  83. bool UseSendSideBwe(const VideoReceiveStream::Config& config) {
  84. return UseSendSideBwe(config.rtp.extensions, config.rtp.transport_cc);
  85. }
  86. bool UseSendSideBwe(const AudioReceiveStream::Config& config) {
  87. return UseSendSideBwe(config.rtp.extensions, config.rtp.transport_cc);
  88. }
  89. bool UseSendSideBwe(const FlexfecReceiveStream::Config& config) {
  90. return UseSendSideBwe(config.rtp_header_extensions, config.transport_cc);
  91. }
  92. const int* FindKeyByValue(const std::map<int, int>& m, int v) {
  93. for (const auto& kv : m) {
  94. if (kv.second == v)
  95. return &kv.first;
  96. }
  97. return nullptr;
  98. }
  99. std::unique_ptr<rtclog::StreamConfig> CreateRtcLogStreamConfig(
  100. const VideoReceiveStream::Config& config) {
  101. auto rtclog_config = std::make_unique<rtclog::StreamConfig>();
  102. rtclog_config->remote_ssrc = config.rtp.remote_ssrc;
  103. rtclog_config->local_ssrc = config.rtp.local_ssrc;
  104. rtclog_config->rtx_ssrc = config.rtp.rtx_ssrc;
  105. rtclog_config->rtcp_mode = config.rtp.rtcp_mode;
  106. rtclog_config->rtp_extensions = config.rtp.extensions;
  107. for (const auto& d : config.decoders) {
  108. const int* search =
  109. FindKeyByValue(config.rtp.rtx_associated_payload_types, d.payload_type);
  110. rtclog_config->codecs.emplace_back(d.video_format.name, d.payload_type,
  111. search ? *search : 0);
  112. }
  113. return rtclog_config;
  114. }
  115. std::unique_ptr<rtclog::StreamConfig> CreateRtcLogStreamConfig(
  116. const VideoSendStream::Config& config,
  117. size_t ssrc_index) {
  118. auto rtclog_config = std::make_unique<rtclog::StreamConfig>();
  119. rtclog_config->local_ssrc = config.rtp.ssrcs[ssrc_index];
  120. if (ssrc_index < config.rtp.rtx.ssrcs.size()) {
  121. rtclog_config->rtx_ssrc = config.rtp.rtx.ssrcs[ssrc_index];
  122. }
  123. rtclog_config->rtcp_mode = config.rtp.rtcp_mode;
  124. rtclog_config->rtp_extensions = config.rtp.extensions;
  125. rtclog_config->codecs.emplace_back(config.rtp.payload_name,
  126. config.rtp.payload_type,
  127. config.rtp.rtx.payload_type);
  128. return rtclog_config;
  129. }
  130. std::unique_ptr<rtclog::StreamConfig> CreateRtcLogStreamConfig(
  131. const AudioReceiveStream::Config& config) {
  132. auto rtclog_config = std::make_unique<rtclog::StreamConfig>();
  133. rtclog_config->remote_ssrc = config.rtp.remote_ssrc;
  134. rtclog_config->local_ssrc = config.rtp.local_ssrc;
  135. rtclog_config->rtp_extensions = config.rtp.extensions;
  136. return rtclog_config;
  137. }
  138. bool IsRtcp(const uint8_t* packet, size_t length) {
  139. RtpUtility::RtpHeaderParser rtp_parser(packet, length);
  140. return rtp_parser.RTCP();
  141. }
  142. } // namespace
  143. namespace internal {
  144. class Call final : public webrtc::Call,
  145. public PacketReceiver,
  146. public RecoveredPacketReceiver,
  147. public TargetTransferRateObserver,
  148. public BitrateAllocator::LimitObserver {
  149. public:
  150. Call(Clock* clock,
  151. const Call::Config& config,
  152. std::unique_ptr<RtpTransportControllerSendInterface> transport_send,
  153. std::unique_ptr<ProcessThread> module_process_thread,
  154. TaskQueueFactory* task_queue_factory);
  155. ~Call() override;
  156. // Implements webrtc::Call.
  157. PacketReceiver* Receiver() override;
  158. webrtc::AudioSendStream* CreateAudioSendStream(
  159. const webrtc::AudioSendStream::Config& config) override;
  160. void DestroyAudioSendStream(webrtc::AudioSendStream* send_stream) override;
  161. webrtc::AudioReceiveStream* CreateAudioReceiveStream(
  162. const webrtc::AudioReceiveStream::Config& config) override;
  163. void DestroyAudioReceiveStream(
  164. webrtc::AudioReceiveStream* receive_stream) override;
  165. webrtc::VideoSendStream* CreateVideoSendStream(
  166. webrtc::VideoSendStream::Config config,
  167. VideoEncoderConfig encoder_config) override;
  168. webrtc::VideoSendStream* CreateVideoSendStream(
  169. webrtc::VideoSendStream::Config config,
  170. VideoEncoderConfig encoder_config,
  171. std::unique_ptr<FecController> fec_controller) override;
  172. void DestroyVideoSendStream(webrtc::VideoSendStream* send_stream) override;
  173. webrtc::VideoReceiveStream* CreateVideoReceiveStream(
  174. webrtc::VideoReceiveStream::Config configuration) override;
  175. void DestroyVideoReceiveStream(
  176. webrtc::VideoReceiveStream* receive_stream) override;
  177. FlexfecReceiveStream* CreateFlexfecReceiveStream(
  178. const FlexfecReceiveStream::Config& config) override;
  179. void DestroyFlexfecReceiveStream(
  180. FlexfecReceiveStream* receive_stream) override;
  181. RtpTransportControllerSendInterface* GetTransportControllerSend() override;
  182. Stats GetStats() const override;
  183. // Implements PacketReceiver.
  184. DeliveryStatus DeliverPacket(MediaType media_type,
  185. rtc::CopyOnWriteBuffer packet,
  186. int64_t packet_time_us) override;
  187. // Implements RecoveredPacketReceiver.
  188. void OnRecoveredPacket(const uint8_t* packet, size_t length) override;
  189. void SignalChannelNetworkState(MediaType media, NetworkState state) override;
  190. void OnAudioTransportOverheadChanged(
  191. int transport_overhead_per_packet) override;
  192. void OnSentPacket(const rtc::SentPacket& sent_packet) override;
  193. // Implements TargetTransferRateObserver,
  194. void OnTargetTransferRate(TargetTransferRate msg) override;
  195. void OnStartRateUpdate(DataRate start_rate) override;
  196. // Implements BitrateAllocator::LimitObserver.
  197. void OnAllocationLimitsChanged(BitrateAllocationLimits limits) override;
  198. void SetClientBitratePreferences(const BitrateSettings& preferences) override;
  199. private:
  200. DeliveryStatus DeliverRtcp(MediaType media_type,
  201. const uint8_t* packet,
  202. size_t length);
  203. DeliveryStatus DeliverRtp(MediaType media_type,
  204. rtc::CopyOnWriteBuffer packet,
  205. int64_t packet_time_us);
  206. void ConfigureSync(const std::string& sync_group)
  207. RTC_EXCLUSIVE_LOCKS_REQUIRED(receive_crit_);
  208. void NotifyBweOfReceivedPacket(const RtpPacketReceived& packet,
  209. MediaType media_type)
  210. RTC_SHARED_LOCKS_REQUIRED(receive_crit_);
  211. void UpdateSendHistograms(Timestamp first_sent_packet)
  212. RTC_EXCLUSIVE_LOCKS_REQUIRED(&bitrate_crit_);
  213. void UpdateReceiveHistograms();
  214. void UpdateHistograms();
  215. void UpdateAggregateNetworkState();
  216. void RegisterRateObserver();
  217. rtc::TaskQueue* network_queue() const {
  218. return transport_send_ptr_->GetWorkerQueue();
  219. }
  220. Clock* const clock_;
  221. TaskQueueFactory* const task_queue_factory_;
  222. const int num_cpu_cores_;
  223. const std::unique_ptr<ProcessThread> module_process_thread_;
  224. const std::unique_ptr<CallStats> call_stats_;
  225. const std::unique_ptr<BitrateAllocator> bitrate_allocator_;
  226. Call::Config config_;
  227. SequenceChecker configuration_sequence_checker_;
  228. SequenceChecker worker_sequence_checker_;
  229. NetworkState audio_network_state_;
  230. NetworkState video_network_state_;
  231. bool aggregate_network_up_ RTC_GUARDED_BY(configuration_sequence_checker_);
  232. std::unique_ptr<RWLockWrapper> receive_crit_;
  233. // Audio, Video, and FlexFEC receive streams are owned by the client that
  234. // creates them.
  235. std::set<AudioReceiveStream*> audio_receive_streams_
  236. RTC_GUARDED_BY(receive_crit_);
  237. std::set<VideoReceiveStream*> video_receive_streams_
  238. RTC_GUARDED_BY(receive_crit_);
  239. std::map<std::string, AudioReceiveStream*> sync_stream_mapping_
  240. RTC_GUARDED_BY(receive_crit_);
  241. // TODO(nisse): Should eventually be injected at creation,
  242. // with a single object in the bundled case.
  243. RtpStreamReceiverController audio_receiver_controller_;
  244. RtpStreamReceiverController video_receiver_controller_;
  245. // This extra map is used for receive processing which is
  246. // independent of media type.
  247. // TODO(nisse): In the RTP transport refactoring, we should have a
  248. // single mapping from ssrc to a more abstract receive stream, with
  249. // accessor methods for all configuration we need at this level.
  250. struct ReceiveRtpConfig {
  251. explicit ReceiveRtpConfig(const webrtc::AudioReceiveStream::Config& config)
  252. : extensions(config.rtp.extensions),
  253. use_send_side_bwe(UseSendSideBwe(config)) {}
  254. explicit ReceiveRtpConfig(const webrtc::VideoReceiveStream::Config& config)
  255. : extensions(config.rtp.extensions),
  256. use_send_side_bwe(UseSendSideBwe(config)) {}
  257. explicit ReceiveRtpConfig(const FlexfecReceiveStream::Config& config)
  258. : extensions(config.rtp_header_extensions),
  259. use_send_side_bwe(UseSendSideBwe(config)) {}
  260. // Registered RTP header extensions for each stream. Note that RTP header
  261. // extensions are negotiated per track ("m= line") in the SDP, but we have
  262. // no notion of tracks at the Call level. We therefore store the RTP header
  263. // extensions per SSRC instead, which leads to some storage overhead.
  264. const RtpHeaderExtensionMap extensions;
  265. // Set if both RTP extension the RTCP feedback message needed for
  266. // send side BWE are negotiated.
  267. const bool use_send_side_bwe;
  268. };
  269. std::map<uint32_t, ReceiveRtpConfig> receive_rtp_config_
  270. RTC_GUARDED_BY(receive_crit_);
  271. std::unique_ptr<RWLockWrapper> send_crit_;
  272. // Audio and Video send streams are owned by the client that creates them.
  273. std::map<uint32_t, AudioSendStream*> audio_send_ssrcs_
  274. RTC_GUARDED_BY(send_crit_);
  275. std::map<uint32_t, VideoSendStream*> video_send_ssrcs_
  276. RTC_GUARDED_BY(send_crit_);
  277. std::set<VideoSendStream*> video_send_streams_ RTC_GUARDED_BY(send_crit_);
  278. using RtpStateMap = std::map<uint32_t, RtpState>;
  279. RtpStateMap suspended_audio_send_ssrcs_
  280. RTC_GUARDED_BY(configuration_sequence_checker_);
  281. RtpStateMap suspended_video_send_ssrcs_
  282. RTC_GUARDED_BY(configuration_sequence_checker_);
  283. using RtpPayloadStateMap = std::map<uint32_t, RtpPayloadState>;
  284. RtpPayloadStateMap suspended_video_payload_states_
  285. RTC_GUARDED_BY(configuration_sequence_checker_);
  286. webrtc::RtcEventLog* event_log_;
  287. // The following members are only accessed (exclusively) from one thread and
  288. // from the destructor, and therefore doesn't need any explicit
  289. // synchronization.
  290. RateCounter received_bytes_per_second_counter_;
  291. RateCounter received_audio_bytes_per_second_counter_;
  292. RateCounter received_video_bytes_per_second_counter_;
  293. RateCounter received_rtcp_bytes_per_second_counter_;
  294. absl::optional<int64_t> first_received_rtp_audio_ms_;
  295. absl::optional<int64_t> last_received_rtp_audio_ms_;
  296. absl::optional<int64_t> first_received_rtp_video_ms_;
  297. absl::optional<int64_t> last_received_rtp_video_ms_;
  298. rtc::CriticalSection last_bandwidth_bps_crit_;
  299. uint32_t last_bandwidth_bps_ RTC_GUARDED_BY(&last_bandwidth_bps_crit_);
  300. // TODO(holmer): Remove this lock once BitrateController no longer calls
  301. // OnNetworkChanged from multiple threads.
  302. rtc::CriticalSection bitrate_crit_;
  303. uint32_t min_allocated_send_bitrate_bps_
  304. RTC_GUARDED_BY(&worker_sequence_checker_);
  305. uint32_t configured_max_padding_bitrate_bps_ RTC_GUARDED_BY(&bitrate_crit_);
  306. AvgCounter estimated_send_bitrate_kbps_counter_
  307. RTC_GUARDED_BY(&bitrate_crit_);
  308. AvgCounter pacer_bitrate_kbps_counter_ RTC_GUARDED_BY(&bitrate_crit_);
  309. ReceiveSideCongestionController receive_side_cc_;
  310. const std::unique_ptr<ReceiveTimeCalculator> receive_time_calculator_;
  311. const std::unique_ptr<SendDelayStats> video_send_delay_stats_;
  312. const int64_t start_ms_;
  313. // Caches transport_send_.get(), to avoid racing with destructor.
  314. // Note that this is declared before transport_send_ to ensure that it is not
  315. // invalidated until no more tasks can be running on the transport_send_ task
  316. // queue.
  317. RtpTransportControllerSendInterface* const transport_send_ptr_;
  318. // Declared last since it will issue callbacks from a task queue. Declaring it
  319. // last ensures that it is destroyed first and any running tasks are finished.
  320. std::unique_ptr<RtpTransportControllerSendInterface> transport_send_;
  321. bool is_target_rate_observer_registered_
  322. RTC_GUARDED_BY(&configuration_sequence_checker_) = false;
  323. RTC_DISALLOW_COPY_AND_ASSIGN(Call);
  324. };
  325. } // namespace internal
  326. std::string Call::Stats::ToString(int64_t time_ms) const {
  327. char buf[1024];
  328. rtc::SimpleStringBuilder ss(buf);
  329. ss << "Call stats: " << time_ms << ", {";
  330. ss << "send_bw_bps: " << send_bandwidth_bps << ", ";
  331. ss << "recv_bw_bps: " << recv_bandwidth_bps << ", ";
  332. ss << "max_pad_bps: " << max_padding_bitrate_bps << ", ";
  333. ss << "pacer_delay_ms: " << pacer_delay_ms << ", ";
  334. ss << "rtt_ms: " << rtt_ms;
  335. ss << '}';
  336. return ss.str();
  337. }
  338. Call* Call::Create(const Call::Config& config) {
  339. return Create(config, Clock::GetRealTimeClock(),
  340. ProcessThread::Create("ModuleProcessThread"),
  341. ProcessThread::Create("PacerThread"));
  342. }
  343. Call* Call::Create(const Call::Config& config,
  344. Clock* clock,
  345. std::unique_ptr<ProcessThread> call_thread,
  346. std::unique_ptr<ProcessThread> pacer_thread) {
  347. RTC_DCHECK(config.task_queue_factory);
  348. return new internal::Call(
  349. clock, config,
  350. std::make_unique<RtpTransportControllerSend>(
  351. clock, config.event_log, config.network_state_predictor_factory,
  352. config.network_controller_factory, config.bitrate_config,
  353. std::move(pacer_thread), config.task_queue_factory),
  354. std::move(call_thread), config.task_queue_factory);
  355. }
  356. // This method here to avoid subclasses has to implement this method.
  357. // Call perf test will use Internal::Call::CreateVideoSendStream() to inject
  358. // FecController.
  359. VideoSendStream* Call::CreateVideoSendStream(
  360. VideoSendStream::Config config,
  361. VideoEncoderConfig encoder_config,
  362. std::unique_ptr<FecController> fec_controller) {
  363. return nullptr;
  364. }
  365. namespace internal {
  366. Call::Call(Clock* clock,
  367. const Call::Config& config,
  368. std::unique_ptr<RtpTransportControllerSendInterface> transport_send,
  369. std::unique_ptr<ProcessThread> module_process_thread,
  370. TaskQueueFactory* task_queue_factory)
  371. : clock_(clock),
  372. task_queue_factory_(task_queue_factory),
  373. num_cpu_cores_(CpuInfo::DetectNumberOfCores()),
  374. module_process_thread_(std::move(module_process_thread)),
  375. call_stats_(new CallStats(clock_, module_process_thread_.get())),
  376. bitrate_allocator_(new BitrateAllocator(this)),
  377. config_(config),
  378. audio_network_state_(kNetworkDown),
  379. video_network_state_(kNetworkDown),
  380. aggregate_network_up_(false),
  381. receive_crit_(RWLockWrapper::CreateRWLock()),
  382. send_crit_(RWLockWrapper::CreateRWLock()),
  383. event_log_(config.event_log),
  384. received_bytes_per_second_counter_(clock_, nullptr, true),
  385. received_audio_bytes_per_second_counter_(clock_, nullptr, true),
  386. received_video_bytes_per_second_counter_(clock_, nullptr, true),
  387. received_rtcp_bytes_per_second_counter_(clock_, nullptr, true),
  388. last_bandwidth_bps_(0),
  389. min_allocated_send_bitrate_bps_(0),
  390. configured_max_padding_bitrate_bps_(0),
  391. estimated_send_bitrate_kbps_counter_(clock_, nullptr, true),
  392. pacer_bitrate_kbps_counter_(clock_, nullptr, true),
  393. receive_side_cc_(clock_, transport_send->packet_router()),
  394. receive_time_calculator_(ReceiveTimeCalculator::CreateFromFieldTrial()),
  395. video_send_delay_stats_(new SendDelayStats(clock_)),
  396. start_ms_(clock_->TimeInMilliseconds()),
  397. transport_send_ptr_(transport_send.get()),
  398. transport_send_(std::move(transport_send)) {
  399. RTC_DCHECK(config.event_log != nullptr);
  400. worker_sequence_checker_.Detach();
  401. call_stats_->RegisterStatsObserver(&receive_side_cc_);
  402. module_process_thread_->RegisterModule(
  403. receive_side_cc_.GetRemoteBitrateEstimator(true), RTC_FROM_HERE);
  404. module_process_thread_->RegisterModule(call_stats_.get(), RTC_FROM_HERE);
  405. module_process_thread_->RegisterModule(&receive_side_cc_, RTC_FROM_HERE);
  406. }
  407. Call::~Call() {
  408. RTC_DCHECK_RUN_ON(&configuration_sequence_checker_);
  409. RTC_CHECK(audio_send_ssrcs_.empty());
  410. RTC_CHECK(video_send_ssrcs_.empty());
  411. RTC_CHECK(video_send_streams_.empty());
  412. RTC_CHECK(audio_receive_streams_.empty());
  413. RTC_CHECK(video_receive_streams_.empty());
  414. module_process_thread_->Stop();
  415. module_process_thread_->DeRegisterModule(
  416. receive_side_cc_.GetRemoteBitrateEstimator(true));
  417. module_process_thread_->DeRegisterModule(&receive_side_cc_);
  418. module_process_thread_->DeRegisterModule(call_stats_.get());
  419. call_stats_->DeregisterStatsObserver(&receive_side_cc_);
  420. absl::optional<Timestamp> first_sent_packet_ms =
  421. transport_send_->GetFirstPacketTime();
  422. // Only update histograms after process threads have been shut down, so that
  423. // they won't try to concurrently update stats.
  424. if (first_sent_packet_ms) {
  425. rtc::CritScope lock(&bitrate_crit_);
  426. UpdateSendHistograms(*first_sent_packet_ms);
  427. }
  428. UpdateReceiveHistograms();
  429. UpdateHistograms();
  430. }
  431. void Call::RegisterRateObserver() {
  432. RTC_DCHECK_RUN_ON(&configuration_sequence_checker_);
  433. if (is_target_rate_observer_registered_)
  434. return;
  435. is_target_rate_observer_registered_ = true;
  436. // This call seems to kick off a number of things, so probably better left
  437. // off being kicked off on request rather than in the ctor.
  438. transport_send_ptr_->RegisterTargetTransferRateObserver(this);
  439. module_process_thread_->Start();
  440. }
  441. void Call::SetClientBitratePreferences(const BitrateSettings& preferences) {
  442. RTC_DCHECK_RUN_ON(&configuration_sequence_checker_);
  443. GetTransportControllerSend()->SetClientBitratePreferences(preferences);
  444. }
  445. void Call::UpdateHistograms() {
  446. RTC_HISTOGRAM_COUNTS_100000(
  447. "WebRTC.Call.LifetimeInSeconds",
  448. (clock_->TimeInMilliseconds() - start_ms_) / 1000);
  449. }
  450. // Called from the dtor.
  451. void Call::UpdateSendHistograms(Timestamp first_sent_packet) {
  452. int64_t elapsed_sec =
  453. (clock_->TimeInMilliseconds() - first_sent_packet.ms()) / 1000;
  454. if (elapsed_sec < metrics::kMinRunTimeInSeconds)
  455. return;
  456. const int kMinRequiredPeriodicSamples = 5;
  457. AggregatedStats send_bitrate_stats =
  458. estimated_send_bitrate_kbps_counter_.ProcessAndGetStats();
  459. if (send_bitrate_stats.num_samples > kMinRequiredPeriodicSamples) {
  460. RTC_HISTOGRAM_COUNTS_100000("WebRTC.Call.EstimatedSendBitrateInKbps",
  461. send_bitrate_stats.average);
  462. RTC_LOG(LS_INFO) << "WebRTC.Call.EstimatedSendBitrateInKbps, "
  463. << send_bitrate_stats.ToString();
  464. }
  465. AggregatedStats pacer_bitrate_stats =
  466. pacer_bitrate_kbps_counter_.ProcessAndGetStats();
  467. if (pacer_bitrate_stats.num_samples > kMinRequiredPeriodicSamples) {
  468. RTC_HISTOGRAM_COUNTS_100000("WebRTC.Call.PacerBitrateInKbps",
  469. pacer_bitrate_stats.average);
  470. RTC_LOG(LS_INFO) << "WebRTC.Call.PacerBitrateInKbps, "
  471. << pacer_bitrate_stats.ToString();
  472. }
  473. }
  474. void Call::UpdateReceiveHistograms() {
  475. if (first_received_rtp_audio_ms_) {
  476. RTC_HISTOGRAM_COUNTS_100000(
  477. "WebRTC.Call.TimeReceivingAudioRtpPacketsInSeconds",
  478. (*last_received_rtp_audio_ms_ - *first_received_rtp_audio_ms_) / 1000);
  479. }
  480. if (first_received_rtp_video_ms_) {
  481. RTC_HISTOGRAM_COUNTS_100000(
  482. "WebRTC.Call.TimeReceivingVideoRtpPacketsInSeconds",
  483. (*last_received_rtp_video_ms_ - *first_received_rtp_video_ms_) / 1000);
  484. }
  485. const int kMinRequiredPeriodicSamples = 5;
  486. AggregatedStats video_bytes_per_sec =
  487. received_video_bytes_per_second_counter_.GetStats();
  488. if (video_bytes_per_sec.num_samples > kMinRequiredPeriodicSamples) {
  489. RTC_HISTOGRAM_COUNTS_100000("WebRTC.Call.VideoBitrateReceivedInKbps",
  490. video_bytes_per_sec.average * 8 / 1000);
  491. RTC_LOG(LS_INFO) << "WebRTC.Call.VideoBitrateReceivedInBps, "
  492. << video_bytes_per_sec.ToStringWithMultiplier(8);
  493. }
  494. AggregatedStats audio_bytes_per_sec =
  495. received_audio_bytes_per_second_counter_.GetStats();
  496. if (audio_bytes_per_sec.num_samples > kMinRequiredPeriodicSamples) {
  497. RTC_HISTOGRAM_COUNTS_100000("WebRTC.Call.AudioBitrateReceivedInKbps",
  498. audio_bytes_per_sec.average * 8 / 1000);
  499. RTC_LOG(LS_INFO) << "WebRTC.Call.AudioBitrateReceivedInBps, "
  500. << audio_bytes_per_sec.ToStringWithMultiplier(8);
  501. }
  502. AggregatedStats rtcp_bytes_per_sec =
  503. received_rtcp_bytes_per_second_counter_.GetStats();
  504. if (rtcp_bytes_per_sec.num_samples > kMinRequiredPeriodicSamples) {
  505. RTC_HISTOGRAM_COUNTS_100000("WebRTC.Call.RtcpBitrateReceivedInBps",
  506. rtcp_bytes_per_sec.average * 8);
  507. RTC_LOG(LS_INFO) << "WebRTC.Call.RtcpBitrateReceivedInBps, "
  508. << rtcp_bytes_per_sec.ToStringWithMultiplier(8);
  509. }
  510. AggregatedStats recv_bytes_per_sec =
  511. received_bytes_per_second_counter_.GetStats();
  512. if (recv_bytes_per_sec.num_samples > kMinRequiredPeriodicSamples) {
  513. RTC_HISTOGRAM_COUNTS_100000("WebRTC.Call.BitrateReceivedInKbps",
  514. recv_bytes_per_sec.average * 8 / 1000);
  515. RTC_LOG(LS_INFO) << "WebRTC.Call.BitrateReceivedInBps, "
  516. << recv_bytes_per_sec.ToStringWithMultiplier(8);
  517. }
  518. }
  519. PacketReceiver* Call::Receiver() {
  520. RTC_DCHECK_RUN_ON(&configuration_sequence_checker_);
  521. return this;
  522. }
  523. webrtc::AudioSendStream* Call::CreateAudioSendStream(
  524. const webrtc::AudioSendStream::Config& config) {
  525. TRACE_EVENT0("webrtc", "Call::CreateAudioSendStream");
  526. RTC_DCHECK_RUN_ON(&configuration_sequence_checker_);
  527. RegisterRateObserver();
  528. // Stream config is logged in AudioSendStream::ConfigureStream, as it may
  529. // change during the stream's lifetime.
  530. absl::optional<RtpState> suspended_rtp_state;
  531. {
  532. const auto& iter = suspended_audio_send_ssrcs_.find(config.rtp.ssrc);
  533. if (iter != suspended_audio_send_ssrcs_.end()) {
  534. suspended_rtp_state.emplace(iter->second);
  535. }
  536. }
  537. AudioSendStream* send_stream =
  538. new AudioSendStream(clock_, config, config_.audio_state,
  539. task_queue_factory_, module_process_thread_.get(),
  540. transport_send_ptr_, bitrate_allocator_.get(),
  541. event_log_, call_stats_.get(), suspended_rtp_state);
  542. {
  543. WriteLockScoped write_lock(*send_crit_);
  544. RTC_DCHECK(audio_send_ssrcs_.find(config.rtp.ssrc) ==
  545. audio_send_ssrcs_.end());
  546. audio_send_ssrcs_[config.rtp.ssrc] = send_stream;
  547. }
  548. {
  549. ReadLockScoped read_lock(*receive_crit_);
  550. for (AudioReceiveStream* stream : audio_receive_streams_) {
  551. if (stream->config().rtp.local_ssrc == config.rtp.ssrc) {
  552. stream->AssociateSendStream(send_stream);
  553. }
  554. }
  555. }
  556. UpdateAggregateNetworkState();
  557. return send_stream;
  558. }
  559. void Call::DestroyAudioSendStream(webrtc::AudioSendStream* send_stream) {
  560. TRACE_EVENT0("webrtc", "Call::DestroyAudioSendStream");
  561. RTC_DCHECK_RUN_ON(&configuration_sequence_checker_);
  562. RTC_DCHECK(send_stream != nullptr);
  563. send_stream->Stop();
  564. const uint32_t ssrc = send_stream->GetConfig().rtp.ssrc;
  565. webrtc::internal::AudioSendStream* audio_send_stream =
  566. static_cast<webrtc::internal::AudioSendStream*>(send_stream);
  567. suspended_audio_send_ssrcs_[ssrc] = audio_send_stream->GetRtpState();
  568. {
  569. WriteLockScoped write_lock(*send_crit_);
  570. size_t num_deleted = audio_send_ssrcs_.erase(ssrc);
  571. RTC_DCHECK_EQ(1, num_deleted);
  572. }
  573. {
  574. ReadLockScoped read_lock(*receive_crit_);
  575. for (AudioReceiveStream* stream : audio_receive_streams_) {
  576. if (stream->config().rtp.local_ssrc == ssrc) {
  577. stream->AssociateSendStream(nullptr);
  578. }
  579. }
  580. }
  581. UpdateAggregateNetworkState();
  582. delete send_stream;
  583. }
  584. webrtc::AudioReceiveStream* Call::CreateAudioReceiveStream(
  585. const webrtc::AudioReceiveStream::Config& config) {
  586. TRACE_EVENT0("webrtc", "Call::CreateAudioReceiveStream");
  587. RTC_DCHECK_RUN_ON(&configuration_sequence_checker_);
  588. RegisterRateObserver();
  589. event_log_->Log(std::make_unique<RtcEventAudioReceiveStreamConfig>(
  590. CreateRtcLogStreamConfig(config)));
  591. AudioReceiveStream* receive_stream = new AudioReceiveStream(
  592. clock_, &audio_receiver_controller_, transport_send_ptr_->packet_router(),
  593. module_process_thread_.get(), config, config_.audio_state, event_log_);
  594. {
  595. WriteLockScoped write_lock(*receive_crit_);
  596. receive_rtp_config_.emplace(config.rtp.remote_ssrc,
  597. ReceiveRtpConfig(config));
  598. audio_receive_streams_.insert(receive_stream);
  599. ConfigureSync(config.sync_group);
  600. }
  601. {
  602. ReadLockScoped read_lock(*send_crit_);
  603. auto it = audio_send_ssrcs_.find(config.rtp.local_ssrc);
  604. if (it != audio_send_ssrcs_.end()) {
  605. receive_stream->AssociateSendStream(it->second);
  606. }
  607. }
  608. UpdateAggregateNetworkState();
  609. return receive_stream;
  610. }
  611. void Call::DestroyAudioReceiveStream(
  612. webrtc::AudioReceiveStream* receive_stream) {
  613. TRACE_EVENT0("webrtc", "Call::DestroyAudioReceiveStream");
  614. RTC_DCHECK_RUN_ON(&configuration_sequence_checker_);
  615. RTC_DCHECK(receive_stream != nullptr);
  616. webrtc::internal::AudioReceiveStream* audio_receive_stream =
  617. static_cast<webrtc::internal::AudioReceiveStream*>(receive_stream);
  618. {
  619. WriteLockScoped write_lock(*receive_crit_);
  620. const AudioReceiveStream::Config& config = audio_receive_stream->config();
  621. uint32_t ssrc = config.rtp.remote_ssrc;
  622. receive_side_cc_.GetRemoteBitrateEstimator(UseSendSideBwe(config))
  623. ->RemoveStream(ssrc);
  624. audio_receive_streams_.erase(audio_receive_stream);
  625. const std::string& sync_group = audio_receive_stream->config().sync_group;
  626. const auto it = sync_stream_mapping_.find(sync_group);
  627. if (it != sync_stream_mapping_.end() &&
  628. it->second == audio_receive_stream) {
  629. sync_stream_mapping_.erase(it);
  630. ConfigureSync(sync_group);
  631. }
  632. receive_rtp_config_.erase(ssrc);
  633. }
  634. UpdateAggregateNetworkState();
  635. delete audio_receive_stream;
  636. }
  637. // This method can be used for Call tests with external fec controller factory.
  638. webrtc::VideoSendStream* Call::CreateVideoSendStream(
  639. webrtc::VideoSendStream::Config config,
  640. VideoEncoderConfig encoder_config,
  641. std::unique_ptr<FecController> fec_controller) {
  642. TRACE_EVENT0("webrtc", "Call::CreateVideoSendStream");
  643. RTC_DCHECK_RUN_ON(&configuration_sequence_checker_);
  644. RegisterRateObserver();
  645. video_send_delay_stats_->AddSsrcs(config);
  646. for (size_t ssrc_index = 0; ssrc_index < config.rtp.ssrcs.size();
  647. ++ssrc_index) {
  648. event_log_->Log(std::make_unique<RtcEventVideoSendStreamConfig>(
  649. CreateRtcLogStreamConfig(config, ssrc_index)));
  650. }
  651. // TODO(mflodman): Base the start bitrate on a current bandwidth estimate, if
  652. // the call has already started.
  653. // Copy ssrcs from |config| since |config| is moved.
  654. std::vector<uint32_t> ssrcs = config.rtp.ssrcs;
  655. VideoSendStream* send_stream = new VideoSendStream(
  656. clock_, num_cpu_cores_, module_process_thread_.get(), task_queue_factory_,
  657. call_stats_.get(), transport_send_ptr_, bitrate_allocator_.get(),
  658. video_send_delay_stats_.get(), event_log_, std::move(config),
  659. std::move(encoder_config), suspended_video_send_ssrcs_,
  660. suspended_video_payload_states_, std::move(fec_controller));
  661. {
  662. WriteLockScoped write_lock(*send_crit_);
  663. for (uint32_t ssrc : ssrcs) {
  664. RTC_DCHECK(video_send_ssrcs_.find(ssrc) == video_send_ssrcs_.end());
  665. video_send_ssrcs_[ssrc] = send_stream;
  666. }
  667. video_send_streams_.insert(send_stream);
  668. }
  669. UpdateAggregateNetworkState();
  670. return send_stream;
  671. }
  672. webrtc::VideoSendStream* Call::CreateVideoSendStream(
  673. webrtc::VideoSendStream::Config config,
  674. VideoEncoderConfig encoder_config) {
  675. if (config_.fec_controller_factory) {
  676. RTC_LOG(LS_INFO) << "External FEC Controller will be used.";
  677. }
  678. std::unique_ptr<FecController> fec_controller =
  679. config_.fec_controller_factory
  680. ? config_.fec_controller_factory->CreateFecController()
  681. : std::make_unique<FecControllerDefault>(clock_);
  682. return CreateVideoSendStream(std::move(config), std::move(encoder_config),
  683. std::move(fec_controller));
  684. }
  685. void Call::DestroyVideoSendStream(webrtc::VideoSendStream* send_stream) {
  686. TRACE_EVENT0("webrtc", "Call::DestroyVideoSendStream");
  687. RTC_DCHECK(send_stream != nullptr);
  688. RTC_DCHECK_RUN_ON(&configuration_sequence_checker_);
  689. send_stream->Stop();
  690. VideoSendStream* send_stream_impl = nullptr;
  691. {
  692. WriteLockScoped write_lock(*send_crit_);
  693. auto it = video_send_ssrcs_.begin();
  694. while (it != video_send_ssrcs_.end()) {
  695. if (it->second == static_cast<VideoSendStream*>(send_stream)) {
  696. send_stream_impl = it->second;
  697. video_send_ssrcs_.erase(it++);
  698. } else {
  699. ++it;
  700. }
  701. }
  702. video_send_streams_.erase(send_stream_impl);
  703. }
  704. RTC_CHECK(send_stream_impl != nullptr);
  705. VideoSendStream::RtpStateMap rtp_states;
  706. VideoSendStream::RtpPayloadStateMap rtp_payload_states;
  707. send_stream_impl->StopPermanentlyAndGetRtpStates(&rtp_states,
  708. &rtp_payload_states);
  709. for (const auto& kv : rtp_states) {
  710. suspended_video_send_ssrcs_[kv.first] = kv.second;
  711. }
  712. for (const auto& kv : rtp_payload_states) {
  713. suspended_video_payload_states_[kv.first] = kv.second;
  714. }
  715. UpdateAggregateNetworkState();
  716. delete send_stream_impl;
  717. }
  718. webrtc::VideoReceiveStream* Call::CreateVideoReceiveStream(
  719. webrtc::VideoReceiveStream::Config configuration) {
  720. TRACE_EVENT0("webrtc", "Call::CreateVideoReceiveStream");
  721. RTC_DCHECK_RUN_ON(&configuration_sequence_checker_);
  722. receive_side_cc_.SetSendPeriodicFeedback(
  723. SendPeriodicFeedback(configuration.rtp.extensions));
  724. RegisterRateObserver();
  725. VideoReceiveStream* receive_stream = new VideoReceiveStream(
  726. task_queue_factory_, &video_receiver_controller_, num_cpu_cores_,
  727. transport_send_ptr_->packet_router(), std::move(configuration),
  728. module_process_thread_.get(), call_stats_.get(), clock_);
  729. const webrtc::VideoReceiveStream::Config& config = receive_stream->config();
  730. {
  731. WriteLockScoped write_lock(*receive_crit_);
  732. if (config.rtp.rtx_ssrc) {
  733. // We record identical config for the rtx stream as for the main
  734. // stream. Since the transport_send_cc negotiation is per payload
  735. // type, we may get an incorrect value for the rtx stream, but
  736. // that is unlikely to matter in practice.
  737. receive_rtp_config_.emplace(config.rtp.rtx_ssrc,
  738. ReceiveRtpConfig(config));
  739. }
  740. receive_rtp_config_.emplace(config.rtp.remote_ssrc,
  741. ReceiveRtpConfig(config));
  742. video_receive_streams_.insert(receive_stream);
  743. ConfigureSync(config.sync_group);
  744. }
  745. receive_stream->SignalNetworkState(video_network_state_);
  746. UpdateAggregateNetworkState();
  747. event_log_->Log(std::make_unique<RtcEventVideoReceiveStreamConfig>(
  748. CreateRtcLogStreamConfig(config)));
  749. return receive_stream;
  750. }
  751. void Call::DestroyVideoReceiveStream(
  752. webrtc::VideoReceiveStream* receive_stream) {
  753. TRACE_EVENT0("webrtc", "Call::DestroyVideoReceiveStream");
  754. RTC_DCHECK_RUN_ON(&configuration_sequence_checker_);
  755. RTC_DCHECK(receive_stream != nullptr);
  756. VideoReceiveStream* receive_stream_impl =
  757. static_cast<VideoReceiveStream*>(receive_stream);
  758. const VideoReceiveStream::Config& config = receive_stream_impl->config();
  759. {
  760. WriteLockScoped write_lock(*receive_crit_);
  761. // Remove all ssrcs pointing to a receive stream. As RTX retransmits on a
  762. // separate SSRC there can be either one or two.
  763. receive_rtp_config_.erase(config.rtp.remote_ssrc);
  764. if (config.rtp.rtx_ssrc) {
  765. receive_rtp_config_.erase(config.rtp.rtx_ssrc);
  766. }
  767. video_receive_streams_.erase(receive_stream_impl);
  768. ConfigureSync(config.sync_group);
  769. }
  770. receive_side_cc_.GetRemoteBitrateEstimator(UseSendSideBwe(config))
  771. ->RemoveStream(config.rtp.remote_ssrc);
  772. UpdateAggregateNetworkState();
  773. delete receive_stream_impl;
  774. }
  775. FlexfecReceiveStream* Call::CreateFlexfecReceiveStream(
  776. const FlexfecReceiveStream::Config& config) {
  777. TRACE_EVENT0("webrtc", "Call::CreateFlexfecReceiveStream");
  778. RTC_DCHECK_RUN_ON(&configuration_sequence_checker_);
  779. RecoveredPacketReceiver* recovered_packet_receiver = this;
  780. FlexfecReceiveStreamImpl* receive_stream;
  781. {
  782. WriteLockScoped write_lock(*receive_crit_);
  783. // Unlike the video and audio receive streams,
  784. // FlexfecReceiveStream implements RtpPacketSinkInterface itself,
  785. // and hence its constructor passes its |this| pointer to
  786. // video_receiver_controller_->CreateStream(). Calling the
  787. // constructor while holding |receive_crit_| ensures that we don't
  788. // call OnRtpPacket until the constructor is finished and the
  789. // object is in a valid state.
  790. // TODO(nisse): Fix constructor so that it can be moved outside of
  791. // this locked scope.
  792. receive_stream = new FlexfecReceiveStreamImpl(
  793. clock_, &video_receiver_controller_, config, recovered_packet_receiver,
  794. call_stats_.get(), module_process_thread_.get());
  795. RTC_DCHECK(receive_rtp_config_.find(config.remote_ssrc) ==
  796. receive_rtp_config_.end());
  797. receive_rtp_config_.emplace(config.remote_ssrc, ReceiveRtpConfig(config));
  798. }
  799. // TODO(brandtr): Store config in RtcEventLog here.
  800. return receive_stream;
  801. }
  802. void Call::DestroyFlexfecReceiveStream(FlexfecReceiveStream* receive_stream) {
  803. TRACE_EVENT0("webrtc", "Call::DestroyFlexfecReceiveStream");
  804. RTC_DCHECK_RUN_ON(&configuration_sequence_checker_);
  805. RTC_DCHECK(receive_stream != nullptr);
  806. {
  807. WriteLockScoped write_lock(*receive_crit_);
  808. const FlexfecReceiveStream::Config& config = receive_stream->GetConfig();
  809. uint32_t ssrc = config.remote_ssrc;
  810. receive_rtp_config_.erase(ssrc);
  811. // Remove all SSRCs pointing to the FlexfecReceiveStreamImpl to be
  812. // destroyed.
  813. receive_side_cc_.GetRemoteBitrateEstimator(UseSendSideBwe(config))
  814. ->RemoveStream(ssrc);
  815. }
  816. delete receive_stream;
  817. }
  818. RtpTransportControllerSendInterface* Call::GetTransportControllerSend() {
  819. return transport_send_ptr_;
  820. }
  821. Call::Stats Call::GetStats() const {
  822. RTC_DCHECK_RUN_ON(&configuration_sequence_checker_);
  823. // TODO(tommi): The following stats are managed on the process thread:
  824. // - pacer_delay_ms (PacedSender::Process)
  825. // - rtt_ms
  826. // - recv_bandwidth_bps
  827. // These are delivered on the network TQ:
  828. // - send_bandwidth_bps (see OnTargetTransferRate)
  829. // - max_padding_bitrate_bps (see OnAllocationLimitsChanged)
  830. Stats stats;
  831. // TODO(srte): It is unclear if we only want to report queues if network is
  832. // available.
  833. stats.pacer_delay_ms =
  834. aggregate_network_up_ ? transport_send_ptr_->GetPacerQueuingDelayMs() : 0;
  835. stats.rtt_ms = call_stats_->LastProcessedRtt();
  836. // Fetch available send/receive bitrates.
  837. std::vector<unsigned int> ssrcs;
  838. uint32_t recv_bandwidth = 0;
  839. receive_side_cc_.GetRemoteBitrateEstimator(false)->LatestEstimate(
  840. &ssrcs, &recv_bandwidth);
  841. stats.recv_bandwidth_bps = recv_bandwidth;
  842. {
  843. rtc::CritScope cs(&last_bandwidth_bps_crit_);
  844. stats.send_bandwidth_bps = last_bandwidth_bps_;
  845. }
  846. {
  847. rtc::CritScope cs(&bitrate_crit_);
  848. stats.max_padding_bitrate_bps = configured_max_padding_bitrate_bps_;
  849. }
  850. return stats;
  851. }
  852. void Call::SignalChannelNetworkState(MediaType media, NetworkState state) {
  853. RTC_DCHECK_RUN_ON(&configuration_sequence_checker_);
  854. switch (media) {
  855. case MediaType::AUDIO:
  856. audio_network_state_ = state;
  857. break;
  858. case MediaType::VIDEO:
  859. video_network_state_ = state;
  860. break;
  861. case MediaType::ANY:
  862. case MediaType::DATA:
  863. RTC_NOTREACHED();
  864. break;
  865. }
  866. UpdateAggregateNetworkState();
  867. {
  868. ReadLockScoped read_lock(*receive_crit_);
  869. for (VideoReceiveStream* video_receive_stream : video_receive_streams_) {
  870. video_receive_stream->SignalNetworkState(video_network_state_);
  871. }
  872. }
  873. }
  874. void Call::OnAudioTransportOverheadChanged(int transport_overhead_per_packet) {
  875. ReadLockScoped read_lock(*send_crit_);
  876. for (auto& kv : audio_send_ssrcs_) {
  877. kv.second->SetTransportOverhead(transport_overhead_per_packet);
  878. }
  879. }
  880. void Call::UpdateAggregateNetworkState() {
  881. RTC_DCHECK_RUN_ON(&configuration_sequence_checker_);
  882. bool have_audio = false;
  883. bool have_video = false;
  884. {
  885. ReadLockScoped read_lock(*send_crit_);
  886. if (!audio_send_ssrcs_.empty())
  887. have_audio = true;
  888. if (!video_send_ssrcs_.empty())
  889. have_video = true;
  890. }
  891. {
  892. ReadLockScoped read_lock(*receive_crit_);
  893. if (!audio_receive_streams_.empty())
  894. have_audio = true;
  895. if (!video_receive_streams_.empty())
  896. have_video = true;
  897. }
  898. bool aggregate_network_up =
  899. ((have_video && video_network_state_ == kNetworkUp) ||
  900. (have_audio && audio_network_state_ == kNetworkUp));
  901. RTC_LOG(LS_INFO) << "UpdateAggregateNetworkState: aggregate_state="
  902. << (aggregate_network_up ? "up" : "down");
  903. aggregate_network_up_ = aggregate_network_up;
  904. transport_send_ptr_->OnNetworkAvailability(aggregate_network_up);
  905. }
  906. void Call::OnSentPacket(const rtc::SentPacket& sent_packet) {
  907. video_send_delay_stats_->OnSentPacket(sent_packet.packet_id,
  908. clock_->TimeInMilliseconds());
  909. transport_send_ptr_->OnSentPacket(sent_packet);
  910. }
  911. void Call::OnStartRateUpdate(DataRate start_rate) {
  912. RTC_DCHECK(network_queue()->IsCurrent());
  913. bitrate_allocator_->UpdateStartRate(start_rate.bps<uint32_t>());
  914. }
  915. void Call::OnTargetTransferRate(TargetTransferRate msg) {
  916. RTC_DCHECK(network_queue()->IsCurrent());
  917. RTC_DCHECK_RUN_ON(&worker_sequence_checker_);
  918. {
  919. rtc::CritScope cs(&last_bandwidth_bps_crit_);
  920. last_bandwidth_bps_ = msg.target_rate.bps();
  921. }
  922. uint32_t target_bitrate_bps = msg.target_rate.bps();
  923. // For controlling the rate of feedback messages.
  924. receive_side_cc_.OnBitrateChanged(target_bitrate_bps);
  925. bitrate_allocator_->OnNetworkEstimateChanged(msg);
  926. // Ignore updates if bitrate is zero (the aggregate network state is down).
  927. if (target_bitrate_bps == 0) {
  928. rtc::CritScope lock(&bitrate_crit_);
  929. estimated_send_bitrate_kbps_counter_.ProcessAndPause();
  930. pacer_bitrate_kbps_counter_.ProcessAndPause();
  931. return;
  932. }
  933. bool sending_video;
  934. {
  935. ReadLockScoped read_lock(*send_crit_);
  936. sending_video = !video_send_streams_.empty();
  937. }
  938. rtc::CritScope lock(&bitrate_crit_);
  939. if (!sending_video) {
  940. // Do not update the stats if we are not sending video.
  941. estimated_send_bitrate_kbps_counter_.ProcessAndPause();
  942. pacer_bitrate_kbps_counter_.ProcessAndPause();
  943. return;
  944. }
  945. estimated_send_bitrate_kbps_counter_.Add(target_bitrate_bps / 1000);
  946. // Pacer bitrate may be higher than bitrate estimate if enforcing min bitrate.
  947. uint32_t pacer_bitrate_bps =
  948. std::max(target_bitrate_bps, min_allocated_send_bitrate_bps_);
  949. pacer_bitrate_kbps_counter_.Add(pacer_bitrate_bps / 1000);
  950. }
  951. void Call::OnAllocationLimitsChanged(BitrateAllocationLimits limits) {
  952. RTC_DCHECK(network_queue()->IsCurrent());
  953. RTC_DCHECK_RUN_ON(&worker_sequence_checker_);
  954. transport_send_ptr_->SetAllocatedSendBitrateLimits(limits);
  955. min_allocated_send_bitrate_bps_ = limits.min_allocatable_rate.bps();
  956. rtc::CritScope lock(&bitrate_crit_);
  957. configured_max_padding_bitrate_bps_ = limits.max_padding_rate.bps();
  958. }
  959. void Call::ConfigureSync(const std::string& sync_group) {
  960. // Set sync only if there was no previous one.
  961. if (sync_group.empty())
  962. return;
  963. AudioReceiveStream* sync_audio_stream = nullptr;
  964. // Find existing audio stream.
  965. const auto it = sync_stream_mapping_.find(sync_group);
  966. if (it != sync_stream_mapping_.end()) {
  967. sync_audio_stream = it->second;
  968. } else {
  969. // No configured audio stream, see if we can find one.
  970. for (AudioReceiveStream* stream : audio_receive_streams_) {
  971. if (stream->config().sync_group == sync_group) {
  972. if (sync_audio_stream != nullptr) {
  973. RTC_LOG(LS_WARNING)
  974. << "Attempting to sync more than one audio stream "
  975. "within the same sync group. This is not "
  976. "supported in the current implementation.";
  977. break;
  978. }
  979. sync_audio_stream = stream;
  980. }
  981. }
  982. }
  983. if (sync_audio_stream)
  984. sync_stream_mapping_[sync_group] = sync_audio_stream;
  985. size_t num_synced_streams = 0;
  986. for (VideoReceiveStream* video_stream : video_receive_streams_) {
  987. if (video_stream->config().sync_group != sync_group)
  988. continue;
  989. ++num_synced_streams;
  990. if (num_synced_streams > 1) {
  991. // TODO(pbos): Support synchronizing more than one A/V pair.
  992. // https://code.google.com/p/webrtc/issues/detail?id=4762
  993. RTC_LOG(LS_WARNING)
  994. << "Attempting to sync more than one audio/video pair "
  995. "within the same sync group. This is not supported in "
  996. "the current implementation.";
  997. }
  998. // Only sync the first A/V pair within this sync group.
  999. if (num_synced_streams == 1) {
  1000. // sync_audio_stream may be null and that's ok.
  1001. video_stream->SetSync(sync_audio_stream);
  1002. } else {
  1003. video_stream->SetSync(nullptr);
  1004. }
  1005. }
  1006. }
  1007. PacketReceiver::DeliveryStatus Call::DeliverRtcp(MediaType media_type,
  1008. const uint8_t* packet,
  1009. size_t length) {
  1010. TRACE_EVENT0("webrtc", "Call::DeliverRtcp");
  1011. // TODO(pbos): Make sure it's a valid packet.
  1012. // Return DELIVERY_UNKNOWN_SSRC if it can be determined that
  1013. // there's no receiver of the packet.
  1014. if (received_bytes_per_second_counter_.HasSample()) {
  1015. // First RTP packet has been received.
  1016. received_bytes_per_second_counter_.Add(static_cast<int>(length));
  1017. received_rtcp_bytes_per_second_counter_.Add(static_cast<int>(length));
  1018. }
  1019. bool rtcp_delivered = false;
  1020. if (media_type == MediaType::ANY || media_type == MediaType::VIDEO) {
  1021. ReadLockScoped read_lock(*receive_crit_);
  1022. for (VideoReceiveStream* stream : video_receive_streams_) {
  1023. if (stream->DeliverRtcp(packet, length))
  1024. rtcp_delivered = true;
  1025. }
  1026. }
  1027. if (media_type == MediaType::ANY || media_type == MediaType::AUDIO) {
  1028. ReadLockScoped read_lock(*receive_crit_);
  1029. for (AudioReceiveStream* stream : audio_receive_streams_) {
  1030. stream->DeliverRtcp(packet, length);
  1031. rtcp_delivered = true;
  1032. }
  1033. }
  1034. if (media_type == MediaType::ANY || media_type == MediaType::VIDEO) {
  1035. ReadLockScoped read_lock(*send_crit_);
  1036. for (VideoSendStream* stream : video_send_streams_) {
  1037. stream->DeliverRtcp(packet, length);
  1038. rtcp_delivered = true;
  1039. }
  1040. }
  1041. if (media_type == MediaType::ANY || media_type == MediaType::AUDIO) {
  1042. ReadLockScoped read_lock(*send_crit_);
  1043. for (auto& kv : audio_send_ssrcs_) {
  1044. kv.second->DeliverRtcp(packet, length);
  1045. rtcp_delivered = true;
  1046. }
  1047. }
  1048. if (rtcp_delivered) {
  1049. event_log_->Log(std::make_unique<RtcEventRtcpPacketIncoming>(
  1050. rtc::MakeArrayView(packet, length)));
  1051. }
  1052. return rtcp_delivered ? DELIVERY_OK : DELIVERY_PACKET_ERROR;
  1053. }
  1054. PacketReceiver::DeliveryStatus Call::DeliverRtp(MediaType media_type,
  1055. rtc::CopyOnWriteBuffer packet,
  1056. int64_t packet_time_us) {
  1057. TRACE_EVENT0("webrtc", "Call::DeliverRtp");
  1058. RtpPacketReceived parsed_packet;
  1059. if (!parsed_packet.Parse(std::move(packet)))
  1060. return DELIVERY_PACKET_ERROR;
  1061. if (packet_time_us != -1) {
  1062. if (receive_time_calculator_) {
  1063. // Repair packet_time_us for clock resets by comparing a new read of
  1064. // the same clock (TimeUTCMicros) to a monotonic clock reading.
  1065. packet_time_us = receive_time_calculator_->ReconcileReceiveTimes(
  1066. packet_time_us, rtc::TimeUTCMicros(), clock_->TimeInMicroseconds());
  1067. }
  1068. parsed_packet.set_arrival_time_ms((packet_time_us + 500) / 1000);
  1069. } else {
  1070. parsed_packet.set_arrival_time_ms(clock_->TimeInMilliseconds());
  1071. }
  1072. // We might get RTP keep-alive packets in accordance with RFC6263 section 4.6.
  1073. // These are empty (zero length payload) RTP packets with an unsignaled
  1074. // payload type.
  1075. const bool is_keep_alive_packet = parsed_packet.payload_size() == 0;
  1076. RTC_DCHECK(media_type == MediaType::AUDIO || media_type == MediaType::VIDEO ||
  1077. is_keep_alive_packet);
  1078. ReadLockScoped read_lock(*receive_crit_);
  1079. auto it = receive_rtp_config_.find(parsed_packet.Ssrc());
  1080. if (it == receive_rtp_config_.end()) {
  1081. RTC_LOG(LS_ERROR) << "receive_rtp_config_ lookup failed for ssrc "
  1082. << parsed_packet.Ssrc();
  1083. // Destruction of the receive stream, including deregistering from the
  1084. // RtpDemuxer, is not protected by the |receive_crit_| lock. But
  1085. // deregistering in the |receive_rtp_config_| map is protected by that lock.
  1086. // So by not passing the packet on to demuxing in this case, we prevent
  1087. // incoming packets to be passed on via the demuxer to a receive stream
  1088. // which is being torned down.
  1089. return DELIVERY_UNKNOWN_SSRC;
  1090. }
  1091. parsed_packet.IdentifyExtensions(it->second.extensions);
  1092. NotifyBweOfReceivedPacket(parsed_packet, media_type);
  1093. // RateCounters expect input parameter as int, save it as int,
  1094. // instead of converting each time it is passed to RateCounter::Add below.
  1095. int length = static_cast<int>(parsed_packet.size());
  1096. if (media_type == MediaType::AUDIO) {
  1097. if (audio_receiver_controller_.OnRtpPacket(parsed_packet)) {
  1098. received_bytes_per_second_counter_.Add(length);
  1099. received_audio_bytes_per_second_counter_.Add(length);
  1100. event_log_->Log(
  1101. std::make_unique<RtcEventRtpPacketIncoming>(parsed_packet));
  1102. const int64_t arrival_time_ms = parsed_packet.arrival_time_ms();
  1103. if (!first_received_rtp_audio_ms_) {
  1104. first_received_rtp_audio_ms_.emplace(arrival_time_ms);
  1105. }
  1106. last_received_rtp_audio_ms_.emplace(arrival_time_ms);
  1107. return DELIVERY_OK;
  1108. }
  1109. } else if (media_type == MediaType::VIDEO) {
  1110. parsed_packet.set_payload_type_frequency(kVideoPayloadTypeFrequency);
  1111. if (video_receiver_controller_.OnRtpPacket(parsed_packet)) {
  1112. received_bytes_per_second_counter_.Add(length);
  1113. received_video_bytes_per_second_counter_.Add(length);
  1114. event_log_->Log(
  1115. std::make_unique<RtcEventRtpPacketIncoming>(parsed_packet));
  1116. const int64_t arrival_time_ms = parsed_packet.arrival_time_ms();
  1117. if (!first_received_rtp_video_ms_) {
  1118. first_received_rtp_video_ms_.emplace(arrival_time_ms);
  1119. }
  1120. last_received_rtp_video_ms_.emplace(arrival_time_ms);
  1121. return DELIVERY_OK;
  1122. }
  1123. }
  1124. return DELIVERY_UNKNOWN_SSRC;
  1125. }
  1126. PacketReceiver::DeliveryStatus Call::DeliverPacket(
  1127. MediaType media_type,
  1128. rtc::CopyOnWriteBuffer packet,
  1129. int64_t packet_time_us) {
  1130. RTC_DCHECK_RUN_ON(&configuration_sequence_checker_);
  1131. if (IsRtcp(packet.cdata(), packet.size()))
  1132. return DeliverRtcp(media_type, packet.cdata(), packet.size());
  1133. return DeliverRtp(media_type, std::move(packet), packet_time_us);
  1134. }
  1135. void Call::OnRecoveredPacket(const uint8_t* packet, size_t length) {
  1136. RtpPacketReceived parsed_packet;
  1137. if (!parsed_packet.Parse(packet, length))
  1138. return;
  1139. parsed_packet.set_recovered(true);
  1140. ReadLockScoped read_lock(*receive_crit_);
  1141. auto it = receive_rtp_config_.find(parsed_packet.Ssrc());
  1142. if (it == receive_rtp_config_.end()) {
  1143. RTC_LOG(LS_ERROR) << "receive_rtp_config_ lookup failed for ssrc "
  1144. << parsed_packet.Ssrc();
  1145. // Destruction of the receive stream, including deregistering from the
  1146. // RtpDemuxer, is not protected by the |receive_crit_| lock. But
  1147. // deregistering in the |receive_rtp_config_| map is protected by that lock.
  1148. // So by not passing the packet on to demuxing in this case, we prevent
  1149. // incoming packets to be passed on via the demuxer to a receive stream
  1150. // which is being torn down.
  1151. return;
  1152. }
  1153. parsed_packet.IdentifyExtensions(it->second.extensions);
  1154. // TODO(brandtr): Update here when we support protecting audio packets too.
  1155. parsed_packet.set_payload_type_frequency(kVideoPayloadTypeFrequency);
  1156. video_receiver_controller_.OnRtpPacket(parsed_packet);
  1157. }
  1158. void Call::NotifyBweOfReceivedPacket(const RtpPacketReceived& packet,
  1159. MediaType media_type) {
  1160. auto it = receive_rtp_config_.find(packet.Ssrc());
  1161. bool use_send_side_bwe =
  1162. (it != receive_rtp_config_.end()) && it->second.use_send_side_bwe;
  1163. RTPHeader header;
  1164. packet.GetHeader(&header);
  1165. ReceivedPacket packet_msg;
  1166. packet_msg.size = DataSize::bytes(packet.payload_size());
  1167. packet_msg.receive_time = Timestamp::ms(packet.arrival_time_ms());
  1168. if (header.extension.hasAbsoluteSendTime) {
  1169. packet_msg.send_time = header.extension.GetAbsoluteSendTimestamp();
  1170. }
  1171. transport_send_ptr_->OnReceivedPacket(packet_msg);
  1172. if (!use_send_side_bwe && header.extension.hasTransportSequenceNumber) {
  1173. // Inconsistent configuration of send side BWE. Do nothing.
  1174. // TODO(nisse): Without this check, we may produce RTCP feedback
  1175. // packets even when not negotiated. But it would be cleaner to
  1176. // move the check down to RTCPSender::SendFeedbackPacket, which
  1177. // would also help the PacketRouter to select an appropriate rtp
  1178. // module in the case that some, but not all, have RTCP feedback
  1179. // enabled.
  1180. return;
  1181. }
  1182. // For audio, we only support send side BWE.
  1183. if (media_type == MediaType::VIDEO ||
  1184. (use_send_side_bwe && header.extension.hasTransportSequenceNumber)) {
  1185. receive_side_cc_.OnReceivedPacket(
  1186. packet.arrival_time_ms(), packet.payload_size() + packet.padding_size(),
  1187. header);
  1188. }
  1189. }
  1190. } // namespace internal
  1191. } // namespace webrtc