2 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
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.
11 #ifndef WEBRTC_MODULES_VIDEO_CODING_MAIN_SOURCE_JITTER_BUFFER_H_
12 #define WEBRTC_MODULES_VIDEO_CODING_MAIN_SOURCE_JITTER_BUFFER_H_
19 #include "webrtc/base/constructormagic.h"
20 #include "webrtc/modules/interface/module_common_types.h"
21 #include "webrtc/modules/video_coding/main/interface/video_coding.h"
22 #include "webrtc/modules/video_coding/main/interface/video_coding_defines.h"
23 #include "webrtc/modules/video_coding/main/source/decoding_state.h"
24 #include "webrtc/modules/video_coding/main/source/inter_frame_delay.h"
25 #include "webrtc/modules/video_coding/main/source/jitter_buffer_common.h"
26 #include "webrtc/modules/video_coding/main/source/jitter_estimator.h"
27 #include "webrtc/system_wrappers/interface/critical_section_wrapper.h"
28 #include "webrtc/typedefs.h"
37 // forward declarations
43 class VCMEncodedFrame;
45 typedef std::list<VCMFrameBuffer*> UnorderedFrameList;
47 struct VCMJitterSample {
48 VCMJitterSample() : timestamp(0), frame_size(0), latest_packet_time(-1) {}
51 int64_t latest_packet_time;
54 class TimestampLessThan {
56 bool operator() (const uint32_t& timestamp1,
57 const uint32_t& timestamp2) const {
58 return IsNewerTimestamp(timestamp2, timestamp1);
63 : public std::map<uint32_t, VCMFrameBuffer*, TimestampLessThan> {
65 void InsertFrame(VCMFrameBuffer* frame);
66 VCMFrameBuffer* FindFrame(uint32_t timestamp) const;
67 VCMFrameBuffer* PopFrame(uint32_t timestamp);
68 VCMFrameBuffer* Front() const;
69 VCMFrameBuffer* Back() const;
70 int RecycleFramesUntilKeyFrame(FrameList::iterator* key_frame_it,
71 UnorderedFrameList* free_frames);
72 int CleanUpOldOrEmptyFrames(VCMDecodingState* decoding_state,
73 UnorderedFrameList* free_frames);
74 void Reset(UnorderedFrameList* free_frames);
77 class VCMJitterBuffer {
79 VCMJitterBuffer(Clock* clock,
80 EventFactory* event_factory);
81 virtual ~VCMJitterBuffer();
83 // Makes |this| a deep copy of |rhs|.
84 void CopyFrom(const VCMJitterBuffer& rhs);
86 // Initializes and starts jitter buffer.
89 // Signals all internal events and stops the jitter buffer.
92 // Returns true if the jitter buffer is running.
95 // Empty the jitter buffer of all its data.
98 // Get the number of received frames, by type, since the jitter buffer
100 std::map<FrameType, uint32_t> FrameStatistics() const;
102 // The number of packets discarded by the jitter buffer because the decoder
103 // won't be able to decode them.
104 int num_not_decodable_packets() const;
106 // Gets number of packets received.
107 int num_packets() const;
109 // Gets number of duplicated packets received.
110 int num_duplicated_packets() const;
112 // Gets number of packets discarded by the jitter buffer.
113 int num_discarded_packets() const;
115 // Statistics, Calculate frame and bit rates.
116 void IncomingRateStatistics(unsigned int* framerate,
117 unsigned int* bitrate);
119 // Checks if the packet sequence will be complete if the next frame would be
120 // grabbed for decoding. That is, if a frame has been lost between the
121 // last decoded frame and the next, or if the next frame is missing one
123 bool CompleteSequenceWithNextFrame();
125 // Wait |max_wait_time_ms| for a complete frame to arrive.
126 // The function returns true once such a frame is found, its corresponding
127 // timestamp is returned. Otherwise, returns false.
128 bool NextCompleteTimestamp(uint32_t max_wait_time_ms, uint32_t* timestamp);
130 // Locates a frame for decoding (even an incomplete) without delay.
131 // The function returns true once such a frame is found, its corresponding
132 // timestamp is returned. Otherwise, returns false.
133 bool NextMaybeIncompleteTimestamp(uint32_t* timestamp);
135 // Extract frame corresponding to input timestamp.
136 // Frame will be set to a decoding state.
137 VCMEncodedFrame* ExtractAndSetDecode(uint32_t timestamp);
139 // Releases a frame returned from the jitter buffer, should be called when
140 // done with decoding.
141 void ReleaseFrame(VCMEncodedFrame* frame);
143 // Returns the time in ms when the latest packet was inserted into the frame.
144 // Retransmitted is set to true if any of the packets belonging to the frame
145 // has been retransmitted.
146 int64_t LastPacketTime(const VCMEncodedFrame* frame,
147 bool* retransmitted) const;
149 // Inserts a packet into a frame returned from GetFrame().
150 // If the return value is <= 0, |frame| is invalidated and the pointer must
151 // be dropped after this function returns.
152 VCMFrameBufferEnum InsertPacket(const VCMPacket& packet,
153 bool* retransmitted);
155 // Returns the estimated jitter in milliseconds.
156 uint32_t EstimatedJitterMs();
158 // Updates the round-trip time estimate.
159 void UpdateRtt(uint32_t rtt_ms);
161 // Set the NACK mode. |highRttNackThreshold| is an RTT threshold in ms above
162 // which NACK will be disabled if the NACK mode is |kNackHybrid|, -1 meaning
163 // that NACK is always enabled in the hybrid mode.
164 // |lowRttNackThreshold| is an RTT threshold in ms below which we expect to
165 // rely on NACK only, and therefore are using larger buffers to have time to
166 // wait for retransmissions.
167 void SetNackMode(VCMNackMode mode, int low_rtt_nack_threshold_ms,
168 int high_rtt_nack_threshold_ms);
170 void SetNackSettings(size_t max_nack_list_size,
171 int max_packet_age_to_nack,
172 int max_incomplete_time_ms);
174 // Returns the current NACK mode.
175 VCMNackMode nack_mode() const;
177 // Returns a list of the sequence numbers currently missing.
178 uint16_t* GetNackList(uint16_t* nack_list_size, bool* request_key_frame);
180 // Set decode error mode - Should not be changed in the middle of the
181 // session. Changes will not influence frames already in the buffer.
182 void SetDecodeErrorMode(VCMDecodeErrorMode error_mode);
183 int64_t LastDecodedTimestamp() const;
184 VCMDecodeErrorMode decode_error_mode() const {return decode_error_mode_;}
186 // Used to compute time of complete continuous frames. Returns the timestamps
187 // corresponding to the start and end of the continuous complete buffer.
188 void RenderBufferSize(uint32_t* timestamp_start, uint32_t* timestamp_end);
191 class SequenceNumberLessThan {
193 bool operator() (const uint16_t& sequence_number1,
194 const uint16_t& sequence_number2) const {
195 return IsNewerSequenceNumber(sequence_number2, sequence_number1);
198 typedef std::set<uint16_t, SequenceNumberLessThan> SequenceNumberSet;
200 // Gets the frame assigned to the timestamp of the packet. May recycle
201 // existing frames if no free frames are available. Returns an error code if
202 // failing, or kNoError on success.
203 VCMFrameBufferEnum GetFrame(const VCMPacket& packet, VCMFrameBuffer** frame);
204 void CopyFrames(FrameList* to_list, const FrameList& from_list);
205 void CopyFrames(FrameList* to_list, const FrameList& from_list, int* index);
206 // Returns true if |frame| is continuous in |decoding_state|, not taking
207 // decodable frames into account.
208 bool IsContinuousInState(const VCMFrameBuffer& frame,
209 const VCMDecodingState& decoding_state) const;
210 // Returns true if |frame| is continuous in the |last_decoded_state_|, taking
211 // all decodable frames into account.
212 bool IsContinuous(const VCMFrameBuffer& frame) const;
213 // Looks for frames in |incomplete_frames_| which are continuous in
214 // |last_decoded_state_| taking all decodable frames into account. Starts
215 // the search from |new_frame|.
216 void FindAndInsertContinuousFrames(const VCMFrameBuffer& new_frame);
217 VCMFrameBuffer* NextFrame() const;
218 // Returns true if the NACK list was updated to cover sequence numbers up to
219 // |sequence_number|. If false a key frame is needed to get into a state where
220 // we can continue decoding.
221 bool UpdateNackList(uint16_t sequence_number);
222 bool TooLargeNackList() const;
223 // Returns true if the NACK list was reduced without problem. If false a key
224 // frame is needed to get into a state where we can continue decoding.
225 bool HandleTooLargeNackList();
226 bool MissingTooOldPacket(uint16_t latest_sequence_number) const;
227 // Returns true if the too old packets was successfully removed from the NACK
228 // list. If false, a key frame is needed to get into a state where we can
229 // continue decoding.
230 bool HandleTooOldPackets(uint16_t latest_sequence_number);
231 // Drops all packets in the NACK list up until |last_decoded_sequence_number|.
232 void DropPacketsFromNackList(uint16_t last_decoded_sequence_number);
234 void ReleaseFrameIfNotDecoding(VCMFrameBuffer* frame);
236 // Gets an empty frame, creating a new frame if necessary (i.e. increases
237 // jitter buffer size).
238 VCMFrameBuffer* GetEmptyFrame();
240 // Attempts to increase the size of the jitter buffer. Returns true on
241 // success, false otherwise.
242 bool TryToIncreaseJitterBufferSize();
244 // Recycles oldest frames until a key frame is found. Used if jitter buffer is
245 // completely full. Returns true if a key frame was found.
246 bool RecycleFramesUntilKeyFrame();
248 // Updates the frame statistics.
249 // Counts only complete frames, so decodable incomplete frames will not be
251 void CountFrame(const VCMFrameBuffer& frame);
253 // Update rolling average of packets per frame.
254 void UpdateAveragePacketsPerFrame(int current_number_packets_);
256 // Cleans the frame list in the JB from old/empty frames.
257 // Should only be called prior to actual use.
258 void CleanUpOldOrEmptyFrames();
260 // Returns true if |packet| is likely to have been retransmitted.
261 bool IsPacketRetransmitted(const VCMPacket& packet) const;
263 // The following three functions update the jitter estimate with the
264 // payload size, receive time and RTP timestamp of a frame.
265 void UpdateJitterEstimate(const VCMJitterSample& sample,
266 bool incomplete_frame);
267 void UpdateJitterEstimate(const VCMFrameBuffer& frame, bool incomplete_frame);
268 void UpdateJitterEstimate(int64_t latest_packet_time_ms,
270 unsigned int frame_size,
271 bool incomplete_frame);
273 // Returns true if we should wait for retransmissions, false otherwise.
274 bool WaitForRetransmissions();
276 int NonContinuousOrIncompleteDuration();
278 uint16_t EstimatedLowSequenceNumber(const VCMFrameBuffer& frame) const;
280 void UpdateHistograms();
283 // If we are running (have started) or not.
285 CriticalSectionWrapper* crit_sect_;
286 // Event to signal when we have a frame ready for decoder.
287 scoped_ptr<EventWrapper> frame_event_;
288 // Event to signal when we have received a packet.
289 scoped_ptr<EventWrapper> packet_event_;
290 // Number of allocated frames.
291 int max_number_of_frames_;
292 // Array of pointers to the frames in jitter buffer.
293 VCMFrameBuffer* frame_buffers_[kMaxNumberOfFrames];
294 UnorderedFrameList free_frames_;
295 FrameList decodable_frames_;
296 FrameList incomplete_frames_;
297 VCMDecodingState last_decoded_state_;
298 bool first_packet_since_reset_;
301 // Frame counts for each type (key, delta, ...)
302 std::map<FrameType, uint32_t> receive_statistics_;
303 // Latest calculated frame rates of incoming stream.
304 unsigned int incoming_frame_rate_;
305 unsigned int incoming_frame_count_;
306 int64_t time_last_incoming_frame_count_;
307 unsigned int incoming_bit_count_;
308 unsigned int incoming_bit_rate_;
309 unsigned int drop_count_; // Frame drop counter.
310 // Number of frames in a row that have been too old.
311 int num_consecutive_old_frames_;
312 // Number of packets in a row that have been too old.
313 int num_consecutive_old_packets_;
314 // Number of packets received.
316 // Number of duplicated packets received.
317 int num_duplicated_packets_;
318 // Number of packets discarded by the jitter buffer.
319 int num_discarded_packets_;
321 // Jitter estimation.
322 // Filter for estimating jitter.
323 VCMJitterEstimator jitter_estimate_;
324 // Calculates network delays used for jitter calculations.
325 VCMInterFrameDelay inter_frame_delay_;
326 VCMJitterSample waiting_for_completion_;
329 // NACK and retransmissions.
330 VCMNackMode nack_mode_;
331 int low_rtt_nack_threshold_ms_;
332 int high_rtt_nack_threshold_ms_;
333 // Holds the internal NACK list (the missing sequence numbers).
334 SequenceNumberSet missing_sequence_numbers_;
335 uint16_t latest_received_sequence_number_;
336 std::vector<uint16_t> nack_seq_nums_;
337 size_t max_nack_list_size_;
338 int max_packet_age_to_nack_; // Measured in sequence numbers.
339 int max_incomplete_time_ms_;
341 VCMDecodeErrorMode decode_error_mode_;
342 // Estimated rolling average of packets per frame
343 float average_packets_per_frame_;
344 // average_packets_per_frame converges fast if we have fewer than this many
347 DISALLOW_COPY_AND_ASSIGN(VCMJitterBuffer);
349 } // namespace webrtc
351 #endif // WEBRTC_MODULES_VIDEO_CODING_MAIN_SOURCE_JITTER_BUFFER_H_