rtp_video_stream_receiver.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. /*
  2. * Copyright (c) 2012 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 VIDEO_RTP_VIDEO_STREAM_RECEIVER_H_
  11. #define VIDEO_RTP_VIDEO_STREAM_RECEIVER_H_
  12. #include <atomic>
  13. #include <list>
  14. #include <map>
  15. #include <memory>
  16. #include <string>
  17. #include <vector>
  18. #include "absl/types/optional.h"
  19. #include "api/array_view.h"
  20. #include "api/crypto/frame_decryptor_interface.h"
  21. #include "api/video/color_space.h"
  22. #include "api/video_codecs/video_codec.h"
  23. #include "call/rtp_packet_sink_interface.h"
  24. #include "call/syncable.h"
  25. #include "call/video_receive_stream.h"
  26. #include "modules/rtp_rtcp/include/receive_statistics.h"
  27. #include "modules/rtp_rtcp/include/remote_ntp_time_estimator.h"
  28. #include "modules/rtp_rtcp/include/rtp_header_extension_map.h"
  29. #include "modules/rtp_rtcp/include/rtp_rtcp.h"
  30. #include "modules/rtp_rtcp/include/rtp_rtcp_defines.h"
  31. #include "modules/rtp_rtcp/source/absolute_capture_time_receiver.h"
  32. #include "modules/rtp_rtcp/source/rtp_dependency_descriptor_extension.h"
  33. #include "modules/rtp_rtcp/source/rtp_packet_received.h"
  34. #include "modules/rtp_rtcp/source/rtp_video_header.h"
  35. #include "modules/rtp_rtcp/source/video_rtp_depacketizer.h"
  36. #include "modules/video_coding/h264_sps_pps_tracker.h"
  37. #include "modules/video_coding/loss_notification_controller.h"
  38. #include "modules/video_coding/packet_buffer.h"
  39. #include "modules/video_coding/rtp_frame_reference_finder.h"
  40. #include "modules/video_coding/unique_timestamp_counter.h"
  41. #include "rtc_base/constructor_magic.h"
  42. #include "rtc_base/experiments/field_trial_parser.h"
  43. #include "rtc_base/numerics/sequence_number_util.h"
  44. #include "rtc_base/synchronization/mutex.h"
  45. #include "rtc_base/synchronization/sequence_checker.h"
  46. #include "rtc_base/system/no_unique_address.h"
  47. #include "rtc_base/thread_annotations.h"
  48. #include "rtc_base/thread_checker.h"
  49. #include "video/buffered_frame_decryptor.h"
  50. #include "video/rtp_video_stream_receiver_frame_transformer_delegate.h"
  51. namespace webrtc {
  52. class DEPRECATED_NackModule;
  53. class PacketRouter;
  54. class ProcessThread;
  55. class ReceiveStatistics;
  56. class ReceiveStatisticsProxy;
  57. class RtcpRttStats;
  58. class RtpPacketReceived;
  59. class Transport;
  60. class UlpfecReceiver;
  61. class RtpVideoStreamReceiver : public LossNotificationSender,
  62. public RecoveredPacketReceiver,
  63. public RtpPacketSinkInterface,
  64. public KeyFrameRequestSender,
  65. public video_coding::OnCompleteFrameCallback,
  66. public OnDecryptedFrameCallback,
  67. public OnDecryptionStatusChangeCallback,
  68. public RtpVideoFrameReceiver {
  69. public:
  70. // DEPRECATED due to dependency on ReceiveStatisticsProxy.
  71. RtpVideoStreamReceiver(
  72. Clock* clock,
  73. Transport* transport,
  74. RtcpRttStats* rtt_stats,
  75. // The packet router is optional; if provided, the RtpRtcp module for this
  76. // stream is registered as a candidate for sending REMB and transport
  77. // feedback.
  78. PacketRouter* packet_router,
  79. const VideoReceiveStream::Config* config,
  80. ReceiveStatistics* rtp_receive_statistics,
  81. ReceiveStatisticsProxy* receive_stats_proxy,
  82. ProcessThread* process_thread,
  83. NackSender* nack_sender,
  84. // The KeyFrameRequestSender is optional; if not provided, key frame
  85. // requests are sent via the internal RtpRtcp module.
  86. KeyFrameRequestSender* keyframe_request_sender,
  87. video_coding::OnCompleteFrameCallback* complete_frame_callback,
  88. rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
  89. rtc::scoped_refptr<FrameTransformerInterface> frame_transformer);
  90. RtpVideoStreamReceiver(
  91. Clock* clock,
  92. Transport* transport,
  93. RtcpRttStats* rtt_stats,
  94. // The packet router is optional; if provided, the RtpRtcp module for this
  95. // stream is registered as a candidate for sending REMB and transport
  96. // feedback.
  97. PacketRouter* packet_router,
  98. const VideoReceiveStream::Config* config,
  99. ReceiveStatistics* rtp_receive_statistics,
  100. RtcpPacketTypeCounterObserver* rtcp_packet_type_counter_observer,
  101. RtcpCnameCallback* rtcp_cname_callback,
  102. ProcessThread* process_thread,
  103. NackSender* nack_sender,
  104. // The KeyFrameRequestSender is optional; if not provided, key frame
  105. // requests are sent via the internal RtpRtcp module.
  106. KeyFrameRequestSender* keyframe_request_sender,
  107. video_coding::OnCompleteFrameCallback* complete_frame_callback,
  108. rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor,
  109. rtc::scoped_refptr<FrameTransformerInterface> frame_transformer);
  110. ~RtpVideoStreamReceiver() override;
  111. void AddReceiveCodec(uint8_t payload_type,
  112. const VideoCodec& video_codec,
  113. const std::map<std::string, std::string>& codec_params,
  114. bool raw_payload);
  115. void StartReceive();
  116. void StopReceive();
  117. // Produces the transport-related timestamps; current_delay_ms is left unset.
  118. absl::optional<Syncable::Info> GetSyncInfo() const;
  119. bool DeliverRtcp(const uint8_t* rtcp_packet, size_t rtcp_packet_length);
  120. void FrameContinuous(int64_t seq_num);
  121. void FrameDecoded(int64_t seq_num);
  122. void SignalNetworkState(NetworkState state);
  123. // Returns number of different frames seen.
  124. int GetUniqueFramesSeen() const {
  125. RTC_DCHECK_RUN_ON(&worker_task_checker_);
  126. return frame_counter_.GetUniqueSeen();
  127. }
  128. // Implements RtpPacketSinkInterface.
  129. void OnRtpPacket(const RtpPacketReceived& packet) override;
  130. // Public only for tests.
  131. void OnReceivedPayloadData(rtc::CopyOnWriteBuffer codec_payload,
  132. const RtpPacketReceived& rtp_packet,
  133. const RTPVideoHeader& video);
  134. // Implements RecoveredPacketReceiver.
  135. void OnRecoveredPacket(const uint8_t* packet, size_t packet_length) override;
  136. // Send an RTCP keyframe request.
  137. void RequestKeyFrame() override;
  138. // Implements LossNotificationSender.
  139. void SendLossNotification(uint16_t last_decoded_seq_num,
  140. uint16_t last_received_seq_num,
  141. bool decodability_flag,
  142. bool buffering_allowed) override;
  143. bool IsUlpfecEnabled() const;
  144. bool IsRetransmissionsEnabled() const;
  145. // Returns true if a decryptor is attached and frames can be decrypted.
  146. // Updated by OnDecryptionStatusChangeCallback. Note this refers to Frame
  147. // Decryption not SRTP.
  148. bool IsDecryptable() const;
  149. // Don't use, still experimental.
  150. void RequestPacketRetransmit(const std::vector<uint16_t>& sequence_numbers);
  151. // Implements OnCompleteFrameCallback.
  152. void OnCompleteFrame(
  153. std::unique_ptr<video_coding::EncodedFrame> frame) override;
  154. // Implements OnDecryptedFrameCallback.
  155. void OnDecryptedFrame(
  156. std::unique_ptr<video_coding::RtpFrameObject> frame) override;
  157. // Implements OnDecryptionStatusChangeCallback.
  158. void OnDecryptionStatusChange(
  159. FrameDecryptorInterface::Status status) override;
  160. // Optionally set a frame decryptor after a stream has started. This will not
  161. // reset the decoder state.
  162. void SetFrameDecryptor(
  163. rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor);
  164. // Sets a frame transformer after a stream has started, if no transformer
  165. // has previously been set. Does not reset the decoder state.
  166. void SetDepacketizerToDecoderFrameTransformer(
  167. rtc::scoped_refptr<FrameTransformerInterface> frame_transformer);
  168. // Called by VideoReceiveStream when stats are updated.
  169. void UpdateRtt(int64_t max_rtt_ms);
  170. absl::optional<int64_t> LastReceivedPacketMs() const;
  171. absl::optional<int64_t> LastReceivedKeyframePacketMs() const;
  172. // RtpDemuxer only forwards a given RTP packet to one sink. However, some
  173. // sinks, such as FlexFEC, might wish to be informed of all of the packets
  174. // a given sink receives (or any set of sinks). They may do so by registering
  175. // themselves as secondary sinks.
  176. void AddSecondarySink(RtpPacketSinkInterface* sink);
  177. void RemoveSecondarySink(const RtpPacketSinkInterface* sink);
  178. private:
  179. // Implements RtpVideoFrameReceiver.
  180. void ManageFrame(
  181. std::unique_ptr<video_coding::RtpFrameObject> frame) override;
  182. // Used for buffering RTCP feedback messages and sending them all together.
  183. // Note:
  184. // 1. Key frame requests and NACKs are mutually exclusive, with the
  185. // former taking precedence over the latter.
  186. // 2. Loss notifications are orthogonal to either. (That is, may be sent
  187. // alongside either.)
  188. class RtcpFeedbackBuffer : public KeyFrameRequestSender,
  189. public NackSender,
  190. public LossNotificationSender {
  191. public:
  192. RtcpFeedbackBuffer(KeyFrameRequestSender* key_frame_request_sender,
  193. NackSender* nack_sender,
  194. LossNotificationSender* loss_notification_sender);
  195. ~RtcpFeedbackBuffer() override = default;
  196. // KeyFrameRequestSender implementation.
  197. void RequestKeyFrame() RTC_LOCKS_EXCLUDED(mutex_) override;
  198. // NackSender implementation.
  199. void SendNack(const std::vector<uint16_t>& sequence_numbers,
  200. bool buffering_allowed) RTC_LOCKS_EXCLUDED(mutex_) override;
  201. // LossNotificationSender implementation.
  202. void SendLossNotification(uint16_t last_decoded_seq_num,
  203. uint16_t last_received_seq_num,
  204. bool decodability_flag,
  205. bool buffering_allowed)
  206. RTC_LOCKS_EXCLUDED(mutex_) override;
  207. // Send all RTCP feedback messages buffered thus far.
  208. void SendBufferedRtcpFeedback() RTC_LOCKS_EXCLUDED(mutex_);
  209. private:
  210. // LNTF-related state.
  211. struct LossNotificationState {
  212. LossNotificationState(uint16_t last_decoded_seq_num,
  213. uint16_t last_received_seq_num,
  214. bool decodability_flag)
  215. : last_decoded_seq_num(last_decoded_seq_num),
  216. last_received_seq_num(last_received_seq_num),
  217. decodability_flag(decodability_flag) {}
  218. uint16_t last_decoded_seq_num;
  219. uint16_t last_received_seq_num;
  220. bool decodability_flag;
  221. };
  222. struct ConsumedRtcpFeedback {
  223. bool request_key_frame = false;
  224. std::vector<uint16_t> nack_sequence_numbers;
  225. absl::optional<LossNotificationState> lntf_state;
  226. };
  227. ConsumedRtcpFeedback ConsumeRtcpFeedback() RTC_LOCKS_EXCLUDED(mutex_);
  228. ConsumedRtcpFeedback ConsumeRtcpFeedbackLocked()
  229. RTC_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
  230. // This method is called both with and without mutex_ held.
  231. void SendRtcpFeedback(ConsumedRtcpFeedback feedback);
  232. KeyFrameRequestSender* const key_frame_request_sender_;
  233. NackSender* const nack_sender_;
  234. LossNotificationSender* const loss_notification_sender_;
  235. // NACKs are accessible from two threads due to nack_module_ being a module.
  236. Mutex mutex_;
  237. // Key-frame-request-related state.
  238. bool request_key_frame_ RTC_GUARDED_BY(mutex_);
  239. // NACK-related state.
  240. std::vector<uint16_t> nack_sequence_numbers_ RTC_GUARDED_BY(mutex_);
  241. absl::optional<LossNotificationState> lntf_state_ RTC_GUARDED_BY(mutex_);
  242. };
  243. enum ParseGenericDependenciesResult {
  244. kDropPacket,
  245. kHasGenericDescriptor,
  246. kNoGenericDescriptor
  247. };
  248. // Entry point doing non-stats work for a received packet. Called
  249. // for the same packet both before and after RED decapsulation.
  250. void ReceivePacket(const RtpPacketReceived& packet);
  251. // Parses and handles RED headers.
  252. // This function assumes that it's being called from only one thread.
  253. void ParseAndHandleEncapsulatingHeader(const RtpPacketReceived& packet);
  254. void NotifyReceiverOfEmptyPacket(uint16_t seq_num);
  255. void UpdateHistograms();
  256. bool IsRedEnabled() const;
  257. void InsertSpsPpsIntoTracker(uint8_t payload_type);
  258. void OnInsertedPacket(video_coding::PacketBuffer::InsertResult result);
  259. ParseGenericDependenciesResult ParseGenericDependenciesExtension(
  260. const RtpPacketReceived& rtp_packet,
  261. RTPVideoHeader* video_header) RTC_RUN_ON(worker_task_checker_);
  262. void OnAssembledFrame(std::unique_ptr<video_coding::RtpFrameObject> frame);
  263. Clock* const clock_;
  264. // Ownership of this object lies with VideoReceiveStream, which owns |this|.
  265. const VideoReceiveStream::Config& config_;
  266. PacketRouter* const packet_router_;
  267. ProcessThread* const process_thread_;
  268. RemoteNtpTimeEstimator ntp_estimator_;
  269. RtpHeaderExtensionMap rtp_header_extensions_;
  270. // Set by the field trial WebRTC-ForcePlayoutDelay to override any playout
  271. // delay that is specified in the received packets.
  272. FieldTrialOptional<int> forced_playout_delay_max_ms_;
  273. FieldTrialOptional<int> forced_playout_delay_min_ms_;
  274. ReceiveStatistics* const rtp_receive_statistics_;
  275. std::unique_ptr<UlpfecReceiver> ulpfec_receiver_;
  276. RTC_NO_UNIQUE_ADDRESS SequenceChecker worker_task_checker_;
  277. bool receiving_ RTC_GUARDED_BY(worker_task_checker_);
  278. int64_t last_packet_log_ms_ RTC_GUARDED_BY(worker_task_checker_);
  279. const std::unique_ptr<RtpRtcp> rtp_rtcp_;
  280. video_coding::OnCompleteFrameCallback* complete_frame_callback_;
  281. KeyFrameRequestSender* const keyframe_request_sender_;
  282. RtcpFeedbackBuffer rtcp_feedback_buffer_;
  283. std::unique_ptr<DEPRECATED_NackModule> nack_module_;
  284. std::unique_ptr<LossNotificationController> loss_notification_controller_;
  285. video_coding::PacketBuffer packet_buffer_;
  286. UniqueTimestampCounter frame_counter_ RTC_GUARDED_BY(worker_task_checker_);
  287. SeqNumUnwrapper<uint16_t> frame_id_unwrapper_
  288. RTC_GUARDED_BY(worker_task_checker_);
  289. // Video structure provided in the dependency descriptor in a first packet
  290. // of a key frame. It is required to parse dependency descriptor in the
  291. // following delta packets.
  292. std::unique_ptr<FrameDependencyStructure> video_structure_
  293. RTC_GUARDED_BY(worker_task_checker_);
  294. // Frame id of the last frame with the attached video structure.
  295. // absl::nullopt when `video_structure_ == nullptr`;
  296. absl::optional<int64_t> video_structure_frame_id_
  297. RTC_GUARDED_BY(worker_task_checker_);
  298. Mutex reference_finder_lock_;
  299. std::unique_ptr<video_coding::RtpFrameReferenceFinder> reference_finder_
  300. RTC_GUARDED_BY(reference_finder_lock_);
  301. absl::optional<VideoCodecType> current_codec_;
  302. uint32_t last_assembled_frame_rtp_timestamp_;
  303. Mutex last_seq_num_mutex_;
  304. std::map<int64_t, uint16_t> last_seq_num_for_pic_id_
  305. RTC_GUARDED_BY(last_seq_num_mutex_);
  306. video_coding::H264SpsPpsTracker tracker_;
  307. // Maps payload id to the depacketizer.
  308. std::map<uint8_t, std::unique_ptr<VideoRtpDepacketizer>> payload_type_map_;
  309. // TODO(johan): Remove pt_codec_params_ once
  310. // https://bugs.chromium.org/p/webrtc/issues/detail?id=6883 is resolved.
  311. // Maps a payload type to a map of out-of-band supplied codec parameters.
  312. std::map<uint8_t, std::map<std::string, std::string>> pt_codec_params_;
  313. int16_t last_payload_type_ = -1;
  314. bool has_received_frame_;
  315. std::vector<RtpPacketSinkInterface*> secondary_sinks_
  316. RTC_GUARDED_BY(worker_task_checker_);
  317. // Info for GetSyncInfo is updated on network or worker thread, and queried on
  318. // the worker thread.
  319. mutable Mutex sync_info_lock_;
  320. absl::optional<uint32_t> last_received_rtp_timestamp_
  321. RTC_GUARDED_BY(sync_info_lock_);
  322. absl::optional<int64_t> last_received_rtp_system_time_ms_
  323. RTC_GUARDED_BY(sync_info_lock_);
  324. // Used to validate the buffered frame decryptor is always run on the correct
  325. // thread.
  326. rtc::ThreadChecker network_tc_;
  327. // Handles incoming encrypted frames and forwards them to the
  328. // rtp_reference_finder if they are decryptable.
  329. std::unique_ptr<BufferedFrameDecryptor> buffered_frame_decryptor_
  330. RTC_PT_GUARDED_BY(network_tc_);
  331. std::atomic<bool> frames_decryptable_;
  332. absl::optional<ColorSpace> last_color_space_;
  333. AbsoluteCaptureTimeReceiver absolute_capture_time_receiver_
  334. RTC_GUARDED_BY(worker_task_checker_);
  335. int64_t last_completed_picture_id_ = 0;
  336. rtc::scoped_refptr<RtpVideoStreamReceiverFrameTransformerDelegate>
  337. frame_transformer_delegate_;
  338. };
  339. } // namespace webrtc
  340. #endif // VIDEO_RTP_VIDEO_STREAM_RECEIVER_H_