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