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