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.

1397 lines
50 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  2. * Copyright 2004 The WebRTC project authors. All Rights Reserved.
  3. *
  4. * Use of this source code is governed by a BSD-style license
  5. * that can be found in the LICENSE file in the root of the source
  6. * tree. An additional intellectual property rights grant can be found
  7. * in the file PATENTS. All contributing project authors may
  8. * be found in the AUTHORS file in the root of the source tree.
  9. */
  10. #include "pc/channel.h"
  11. #include <iterator>
  12. #include <utility>
  13. #include "absl/algorithm/container.h"
  14. #include "absl/memory/memory.h"
  15. #include "api/call/audio_sink.h"
  16. #include "api/transport/media/media_transport_config.h"
  17. #include "media/base/media_constants.h"
  18. #include "media/base/rtp_utils.h"
  19. #include "modules/rtp_rtcp/source/rtp_packet_received.h"
  20. #include "p2p/base/packet_transport_internal.h"
  21. #include "pc/channel_manager.h"
  22. #include "pc/rtp_media_utils.h"
  23. #include "rtc_base/bind.h"
  24. #include "rtc_base/byte_order.h"
  25. #include "rtc_base/checks.h"
  26. #include "rtc_base/copy_on_write_buffer.h"
  27. #include "rtc_base/dscp.h"
  28. #include "rtc_base/logging.h"
  29. #include "rtc_base/network_route.h"
  30. #include "rtc_base/strings/string_builder.h"
  31. #include "rtc_base/trace_event.h"
  32. namespace cricket {
  33. using rtc::Bind;
  34. using rtc::UniqueRandomIdGenerator;
  35. using webrtc::SdpType;
  36. namespace {
  37. struct SendPacketMessageData : public rtc::MessageData {
  38. rtc::CopyOnWriteBuffer packet;
  39. rtc::PacketOptions options;
  40. };
  41. // Finds a stream based on target's Primary SSRC or RIDs.
  42. // This struct is used in BaseChannel::UpdateLocalStreams_w.
  43. struct StreamFinder {
  44. explicit StreamFinder(const StreamParams* target) : target_(target) {
  45. RTC_DCHECK(target);
  46. }
  47. bool operator()(const StreamParams& sp) const {
  48. if (target_->has_ssrcs() && sp.has_ssrcs()) {
  49. return sp.has_ssrc(target_->first_ssrc());
  50. }
  51. if (!target_->has_rids() && !sp.has_rids()) {
  52. return false;
  53. }
  54. const std::vector<RidDescription>& target_rids = target_->rids();
  55. const std::vector<RidDescription>& source_rids = sp.rids();
  56. if (source_rids.size() != target_rids.size()) {
  57. return false;
  58. }
  59. // Check that all RIDs match.
  60. return std::equal(source_rids.begin(), source_rids.end(),
  61. target_rids.begin(),
  62. [](const RidDescription& lhs, const RidDescription& rhs) {
  63. return lhs.rid == rhs.rid;
  64. });
  65. }
  66. const StreamParams* target_;
  67. };
  68. } // namespace
  69. enum {
  70. MSG_SEND_RTP_PACKET = 1,
  71. MSG_SEND_RTCP_PACKET,
  72. MSG_READYTOSENDDATA,
  73. MSG_DATARECEIVED,
  74. MSG_FIRSTPACKETRECEIVED,
  75. };
  76. static void SafeSetError(const std::string& message, std::string* error_desc) {
  77. if (error_desc) {
  78. *error_desc = message;
  79. }
  80. }
  81. template <class Codec>
  82. void RtpParametersFromMediaDescription(
  83. const MediaContentDescriptionImpl<Codec>* desc,
  84. const RtpHeaderExtensions& extensions,
  85. RtpParameters<Codec>* params) {
  86. // TODO(pthatcher): Remove this once we're sure no one will give us
  87. // a description without codecs. Currently the ORTC implementation is relying
  88. // on this.
  89. if (desc->has_codecs()) {
  90. params->codecs = desc->codecs();
  91. }
  92. // TODO(pthatcher): See if we really need
  93. // rtp_header_extensions_set() and remove it if we don't.
  94. if (desc->rtp_header_extensions_set()) {
  95. params->extensions = extensions;
  96. }
  97. params->rtcp.reduced_size = desc->rtcp_reduced_size();
  98. params->rtcp.remote_estimate = desc->remote_estimate();
  99. }
  100. template <class Codec>
  101. void RtpSendParametersFromMediaDescription(
  102. const MediaContentDescriptionImpl<Codec>* desc,
  103. const RtpHeaderExtensions& extensions,
  104. RtpSendParameters<Codec>* send_params) {
  105. RtpParametersFromMediaDescription(desc, extensions, send_params);
  106. send_params->max_bandwidth_bps = desc->bandwidth();
  107. send_params->extmap_allow_mixed = desc->extmap_allow_mixed();
  108. }
  109. BaseChannel::BaseChannel(rtc::Thread* worker_thread,
  110. rtc::Thread* network_thread,
  111. rtc::Thread* signaling_thread,
  112. std::unique_ptr<MediaChannel> media_channel,
  113. const std::string& content_name,
  114. bool srtp_required,
  115. webrtc::CryptoOptions crypto_options,
  116. UniqueRandomIdGenerator* ssrc_generator)
  117. : worker_thread_(worker_thread),
  118. network_thread_(network_thread),
  119. signaling_thread_(signaling_thread),
  120. content_name_(content_name),
  121. srtp_required_(srtp_required),
  122. crypto_options_(crypto_options),
  123. media_channel_(std::move(media_channel)),
  124. ssrc_generator_(ssrc_generator) {
  125. RTC_DCHECK_RUN_ON(worker_thread_);
  126. RTC_DCHECK(ssrc_generator_);
  127. demuxer_criteria_.mid = content_name;
  128. RTC_LOG(LS_INFO) << "Created channel for " << content_name;
  129. }
  130. BaseChannel::~BaseChannel() {
  131. TRACE_EVENT0("webrtc", "BaseChannel::~BaseChannel");
  132. RTC_DCHECK_RUN_ON(worker_thread_);
  133. if (media_transport_config_.media_transport) {
  134. media_transport_config_.media_transport->RemoveNetworkChangeCallback(this);
  135. }
  136. // Eats any outstanding messages or packets.
  137. worker_thread_->Clear(&invoker_);
  138. worker_thread_->Clear(this);
  139. // We must destroy the media channel before the transport channel, otherwise
  140. // the media channel may try to send on the dead transport channel. NULLing
  141. // is not an effective strategy since the sends will come on another thread.
  142. media_channel_.reset();
  143. RTC_LOG(LS_INFO) << "Destroyed channel: " << content_name_;
  144. }
  145. bool BaseChannel::ConnectToRtpTransport() {
  146. RTC_DCHECK(rtp_transport_);
  147. if (!RegisterRtpDemuxerSink()) {
  148. return false;
  149. }
  150. rtp_transport_->SignalReadyToSend.connect(
  151. this, &BaseChannel::OnTransportReadyToSend);
  152. // If media transport is used, it's responsible for providing network
  153. // route changed callbacks.
  154. if (!media_transport_config_.media_transport) {
  155. rtp_transport_->SignalNetworkRouteChanged.connect(
  156. this, &BaseChannel::OnNetworkRouteChanged);
  157. }
  158. // TODO(bugs.webrtc.org/9719): Media transport should also be used to provide
  159. // 'writable' state here.
  160. rtp_transport_->SignalWritableState.connect(this,
  161. &BaseChannel::OnWritableState);
  162. rtp_transport_->SignalSentPacket.connect(this,
  163. &BaseChannel::SignalSentPacket_n);
  164. return true;
  165. }
  166. void BaseChannel::DisconnectFromRtpTransport() {
  167. RTC_DCHECK(rtp_transport_);
  168. rtp_transport_->UnregisterRtpDemuxerSink(this);
  169. rtp_transport_->SignalReadyToSend.disconnect(this);
  170. rtp_transport_->SignalNetworkRouteChanged.disconnect(this);
  171. rtp_transport_->SignalWritableState.disconnect(this);
  172. rtp_transport_->SignalSentPacket.disconnect(this);
  173. }
  174. void BaseChannel::Init_w(
  175. webrtc::RtpTransportInternal* rtp_transport,
  176. const webrtc::MediaTransportConfig& media_transport_config) {
  177. RTC_DCHECK_RUN_ON(worker_thread_);
  178. media_transport_config_ = media_transport_config;
  179. network_thread_->Invoke<void>(
  180. RTC_FROM_HERE, [this, rtp_transport] { SetRtpTransport(rtp_transport); });
  181. // Both RTP and RTCP channels should be set, we can call SetInterface on
  182. // the media channel and it can set network options.
  183. media_channel_->SetInterface(this, media_transport_config);
  184. RTC_LOG(LS_INFO) << "BaseChannel::Init_w, media_transport_config="
  185. << media_transport_config.DebugString();
  186. if (media_transport_config_.media_transport) {
  187. media_transport_config_.media_transport->AddNetworkChangeCallback(this);
  188. }
  189. }
  190. void BaseChannel::Deinit() {
  191. RTC_DCHECK(worker_thread_->IsCurrent());
  192. media_channel_->SetInterface(/*iface=*/nullptr,
  193. webrtc::MediaTransportConfig());
  194. // Packets arrive on the network thread, processing packets calls virtual
  195. // functions, so need to stop this process in Deinit that is called in
  196. // derived classes destructor.
  197. network_thread_->Invoke<void>(RTC_FROM_HERE, [&] {
  198. FlushRtcpMessages_n();
  199. if (rtp_transport_) {
  200. DisconnectFromRtpTransport();
  201. }
  202. // Clear pending read packets/messages.
  203. network_thread_->Clear(&invoker_);
  204. network_thread_->Clear(this);
  205. });
  206. }
  207. bool BaseChannel::SetRtpTransport(webrtc::RtpTransportInternal* rtp_transport) {
  208. if (rtp_transport == rtp_transport_) {
  209. return true;
  210. }
  211. if (!network_thread_->IsCurrent()) {
  212. return network_thread_->Invoke<bool>(RTC_FROM_HERE, [this, rtp_transport] {
  213. return SetRtpTransport(rtp_transport);
  214. });
  215. }
  216. if (rtp_transport_) {
  217. DisconnectFromRtpTransport();
  218. }
  219. rtp_transport_ = rtp_transport;
  220. if (rtp_transport_) {
  221. transport_name_ = rtp_transport_->transport_name();
  222. if (!ConnectToRtpTransport()) {
  223. RTC_LOG(LS_ERROR) << "Failed to connect to the new RtpTransport.";
  224. return false;
  225. }
  226. OnTransportReadyToSend(rtp_transport_->IsReadyToSend());
  227. UpdateWritableState_n();
  228. // Set the cached socket options.
  229. for (const auto& pair : socket_options_) {
  230. rtp_transport_->SetRtpOption(pair.first, pair.second);
  231. }
  232. if (!rtp_transport_->rtcp_mux_enabled()) {
  233. for (const auto& pair : rtcp_socket_options_) {
  234. rtp_transport_->SetRtcpOption(pair.first, pair.second);
  235. }
  236. }
  237. }
  238. return true;
  239. }
  240. bool BaseChannel::Enable(bool enable) {
  241. worker_thread_->Invoke<void>(
  242. RTC_FROM_HERE,
  243. Bind(enable ? &BaseChannel::EnableMedia_w : &BaseChannel::DisableMedia_w,
  244. this));
  245. return true;
  246. }
  247. bool BaseChannel::SetLocalContent(const MediaContentDescription* content,
  248. SdpType type,
  249. std::string* error_desc) {
  250. TRACE_EVENT0("webrtc", "BaseChannel::SetLocalContent");
  251. return InvokeOnWorker<bool>(
  252. RTC_FROM_HERE,
  253. Bind(&BaseChannel::SetLocalContent_w, this, content, type, error_desc));
  254. }
  255. bool BaseChannel::SetRemoteContent(const MediaContentDescription* content,
  256. SdpType type,
  257. std::string* error_desc) {
  258. TRACE_EVENT0("webrtc", "BaseChannel::SetRemoteContent");
  259. return InvokeOnWorker<bool>(
  260. RTC_FROM_HERE,
  261. Bind(&BaseChannel::SetRemoteContent_w, this, content, type, error_desc));
  262. }
  263. bool BaseChannel::IsReadyToReceiveMedia_w() const {
  264. // Receive data if we are enabled and have local content,
  265. return enabled() &&
  266. webrtc::RtpTransceiverDirectionHasRecv(local_content_direction_);
  267. }
  268. bool BaseChannel::IsReadyToSendMedia_w() const {
  269. // Need to access some state updated on the network thread.
  270. return network_thread_->Invoke<bool>(
  271. RTC_FROM_HERE, Bind(&BaseChannel::IsReadyToSendMedia_n, this));
  272. }
  273. bool BaseChannel::IsReadyToSendMedia_n() const {
  274. // Send outgoing data if we are enabled, have local and remote content,
  275. // and we have had some form of connectivity.
  276. return enabled() &&
  277. webrtc::RtpTransceiverDirectionHasRecv(remote_content_direction_) &&
  278. webrtc::RtpTransceiverDirectionHasSend(local_content_direction_) &&
  279. was_ever_writable();
  280. }
  281. bool BaseChannel::SendPacket(rtc::CopyOnWriteBuffer* packet,
  282. const rtc::PacketOptions& options) {
  283. return SendPacket(false, packet, options);
  284. }
  285. bool BaseChannel::SendRtcp(rtc::CopyOnWriteBuffer* packet,
  286. const rtc::PacketOptions& options) {
  287. return SendPacket(true, packet, options);
  288. }
  289. int BaseChannel::SetOption(SocketType type,
  290. rtc::Socket::Option opt,
  291. int value) {
  292. return network_thread_->Invoke<int>(
  293. RTC_FROM_HERE, Bind(&BaseChannel::SetOption_n, this, type, opt, value));
  294. }
  295. int BaseChannel::SetOption_n(SocketType type,
  296. rtc::Socket::Option opt,
  297. int value) {
  298. RTC_DCHECK(network_thread_->IsCurrent());
  299. RTC_DCHECK(rtp_transport_);
  300. switch (type) {
  301. case ST_RTP:
  302. socket_options_.push_back(
  303. std::pair<rtc::Socket::Option, int>(opt, value));
  304. return rtp_transport_->SetRtpOption(opt, value);
  305. case ST_RTCP:
  306. rtcp_socket_options_.push_back(
  307. std::pair<rtc::Socket::Option, int>(opt, value));
  308. return rtp_transport_->SetRtcpOption(opt, value);
  309. }
  310. return -1;
  311. }
  312. void BaseChannel::OnWritableState(bool writable) {
  313. RTC_DCHECK(network_thread_->IsCurrent());
  314. if (writable) {
  315. ChannelWritable_n();
  316. } else {
  317. ChannelNotWritable_n();
  318. }
  319. }
  320. void BaseChannel::OnNetworkRouteChanged(
  321. absl::optional<rtc::NetworkRoute> network_route) {
  322. RTC_LOG(LS_INFO) << "Network route was changed.";
  323. RTC_DCHECK(network_thread_->IsCurrent());
  324. rtc::NetworkRoute new_route;
  325. if (network_route) {
  326. new_route = *(network_route);
  327. }
  328. // Note: When the RTCP-muxing is not enabled, RTCP transport and RTP transport
  329. // use the same transport name and MediaChannel::OnNetworkRouteChanged cannot
  330. // work correctly. Intentionally leave it broken to simplify the code and
  331. // encourage the users to stop using non-muxing RTCP.
  332. invoker_.AsyncInvoke<void>(RTC_FROM_HERE, worker_thread_, [=] {
  333. media_channel_->OnNetworkRouteChanged(transport_name_, new_route);
  334. });
  335. }
  336. void BaseChannel::OnTransportReadyToSend(bool ready) {
  337. invoker_.AsyncInvoke<void>(RTC_FROM_HERE, worker_thread_,
  338. [=] { media_channel_->OnReadyToSend(ready); });
  339. }
  340. bool BaseChannel::SendPacket(bool rtcp,
  341. rtc::CopyOnWriteBuffer* packet,
  342. const rtc::PacketOptions& options) {
  343. // Until all the code is migrated to use RtpPacketType instead of bool.
  344. RtpPacketType packet_type = rtcp ? RtpPacketType::kRtcp : RtpPacketType::kRtp;
  345. // SendPacket gets called from MediaEngine, on a pacer or an encoder thread.
  346. // If the thread is not our network thread, we will post to our network
  347. // so that the real work happens on our network. This avoids us having to
  348. // synchronize access to all the pieces of the send path, including
  349. // SRTP and the inner workings of the transport channels.
  350. // The only downside is that we can't return a proper failure code if
  351. // needed. Since UDP is unreliable anyway, this should be a non-issue.
  352. if (!network_thread_->IsCurrent()) {
  353. // Avoid a copy by transferring the ownership of the packet data.
  354. int message_id = rtcp ? MSG_SEND_RTCP_PACKET : MSG_SEND_RTP_PACKET;
  355. SendPacketMessageData* data = new SendPacketMessageData;
  356. data->packet = std::move(*packet);
  357. data->options = options;
  358. network_thread_->Post(RTC_FROM_HERE, this, message_id, data);
  359. return true;
  360. }
  361. TRACE_EVENT0("webrtc", "BaseChannel::SendPacket");
  362. // Now that we are on the correct thread, ensure we have a place to send this
  363. // packet before doing anything. (We might get RTCP packets that we don't
  364. // intend to send.) If we've negotiated RTCP mux, send RTCP over the RTP
  365. // transport.
  366. if (!rtp_transport_ || !rtp_transport_->IsWritable(rtcp)) {
  367. return false;
  368. }
  369. // Protect ourselves against crazy data.
  370. if (!IsValidRtpPacketSize(packet_type, packet->size())) {
  371. RTC_LOG(LS_ERROR) << "Dropping outgoing " << content_name_ << " "
  372. << RtpPacketTypeToString(packet_type)
  373. << " packet: wrong size=" << packet->size();
  374. return false;
  375. }
  376. if (!srtp_active()) {
  377. if (srtp_required_) {
  378. // The audio/video engines may attempt to send RTCP packets as soon as the
  379. // streams are created, so don't treat this as an error for RTCP.
  380. // See: https://bugs.chromium.org/p/webrtc/issues/detail?id=6809
  381. if (rtcp) {
  382. return false;
  383. }
  384. // However, there shouldn't be any RTP packets sent before SRTP is set up
  385. // (and SetSend(true) is called).
  386. RTC_LOG(LS_ERROR)
  387. << "Can't send outgoing RTP packet when SRTP is inactive"
  388. << " and crypto is required";
  389. RTC_NOTREACHED();
  390. return false;
  391. }
  392. std::string packet_type = rtcp ? "RTCP" : "RTP";
  393. RTC_LOG(LS_WARNING) << "Sending an " << packet_type
  394. << " packet without encryption.";
  395. }
  396. // Bon voyage.
  397. return rtcp ? rtp_transport_->SendRtcpPacket(packet, options, PF_SRTP_BYPASS)
  398. : rtp_transport_->SendRtpPacket(packet, options, PF_SRTP_BYPASS);
  399. }
  400. void BaseChannel::OnRtpPacket(const webrtc::RtpPacketReceived& parsed_packet) {
  401. // Take packet time from the |parsed_packet|.
  402. // RtpPacketReceived.arrival_time_ms = (timestamp_us + 500) / 1000;
  403. int64_t packet_time_us = -1;
  404. if (parsed_packet.arrival_time_ms() > 0) {
  405. packet_time_us = parsed_packet.arrival_time_ms() * 1000;
  406. }
  407. if (!has_received_packet_) {
  408. has_received_packet_ = true;
  409. signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FIRSTPACKETRECEIVED);
  410. }
  411. if (!srtp_active() && srtp_required_) {
  412. // Our session description indicates that SRTP is required, but we got a
  413. // packet before our SRTP filter is active. This means either that
  414. // a) we got SRTP packets before we received the SDES keys, in which case
  415. // we can't decrypt it anyway, or
  416. // b) we got SRTP packets before DTLS completed on both the RTP and RTCP
  417. // transports, so we haven't yet extracted keys, even if DTLS did
  418. // complete on the transport that the packets are being sent on. It's
  419. // really good practice to wait for both RTP and RTCP to be good to go
  420. // before sending media, to prevent weird failure modes, so it's fine
  421. // for us to just eat packets here. This is all sidestepped if RTCP mux
  422. // is used anyway.
  423. RTC_LOG(LS_WARNING) << "Can't process incoming RTP packet when "
  424. "SRTP is inactive and crypto is required";
  425. return;
  426. }
  427. auto packet_buffer = parsed_packet.Buffer();
  428. invoker_.AsyncInvoke<void>(
  429. RTC_FROM_HERE, worker_thread_, [this, packet_buffer, packet_time_us] {
  430. RTC_DCHECK(worker_thread_->IsCurrent());
  431. media_channel_->OnPacketReceived(packet_buffer, packet_time_us);
  432. });
  433. }
  434. void BaseChannel::UpdateRtpHeaderExtensionMap(
  435. const RtpHeaderExtensions& header_extensions) {
  436. RTC_DCHECK(rtp_transport_);
  437. // Update the header extension map on network thread in case there is data
  438. // race.
  439. // TODO(zhihuang): Add an rtc::ThreadChecker make sure to RtpTransport won't
  440. // be accessed from different threads.
  441. //
  442. // NOTE: This doesn't take the BUNDLE case in account meaning the RTP header
  443. // extension maps are not merged when BUNDLE is enabled. This is fine because
  444. // the ID for MID should be consistent among all the RTP transports.
  445. network_thread_->Invoke<void>(RTC_FROM_HERE, [this, &header_extensions] {
  446. rtp_transport_->UpdateRtpHeaderExtensionMap(header_extensions);
  447. });
  448. }
  449. bool BaseChannel::RegisterRtpDemuxerSink() {
  450. RTC_DCHECK(rtp_transport_);
  451. return network_thread_->Invoke<bool>(RTC_FROM_HERE, [this] {
  452. return rtp_transport_->RegisterRtpDemuxerSink(demuxer_criteria_, this);
  453. });
  454. }
  455. void BaseChannel::EnableMedia_w() {
  456. RTC_DCHECK(worker_thread_ == rtc::Thread::Current());
  457. if (enabled_)
  458. return;
  459. RTC_LOG(LS_INFO) << "Channel enabled";
  460. enabled_ = true;
  461. UpdateMediaSendRecvState_w();
  462. }
  463. void BaseChannel::DisableMedia_w() {
  464. RTC_DCHECK(worker_thread_ == rtc::Thread::Current());
  465. if (!enabled_)
  466. return;
  467. RTC_LOG(LS_INFO) << "Channel disabled";
  468. enabled_ = false;
  469. UpdateMediaSendRecvState_w();
  470. }
  471. void BaseChannel::UpdateWritableState_n() {
  472. if (rtp_transport_->IsWritable(/*rtcp=*/true) &&
  473. rtp_transport_->IsWritable(/*rtcp=*/false)) {
  474. ChannelWritable_n();
  475. } else {
  476. ChannelNotWritable_n();
  477. }
  478. }
  479. void BaseChannel::ChannelWritable_n() {
  480. RTC_DCHECK(network_thread_->IsCurrent());
  481. if (writable_) {
  482. return;
  483. }
  484. RTC_LOG(LS_INFO) << "Channel writable (" << content_name_ << ")"
  485. << (was_ever_writable_ ? "" : " for the first time");
  486. was_ever_writable_ = true;
  487. writable_ = true;
  488. UpdateMediaSendRecvState();
  489. }
  490. void BaseChannel::ChannelNotWritable_n() {
  491. RTC_DCHECK(network_thread_->IsCurrent());
  492. if (!writable_)
  493. return;
  494. RTC_LOG(LS_INFO) << "Channel not writable (" << content_name_ << ")";
  495. writable_ = false;
  496. UpdateMediaSendRecvState();
  497. }
  498. bool BaseChannel::AddRecvStream_w(const StreamParams& sp) {
  499. RTC_DCHECK(worker_thread() == rtc::Thread::Current());
  500. return media_channel()->AddRecvStream(sp);
  501. }
  502. bool BaseChannel::RemoveRecvStream_w(uint32_t ssrc) {
  503. RTC_DCHECK(worker_thread() == rtc::Thread::Current());
  504. return media_channel()->RemoveRecvStream(ssrc);
  505. }
  506. void BaseChannel::ResetUnsignaledRecvStream_w() {
  507. RTC_DCHECK(worker_thread() == rtc::Thread::Current());
  508. media_channel()->ResetUnsignaledRecvStream();
  509. }
  510. bool BaseChannel::UpdateLocalStreams_w(const std::vector<StreamParams>& streams,
  511. SdpType type,
  512. std::string* error_desc) {
  513. // In the case of RIDs (where SSRCs are not negotiated), this method will
  514. // generate an SSRC for each layer in StreamParams. That representation will
  515. // be stored internally in |local_streams_|.
  516. // In subsequent offers, the same stream can appear in |streams| again
  517. // (without the SSRCs), so it should be looked up using RIDs (if available)
  518. // and then by primary SSRC.
  519. // In both scenarios, it is safe to assume that the media channel will be
  520. // created with a StreamParams object with SSRCs. However, it is not safe to
  521. // assume that |local_streams_| will always have SSRCs as there are scenarios
  522. // in which niether SSRCs or RIDs are negotiated.
  523. // Check for streams that have been removed.
  524. bool ret = true;
  525. for (const StreamParams& old_stream : local_streams_) {
  526. if (!old_stream.has_ssrcs() ||
  527. GetStream(streams, StreamFinder(&old_stream))) {
  528. continue;
  529. }
  530. if (!media_channel()->RemoveSendStream(old_stream.first_ssrc())) {
  531. rtc::StringBuilder desc;
  532. desc << "Failed to remove send stream with ssrc "
  533. << old_stream.first_ssrc() << ".";
  534. SafeSetError(desc.str(), error_desc);
  535. ret = false;
  536. }
  537. }
  538. // Check for new streams.
  539. std::vector<StreamParams> all_streams;
  540. for (const StreamParams& stream : streams) {
  541. StreamParams* existing = GetStream(local_streams_, StreamFinder(&stream));
  542. if (existing) {
  543. // Parameters cannot change for an existing stream.
  544. all_streams.push_back(*existing);
  545. continue;
  546. }
  547. all_streams.push_back(stream);
  548. StreamParams& new_stream = all_streams.back();
  549. if (!new_stream.has_ssrcs() && !new_stream.has_rids()) {
  550. continue;
  551. }
  552. RTC_DCHECK(new_stream.has_ssrcs() || new_stream.has_rids());
  553. if (new_stream.has_ssrcs() && new_stream.has_rids()) {
  554. rtc::StringBuilder desc;
  555. desc << "Failed to add send stream: " << new_stream.first_ssrc()
  556. << ". Stream has both SSRCs and RIDs.";
  557. SafeSetError(desc.str(), error_desc);
  558. ret = false;
  559. continue;
  560. }
  561. // At this point we use the legacy simulcast group in StreamParams to
  562. // indicate that we want multiple layers to the media channel.
  563. if (!new_stream.has_ssrcs()) {
  564. // TODO(bugs.webrtc.org/10250): Indicate if flex is desired here.
  565. new_stream.GenerateSsrcs(new_stream.rids().size(), /* rtx = */ true,
  566. /* flex_fec = */ false, ssrc_generator_);
  567. }
  568. if (media_channel()->AddSendStream(new_stream)) {
  569. RTC_LOG(LS_INFO) << "Add send stream ssrc: " << new_stream.ssrcs[0];
  570. } else {
  571. rtc::StringBuilder desc;
  572. desc << "Failed to add send stream ssrc: " << new_stream.first_ssrc();
  573. SafeSetError(desc.str(), error_desc);
  574. ret = false;
  575. }
  576. }
  577. local_streams_ = all_streams;
  578. return ret;
  579. }
  580. bool BaseChannel::UpdateRemoteStreams_w(
  581. const std::vector<StreamParams>& streams,
  582. SdpType type,
  583. std::string* error_desc) {
  584. // Check for streams that have been removed.
  585. bool ret = true;
  586. for (const StreamParams& old_stream : remote_streams_) {
  587. // If we no longer have an unsignaled stream, we would like to remove
  588. // the unsignaled stream params that are cached.
  589. if (!old_stream.has_ssrcs() && !HasStreamWithNoSsrcs(streams)) {
  590. ResetUnsignaledRecvStream_w();
  591. RTC_LOG(LS_INFO) << "Reset unsignaled remote stream.";
  592. } else if (old_stream.has_ssrcs() &&
  593. !GetStreamBySsrc(streams, old_stream.first_ssrc())) {
  594. if (RemoveRecvStream_w(old_stream.first_ssrc())) {
  595. RTC_LOG(LS_INFO) << "Remove remote ssrc: " << old_stream.first_ssrc();
  596. } else {
  597. rtc::StringBuilder desc;
  598. desc << "Failed to remove remote stream with ssrc "
  599. << old_stream.first_ssrc() << ".";
  600. SafeSetError(desc.str(), error_desc);
  601. ret = false;
  602. }
  603. }
  604. }
  605. demuxer_criteria_.ssrcs.clear();
  606. // Check for new streams.
  607. for (const StreamParams& new_stream : streams) {
  608. // We allow a StreamParams with an empty list of SSRCs, in which case the
  609. // MediaChannel will cache the parameters and use them for any unsignaled
  610. // stream received later.
  611. if ((!new_stream.has_ssrcs() && !HasStreamWithNoSsrcs(remote_streams_)) ||
  612. !GetStreamBySsrc(remote_streams_, new_stream.first_ssrc())) {
  613. if (AddRecvStream_w(new_stream)) {
  614. RTC_LOG(LS_INFO) << "Add remote ssrc: "
  615. << (new_stream.has_ssrcs()
  616. ? std::to_string(new_stream.first_ssrc())
  617. : "unsignaled");
  618. } else {
  619. rtc::StringBuilder desc;
  620. desc << "Failed to add remote stream ssrc: "
  621. << (new_stream.has_ssrcs()
  622. ? std::to_string(new_stream.first_ssrc())
  623. : "unsignaled");
  624. SafeSetError(desc.str(), error_desc);
  625. ret = false;
  626. }
  627. }
  628. // Update the receiving SSRCs.
  629. demuxer_criteria_.ssrcs.insert(new_stream.ssrcs.begin(),
  630. new_stream.ssrcs.end());
  631. }
  632. // Re-register the sink to update the receiving ssrcs.
  633. RegisterRtpDemuxerSink();
  634. remote_streams_ = streams;
  635. return ret;
  636. }
  637. RtpHeaderExtensions BaseChannel::GetFilteredRtpHeaderExtensions(
  638. const RtpHeaderExtensions& extensions) {
  639. RTC_DCHECK(rtp_transport_);
  640. if (crypto_options_.srtp.enable_encrypted_rtp_header_extensions) {
  641. RtpHeaderExtensions filtered;
  642. absl::c_copy_if(extensions, std::back_inserter(filtered),
  643. [](const webrtc::RtpExtension& extension) {
  644. return !extension.encrypt;
  645. });
  646. return filtered;
  647. }
  648. return webrtc::RtpExtension::FilterDuplicateNonEncrypted(extensions);
  649. }
  650. void BaseChannel::OnMessage(rtc::Message* pmsg) {
  651. TRACE_EVENT0("webrtc", "BaseChannel::OnMessage");
  652. switch (pmsg->message_id) {
  653. case MSG_SEND_RTP_PACKET:
  654. case MSG_SEND_RTCP_PACKET: {
  655. RTC_DCHECK(network_thread_->IsCurrent());
  656. SendPacketMessageData* data =
  657. static_cast<SendPacketMessageData*>(pmsg->pdata);
  658. bool rtcp = pmsg->message_id == MSG_SEND_RTCP_PACKET;
  659. SendPacket(rtcp, &data->packet, data->options);
  660. delete data;
  661. break;
  662. }
  663. case MSG_FIRSTPACKETRECEIVED: {
  664. SignalFirstPacketReceived_(this);
  665. break;
  666. }
  667. }
  668. }
  669. void BaseChannel::AddHandledPayloadType(int payload_type) {
  670. demuxer_criteria_.payload_types.insert(static_cast<uint8_t>(payload_type));
  671. }
  672. void BaseChannel::ClearHandledPayloadTypes() {
  673. demuxer_criteria_.payload_types.clear();
  674. }
  675. void BaseChannel::FlushRtcpMessages_n() {
  676. // Flush all remaining RTCP messages. This should only be called in
  677. // destructor.
  678. RTC_DCHECK(network_thread_->IsCurrent());
  679. rtc::MessageList rtcp_messages;
  680. network_thread_->Clear(this, MSG_SEND_RTCP_PACKET, &rtcp_messages);
  681. for (const auto& message : rtcp_messages) {
  682. network_thread_->Send(RTC_FROM_HERE, this, MSG_SEND_RTCP_PACKET,
  683. message.pdata);
  684. }
  685. }
  686. void BaseChannel::SignalSentPacket_n(const rtc::SentPacket& sent_packet) {
  687. RTC_DCHECK(network_thread_->IsCurrent());
  688. invoker_.AsyncInvoke<void>(RTC_FROM_HERE, worker_thread_,
  689. [this, sent_packet] {
  690. RTC_DCHECK(worker_thread_->IsCurrent());
  691. SignalSentPacket(sent_packet);
  692. });
  693. }
  694. VoiceChannel::VoiceChannel(rtc::Thread* worker_thread,
  695. rtc::Thread* network_thread,
  696. rtc::Thread* signaling_thread,
  697. std::unique_ptr<VoiceMediaChannel> media_channel,
  698. const std::string& content_name,
  699. bool srtp_required,
  700. webrtc::CryptoOptions crypto_options,
  701. UniqueRandomIdGenerator* ssrc_generator)
  702. : BaseChannel(worker_thread,
  703. network_thread,
  704. signaling_thread,
  705. std::move(media_channel),
  706. content_name,
  707. srtp_required,
  708. crypto_options,
  709. ssrc_generator) {}
  710. VoiceChannel::~VoiceChannel() {
  711. if (media_transport()) {
  712. media_transport()->SetFirstAudioPacketReceivedObserver(nullptr);
  713. }
  714. TRACE_EVENT0("webrtc", "VoiceChannel::~VoiceChannel");
  715. // this can't be done in the base class, since it calls a virtual
  716. DisableMedia_w();
  717. Deinit();
  718. }
  719. void BaseChannel::UpdateMediaSendRecvState() {
  720. RTC_DCHECK(network_thread_->IsCurrent());
  721. invoker_.AsyncInvoke<void>(RTC_FROM_HERE, worker_thread_,
  722. [this] { UpdateMediaSendRecvState_w(); });
  723. }
  724. void BaseChannel::OnNetworkRouteChanged(
  725. const rtc::NetworkRoute& network_route) {
  726. OnNetworkRouteChanged(absl::make_optional(network_route));
  727. }
  728. void VoiceChannel::Init_w(
  729. webrtc::RtpTransportInternal* rtp_transport,
  730. const webrtc::MediaTransportConfig& media_transport_config) {
  731. BaseChannel::Init_w(rtp_transport, media_transport_config);
  732. if (media_transport_config.media_transport) {
  733. media_transport_config.media_transport->SetFirstAudioPacketReceivedObserver(
  734. this);
  735. }
  736. }
  737. void VoiceChannel::OnFirstAudioPacketReceived(int64_t channel_id) {
  738. has_received_packet_ = true;
  739. signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FIRSTPACKETRECEIVED);
  740. }
  741. void VoiceChannel::UpdateMediaSendRecvState_w() {
  742. // Render incoming data if we're the active call, and we have the local
  743. // content. We receive data on the default channel and multiplexed streams.
  744. bool recv = IsReadyToReceiveMedia_w();
  745. media_channel()->SetPlayout(recv);
  746. // Send outgoing data if we're the active call, we have the remote content,
  747. // and we have had some form of connectivity.
  748. bool send = IsReadyToSendMedia_w();
  749. media_channel()->SetSend(send);
  750. RTC_LOG(LS_INFO) << "Changing voice state, recv=" << recv << " send=" << send;
  751. }
  752. bool VoiceChannel::SetLocalContent_w(const MediaContentDescription* content,
  753. SdpType type,
  754. std::string* error_desc) {
  755. TRACE_EVENT0("webrtc", "VoiceChannel::SetLocalContent_w");
  756. RTC_DCHECK_RUN_ON(worker_thread());
  757. RTC_LOG(LS_INFO) << "Setting local voice description";
  758. RTC_DCHECK(content);
  759. if (!content) {
  760. SafeSetError("Can't find audio content in local description.", error_desc);
  761. return false;
  762. }
  763. const AudioContentDescription* audio = content->as_audio();
  764. RtpHeaderExtensions rtp_header_extensions =
  765. GetFilteredRtpHeaderExtensions(audio->rtp_header_extensions());
  766. UpdateRtpHeaderExtensionMap(rtp_header_extensions);
  767. media_channel()->SetExtmapAllowMixed(audio->extmap_allow_mixed());
  768. AudioRecvParameters recv_params = last_recv_params_;
  769. RtpParametersFromMediaDescription(audio, rtp_header_extensions, &recv_params);
  770. if (!media_channel()->SetRecvParameters(recv_params)) {
  771. SafeSetError("Failed to set local audio description recv parameters.",
  772. error_desc);
  773. return false;
  774. }
  775. if (webrtc::RtpTransceiverDirectionHasRecv(audio->direction())) {
  776. for (const AudioCodec& codec : audio->codecs()) {
  777. AddHandledPayloadType(codec.id);
  778. }
  779. // Need to re-register the sink to update the handled payload.
  780. if (!RegisterRtpDemuxerSink()) {
  781. RTC_LOG(LS_ERROR) << "Failed to set up audio demuxing.";
  782. return false;
  783. }
  784. }
  785. last_recv_params_ = recv_params;
  786. // TODO(pthatcher): Move local streams into AudioSendParameters, and
  787. // only give it to the media channel once we have a remote
  788. // description too (without a remote description, we won't be able
  789. // to send them anyway).
  790. if (!UpdateLocalStreams_w(audio->streams(), type, error_desc)) {
  791. SafeSetError("Failed to set local audio description streams.", error_desc);
  792. return false;
  793. }
  794. set_local_content_direction(content->direction());
  795. UpdateMediaSendRecvState_w();
  796. return true;
  797. }
  798. bool VoiceChannel::SetRemoteContent_w(const MediaContentDescription* content,
  799. SdpType type,
  800. std::string* error_desc) {
  801. TRACE_EVENT0("webrtc", "VoiceChannel::SetRemoteContent_w");
  802. RTC_DCHECK_RUN_ON(worker_thread());
  803. RTC_LOG(LS_INFO) << "Setting remote voice description";
  804. RTC_DCHECK(content);
  805. if (!content) {
  806. SafeSetError("Can't find audio content in remote description.", error_desc);
  807. return false;
  808. }
  809. const AudioContentDescription* audio = content->as_audio();
  810. RtpHeaderExtensions rtp_header_extensions =
  811. GetFilteredRtpHeaderExtensions(audio->rtp_header_extensions());
  812. AudioSendParameters send_params = last_send_params_;
  813. RtpSendParametersFromMediaDescription(audio, rtp_header_extensions,
  814. &send_params);
  815. send_params.mid = content_name();
  816. bool parameters_applied = media_channel()->SetSendParameters(send_params);
  817. if (!parameters_applied) {
  818. SafeSetError("Failed to set remote audio description send parameters.",
  819. error_desc);
  820. return false;
  821. }
  822. last_send_params_ = send_params;
  823. if (!webrtc::RtpTransceiverDirectionHasSend(content->direction())) {
  824. RTC_DLOG(LS_VERBOSE) << "SetRemoteContent_w: remote side will not send - "
  825. "disable payload type demuxing";
  826. ClearHandledPayloadTypes();
  827. if (!RegisterRtpDemuxerSink()) {
  828. RTC_LOG(LS_ERROR) << "Failed to update audio demuxing.";
  829. return false;
  830. }
  831. }
  832. // TODO(pthatcher): Move remote streams into AudioRecvParameters,
  833. // and only give it to the media channel once we have a local
  834. // description too (without a local description, we won't be able to
  835. // recv them anyway).
  836. if (!UpdateRemoteStreams_w(audio->streams(), type, error_desc)) {
  837. SafeSetError("Failed to set remote audio description streams.", error_desc);
  838. return false;
  839. }
  840. set_remote_content_direction(content->direction());
  841. UpdateMediaSendRecvState_w();
  842. return true;
  843. }
  844. VideoChannel::VideoChannel(rtc::Thread* worker_thread,
  845. rtc::Thread* network_thread,
  846. rtc::Thread* signaling_thread,
  847. std::unique_ptr<VideoMediaChannel> media_channel,
  848. const std::string& content_name,
  849. bool srtp_required,
  850. webrtc::CryptoOptions crypto_options,
  851. UniqueRandomIdGenerator* ssrc_generator)
  852. : BaseChannel(worker_thread,
  853. network_thread,
  854. signaling_thread,
  855. std::move(media_channel),
  856. content_name,
  857. srtp_required,
  858. crypto_options,
  859. ssrc_generator) {}
  860. VideoChannel::~VideoChannel() {
  861. TRACE_EVENT0("webrtc", "VideoChannel::~VideoChannel");
  862. // this can't be done in the base class, since it calls a virtual
  863. DisableMedia_w();
  864. Deinit();
  865. }
  866. void VideoChannel::UpdateMediaSendRecvState_w() {
  867. // Send outgoing data if we're the active call, we have the remote content,
  868. // and we have had some form of connectivity.
  869. bool send = IsReadyToSendMedia_w();
  870. if (!media_channel()->SetSend(send)) {
  871. RTC_LOG(LS_ERROR) << "Failed to SetSend on video channel";
  872. // TODO(gangji): Report error back to server.
  873. }
  874. RTC_LOG(LS_INFO) << "Changing video state, send=" << send;
  875. }
  876. void VideoChannel::FillBitrateInfo(BandwidthEstimationInfo* bwe_info) {
  877. InvokeOnWorker<void>(RTC_FROM_HERE, Bind(&VideoMediaChannel::FillBitrateInfo,
  878. media_channel(), bwe_info));
  879. }
  880. bool VideoChannel::SetLocalContent_w(const MediaContentDescription* content,
  881. SdpType type,
  882. std::string* error_desc) {
  883. TRACE_EVENT0("webrtc", "VideoChannel::SetLocalContent_w");
  884. RTC_DCHECK_RUN_ON(worker_thread());
  885. RTC_LOG(LS_INFO) << "Setting local video description";
  886. RTC_DCHECK(content);
  887. if (!content) {
  888. SafeSetError("Can't find video content in local description.", error_desc);
  889. return false;
  890. }
  891. const VideoContentDescription* video = content->as_video();
  892. RtpHeaderExtensions rtp_header_extensions =
  893. GetFilteredRtpHeaderExtensions(video->rtp_header_extensions());
  894. UpdateRtpHeaderExtensionMap(rtp_header_extensions);
  895. media_channel()->SetExtmapAllowMixed(video->extmap_allow_mixed());
  896. VideoRecvParameters recv_params = last_recv_params_;
  897. RtpParametersFromMediaDescription(video, rtp_header_extensions, &recv_params);
  898. VideoSendParameters send_params = last_send_params_;
  899. bool needs_send_params_update = false;
  900. if (type == SdpType::kAnswer || type == SdpType::kPrAnswer) {
  901. for (auto& send_codec : send_params.codecs) {
  902. auto* recv_codec = FindMatchingCodec(recv_params.codecs, send_codec);
  903. if (recv_codec) {
  904. if (!recv_codec->packetization && send_codec.packetization) {
  905. send_codec.packetization.reset();
  906. needs_send_params_update = true;
  907. } else if (recv_codec->packetization != send_codec.packetization) {
  908. SafeSetError(
  909. "Failed to set local answer due to invalid codec packetization.",
  910. error_desc);
  911. return false;
  912. }
  913. }
  914. }
  915. }
  916. if (!media_channel()->SetRecvParameters(recv_params)) {
  917. SafeSetError("Failed to set local video description recv parameters.",
  918. error_desc);
  919. return false;
  920. }
  921. if (webrtc::RtpTransceiverDirectionHasRecv(video->direction())) {
  922. for (const VideoCodec& codec : video->codecs()) {
  923. AddHandledPayloadType(codec.id);
  924. }
  925. // Need to re-register the sink to update the handled payload.
  926. if (!RegisterRtpDemuxerSink()) {
  927. RTC_LOG(LS_ERROR) << "Failed to set up video demuxing.";
  928. return false;
  929. }
  930. }
  931. last_recv_params_ = recv_params;
  932. if (needs_send_params_update) {
  933. if (!media_channel()->SetSendParameters(send_params)) {
  934. SafeSetError("Failed to set send parameters.", error_desc);
  935. return false;
  936. }
  937. last_send_params_ = send_params;
  938. }
  939. // TODO(pthatcher): Move local streams into VideoSendParameters, and
  940. // only give it to the media channel once we have a remote
  941. // description too (without a remote description, we won't be able
  942. // to send them anyway).
  943. if (!UpdateLocalStreams_w(video->streams(), type, error_desc)) {
  944. SafeSetError("Failed to set local video description streams.", error_desc);
  945. return false;
  946. }
  947. set_local_content_direction(content->direction());
  948. UpdateMediaSendRecvState_w();
  949. return true;
  950. }
  951. bool VideoChannel::SetRemoteContent_w(const MediaContentDescription* content,
  952. SdpType type,
  953. std::string* error_desc) {
  954. TRACE_EVENT0("webrtc", "VideoChannel::SetRemoteContent_w");
  955. RTC_DCHECK_RUN_ON(worker_thread());
  956. RTC_LOG(LS_INFO) << "Setting remote video description";
  957. RTC_DCHECK(content);
  958. if (!content) {
  959. SafeSetError("Can't find video content in remote description.", error_desc);
  960. return false;
  961. }
  962. const VideoContentDescription* video = content->as_video();
  963. RtpHeaderExtensions rtp_header_extensions =
  964. GetFilteredRtpHeaderExtensions(video->rtp_header_extensions());
  965. VideoSendParameters send_params = last_send_params_;
  966. RtpSendParametersFromMediaDescription(video, rtp_header_extensions,
  967. &send_params);
  968. if (video->conference_mode()) {
  969. send_params.conference_mode = true;
  970. }
  971. send_params.mid = content_name();
  972. VideoRecvParameters recv_params = last_recv_params_;
  973. bool needs_recv_params_update = false;
  974. if (type == SdpType::kAnswer || type == SdpType::kPrAnswer) {
  975. for (auto& recv_codec : recv_params.codecs) {
  976. auto* send_codec = FindMatchingCodec(send_params.codecs, recv_codec);
  977. if (send_codec) {
  978. if (!send_codec->packetization && recv_codec.packetization) {
  979. recv_codec.packetization.reset();
  980. needs_recv_params_update = true;
  981. } else if (send_codec->packetization != recv_codec.packetization) {
  982. SafeSetError(
  983. "Failed to set remote answer due to invalid codec packetization.",
  984. error_desc);
  985. return false;
  986. }
  987. }
  988. }
  989. }
  990. if (!media_channel()->SetSendParameters(send_params)) {
  991. SafeSetError("Failed to set remote video description send parameters.",
  992. error_desc);
  993. return false;
  994. }
  995. last_send_params_ = send_params;
  996. if (needs_recv_params_update) {
  997. if (!media_channel()->SetRecvParameters(recv_params)) {
  998. SafeSetError("Failed to set recv parameters.", error_desc);
  999. return false;
  1000. }
  1001. last_recv_params_ = recv_params;
  1002. }
  1003. if (!webrtc::RtpTransceiverDirectionHasSend(content->direction())) {
  1004. RTC_DLOG(LS_VERBOSE) << "SetRemoteContent_w: remote side will not send - "
  1005. "disable payload type demuxing";
  1006. ClearHandledPayloadTypes();
  1007. if (!RegisterRtpDemuxerSink()) {
  1008. RTC_LOG(LS_ERROR) << "Failed to update video demuxing.";
  1009. return false;
  1010. }
  1011. }
  1012. // TODO(pthatcher): Move remote streams into VideoRecvParameters,
  1013. // and only give it to the media channel once we have a local
  1014. // description too (without a local description, we won't be able to
  1015. // recv them anyway).
  1016. if (!UpdateRemoteStreams_w(video->streams(), type, error_desc)) {
  1017. SafeSetError("Failed to set remote video description streams.", error_desc);
  1018. return false;
  1019. }
  1020. set_remote_content_direction(content->direction());
  1021. UpdateMediaSendRecvState_w();
  1022. return true;
  1023. }
  1024. RtpDataChannel::RtpDataChannel(rtc::Thread* worker_thread,
  1025. rtc::Thread* network_thread,
  1026. rtc::Thread* signaling_thread,
  1027. std::unique_ptr<DataMediaChannel> media_channel,
  1028. const std::string& content_name,
  1029. bool srtp_required,
  1030. webrtc::CryptoOptions crypto_options,
  1031. UniqueRandomIdGenerator* ssrc_generator)
  1032. : BaseChannel(worker_thread,
  1033. network_thread,
  1034. signaling_thread,
  1035. std::move(media_channel),
  1036. content_name,
  1037. srtp_required,
  1038. crypto_options,
  1039. ssrc_generator) {}
  1040. RtpDataChannel::~RtpDataChannel() {
  1041. TRACE_EVENT0("webrtc", "RtpDataChannel::~RtpDataChannel");
  1042. // this can't be done in the base class, since it calls a virtual
  1043. DisableMedia_w();
  1044. Deinit();
  1045. }
  1046. void RtpDataChannel::Init_w(
  1047. webrtc::RtpTransportInternal* rtp_transport,
  1048. const webrtc::MediaTransportConfig& media_transport_config) {
  1049. BaseChannel::Init_w(rtp_transport, media_transport_config);
  1050. media_channel()->SignalDataReceived.connect(this,
  1051. &RtpDataChannel::OnDataReceived);
  1052. media_channel()->SignalReadyToSend.connect(
  1053. this, &RtpDataChannel::OnDataChannelReadyToSend);
  1054. }
  1055. bool RtpDataChannel::SendData(const SendDataParams& params,
  1056. const rtc::CopyOnWriteBuffer& payload,
  1057. SendDataResult* result) {
  1058. return InvokeOnWorker<bool>(
  1059. RTC_FROM_HERE, Bind(&DataMediaChannel::SendData, media_channel(), params,
  1060. payload, result));
  1061. }
  1062. bool RtpDataChannel::CheckDataChannelTypeFromContent(
  1063. const RtpDataContentDescription* content,
  1064. std::string* error_desc) {
  1065. bool is_sctp = ((content->protocol() == kMediaProtocolSctp) ||
  1066. (content->protocol() == kMediaProtocolDtlsSctp));
  1067. // It's been set before, but doesn't match. That's bad.
  1068. if (is_sctp) {
  1069. SafeSetError("Data channel type mismatch. Expected RTP, got SCTP.",
  1070. error_desc);
  1071. return false;
  1072. }
  1073. return true;
  1074. }
  1075. bool RtpDataChannel::SetLocalContent_w(const MediaContentDescription* content,
  1076. SdpType type,
  1077. std::string* error_desc) {
  1078. TRACE_EVENT0("webrtc", "RtpDataChannel::SetLocalContent_w");
  1079. RTC_DCHECK_RUN_ON(worker_thread());
  1080. RTC_LOG(LS_INFO) << "Setting local data description";
  1081. RTC_DCHECK(content);
  1082. if (!content) {
  1083. SafeSetError("Can't find data content in local description.", error_desc);
  1084. return false;
  1085. }
  1086. const RtpDataContentDescription* data = content->as_rtp_data();
  1087. if (!CheckDataChannelTypeFromContent(data, error_desc)) {
  1088. return false;
  1089. }
  1090. RtpHeaderExtensions rtp_header_extensions =
  1091. GetFilteredRtpHeaderExtensions(data->rtp_header_extensions());
  1092. DataRecvParameters recv_params = last_recv_params_;
  1093. RtpParametersFromMediaDescription(data, rtp_header_extensions, &recv_params);
  1094. if (!media_channel()->SetRecvParameters(recv_params)) {
  1095. SafeSetError("Failed to set remote data description recv parameters.",
  1096. error_desc);
  1097. return false;
  1098. }
  1099. for (const DataCodec& codec : data->codecs()) {
  1100. AddHandledPayloadType(codec.id);
  1101. }
  1102. // Need to re-register the sink to update the handled payload.
  1103. if (!RegisterRtpDemuxerSink()) {
  1104. RTC_LOG(LS_ERROR) << "Failed to set up data demuxing.";
  1105. return false;
  1106. }
  1107. last_recv_params_ = recv_params;
  1108. // TODO(pthatcher): Move local streams into DataSendParameters, and
  1109. // only give it to the media channel once we have a remote
  1110. // description too (without a remote description, we won't be able
  1111. // to send them anyway).
  1112. if (!UpdateLocalStreams_w(data->streams(), type, error_desc)) {
  1113. SafeSetError("Failed to set local data description streams.", error_desc);
  1114. return false;
  1115. }
  1116. set_local_content_direction(content->direction());
  1117. UpdateMediaSendRecvState_w();
  1118. return true;
  1119. }
  1120. bool RtpDataChannel::SetRemoteContent_w(const MediaContentDescription* content,
  1121. SdpType type,
  1122. std::string* error_desc) {
  1123. TRACE_EVENT0("webrtc", "RtpDataChannel::SetRemoteContent_w");
  1124. RTC_DCHECK_RUN_ON(worker_thread());
  1125. RTC_LOG(LS_INFO) << "Setting remote data description";
  1126. RTC_DCHECK(content);
  1127. if (!content) {
  1128. SafeSetError("Can't find data content in remote description.", error_desc);
  1129. return false;
  1130. }
  1131. const RtpDataContentDescription* data = content->as_rtp_data();
  1132. if (!data) {
  1133. RTC_LOG(LS_INFO) << "Accepting and ignoring non-RTP content description";
  1134. return true;
  1135. }
  1136. // If the remote data doesn't have codecs, it must be empty, so ignore it.
  1137. if (!data->has_codecs()) {
  1138. return true;
  1139. }
  1140. if (!CheckDataChannelTypeFromContent(data, error_desc)) {
  1141. return false;
  1142. }
  1143. RtpHeaderExtensions rtp_header_extensions =
  1144. GetFilteredRtpHeaderExtensions(data->rtp_header_extensions());
  1145. RTC_LOG(LS_INFO) << "Setting remote data description";
  1146. DataSendParameters send_params = last_send_params_;
  1147. RtpSendParametersFromMediaDescription<DataCodec>(data, rtp_header_extensions,
  1148. &send_params);
  1149. if (!media_channel()->SetSendParameters(send_params)) {
  1150. SafeSetError("Failed to set remote data description send parameters.",
  1151. error_desc);
  1152. return false;
  1153. }
  1154. last_send_params_ = send_params;
  1155. // TODO(pthatcher): Move remote streams into DataRecvParameters,
  1156. // and only give it to the media channel once we have a local
  1157. // description too (without a local description, we won't be able to
  1158. // recv them anyway).
  1159. if (!UpdateRemoteStreams_w(data->streams(), type, error_desc)) {
  1160. SafeSetError("Failed to set remote data description streams.", error_desc);
  1161. return false;
  1162. }
  1163. set_remote_content_direction(content->direction());
  1164. UpdateMediaSendRecvState_w();
  1165. return true;
  1166. }
  1167. void RtpDataChannel::UpdateMediaSendRecvState_w() {
  1168. // Render incoming data if we're the active call, and we have the local
  1169. // content. We receive data on the default channel and multiplexed streams.
  1170. bool recv = IsReadyToReceiveMedia_w();
  1171. if (!media_channel()->SetReceive(recv)) {
  1172. RTC_LOG(LS_ERROR) << "Failed to SetReceive on data channel";
  1173. }
  1174. // Send outgoing data if we're the active call, we have the remote content,
  1175. // and we have had some form of connectivity.
  1176. bool send = IsReadyToSendMedia_w();
  1177. if (!media_channel()->SetSend(send)) {
  1178. RTC_LOG(LS_ERROR) << "Failed to SetSend on data channel";
  1179. }
  1180. // Trigger SignalReadyToSendData asynchronously.
  1181. OnDataChannelReadyToSend(send);
  1182. RTC_LOG(LS_INFO) << "Changing data state, recv=" << recv << " send=" << send;
  1183. }
  1184. void RtpDataChannel::OnMessage(rtc::Message* pmsg) {
  1185. switch (pmsg->message_id) {
  1186. case MSG_READYTOSENDDATA: {
  1187. DataChannelReadyToSendMessageData* data =
  1188. static_cast<DataChannelReadyToSendMessageData*>(pmsg->pdata);
  1189. ready_to_send_data_ = data->data();
  1190. SignalReadyToSendData(ready_to_send_data_);
  1191. delete data;
  1192. break;
  1193. }
  1194. case MSG_DATARECEIVED: {
  1195. DataReceivedMessageData* data =
  1196. static_cast<DataReceivedMessageData*>(pmsg->pdata);
  1197. SignalDataReceived(data->params, data->payload);
  1198. delete data;
  1199. break;
  1200. }
  1201. default:
  1202. BaseChannel::OnMessage(pmsg);
  1203. break;
  1204. }
  1205. }
  1206. void RtpDataChannel::OnDataReceived(const ReceiveDataParams& params,
  1207. const char* data,
  1208. size_t len) {
  1209. DataReceivedMessageData* msg = new DataReceivedMessageData(params, data, len);
  1210. signaling_thread()->Post(RTC_FROM_HERE, this, MSG_DATARECEIVED, msg);
  1211. }
  1212. void RtpDataChannel::OnDataChannelReadyToSend(bool writable) {
  1213. // This is usded for congestion control to indicate that the stream is ready
  1214. // to send by the MediaChannel, as opposed to OnReadyToSend, which indicates
  1215. // that the transport channel is ready.
  1216. signaling_thread()->Post(RTC_FROM_HERE, this, MSG_READYTOSENDDATA,
  1217. new DataChannelReadyToSendMessageData(writable));
  1218. }
  1219. } // namespace cricket