channel.h 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  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/transport/media/media_transport_config.h"
  23. #include "api/video/video_sink_interface.h"
  24. #include "api/video/video_source_interface.h"
  25. #include "call/rtp_packet_sink_interface.h"
  26. #include "media/base/media_channel.h"
  27. #include "media/base/media_engine.h"
  28. #include "media/base/stream_params.h"
  29. #include "p2p/base/dtls_transport_internal.h"
  30. #include "p2p/base/packet_transport_internal.h"
  31. #include "pc/channel_interface.h"
  32. #include "pc/dtls_srtp_transport.h"
  33. #include "pc/media_session.h"
  34. #include "pc/rtp_transport.h"
  35. #include "pc/srtp_filter.h"
  36. #include "pc/srtp_transport.h"
  37. #include "rtc_base/async_invoker.h"
  38. #include "rtc_base/async_udp_socket.h"
  39. #include "rtc_base/critical_section.h"
  40. #include "rtc_base/network.h"
  41. #include "rtc_base/third_party/sigslot/sigslot.h"
  42. #include "rtc_base/unique_id_generator.h"
  43. namespace webrtc {
  44. class AudioSinkInterface;
  45. class MediaTransportInterface;
  46. } // namespace webrtc
  47. namespace cricket {
  48. struct CryptoParams;
  49. // BaseChannel contains logic common to voice and video, including enable,
  50. // marshaling calls to a worker and network threads, and connection and media
  51. // monitors.
  52. //
  53. // BaseChannel assumes signaling and other threads are allowed to make
  54. // synchronous calls to the worker thread, the worker thread makes synchronous
  55. // calls only to the network thread, and the network thread can't be blocked by
  56. // other threads.
  57. // All methods with _n suffix must be called on network thread,
  58. // methods with _w suffix on worker thread
  59. // and methods with _s suffix on signaling thread.
  60. // Network and worker threads may be the same thread.
  61. //
  62. // WARNING! SUBCLASSES MUST CALL Deinit() IN THEIR DESTRUCTORS!
  63. // This is required to avoid a data race between the destructor modifying the
  64. // vtable, and the media channel's thread using BaseChannel as the
  65. // NetworkInterface.
  66. class BaseChannel : public ChannelInterface,
  67. public rtc::MessageHandler,
  68. public sigslot::has_slots<>,
  69. public MediaChannel::NetworkInterface,
  70. public webrtc::RtpPacketSinkInterface {
  71. public:
  72. // If |srtp_required| is true, the channel will not send or receive any
  73. // RTP/RTCP packets without using SRTP (either using SDES or DTLS-SRTP).
  74. // The BaseChannel does not own the UniqueRandomIdGenerator so it is the
  75. // responsibility of the user to ensure it outlives this object.
  76. // TODO(zhihuang:) Create a BaseChannel::Config struct for the parameter lists
  77. // which will make it easier to change the constructor.
  78. BaseChannel(rtc::Thread* worker_thread,
  79. rtc::Thread* network_thread,
  80. rtc::Thread* signaling_thread,
  81. std::unique_ptr<MediaChannel> media_channel,
  82. const std::string& content_name,
  83. bool srtp_required,
  84. webrtc::CryptoOptions crypto_options,
  85. rtc::UniqueRandomIdGenerator* ssrc_generator);
  86. virtual ~BaseChannel();
  87. virtual void Init_w(
  88. webrtc::RtpTransportInternal* rtp_transport,
  89. const webrtc::MediaTransportConfig& media_transport_config);
  90. // Deinit may be called multiple times and is simply ignored if it's already
  91. // done.
  92. void Deinit();
  93. rtc::Thread* worker_thread() const { return worker_thread_; }
  94. rtc::Thread* network_thread() const { return network_thread_; }
  95. const std::string& content_name() const override { return content_name_; }
  96. // TODO(deadbeef): This is redundant; remove this.
  97. const std::string& transport_name() const override { return transport_name_; }
  98. bool enabled() const override { return enabled_; }
  99. // This function returns true if using SRTP (DTLS-based keying or SDES).
  100. bool srtp_active() const {
  101. return rtp_transport_ && rtp_transport_->IsSrtpActive();
  102. }
  103. bool writable() const { return writable_; }
  104. // Set an RTP level transport which could be an RtpTransport without
  105. // encryption, an SrtpTransport for SDES or a DtlsSrtpTransport for DTLS-SRTP.
  106. // This can be called from any thread and it hops to the network thread
  107. // internally. It would replace the |SetTransports| and its variants.
  108. bool SetRtpTransport(webrtc::RtpTransportInternal* rtp_transport) override;
  109. webrtc::RtpTransportInternal* rtp_transport() const { return rtp_transport_; }
  110. // Channel control
  111. bool SetLocalContent(const MediaContentDescription* content,
  112. webrtc::SdpType type,
  113. std::string* error_desc) override;
  114. bool SetRemoteContent(const MediaContentDescription* content,
  115. webrtc::SdpType type,
  116. std::string* error_desc) override;
  117. bool Enable(bool enable) override;
  118. const std::vector<StreamParams>& local_streams() const override {
  119. return local_streams_;
  120. }
  121. const std::vector<StreamParams>& remote_streams() const override {
  122. return remote_streams_;
  123. }
  124. sigslot::signal2<BaseChannel*, bool> SignalDtlsSrtpSetupFailure;
  125. void SignalDtlsSrtpSetupFailure_n(bool rtcp);
  126. void SignalDtlsSrtpSetupFailure_s(bool rtcp);
  127. // Used for latency measurements.
  128. sigslot::signal1<ChannelInterface*>& SignalFirstPacketReceived() override {
  129. return SignalFirstPacketReceived_;
  130. }
  131. // Forward SignalSentPacket to worker thread.
  132. sigslot::signal1<const rtc::SentPacket&> SignalSentPacket;
  133. // Emitted whenever rtcp-mux is fully negotiated and the rtcp-transport can
  134. // be destroyed.
  135. // Fired on the network thread.
  136. sigslot::signal1<const std::string&> SignalRtcpMuxFullyActive;
  137. // From RtpTransport - public for testing only
  138. void OnTransportReadyToSend(bool ready);
  139. // Only public for unit tests. Otherwise, consider protected.
  140. int SetOption(SocketType type, rtc::Socket::Option o, int val) override;
  141. int SetOption_n(SocketType type, rtc::Socket::Option o, int val);
  142. // RtpPacketSinkInterface overrides.
  143. void OnRtpPacket(const webrtc::RtpPacketReceived& packet) override;
  144. // Used by the RTCStatsCollector tests to set the transport name without
  145. // creating RtpTransports.
  146. void set_transport_name_for_testing(const std::string& transport_name) {
  147. transport_name_ = transport_name;
  148. }
  149. MediaChannel* media_channel() const override { return media_channel_.get(); }
  150. protected:
  151. bool was_ever_writable() const { return was_ever_writable_; }
  152. void set_local_content_direction(webrtc::RtpTransceiverDirection direction) {
  153. local_content_direction_ = direction;
  154. }
  155. void set_remote_content_direction(webrtc::RtpTransceiverDirection direction) {
  156. remote_content_direction_ = direction;
  157. }
  158. // These methods verify that:
  159. // * The required content description directions have been set.
  160. // * The channel is enabled.
  161. // * And for sending:
  162. // - The SRTP filter is active if it's needed.
  163. // - The transport has been writable before, meaning it should be at least
  164. // possible to succeed in sending a packet.
  165. //
  166. // When any of these properties change, UpdateMediaSendRecvState_w should be
  167. // called.
  168. bool IsReadyToReceiveMedia_w() const;
  169. bool IsReadyToSendMedia_w() const;
  170. rtc::Thread* signaling_thread() { return signaling_thread_; }
  171. void FlushRtcpMessages_n();
  172. // NetworkInterface implementation, called by MediaEngine
  173. bool SendPacket(rtc::CopyOnWriteBuffer* packet,
  174. const rtc::PacketOptions& options) override;
  175. bool SendRtcp(rtc::CopyOnWriteBuffer* packet,
  176. const rtc::PacketOptions& options) override;
  177. // From RtpTransportInternal
  178. void OnWritableState(bool writable);
  179. void OnNetworkRouteChanged(absl::optional<rtc::NetworkRoute> network_route);
  180. bool PacketIsRtcp(const rtc::PacketTransportInternal* transport,
  181. const char* data,
  182. size_t len);
  183. bool SendPacket(bool rtcp,
  184. rtc::CopyOnWriteBuffer* packet,
  185. const rtc::PacketOptions& options);
  186. void EnableMedia_w();
  187. void DisableMedia_w();
  188. // Performs actions if the RTP/RTCP writable state changed. This should
  189. // be called whenever a channel's writable state changes or when RTCP muxing
  190. // becomes active/inactive.
  191. void UpdateWritableState_n();
  192. void ChannelWritable_n();
  193. void ChannelNotWritable_n();
  194. bool AddRecvStream_w(const StreamParams& sp);
  195. bool RemoveRecvStream_w(uint32_t ssrc);
  196. void ResetUnsignaledRecvStream_w();
  197. bool AddSendStream_w(const StreamParams& sp);
  198. bool RemoveSendStream_w(uint32_t ssrc);
  199. // Should be called whenever the conditions for
  200. // IsReadyToReceiveMedia/IsReadyToSendMedia are satisfied (or unsatisfied).
  201. // Updates the send/recv state of the media channel.
  202. void UpdateMediaSendRecvState();
  203. virtual void UpdateMediaSendRecvState_w() = 0;
  204. bool UpdateLocalStreams_w(const std::vector<StreamParams>& streams,
  205. webrtc::SdpType type,
  206. std::string* error_desc);
  207. bool UpdateRemoteStreams_w(const std::vector<StreamParams>& streams,
  208. webrtc::SdpType type,
  209. std::string* error_desc);
  210. virtual bool SetLocalContent_w(const MediaContentDescription* content,
  211. webrtc::SdpType type,
  212. std::string* error_desc) = 0;
  213. virtual bool SetRemoteContent_w(const MediaContentDescription* content,
  214. webrtc::SdpType type,
  215. std::string* error_desc) = 0;
  216. // Return a list of RTP header extensions with the non-encrypted extensions
  217. // removed depending on the current crypto_options_ and only if both the
  218. // non-encrypted and encrypted extension is present for the same URI.
  219. RtpHeaderExtensions GetFilteredRtpHeaderExtensions(
  220. const RtpHeaderExtensions& extensions);
  221. // From MessageHandler
  222. void OnMessage(rtc::Message* pmsg) override;
  223. // Helper function template for invoking methods on the worker thread.
  224. template <class T>
  225. T InvokeOnWorker(const rtc::Location& posted_from,
  226. rtc::FunctionView<T()> functor) {
  227. return worker_thread_->Invoke<T>(posted_from, functor);
  228. }
  229. void AddHandledPayloadType(int payload_type);
  230. void ClearHandledPayloadTypes();
  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. const std::string content_name_;
  248. // Won't be set when using raw packet transports. SDP-specific thing.
  249. std::string transport_name_;
  250. webrtc::RtpTransportInternal* rtp_transport_ = nullptr;
  251. // Optional media transport configuration (experimental).
  252. webrtc::MediaTransportConfig media_transport_config_;
  253. std::vector<std::pair<rtc::Socket::Option, int> > socket_options_;
  254. std::vector<std::pair<rtc::Socket::Option, int> > rtcp_socket_options_;
  255. bool writable_ = false;
  256. bool was_ever_writable_ = false;
  257. const bool srtp_required_ = true;
  258. webrtc::CryptoOptions crypto_options_;
  259. // MediaChannel related members that should be accessed from the worker
  260. // thread.
  261. std::unique_ptr<MediaChannel> media_channel_;
  262. // Currently the |enabled_| flag is accessed from the signaling thread as
  263. // well, but it can be changed only when signaling thread does a synchronous
  264. // call to the worker thread, so it should be safe.
  265. bool enabled_ = false;
  266. std::vector<StreamParams> local_streams_;
  267. std::vector<StreamParams> remote_streams_;
  268. webrtc::RtpTransceiverDirection local_content_direction_ =
  269. webrtc::RtpTransceiverDirection::kInactive;
  270. webrtc::RtpTransceiverDirection remote_content_direction_ =
  271. webrtc::RtpTransceiverDirection::kInactive;
  272. webrtc::RtpDemuxerCriteria demuxer_criteria_;
  273. // This generator is used to generate SSRCs for local streams.
  274. // This is needed in cases where SSRCs are not negotiated or set explicitly
  275. // like in Simulcast.
  276. // This object is not owned by the channel so it must outlive it.
  277. rtc::UniqueRandomIdGenerator* const ssrc_generator_;
  278. };
  279. // VoiceChannel is a specialization that adds support for early media, DTMF,
  280. // and input/output level monitoring.
  281. class VoiceChannel : public BaseChannel {
  282. public:
  283. VoiceChannel(rtc::Thread* worker_thread,
  284. rtc::Thread* network_thread,
  285. rtc::Thread* signaling_thread,
  286. std::unique_ptr<VoiceMediaChannel> channel,
  287. const std::string& content_name,
  288. bool srtp_required,
  289. webrtc::CryptoOptions crypto_options,
  290. rtc::UniqueRandomIdGenerator* ssrc_generator);
  291. ~VoiceChannel();
  292. // downcasts a MediaChannel
  293. VoiceMediaChannel* media_channel() const override {
  294. return static_cast<VoiceMediaChannel*>(BaseChannel::media_channel());
  295. }
  296. cricket::MediaType media_type() const override {
  297. return cricket::MEDIA_TYPE_AUDIO;
  298. }
  299. void Init_w(
  300. webrtc::RtpTransportInternal* rtp_transport,
  301. const webrtc::MediaTransportConfig& media_transport_config) override;
  302. private:
  303. // overrides from BaseChannel
  304. void UpdateMediaSendRecvState_w() override;
  305. bool SetLocalContent_w(const MediaContentDescription* content,
  306. webrtc::SdpType type,
  307. std::string* error_desc) override;
  308. bool SetRemoteContent_w(const MediaContentDescription* content,
  309. webrtc::SdpType type,
  310. std::string* error_desc) override;
  311. // Last AudioSendParameters sent down to the media_channel() via
  312. // SetSendParameters.
  313. AudioSendParameters last_send_params_;
  314. // Last AudioRecvParameters sent down to the media_channel() via
  315. // SetRecvParameters.
  316. AudioRecvParameters last_recv_params_;
  317. };
  318. // VideoChannel is a specialization for video.
  319. class VideoChannel : public BaseChannel {
  320. public:
  321. VideoChannel(rtc::Thread* worker_thread,
  322. rtc::Thread* network_thread,
  323. rtc::Thread* signaling_thread,
  324. std::unique_ptr<VideoMediaChannel> media_channel,
  325. const std::string& content_name,
  326. bool srtp_required,
  327. webrtc::CryptoOptions crypto_options,
  328. rtc::UniqueRandomIdGenerator* ssrc_generator);
  329. ~VideoChannel();
  330. // downcasts a MediaChannel
  331. VideoMediaChannel* media_channel() const override {
  332. return static_cast<VideoMediaChannel*>(BaseChannel::media_channel());
  333. }
  334. void FillBitrateInfo(BandwidthEstimationInfo* bwe_info);
  335. cricket::MediaType media_type() const override {
  336. return cricket::MEDIA_TYPE_VIDEO;
  337. }
  338. private:
  339. // overrides from BaseChannel
  340. void UpdateMediaSendRecvState_w() override;
  341. bool SetLocalContent_w(const MediaContentDescription* content,
  342. webrtc::SdpType type,
  343. std::string* error_desc) override;
  344. bool SetRemoteContent_w(const MediaContentDescription* content,
  345. webrtc::SdpType type,
  346. std::string* error_desc) override;
  347. // Last VideoSendParameters sent down to the media_channel() via
  348. // SetSendParameters.
  349. VideoSendParameters last_send_params_;
  350. // Last VideoRecvParameters sent down to the media_channel() via
  351. // SetRecvParameters.
  352. VideoRecvParameters last_recv_params_;
  353. };
  354. // RtpDataChannel is a specialization for data.
  355. class RtpDataChannel : public BaseChannel {
  356. public:
  357. RtpDataChannel(rtc::Thread* worker_thread,
  358. rtc::Thread* network_thread,
  359. rtc::Thread* signaling_thread,
  360. std::unique_ptr<DataMediaChannel> channel,
  361. const std::string& content_name,
  362. bool srtp_required,
  363. webrtc::CryptoOptions crypto_options,
  364. rtc::UniqueRandomIdGenerator* ssrc_generator);
  365. ~RtpDataChannel();
  366. // TODO(zhihuang): Remove this once the RtpTransport can be shared between
  367. // BaseChannels.
  368. void Init_w(DtlsTransportInternal* rtp_dtls_transport,
  369. DtlsTransportInternal* rtcp_dtls_transport,
  370. rtc::PacketTransportInternal* rtp_packet_transport,
  371. rtc::PacketTransportInternal* rtcp_packet_transport);
  372. void Init_w(
  373. webrtc::RtpTransportInternal* rtp_transport,
  374. const webrtc::MediaTransportConfig& media_transport_config) 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_