channel.h 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  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. #ifndef PC_CHANNEL_H_
  11. #define PC_CHANNEL_H_
  12. #include <map>
  13. #include <memory>
  14. #include <set>
  15. #include <string>
  16. #include <utility>
  17. #include <vector>
  18. #include "api/call/audio_sink.h"
  19. #include "api/function_view.h"
  20. #include "api/jsep.h"
  21. #include "api/rtp_receiver_interface.h"
  22. #include "api/video/video_sink_interface.h"
  23. #include "api/video/video_source_interface.h"
  24. #include "call/rtp_packet_sink_interface.h"
  25. #include "media/base/media_channel.h"
  26. #include "media/base/media_engine.h"
  27. #include "media/base/stream_params.h"
  28. #include "p2p/base/dtls_transport_internal.h"
  29. #include "p2p/base/packet_transport_internal.h"
  30. #include "pc/channel_interface.h"
  31. #include "pc/dtls_srtp_transport.h"
  32. #include "pc/media_session.h"
  33. #include "pc/rtp_transport.h"
  34. #include "pc/srtp_filter.h"
  35. #include "pc/srtp_transport.h"
  36. #include "rtc_base/async_invoker.h"
  37. #include "rtc_base/async_udp_socket.h"
  38. #include "rtc_base/network.h"
  39. #include "rtc_base/synchronization/sequence_checker.h"
  40. #include "rtc_base/third_party/sigslot/sigslot.h"
  41. #include "rtc_base/thread_annotations.h"
  42. #include "rtc_base/unique_id_generator.h"
  43. namespace webrtc {
  44. class AudioSinkInterface;
  45. } // namespace webrtc
  46. namespace cricket {
  47. struct CryptoParams;
  48. // BaseChannel contains logic common to voice and video, including enable,
  49. // marshaling calls to a worker and network threads, and connection and media
  50. // monitors.
  51. //
  52. // BaseChannel assumes signaling and other threads are allowed to make
  53. // synchronous calls to the worker thread, the worker thread makes synchronous
  54. // calls only to the network thread, and the network thread can't be blocked by
  55. // other threads.
  56. // All methods with _n suffix must be called on network thread,
  57. // methods with _w suffix on worker thread
  58. // and methods with _s suffix on signaling thread.
  59. // Network and worker threads may be the same thread.
  60. //
  61. // WARNING! SUBCLASSES MUST CALL Deinit() IN THEIR DESTRUCTORS!
  62. // This is required to avoid a data race between the destructor modifying the
  63. // vtable, and the media channel's thread using BaseChannel as the
  64. // NetworkInterface.
  65. class BaseChannel : public ChannelInterface,
  66. public rtc::MessageHandlerAutoCleanup,
  67. public sigslot::has_slots<>,
  68. public MediaChannel::NetworkInterface,
  69. public webrtc::RtpPacketSinkInterface {
  70. public:
  71. // If |srtp_required| is true, the channel will not send or receive any
  72. // RTP/RTCP packets without using SRTP (either using SDES or DTLS-SRTP).
  73. // The BaseChannel does not own the UniqueRandomIdGenerator so it is the
  74. // responsibility of the user to ensure it outlives this object.
  75. // TODO(zhihuang:) Create a BaseChannel::Config struct for the parameter lists
  76. // which will make it easier to change the constructor.
  77. BaseChannel(rtc::Thread* worker_thread,
  78. rtc::Thread* network_thread,
  79. rtc::Thread* signaling_thread,
  80. std::unique_ptr<MediaChannel> media_channel,
  81. const std::string& content_name,
  82. bool srtp_required,
  83. webrtc::CryptoOptions crypto_options,
  84. rtc::UniqueRandomIdGenerator* ssrc_generator);
  85. virtual ~BaseChannel();
  86. virtual void Init_w(webrtc::RtpTransportInternal* rtp_transport);
  87. // Deinit may be called multiple times and is simply ignored if it's already
  88. // done.
  89. void Deinit();
  90. rtc::Thread* worker_thread() const { return worker_thread_; }
  91. rtc::Thread* network_thread() const { return network_thread_; }
  92. const std::string& content_name() const override { return content_name_; }
  93. // TODO(deadbeef): This is redundant; remove this.
  94. const std::string& transport_name() const override { return transport_name_; }
  95. bool enabled() const override { return enabled_; }
  96. // This function returns true if using SRTP (DTLS-based keying or SDES).
  97. bool srtp_active() const {
  98. return rtp_transport_ && rtp_transport_->IsSrtpActive();
  99. }
  100. bool writable() const { return writable_; }
  101. // Set an RTP level transport which could be an RtpTransport without
  102. // encryption, an SrtpTransport for SDES or a DtlsSrtpTransport for DTLS-SRTP.
  103. // This can be called from any thread and it hops to the network thread
  104. // internally. It would replace the |SetTransports| and its variants.
  105. bool SetRtpTransport(webrtc::RtpTransportInternal* rtp_transport) override;
  106. webrtc::RtpTransportInternal* rtp_transport() const { return rtp_transport_; }
  107. // Channel control
  108. bool SetLocalContent(const MediaContentDescription* content,
  109. webrtc::SdpType type,
  110. std::string* error_desc) override;
  111. bool SetRemoteContent(const MediaContentDescription* content,
  112. webrtc::SdpType type,
  113. std::string* error_desc) override;
  114. // Controls whether this channel will receive packets on the basis of
  115. // matching payload type alone. This is needed for legacy endpoints that
  116. // don't signal SSRCs or use MID/RID, but doesn't make sense if there is
  117. // more than channel of specific media type, As that creates an ambiguity.
  118. //
  119. // This method will also remove any existing streams that were bound to this
  120. // channel on the basis of payload type, since one of these streams might
  121. // actually belong to a new channel. See: crbug.com/webrtc/11477
  122. bool SetPayloadTypeDemuxingEnabled(bool enabled) override;
  123. bool Enable(bool enable) override;
  124. const std::vector<StreamParams>& local_streams() const override {
  125. return local_streams_;
  126. }
  127. const std::vector<StreamParams>& remote_streams() const override {
  128. return remote_streams_;
  129. }
  130. // Used for latency measurements.
  131. sigslot::signal1<ChannelInterface*>& SignalFirstPacketReceived() override;
  132. // Forward SignalSentPacket to worker thread.
  133. sigslot::signal1<const rtc::SentPacket&>& SignalSentPacket();
  134. // From RtpTransport - public for testing only
  135. void OnTransportReadyToSend(bool ready);
  136. // Only public for unit tests. Otherwise, consider protected.
  137. int SetOption(SocketType type, rtc::Socket::Option o, int val) override;
  138. int SetOption_n(SocketType type, rtc::Socket::Option o, int val);
  139. // RtpPacketSinkInterface overrides.
  140. void OnRtpPacket(const webrtc::RtpPacketReceived& packet) override;
  141. // Used by the RTCStatsCollector tests to set the transport name without
  142. // creating RtpTransports.
  143. void set_transport_name_for_testing(const std::string& transport_name) {
  144. transport_name_ = transport_name;
  145. }
  146. MediaChannel* media_channel() const override { return media_channel_.get(); }
  147. protected:
  148. bool was_ever_writable() const { return was_ever_writable_; }
  149. void set_local_content_direction(webrtc::RtpTransceiverDirection direction) {
  150. local_content_direction_ = direction;
  151. }
  152. void set_remote_content_direction(webrtc::RtpTransceiverDirection direction) {
  153. remote_content_direction_ = direction;
  154. }
  155. // These methods verify that:
  156. // * The required content description directions have been set.
  157. // * The channel is enabled.
  158. // * And for sending:
  159. // - The SRTP filter is active if it's needed.
  160. // - The transport has been writable before, meaning it should be at least
  161. // possible to succeed in sending a packet.
  162. //
  163. // When any of these properties change, UpdateMediaSendRecvState_w should be
  164. // called.
  165. bool IsReadyToReceiveMedia_w() const;
  166. bool IsReadyToSendMedia_w() const;
  167. rtc::Thread* signaling_thread() { return signaling_thread_; }
  168. void FlushRtcpMessages_n();
  169. // NetworkInterface implementation, called by MediaEngine
  170. bool SendPacket(rtc::CopyOnWriteBuffer* packet,
  171. const rtc::PacketOptions& options) override;
  172. bool SendRtcp(rtc::CopyOnWriteBuffer* packet,
  173. const rtc::PacketOptions& options) override;
  174. // From RtpTransportInternal
  175. void OnWritableState(bool writable);
  176. void OnNetworkRouteChanged(absl::optional<rtc::NetworkRoute> network_route);
  177. bool PacketIsRtcp(const rtc::PacketTransportInternal* transport,
  178. const char* data,
  179. size_t len);
  180. bool SendPacket(bool rtcp,
  181. rtc::CopyOnWriteBuffer* packet,
  182. const rtc::PacketOptions& options);
  183. void EnableMedia_w();
  184. void DisableMedia_w();
  185. // Performs actions if the RTP/RTCP writable state changed. This should
  186. // be called whenever a channel's writable state changes or when RTCP muxing
  187. // becomes active/inactive.
  188. void UpdateWritableState_n();
  189. void ChannelWritable_n();
  190. void ChannelNotWritable_n();
  191. bool AddRecvStream_w(const StreamParams& sp);
  192. bool RemoveRecvStream_w(uint32_t ssrc);
  193. void ResetUnsignaledRecvStream_w();
  194. bool SetPayloadTypeDemuxingEnabled_w(bool enabled);
  195. bool AddSendStream_w(const StreamParams& sp);
  196. bool RemoveSendStream_w(uint32_t ssrc);
  197. // Should be called whenever the conditions for
  198. // IsReadyToReceiveMedia/IsReadyToSendMedia are satisfied (or unsatisfied).
  199. // Updates the send/recv state of the media channel.
  200. void UpdateMediaSendRecvState();
  201. virtual void UpdateMediaSendRecvState_w() = 0;
  202. bool UpdateLocalStreams_w(const std::vector<StreamParams>& streams,
  203. webrtc::SdpType type,
  204. std::string* error_desc);
  205. bool UpdateRemoteStreams_w(const std::vector<StreamParams>& streams,
  206. webrtc::SdpType type,
  207. std::string* error_desc);
  208. virtual bool SetLocalContent_w(const MediaContentDescription* content,
  209. webrtc::SdpType type,
  210. std::string* error_desc) = 0;
  211. virtual bool SetRemoteContent_w(const MediaContentDescription* content,
  212. webrtc::SdpType type,
  213. std::string* error_desc) = 0;
  214. // Return a list of RTP header extensions with the non-encrypted extensions
  215. // removed depending on the current crypto_options_ and only if both the
  216. // non-encrypted and encrypted extension is present for the same URI.
  217. RtpHeaderExtensions GetFilteredRtpHeaderExtensions(
  218. const RtpHeaderExtensions& extensions);
  219. // From MessageHandler
  220. void OnMessage(rtc::Message* pmsg) override;
  221. // Helper function template for invoking methods on the worker thread.
  222. template <class T>
  223. T InvokeOnWorker(const rtc::Location& posted_from,
  224. rtc::FunctionView<T()> functor) {
  225. return worker_thread_->Invoke<T>(posted_from, functor);
  226. }
  227. // Add |payload_type| to |demuxer_criteria_| if payload type demuxing is
  228. // enabled.
  229. void MaybeAddHandledPayloadType(int payload_type) RTC_RUN_ON(worker_thread());
  230. void ClearHandledPayloadTypes() RTC_RUN_ON(worker_thread());
  231. void UpdateRtpHeaderExtensionMap(
  232. const RtpHeaderExtensions& header_extensions);
  233. bool RegisterRtpDemuxerSink();
  234. // Return description of media channel to facilitate logging
  235. std::string ToString() const;
  236. bool has_received_packet_ = false;
  237. private:
  238. bool ConnectToRtpTransport();
  239. void DisconnectFromRtpTransport();
  240. void SignalSentPacket_n(const rtc::SentPacket& sent_packet);
  241. bool IsReadyToSendMedia_n() const;
  242. rtc::Thread* const worker_thread_;
  243. rtc::Thread* const network_thread_;
  244. rtc::Thread* const signaling_thread_;
  245. rtc::AsyncInvoker invoker_;
  246. sigslot::signal1<ChannelInterface*> SignalFirstPacketReceived_
  247. RTC_GUARDED_BY(signaling_thread_);
  248. sigslot::signal1<const rtc::SentPacket&> SignalSentPacket_
  249. RTC_GUARDED_BY(worker_thread_);
  250. const std::string content_name_;
  251. // Won't be set when using raw packet transports. SDP-specific thing.
  252. std::string transport_name_;
  253. webrtc::RtpTransportInternal* rtp_transport_ = nullptr;
  254. std::vector<std::pair<rtc::Socket::Option, int> > socket_options_;
  255. std::vector<std::pair<rtc::Socket::Option, int> > rtcp_socket_options_;
  256. bool writable_ = false;
  257. bool was_ever_writable_ = false;
  258. const bool srtp_required_ = true;
  259. webrtc::CryptoOptions crypto_options_;
  260. // MediaChannel related members that should be accessed from the worker
  261. // thread.
  262. std::unique_ptr<MediaChannel> media_channel_;
  263. // Currently the |enabled_| flag is accessed from the signaling thread as
  264. // well, but it can be changed only when signaling thread does a synchronous
  265. // call to the worker thread, so it should be safe.
  266. bool enabled_ = false;
  267. bool payload_type_demuxing_enabled_ RTC_GUARDED_BY(worker_thread()) = true;
  268. std::vector<StreamParams> local_streams_;
  269. std::vector<StreamParams> remote_streams_;
  270. webrtc::RtpTransceiverDirection local_content_direction_ =
  271. webrtc::RtpTransceiverDirection::kInactive;
  272. webrtc::RtpTransceiverDirection remote_content_direction_ =
  273. webrtc::RtpTransceiverDirection::kInactive;
  274. // Cached list of payload types, used if payload type demuxing is re-enabled.
  275. std::set<uint8_t> payload_types_ RTC_GUARDED_BY(worker_thread());
  276. webrtc::RtpDemuxerCriteria demuxer_criteria_;
  277. // This generator is used to generate SSRCs for local streams.
  278. // This is needed in cases where SSRCs are not negotiated or set explicitly
  279. // like in Simulcast.
  280. // This object is not owned by the channel so it must outlive it.
  281. rtc::UniqueRandomIdGenerator* const ssrc_generator_;
  282. };
  283. // VoiceChannel is a specialization that adds support for early media, DTMF,
  284. // and input/output level monitoring.
  285. class VoiceChannel : public BaseChannel {
  286. public:
  287. VoiceChannel(rtc::Thread* worker_thread,
  288. rtc::Thread* network_thread,
  289. rtc::Thread* signaling_thread,
  290. std::unique_ptr<VoiceMediaChannel> channel,
  291. const std::string& content_name,
  292. bool srtp_required,
  293. webrtc::CryptoOptions crypto_options,
  294. rtc::UniqueRandomIdGenerator* ssrc_generator);
  295. ~VoiceChannel();
  296. // downcasts a MediaChannel
  297. VoiceMediaChannel* media_channel() const override {
  298. return static_cast<VoiceMediaChannel*>(BaseChannel::media_channel());
  299. }
  300. cricket::MediaType media_type() const override {
  301. return cricket::MEDIA_TYPE_AUDIO;
  302. }
  303. void Init_w(webrtc::RtpTransportInternal* rtp_transport) override;
  304. private:
  305. // overrides from BaseChannel
  306. void UpdateMediaSendRecvState_w() override;
  307. bool SetLocalContent_w(const MediaContentDescription* content,
  308. webrtc::SdpType type,
  309. std::string* error_desc) override;
  310. bool SetRemoteContent_w(const MediaContentDescription* content,
  311. webrtc::SdpType type,
  312. std::string* error_desc) override;
  313. // Last AudioSendParameters sent down to the media_channel() via
  314. // SetSendParameters.
  315. AudioSendParameters last_send_params_;
  316. // Last AudioRecvParameters sent down to the media_channel() via
  317. // SetRecvParameters.
  318. AudioRecvParameters last_recv_params_;
  319. };
  320. // VideoChannel is a specialization for video.
  321. class VideoChannel : public BaseChannel {
  322. public:
  323. VideoChannel(rtc::Thread* worker_thread,
  324. rtc::Thread* network_thread,
  325. rtc::Thread* signaling_thread,
  326. std::unique_ptr<VideoMediaChannel> media_channel,
  327. const std::string& content_name,
  328. bool srtp_required,
  329. webrtc::CryptoOptions crypto_options,
  330. rtc::UniqueRandomIdGenerator* ssrc_generator);
  331. ~VideoChannel();
  332. // downcasts a MediaChannel
  333. VideoMediaChannel* media_channel() const override {
  334. return static_cast<VideoMediaChannel*>(BaseChannel::media_channel());
  335. }
  336. void FillBitrateInfo(BandwidthEstimationInfo* bwe_info);
  337. cricket::MediaType media_type() const override {
  338. return cricket::MEDIA_TYPE_VIDEO;
  339. }
  340. private:
  341. // overrides from BaseChannel
  342. void UpdateMediaSendRecvState_w() override;
  343. bool SetLocalContent_w(const MediaContentDescription* content,
  344. webrtc::SdpType type,
  345. std::string* error_desc) override;
  346. bool SetRemoteContent_w(const MediaContentDescription* content,
  347. webrtc::SdpType type,
  348. std::string* error_desc) override;
  349. // Last VideoSendParameters sent down to the media_channel() via
  350. // SetSendParameters.
  351. VideoSendParameters last_send_params_;
  352. // Last VideoRecvParameters sent down to the media_channel() via
  353. // SetRecvParameters.
  354. VideoRecvParameters last_recv_params_;
  355. };
  356. // RtpDataChannel is a specialization for data.
  357. class RtpDataChannel : public BaseChannel {
  358. public:
  359. RtpDataChannel(rtc::Thread* worker_thread,
  360. rtc::Thread* network_thread,
  361. rtc::Thread* signaling_thread,
  362. std::unique_ptr<DataMediaChannel> channel,
  363. const std::string& content_name,
  364. bool srtp_required,
  365. webrtc::CryptoOptions crypto_options,
  366. rtc::UniqueRandomIdGenerator* ssrc_generator);
  367. ~RtpDataChannel();
  368. // TODO(zhihuang): Remove this once the RtpTransport can be shared between
  369. // BaseChannels.
  370. void Init_w(DtlsTransportInternal* rtp_dtls_transport,
  371. DtlsTransportInternal* rtcp_dtls_transport,
  372. rtc::PacketTransportInternal* rtp_packet_transport,
  373. rtc::PacketTransportInternal* rtcp_packet_transport);
  374. void Init_w(webrtc::RtpTransportInternal* rtp_transport) override;
  375. virtual bool SendData(const SendDataParams& params,
  376. const rtc::CopyOnWriteBuffer& payload,
  377. SendDataResult* result);
  378. // Should be called on the signaling thread only.
  379. bool ready_to_send_data() const { return ready_to_send_data_; }
  380. sigslot::signal2<const ReceiveDataParams&, const rtc::CopyOnWriteBuffer&>
  381. SignalDataReceived;
  382. // Signal for notifying when the channel becomes ready to send data.
  383. // That occurs when the channel is enabled, the transport is writable,
  384. // both local and remote descriptions are set, and the channel is unblocked.
  385. sigslot::signal1<bool> SignalReadyToSendData;
  386. cricket::MediaType media_type() const override {
  387. return cricket::MEDIA_TYPE_DATA;
  388. }
  389. protected:
  390. // downcasts a MediaChannel.
  391. DataMediaChannel* media_channel() const override {
  392. return static_cast<DataMediaChannel*>(BaseChannel::media_channel());
  393. }
  394. private:
  395. struct SendDataMessageData : public rtc::MessageData {
  396. SendDataMessageData(const SendDataParams& params,
  397. const rtc::CopyOnWriteBuffer* payload,
  398. SendDataResult* result)
  399. : params(params), payload(payload), result(result), succeeded(false) {}
  400. const SendDataParams& params;
  401. const rtc::CopyOnWriteBuffer* payload;
  402. SendDataResult* result;
  403. bool succeeded;
  404. };
  405. struct DataReceivedMessageData : public rtc::MessageData {
  406. // We copy the data because the data will become invalid after we
  407. // handle DataMediaChannel::SignalDataReceived but before we fire
  408. // SignalDataReceived.
  409. DataReceivedMessageData(const ReceiveDataParams& params,
  410. const char* data,
  411. size_t len)
  412. : params(params), payload(data, len) {}
  413. const ReceiveDataParams params;
  414. const rtc::CopyOnWriteBuffer payload;
  415. };
  416. typedef rtc::TypedMessageData<bool> DataChannelReadyToSendMessageData;
  417. // overrides from BaseChannel
  418. // Checks that data channel type is RTP.
  419. bool CheckDataChannelTypeFromContent(const MediaContentDescription* content,
  420. std::string* error_desc);
  421. bool SetLocalContent_w(const MediaContentDescription* content,
  422. webrtc::SdpType type,
  423. std::string* error_desc) override;
  424. bool SetRemoteContent_w(const MediaContentDescription* content,
  425. webrtc::SdpType type,
  426. std::string* error_desc) override;
  427. void UpdateMediaSendRecvState_w() override;
  428. void OnMessage(rtc::Message* pmsg) override;
  429. void OnDataReceived(const ReceiveDataParams& params,
  430. const char* data,
  431. size_t len);
  432. void OnDataChannelReadyToSend(bool writable);
  433. bool ready_to_send_data_ = false;
  434. // Last DataSendParameters sent down to the media_channel() via
  435. // SetSendParameters.
  436. DataSendParameters last_send_params_;
  437. // Last DataRecvParameters sent down to the media_channel() via
  438. // SetRecvParameters.
  439. DataRecvParameters last_recv_params_;
  440. };
  441. } // namespace cricket
  442. #endif // PC_CHANNEL_H_