rtp_video_stream_receiver.h 16 KB

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