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 MODULES_VIDEO_CODING_JITTER_BUFFER_H_
12 #define MODULES_VIDEO_CODING_JITTER_BUFFER_H_
13 
14 #include <list>
15 #include <map>
16 #include <memory>
17 #include <set>
18 #include <vector>
19 
20 #include "modules/include/module_common_types.h"
21 #include "modules/include/module_common_types_public.h"
22 #include "modules/utility/include/process_thread.h"
23 #include "modules/video_coding/decoding_state.h"
24 #include "modules/video_coding/event_wrapper.h"
25 #include "modules/video_coding/include/video_coding.h"
26 #include "modules/video_coding/include/video_coding_defines.h"
27 #include "modules/video_coding/inter_frame_delay.h"
28 #include "modules/video_coding/jitter_buffer_common.h"
29 #include "modules/video_coding/jitter_estimator.h"
30 #include "rtc_base/constructor_magic.h"
31 #include "rtc_base/critical_section.h"
32 #include "rtc_base/thread_annotations.h"
33 
34 namespace webrtc {
35 
36 // forward declarations
37 class Clock;
38 class VCMFrameBuffer;
39 class VCMPacket;
40 class VCMEncodedFrame;
41 
42 typedef std::list<VCMFrameBuffer*> UnorderedFrameList;
43 
44 struct VCMJitterSample {
VCMJitterSampleVCMJitterSample45   VCMJitterSample() : timestamp(0), frame_size(0), latest_packet_time(-1) {}
46   uint32_t timestamp;
47   uint32_t frame_size;
48   int64_t latest_packet_time;
49 };
50 
51 class TimestampLessThan {
52  public:
operator()53   bool operator()(uint32_t timestamp1, uint32_t timestamp2) const {
54     return IsNewerTimestamp(timestamp2, timestamp1);
55   }
56 };
57 
58 class FrameList
59     : public std::map<uint32_t, VCMFrameBuffer*, TimestampLessThan> {
60  public:
61   void InsertFrame(VCMFrameBuffer* frame);
62   VCMFrameBuffer* PopFrame(uint32_t timestamp);
63   VCMFrameBuffer* Front() const;
64   VCMFrameBuffer* Back() const;
65   int RecycleFramesUntilKeyFrame(FrameList::iterator* key_frame_it,
66                                  UnorderedFrameList* free_frames);
67   void CleanUpOldOrEmptyFrames(VCMDecodingState* decoding_state,
68                                UnorderedFrameList* free_frames);
69   void Reset(UnorderedFrameList* free_frames);
70 };
71 
72 class VCMJitterBuffer {
73  public:
74   VCMJitterBuffer(Clock* clock, std::unique_ptr<EventWrapper> event);
75 
76   ~VCMJitterBuffer();
77 
78   // Initializes and starts jitter buffer.
79   void Start();
80 
81   // Signals all internal events and stops the jitter buffer.
82   void Stop();
83 
84   // Returns true if the jitter buffer is running.
85   bool Running() const;
86 
87   // Empty the jitter buffer of all its data.
88   void Flush();
89 
90   // Gets number of packets received.
91   int num_packets() const;
92 
93   // Gets number of duplicated packets received.
94   int num_duplicated_packets() const;
95 
96   // Wait |max_wait_time_ms| for a complete frame to arrive.
97   // If found, a pointer to the frame is returned. Returns nullptr otherwise.
98   VCMEncodedFrame* NextCompleteFrame(uint32_t max_wait_time_ms);
99 
100   // Extract frame corresponding to input timestamp.
101   // Frame will be set to a decoding state.
102   VCMEncodedFrame* ExtractAndSetDecode(uint32_t timestamp);
103 
104   // Releases a frame returned from the jitter buffer, should be called when
105   // done with decoding.
106   void ReleaseFrame(VCMEncodedFrame* frame);
107 
108   // Returns the time in ms when the latest packet was inserted into the frame.
109   // Retransmitted is set to true if any of the packets belonging to the frame
110   // has been retransmitted.
111   int64_t LastPacketTime(const VCMEncodedFrame* frame,
112                          bool* retransmitted) const;
113 
114   // Inserts a packet into a frame returned from GetFrame().
115   // If the return value is <= 0, |frame| is invalidated and the pointer must
116   // be dropped after this function returns.
117   VCMFrameBufferEnum InsertPacket(const VCMPacket& packet, bool* retransmitted);
118 
119   // Returns the estimated jitter in milliseconds.
120   uint32_t EstimatedJitterMs();
121 
122   void SetNackSettings(size_t max_nack_list_size,
123                        int max_packet_age_to_nack,
124                        int max_incomplete_time_ms);
125 
126   // Returns a list of the sequence numbers currently missing.
127   std::vector<uint16_t> GetNackList(bool* request_key_frame);
128 
129  private:
130   class SequenceNumberLessThan {
131    public:
operator()132     bool operator()(const uint16_t& sequence_number1,
133                     const uint16_t& sequence_number2) const {
134       return IsNewerSequenceNumber(sequence_number2, sequence_number1);
135     }
136   };
137   typedef std::set<uint16_t, SequenceNumberLessThan> SequenceNumberSet;
138 
139   // Gets the frame assigned to the timestamp of the packet. May recycle
140   // existing frames if no free frames are available. Returns an error code if
141   // failing, or kNoError on success. |frame_list| contains which list the
142   // packet was in, or NULL if it was not in a FrameList (a new frame).
143   VCMFrameBufferEnum GetFrame(const VCMPacket& packet,
144                               VCMFrameBuffer** frame,
145                               FrameList** frame_list)
146       RTC_EXCLUSIVE_LOCKS_REQUIRED(crit_sect_);
147 
148   // Returns true if |frame| is continuous in |decoding_state|, not taking
149   // decodable frames into account.
150   bool IsContinuousInState(const VCMFrameBuffer& frame,
151                            const VCMDecodingState& decoding_state) const
152       RTC_EXCLUSIVE_LOCKS_REQUIRED(crit_sect_);
153   // Returns true if |frame| is continuous in the |last_decoded_state_|, taking
154   // all decodable frames into account.
155   bool IsContinuous(const VCMFrameBuffer& frame) const
156       RTC_EXCLUSIVE_LOCKS_REQUIRED(crit_sect_);
157   // Looks for frames in |incomplete_frames_| which are continuous in the
158   // provided |decoded_state|. Starts the search from the timestamp of
159   // |decoded_state|.
160   void FindAndInsertContinuousFramesWithState(
161       const VCMDecodingState& decoded_state)
162       RTC_EXCLUSIVE_LOCKS_REQUIRED(crit_sect_);
163   // Looks for frames in |incomplete_frames_| which are continuous in
164   // |last_decoded_state_| taking all decodable frames into account. Starts
165   // the search from |new_frame|.
166   void FindAndInsertContinuousFrames(const VCMFrameBuffer& new_frame)
167       RTC_EXCLUSIVE_LOCKS_REQUIRED(crit_sect_);
168   VCMFrameBuffer* NextFrame() const RTC_EXCLUSIVE_LOCKS_REQUIRED(crit_sect_);
169   // Returns true if the NACK list was updated to cover sequence numbers up to
170   // |sequence_number|. If false a key frame is needed to get into a state where
171   // we can continue decoding.
172   bool UpdateNackList(uint16_t sequence_number)
173       RTC_EXCLUSIVE_LOCKS_REQUIRED(crit_sect_);
174   bool TooLargeNackList() const;
175   // Returns true if the NACK list was reduced without problem. If false a key
176   // frame is needed to get into a state where we can continue decoding.
177   bool HandleTooLargeNackList() RTC_EXCLUSIVE_LOCKS_REQUIRED(crit_sect_);
178   bool MissingTooOldPacket(uint16_t latest_sequence_number) const
179       RTC_EXCLUSIVE_LOCKS_REQUIRED(crit_sect_);
180   // Returns true if the too old packets was successfully removed from the NACK
181   // list. If false, a key frame is needed to get into a state where we can
182   // continue decoding.
183   bool HandleTooOldPackets(uint16_t latest_sequence_number)
184       RTC_EXCLUSIVE_LOCKS_REQUIRED(crit_sect_);
185   // Drops all packets in the NACK list up until |last_decoded_sequence_number|.
186   void DropPacketsFromNackList(uint16_t last_decoded_sequence_number);
187 
188   // Gets an empty frame, creating a new frame if necessary (i.e. increases
189   // jitter buffer size).
190   VCMFrameBuffer* GetEmptyFrame() RTC_EXCLUSIVE_LOCKS_REQUIRED(crit_sect_);
191 
192   // Attempts to increase the size of the jitter buffer. Returns true on
193   // success, false otherwise.
194   bool TryToIncreaseJitterBufferSize() RTC_EXCLUSIVE_LOCKS_REQUIRED(crit_sect_);
195 
196   // Recycles oldest frames until a key frame is found. Used if jitter buffer is
197   // completely full. Returns true if a key frame was found.
198   bool RecycleFramesUntilKeyFrame() RTC_EXCLUSIVE_LOCKS_REQUIRED(crit_sect_);
199 
200   // Update rolling average of packets per frame.
201   void UpdateAveragePacketsPerFrame(int current_number_packets_);
202 
203   // Cleans the frame list in the JB from old/empty frames.
204   // Should only be called prior to actual use.
205   void CleanUpOldOrEmptyFrames() RTC_EXCLUSIVE_LOCKS_REQUIRED(crit_sect_);
206 
207   // Returns true if |packet| is likely to have been retransmitted.
208   bool IsPacketRetransmitted(const VCMPacket& packet) const;
209 
210   // The following three functions update the jitter estimate with the
211   // payload size, receive time and RTP timestamp of a frame.
212   void UpdateJitterEstimate(const VCMJitterSample& sample,
213                             bool incomplete_frame);
214   void UpdateJitterEstimate(const VCMFrameBuffer& frame, bool incomplete_frame);
215   void UpdateJitterEstimate(int64_t latest_packet_time_ms,
216                             uint32_t timestamp,
217                             unsigned int frame_size,
218                             bool incomplete_frame);
219 
220   int NonContinuousOrIncompleteDuration()
221       RTC_EXCLUSIVE_LOCKS_REQUIRED(crit_sect_);
222 
223   uint16_t EstimatedLowSequenceNumber(const VCMFrameBuffer& frame) const;
224 
225   // Reset frame buffer and return it to free_frames_.
226   void RecycleFrameBuffer(VCMFrameBuffer* frame)
227       RTC_EXCLUSIVE_LOCKS_REQUIRED(crit_sect_);
228 
229   Clock* clock_;
230   // If we are running (have started) or not.
231   bool running_;
232   rtc::CriticalSection crit_sect_;
233   // Event to signal when we have a frame ready for decoder.
234   std::unique_ptr<EventWrapper> frame_event_;
235   // Number of allocated frames.
236   int max_number_of_frames_;
237   UnorderedFrameList free_frames_ RTC_GUARDED_BY(crit_sect_);
238   FrameList decodable_frames_ RTC_GUARDED_BY(crit_sect_);
239   FrameList incomplete_frames_ RTC_GUARDED_BY(crit_sect_);
240   VCMDecodingState last_decoded_state_ RTC_GUARDED_BY(crit_sect_);
241   bool first_packet_since_reset_;
242 
243   // Number of packets in a row that have been too old.
244   int num_consecutive_old_packets_;
245   // Number of packets received.
246   int num_packets_ RTC_GUARDED_BY(crit_sect_);
247   // Number of duplicated packets received.
248   int num_duplicated_packets_ RTC_GUARDED_BY(crit_sect_);
249 
250   // Jitter estimation.
251   // Filter for estimating jitter.
252   VCMJitterEstimator jitter_estimate_;
253   // Calculates network delays used for jitter calculations.
254   VCMInterFrameDelay inter_frame_delay_;
255   VCMJitterSample waiting_for_completion_;
256 
257   // Holds the internal NACK list (the missing sequence numbers).
258   SequenceNumberSet missing_sequence_numbers_;
259   uint16_t latest_received_sequence_number_;
260   size_t max_nack_list_size_;
261   int max_packet_age_to_nack_;  // Measured in sequence numbers.
262   int max_incomplete_time_ms_;
263 
264   // Estimated rolling average of packets per frame
265   float average_packets_per_frame_;
266   // average_packets_per_frame converges fast if we have fewer than this many
267   // frames.
268   int frame_counter_;
269 
270   RTC_DISALLOW_COPY_AND_ASSIGN(VCMJitterBuffer);
271 };
272 }  // namespace webrtc
273 
274 #endif  // MODULES_VIDEO_CODING_JITTER_BUFFER_H_
275