rtp_video_stream_receiver2.h 15 KB

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