rtp_video_stream_receiver2.h 15 KB

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