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 #include "modules/video_coding/jitter_buffer.h"
11 
12 #include <assert.h>
13 
14 #include <algorithm>
15 #include <limits>
16 #include <utility>
17 
18 #include "modules/video_coding/frame_buffer.h"
19 #include "modules/video_coding/include/video_coding.h"
20 #include "modules/video_coding/inter_frame_delay.h"
21 #include "modules/video_coding/internal_defines.h"
22 #include "modules/video_coding/jitter_buffer_common.h"
23 #include "modules/video_coding/jitter_estimator.h"
24 #include "modules/video_coding/packet.h"
25 #include "rtc_base/checks.h"
26 #include "rtc_base/logging.h"
27 #include "system_wrappers/include/clock.h"
28 
29 namespace webrtc {
30 // Use this rtt if no value has been reported.
31 static const int64_t kDefaultRtt = 200;
32 
33 typedef std::pair<uint32_t, VCMFrameBuffer*> FrameListPair;
34 
IsKeyFrame(FrameListPair pair)35 bool IsKeyFrame(FrameListPair pair) {
36   return pair.second->FrameType() == VideoFrameType::kVideoFrameKey;
37 }
38 
HasNonEmptyState(FrameListPair pair)39 bool HasNonEmptyState(FrameListPair pair) {
40   return pair.second->GetState() != kStateEmpty;
41 }
42 
InsertFrame(VCMFrameBuffer * frame)43 void FrameList::InsertFrame(VCMFrameBuffer* frame) {
44   insert(rbegin().base(), FrameListPair(frame->Timestamp(), frame));
45 }
46 
PopFrame(uint32_t timestamp)47 VCMFrameBuffer* FrameList::PopFrame(uint32_t timestamp) {
48   FrameList::iterator it = find(timestamp);
49   if (it == end())
50     return NULL;
51   VCMFrameBuffer* frame = it->second;
52   erase(it);
53   return frame;
54 }
55 
Front() const56 VCMFrameBuffer* FrameList::Front() const {
57   return begin()->second;
58 }
59 
Back() const60 VCMFrameBuffer* FrameList::Back() const {
61   return rbegin()->second;
62 }
63 
RecycleFramesUntilKeyFrame(FrameList::iterator * key_frame_it,UnorderedFrameList * free_frames)64 int FrameList::RecycleFramesUntilKeyFrame(FrameList::iterator* key_frame_it,
65                                           UnorderedFrameList* free_frames) {
66   int drop_count = 0;
67   FrameList::iterator it = begin();
68   while (!empty()) {
69     // Throw at least one frame.
70     it->second->Reset();
71     free_frames->push_back(it->second);
72     erase(it++);
73     ++drop_count;
74     if (it != end() &&
75         it->second->FrameType() == VideoFrameType::kVideoFrameKey) {
76       *key_frame_it = it;
77       return drop_count;
78     }
79   }
80   *key_frame_it = end();
81   return drop_count;
82 }
83 
CleanUpOldOrEmptyFrames(VCMDecodingState * decoding_state,UnorderedFrameList * free_frames)84 void FrameList::CleanUpOldOrEmptyFrames(VCMDecodingState* decoding_state,
85                                         UnorderedFrameList* free_frames) {
86   while (!empty()) {
87     VCMFrameBuffer* oldest_frame = Front();
88     bool remove_frame = false;
89     if (oldest_frame->GetState() == kStateEmpty && size() > 1) {
90       // This frame is empty, try to update the last decoded state and drop it
91       // if successful.
92       remove_frame = decoding_state->UpdateEmptyFrame(oldest_frame);
93     } else {
94       remove_frame = decoding_state->IsOldFrame(oldest_frame);
95     }
96     if (!remove_frame) {
97       break;
98     }
99     free_frames->push_back(oldest_frame);
100     erase(begin());
101   }
102 }
103 
Reset(UnorderedFrameList * free_frames)104 void FrameList::Reset(UnorderedFrameList* free_frames) {
105   while (!empty()) {
106     begin()->second->Reset();
107     free_frames->push_back(begin()->second);
108     erase(begin());
109   }
110 }
111 
VCMJitterBuffer(Clock * clock,std::unique_ptr<EventWrapper> event)112 VCMJitterBuffer::VCMJitterBuffer(Clock* clock,
113                                  std::unique_ptr<EventWrapper> event)
114     : clock_(clock),
115       running_(false),
116       frame_event_(std::move(event)),
117       max_number_of_frames_(kStartNumberOfFrames),
118       free_frames_(),
119       decodable_frames_(),
120       incomplete_frames_(),
121       last_decoded_state_(),
122       first_packet_since_reset_(true),
123       num_consecutive_old_packets_(0),
124       num_packets_(0),
125       num_duplicated_packets_(0),
126       jitter_estimate_(clock),
127       inter_frame_delay_(clock_->TimeInMilliseconds()),
128       missing_sequence_numbers_(SequenceNumberLessThan()),
129       latest_received_sequence_number_(0),
130       max_nack_list_size_(0),
131       max_packet_age_to_nack_(0),
132       max_incomplete_time_ms_(0),
133       average_packets_per_frame_(0.0f),
134       frame_counter_(0) {
135   for (int i = 0; i < kStartNumberOfFrames; i++)
136     free_frames_.push_back(new VCMFrameBuffer());
137 }
138 
~VCMJitterBuffer()139 VCMJitterBuffer::~VCMJitterBuffer() {
140   Stop();
141   for (UnorderedFrameList::iterator it = free_frames_.begin();
142        it != free_frames_.end(); ++it) {
143     delete *it;
144   }
145   for (FrameList::iterator it = incomplete_frames_.begin();
146        it != incomplete_frames_.end(); ++it) {
147     delete it->second;
148   }
149   for (FrameList::iterator it = decodable_frames_.begin();
150        it != decodable_frames_.end(); ++it) {
151     delete it->second;
152   }
153 }
154 
Start()155 void VCMJitterBuffer::Start() {
156   MutexLock lock(&mutex_);
157   running_ = true;
158 
159   num_consecutive_old_packets_ = 0;
160   num_packets_ = 0;
161   num_duplicated_packets_ = 0;
162 
163   // Start in a non-signaled state.
164   waiting_for_completion_.frame_size = 0;
165   waiting_for_completion_.timestamp = 0;
166   waiting_for_completion_.latest_packet_time = -1;
167   first_packet_since_reset_ = true;
168   last_decoded_state_.Reset();
169 
170   decodable_frames_.Reset(&free_frames_);
171   incomplete_frames_.Reset(&free_frames_);
172 }
173 
Stop()174 void VCMJitterBuffer::Stop() {
175   MutexLock lock(&mutex_);
176   running_ = false;
177   last_decoded_state_.Reset();
178 
179   // Make sure we wake up any threads waiting on these events.
180   frame_event_->Set();
181 }
182 
Running() const183 bool VCMJitterBuffer::Running() const {
184   MutexLock lock(&mutex_);
185   return running_;
186 }
187 
Flush()188 void VCMJitterBuffer::Flush() {
189   MutexLock lock(&mutex_);
190   decodable_frames_.Reset(&free_frames_);
191   incomplete_frames_.Reset(&free_frames_);
192   last_decoded_state_.Reset();  // TODO(mikhal): sync reset.
193   num_consecutive_old_packets_ = 0;
194   // Also reset the jitter and delay estimates
195   jitter_estimate_.Reset();
196   inter_frame_delay_.Reset(clock_->TimeInMilliseconds());
197   waiting_for_completion_.frame_size = 0;
198   waiting_for_completion_.timestamp = 0;
199   waiting_for_completion_.latest_packet_time = -1;
200   first_packet_since_reset_ = true;
201   missing_sequence_numbers_.clear();
202 }
203 
num_packets() const204 int VCMJitterBuffer::num_packets() const {
205   MutexLock lock(&mutex_);
206   return num_packets_;
207 }
208 
num_duplicated_packets() const209 int VCMJitterBuffer::num_duplicated_packets() const {
210   MutexLock lock(&mutex_);
211   return num_duplicated_packets_;
212 }
213 
214 // Returns immediately or a |max_wait_time_ms| ms event hang waiting for a
215 // complete frame, |max_wait_time_ms| decided by caller.
NextCompleteFrame(uint32_t max_wait_time_ms)216 VCMEncodedFrame* VCMJitterBuffer::NextCompleteFrame(uint32_t max_wait_time_ms) {
217   MutexLock lock(&mutex_);
218   if (!running_) {
219     return nullptr;
220   }
221   CleanUpOldOrEmptyFrames();
222 
223   if (decodable_frames_.empty() ||
224       decodable_frames_.Front()->GetState() != kStateComplete) {
225     const int64_t end_wait_time_ms =
226         clock_->TimeInMilliseconds() + max_wait_time_ms;
227     int64_t wait_time_ms = max_wait_time_ms;
228     while (wait_time_ms > 0) {
229       mutex_.Unlock();
230       const EventTypeWrapper ret =
231           frame_event_->Wait(static_cast<uint32_t>(wait_time_ms));
232       mutex_.Lock();
233       if (ret == kEventSignaled) {
234         // Are we shutting down the jitter buffer?
235         if (!running_) {
236           return nullptr;
237         }
238         // Finding oldest frame ready for decoder.
239         CleanUpOldOrEmptyFrames();
240         if (decodable_frames_.empty() ||
241             decodable_frames_.Front()->GetState() != kStateComplete) {
242           wait_time_ms = end_wait_time_ms - clock_->TimeInMilliseconds();
243         } else {
244           break;
245         }
246       } else {
247         break;
248       }
249     }
250   }
251   if (decodable_frames_.empty() ||
252       decodable_frames_.Front()->GetState() != kStateComplete) {
253     return nullptr;
254   }
255   return decodable_frames_.Front();
256 }
257 
ExtractAndSetDecode(uint32_t timestamp)258 VCMEncodedFrame* VCMJitterBuffer::ExtractAndSetDecode(uint32_t timestamp) {
259   MutexLock lock(&mutex_);
260   if (!running_) {
261     return NULL;
262   }
263   // Extract the frame with the desired timestamp.
264   VCMFrameBuffer* frame = decodable_frames_.PopFrame(timestamp);
265   bool continuous = true;
266   if (!frame) {
267     frame = incomplete_frames_.PopFrame(timestamp);
268     if (frame)
269       continuous = last_decoded_state_.ContinuousFrame(frame);
270     else
271       return NULL;
272   }
273   // Frame pulled out from jitter buffer, update the jitter estimate.
274   const bool retransmitted = (frame->GetNackCount() > 0);
275   if (retransmitted) {
276     jitter_estimate_.FrameNacked();
277   } else if (frame->size() > 0) {
278     // Ignore retransmitted and empty frames.
279     if (waiting_for_completion_.latest_packet_time >= 0) {
280       UpdateJitterEstimate(waiting_for_completion_, true);
281     }
282     if (frame->GetState() == kStateComplete) {
283       UpdateJitterEstimate(*frame, false);
284     } else {
285       // Wait for this one to get complete.
286       waiting_for_completion_.frame_size = frame->size();
287       waiting_for_completion_.latest_packet_time = frame->LatestPacketTimeMs();
288       waiting_for_completion_.timestamp = frame->Timestamp();
289     }
290   }
291 
292   // The state must be changed to decoding before cleaning up zero sized
293   // frames to avoid empty frames being cleaned up and then given to the
294   // decoder. Propagates the missing_frame bit.
295   frame->PrepareForDecode(continuous);
296 
297   // We have a frame - update the last decoded state and nack list.
298   last_decoded_state_.SetState(frame);
299   DropPacketsFromNackList(last_decoded_state_.sequence_num());
300 
301   if ((*frame).IsSessionComplete())
302     UpdateAveragePacketsPerFrame(frame->NumPackets());
303 
304   return frame;
305 }
306 
307 // Release frame when done with decoding. Should never be used to release
308 // frames from within the jitter buffer.
ReleaseFrame(VCMEncodedFrame * frame)309 void VCMJitterBuffer::ReleaseFrame(VCMEncodedFrame* frame) {
310   RTC_CHECK(frame != nullptr);
311   MutexLock lock(&mutex_);
312   VCMFrameBuffer* frame_buffer = static_cast<VCMFrameBuffer*>(frame);
313   RecycleFrameBuffer(frame_buffer);
314 }
315 
316 // Gets frame to use for this timestamp. If no match, get empty frame.
GetFrame(const VCMPacket & packet,VCMFrameBuffer ** frame,FrameList ** frame_list)317 VCMFrameBufferEnum VCMJitterBuffer::GetFrame(const VCMPacket& packet,
318                                              VCMFrameBuffer** frame,
319                                              FrameList** frame_list) {
320   *frame = incomplete_frames_.PopFrame(packet.timestamp);
321   if (*frame != NULL) {
322     *frame_list = &incomplete_frames_;
323     return kNoError;
324   }
325   *frame = decodable_frames_.PopFrame(packet.timestamp);
326   if (*frame != NULL) {
327     *frame_list = &decodable_frames_;
328     return kNoError;
329   }
330 
331   *frame_list = NULL;
332   // No match, return empty frame.
333   *frame = GetEmptyFrame();
334   if (*frame == NULL) {
335     // No free frame! Try to reclaim some...
336     RTC_LOG(LS_WARNING) << "Unable to get empty frame; Recycling.";
337     bool found_key_frame = RecycleFramesUntilKeyFrame();
338     *frame = GetEmptyFrame();
339     RTC_CHECK(*frame);
340     if (!found_key_frame) {
341       RecycleFrameBuffer(*frame);
342       return kFlushIndicator;
343     }
344   }
345   (*frame)->Reset();
346   return kNoError;
347 }
348 
LastPacketTime(const VCMEncodedFrame * frame,bool * retransmitted) const349 int64_t VCMJitterBuffer::LastPacketTime(const VCMEncodedFrame* frame,
350                                         bool* retransmitted) const {
351   assert(retransmitted);
352   MutexLock lock(&mutex_);
353   const VCMFrameBuffer* frame_buffer =
354       static_cast<const VCMFrameBuffer*>(frame);
355   *retransmitted = (frame_buffer->GetNackCount() > 0);
356   return frame_buffer->LatestPacketTimeMs();
357 }
358 
InsertPacket(const VCMPacket & packet,bool * retransmitted)359 VCMFrameBufferEnum VCMJitterBuffer::InsertPacket(const VCMPacket& packet,
360                                                  bool* retransmitted) {
361   MutexLock lock(&mutex_);
362 
363   ++num_packets_;
364   // Does this packet belong to an old frame?
365   if (last_decoded_state_.IsOldPacket(&packet)) {
366     // Account only for media packets.
367     if (packet.sizeBytes > 0) {
368       num_consecutive_old_packets_++;
369     }
370     // Update last decoded sequence number if the packet arrived late and
371     // belongs to a frame with a timestamp equal to the last decoded
372     // timestamp.
373     last_decoded_state_.UpdateOldPacket(&packet);
374     DropPacketsFromNackList(last_decoded_state_.sequence_num());
375 
376     // Also see if this old packet made more incomplete frames continuous.
377     FindAndInsertContinuousFramesWithState(last_decoded_state_);
378 
379     if (num_consecutive_old_packets_ > kMaxConsecutiveOldPackets) {
380       RTC_LOG(LS_WARNING)
381           << num_consecutive_old_packets_
382           << " consecutive old packets received. Flushing the jitter buffer.";
383       Flush();
384       return kFlushIndicator;
385     }
386     return kOldPacket;
387   }
388 
389   num_consecutive_old_packets_ = 0;
390 
391   VCMFrameBuffer* frame;
392   FrameList* frame_list;
393   const VCMFrameBufferEnum error = GetFrame(packet, &frame, &frame_list);
394   if (error != kNoError)
395     return error;
396 
397   int64_t now_ms = clock_->TimeInMilliseconds();
398   // We are keeping track of the first and latest seq numbers, and
399   // the number of wraps to be able to calculate how many packets we expect.
400   if (first_packet_since_reset_) {
401     // Now it's time to start estimating jitter
402     // reset the delay estimate.
403     inter_frame_delay_.Reset(now_ms);
404   }
405 
406   // Empty packets may bias the jitter estimate (lacking size component),
407   // therefore don't let empty packet trigger the following updates:
408   if (packet.video_header.frame_type != VideoFrameType::kEmptyFrame) {
409     if (waiting_for_completion_.timestamp == packet.timestamp) {
410       // This can get bad if we have a lot of duplicate packets,
411       // we will then count some packet multiple times.
412       waiting_for_completion_.frame_size += packet.sizeBytes;
413       waiting_for_completion_.latest_packet_time = now_ms;
414     } else if (waiting_for_completion_.latest_packet_time >= 0 &&
415                waiting_for_completion_.latest_packet_time + 2000 <= now_ms) {
416       // A packet should never be more than two seconds late
417       UpdateJitterEstimate(waiting_for_completion_, true);
418       waiting_for_completion_.latest_packet_time = -1;
419       waiting_for_completion_.frame_size = 0;
420       waiting_for_completion_.timestamp = 0;
421     }
422   }
423 
424   VCMFrameBufferStateEnum previous_state = frame->GetState();
425   // Insert packet.
426   FrameData frame_data;
427   frame_data.rtt_ms = kDefaultRtt;
428   frame_data.rolling_average_packets_per_frame = average_packets_per_frame_;
429   VCMFrameBufferEnum buffer_state =
430       frame->InsertPacket(packet, now_ms, frame_data);
431 
432   if (buffer_state > 0) {
433     if (first_packet_since_reset_) {
434       latest_received_sequence_number_ = packet.seqNum;
435       first_packet_since_reset_ = false;
436     } else {
437       if (IsPacketRetransmitted(packet)) {
438         frame->IncrementNackCount();
439       }
440       if (!UpdateNackList(packet.seqNum) &&
441           packet.video_header.frame_type != VideoFrameType::kVideoFrameKey) {
442         buffer_state = kFlushIndicator;
443       }
444 
445       latest_received_sequence_number_ =
446           LatestSequenceNumber(latest_received_sequence_number_, packet.seqNum);
447     }
448   }
449 
450   // Is the frame already in the decodable list?
451   bool continuous = IsContinuous(*frame);
452   switch (buffer_state) {
453     case kGeneralError:
454     case kTimeStampError:
455     case kSizeError: {
456       RecycleFrameBuffer(frame);
457       break;
458     }
459     case kCompleteSession: {
460       if (previous_state != kStateComplete) {
461         if (continuous) {
462           // Signal that we have a complete session.
463           frame_event_->Set();
464         }
465       }
466 
467       *retransmitted = (frame->GetNackCount() > 0);
468       if (continuous) {
469         decodable_frames_.InsertFrame(frame);
470         FindAndInsertContinuousFrames(*frame);
471       } else {
472         incomplete_frames_.InsertFrame(frame);
473       }
474       break;
475     }
476     case kIncomplete: {
477       if (frame->GetState() == kStateEmpty &&
478           last_decoded_state_.UpdateEmptyFrame(frame)) {
479         RecycleFrameBuffer(frame);
480         return kNoError;
481       } else {
482         incomplete_frames_.InsertFrame(frame);
483       }
484       break;
485     }
486     case kNoError:
487     case kOutOfBoundsPacket:
488     case kDuplicatePacket: {
489       // Put back the frame where it came from.
490       if (frame_list != NULL) {
491         frame_list->InsertFrame(frame);
492       } else {
493         RecycleFrameBuffer(frame);
494       }
495       ++num_duplicated_packets_;
496       break;
497     }
498     case kFlushIndicator:
499       RecycleFrameBuffer(frame);
500       return kFlushIndicator;
501     default:
502       assert(false);
503   }
504   return buffer_state;
505 }
506 
IsContinuousInState(const VCMFrameBuffer & frame,const VCMDecodingState & decoding_state) const507 bool VCMJitterBuffer::IsContinuousInState(
508     const VCMFrameBuffer& frame,
509     const VCMDecodingState& decoding_state) const {
510   // Is this frame complete and continuous?
511   return (frame.GetState() == kStateComplete) &&
512          decoding_state.ContinuousFrame(&frame);
513 }
514 
IsContinuous(const VCMFrameBuffer & frame) const515 bool VCMJitterBuffer::IsContinuous(const VCMFrameBuffer& frame) const {
516   if (IsContinuousInState(frame, last_decoded_state_)) {
517     return true;
518   }
519   VCMDecodingState decoding_state;
520   decoding_state.CopyFrom(last_decoded_state_);
521   for (FrameList::const_iterator it = decodable_frames_.begin();
522        it != decodable_frames_.end(); ++it) {
523     VCMFrameBuffer* decodable_frame = it->second;
524     if (IsNewerTimestamp(decodable_frame->Timestamp(), frame.Timestamp())) {
525       break;
526     }
527     decoding_state.SetState(decodable_frame);
528     if (IsContinuousInState(frame, decoding_state)) {
529       return true;
530     }
531   }
532   return false;
533 }
534 
FindAndInsertContinuousFrames(const VCMFrameBuffer & new_frame)535 void VCMJitterBuffer::FindAndInsertContinuousFrames(
536     const VCMFrameBuffer& new_frame) {
537   VCMDecodingState decoding_state;
538   decoding_state.CopyFrom(last_decoded_state_);
539   decoding_state.SetState(&new_frame);
540   FindAndInsertContinuousFramesWithState(decoding_state);
541 }
542 
FindAndInsertContinuousFramesWithState(const VCMDecodingState & original_decoded_state)543 void VCMJitterBuffer::FindAndInsertContinuousFramesWithState(
544     const VCMDecodingState& original_decoded_state) {
545   // Copy original_decoded_state so we can move the state forward with each
546   // decodable frame we find.
547   VCMDecodingState decoding_state;
548   decoding_state.CopyFrom(original_decoded_state);
549 
550   // When temporal layers are available, we search for a complete or decodable
551   // frame until we hit one of the following:
552   // 1. Continuous base or sync layer.
553   // 2. The end of the list was reached.
554   for (FrameList::iterator it = incomplete_frames_.begin();
555        it != incomplete_frames_.end();) {
556     VCMFrameBuffer* frame = it->second;
557     if (IsNewerTimestamp(original_decoded_state.time_stamp(),
558                          frame->Timestamp())) {
559       ++it;
560       continue;
561     }
562     if (IsContinuousInState(*frame, decoding_state)) {
563       decodable_frames_.InsertFrame(frame);
564       incomplete_frames_.erase(it++);
565       decoding_state.SetState(frame);
566     } else if (frame->TemporalId() <= 0) {
567       break;
568     } else {
569       ++it;
570     }
571   }
572 }
573 
EstimatedJitterMs()574 uint32_t VCMJitterBuffer::EstimatedJitterMs() {
575   MutexLock lock(&mutex_);
576   const double rtt_mult = 1.0f;
577   return jitter_estimate_.GetJitterEstimate(rtt_mult, absl::nullopt);
578 }
579 
SetNackSettings(size_t max_nack_list_size,int max_packet_age_to_nack,int max_incomplete_time_ms)580 void VCMJitterBuffer::SetNackSettings(size_t max_nack_list_size,
581                                       int max_packet_age_to_nack,
582                                       int max_incomplete_time_ms) {
583   MutexLock lock(&mutex_);
584   assert(max_packet_age_to_nack >= 0);
585   assert(max_incomplete_time_ms_ >= 0);
586   max_nack_list_size_ = max_nack_list_size;
587   max_packet_age_to_nack_ = max_packet_age_to_nack;
588   max_incomplete_time_ms_ = max_incomplete_time_ms;
589 }
590 
NonContinuousOrIncompleteDuration()591 int VCMJitterBuffer::NonContinuousOrIncompleteDuration() {
592   if (incomplete_frames_.empty()) {
593     return 0;
594   }
595   uint32_t start_timestamp = incomplete_frames_.Front()->Timestamp();
596   if (!decodable_frames_.empty()) {
597     start_timestamp = decodable_frames_.Back()->Timestamp();
598   }
599   return incomplete_frames_.Back()->Timestamp() - start_timestamp;
600 }
601 
EstimatedLowSequenceNumber(const VCMFrameBuffer & frame) const602 uint16_t VCMJitterBuffer::EstimatedLowSequenceNumber(
603     const VCMFrameBuffer& frame) const {
604   assert(frame.GetLowSeqNum() >= 0);
605   if (frame.HaveFirstPacket())
606     return frame.GetLowSeqNum();
607 
608   // This estimate is not accurate if more than one packet with lower sequence
609   // number is lost.
610   return frame.GetLowSeqNum() - 1;
611 }
612 
GetNackList(bool * request_key_frame)613 std::vector<uint16_t> VCMJitterBuffer::GetNackList(bool* request_key_frame) {
614   MutexLock lock(&mutex_);
615   *request_key_frame = false;
616   if (last_decoded_state_.in_initial_state()) {
617     VCMFrameBuffer* next_frame = NextFrame();
618     const bool first_frame_is_key =
619         next_frame &&
620         next_frame->FrameType() == VideoFrameType::kVideoFrameKey &&
621         next_frame->HaveFirstPacket();
622     if (!first_frame_is_key) {
623       bool have_non_empty_frame =
624           decodable_frames_.end() != find_if(decodable_frames_.begin(),
625                                              decodable_frames_.end(),
626                                              HasNonEmptyState);
627       if (!have_non_empty_frame) {
628         have_non_empty_frame =
629             incomplete_frames_.end() != find_if(incomplete_frames_.begin(),
630                                                 incomplete_frames_.end(),
631                                                 HasNonEmptyState);
632       }
633       bool found_key_frame = RecycleFramesUntilKeyFrame();
634       if (!found_key_frame) {
635         *request_key_frame = have_non_empty_frame;
636         return std::vector<uint16_t>();
637       }
638     }
639   }
640   if (TooLargeNackList()) {
641     *request_key_frame = !HandleTooLargeNackList();
642   }
643   if (max_incomplete_time_ms_ > 0) {
644     int non_continuous_incomplete_duration =
645         NonContinuousOrIncompleteDuration();
646     if (non_continuous_incomplete_duration > 90 * max_incomplete_time_ms_) {
647       RTC_LOG_F(LS_WARNING) << "Too long non-decodable duration: "
648                             << non_continuous_incomplete_duration << " > "
649                             << 90 * max_incomplete_time_ms_;
650       FrameList::reverse_iterator rit = find_if(
651           incomplete_frames_.rbegin(), incomplete_frames_.rend(), IsKeyFrame);
652       if (rit == incomplete_frames_.rend()) {
653         // Request a key frame if we don't have one already.
654         *request_key_frame = true;
655         return std::vector<uint16_t>();
656       } else {
657         // Skip to the last key frame. If it's incomplete we will start
658         // NACKing it.
659         // Note that the estimated low sequence number is correct for VP8
660         // streams because only the first packet of a key frame is marked.
661         last_decoded_state_.Reset();
662         DropPacketsFromNackList(EstimatedLowSequenceNumber(*rit->second));
663       }
664     }
665   }
666   std::vector<uint16_t> nack_list(missing_sequence_numbers_.begin(),
667                                   missing_sequence_numbers_.end());
668   return nack_list;
669 }
670 
NextFrame() const671 VCMFrameBuffer* VCMJitterBuffer::NextFrame() const {
672   if (!decodable_frames_.empty())
673     return decodable_frames_.Front();
674   if (!incomplete_frames_.empty())
675     return incomplete_frames_.Front();
676   return NULL;
677 }
678 
UpdateNackList(uint16_t sequence_number)679 bool VCMJitterBuffer::UpdateNackList(uint16_t sequence_number) {
680   // Make sure we don't add packets which are already too old to be decoded.
681   if (!last_decoded_state_.in_initial_state()) {
682     latest_received_sequence_number_ = LatestSequenceNumber(
683         latest_received_sequence_number_, last_decoded_state_.sequence_num());
684   }
685   if (IsNewerSequenceNumber(sequence_number,
686                             latest_received_sequence_number_)) {
687     // Push any missing sequence numbers to the NACK list.
688     for (uint16_t i = latest_received_sequence_number_ + 1;
689          IsNewerSequenceNumber(sequence_number, i); ++i) {
690       missing_sequence_numbers_.insert(missing_sequence_numbers_.end(), i);
691     }
692     if (TooLargeNackList() && !HandleTooLargeNackList()) {
693       RTC_LOG(LS_WARNING) << "Requesting key frame due to too large NACK list.";
694       return false;
695     }
696     if (MissingTooOldPacket(sequence_number) &&
697         !HandleTooOldPackets(sequence_number)) {
698       RTC_LOG(LS_WARNING)
699           << "Requesting key frame due to missing too old packets";
700       return false;
701     }
702   } else {
703     missing_sequence_numbers_.erase(sequence_number);
704   }
705   return true;
706 }
707 
TooLargeNackList() const708 bool VCMJitterBuffer::TooLargeNackList() const {
709   return missing_sequence_numbers_.size() > max_nack_list_size_;
710 }
711 
HandleTooLargeNackList()712 bool VCMJitterBuffer::HandleTooLargeNackList() {
713   // Recycle frames until the NACK list is small enough. It is likely cheaper to
714   // request a key frame than to retransmit this many missing packets.
715   RTC_LOG_F(LS_WARNING) << "NACK list has grown too large: "
716                         << missing_sequence_numbers_.size() << " > "
717                         << max_nack_list_size_;
718   bool key_frame_found = false;
719   while (TooLargeNackList()) {
720     key_frame_found = RecycleFramesUntilKeyFrame();
721   }
722   return key_frame_found;
723 }
724 
MissingTooOldPacket(uint16_t latest_sequence_number) const725 bool VCMJitterBuffer::MissingTooOldPacket(
726     uint16_t latest_sequence_number) const {
727   if (missing_sequence_numbers_.empty()) {
728     return false;
729   }
730   const uint16_t age_of_oldest_missing_packet =
731       latest_sequence_number - *missing_sequence_numbers_.begin();
732   // Recycle frames if the NACK list contains too old sequence numbers as
733   // the packets may have already been dropped by the sender.
734   return age_of_oldest_missing_packet > max_packet_age_to_nack_;
735 }
736 
HandleTooOldPackets(uint16_t latest_sequence_number)737 bool VCMJitterBuffer::HandleTooOldPackets(uint16_t latest_sequence_number) {
738   bool key_frame_found = false;
739   const uint16_t age_of_oldest_missing_packet =
740       latest_sequence_number - *missing_sequence_numbers_.begin();
741   RTC_LOG_F(LS_WARNING) << "NACK list contains too old sequence numbers: "
742                         << age_of_oldest_missing_packet << " > "
743                         << max_packet_age_to_nack_;
744   while (MissingTooOldPacket(latest_sequence_number)) {
745     key_frame_found = RecycleFramesUntilKeyFrame();
746   }
747   return key_frame_found;
748 }
749 
DropPacketsFromNackList(uint16_t last_decoded_sequence_number)750 void VCMJitterBuffer::DropPacketsFromNackList(
751     uint16_t last_decoded_sequence_number) {
752   // Erase all sequence numbers from the NACK list which we won't need any
753   // longer.
754   missing_sequence_numbers_.erase(
755       missing_sequence_numbers_.begin(),
756       missing_sequence_numbers_.upper_bound(last_decoded_sequence_number));
757 }
758 
GetEmptyFrame()759 VCMFrameBuffer* VCMJitterBuffer::GetEmptyFrame() {
760   if (free_frames_.empty()) {
761     if (!TryToIncreaseJitterBufferSize()) {
762       return NULL;
763     }
764   }
765   VCMFrameBuffer* frame = free_frames_.front();
766   free_frames_.pop_front();
767   return frame;
768 }
769 
TryToIncreaseJitterBufferSize()770 bool VCMJitterBuffer::TryToIncreaseJitterBufferSize() {
771   if (max_number_of_frames_ >= kMaxNumberOfFrames)
772     return false;
773   free_frames_.push_back(new VCMFrameBuffer());
774   ++max_number_of_frames_;
775   return true;
776 }
777 
778 // Recycle oldest frames up to a key frame, used if jitter buffer is completely
779 // full.
RecycleFramesUntilKeyFrame()780 bool VCMJitterBuffer::RecycleFramesUntilKeyFrame() {
781   // First release incomplete frames, and only release decodable frames if there
782   // are no incomplete ones.
783   FrameList::iterator key_frame_it;
784   bool key_frame_found = false;
785   int dropped_frames = 0;
786   dropped_frames += incomplete_frames_.RecycleFramesUntilKeyFrame(
787       &key_frame_it, &free_frames_);
788   key_frame_found = key_frame_it != incomplete_frames_.end();
789   if (dropped_frames == 0) {
790     dropped_frames += decodable_frames_.RecycleFramesUntilKeyFrame(
791         &key_frame_it, &free_frames_);
792     key_frame_found = key_frame_it != decodable_frames_.end();
793   }
794   if (key_frame_found) {
795     RTC_LOG(LS_INFO) << "Found key frame while dropping frames.";
796     // Reset last decoded state to make sure the next frame decoded is a key
797     // frame, and start NACKing from here.
798     last_decoded_state_.Reset();
799     DropPacketsFromNackList(EstimatedLowSequenceNumber(*key_frame_it->second));
800   } else if (decodable_frames_.empty()) {
801     // All frames dropped. Reset the decoding state and clear missing sequence
802     // numbers as we're starting fresh.
803     last_decoded_state_.Reset();
804     missing_sequence_numbers_.clear();
805   }
806   return key_frame_found;
807 }
808 
UpdateAveragePacketsPerFrame(int current_number_packets)809 void VCMJitterBuffer::UpdateAveragePacketsPerFrame(int current_number_packets) {
810   if (frame_counter_ > kFastConvergeThreshold) {
811     average_packets_per_frame_ =
812         average_packets_per_frame_ * (1 - kNormalConvergeMultiplier) +
813         current_number_packets * kNormalConvergeMultiplier;
814   } else if (frame_counter_ > 0) {
815     average_packets_per_frame_ =
816         average_packets_per_frame_ * (1 - kFastConvergeMultiplier) +
817         current_number_packets * kFastConvergeMultiplier;
818     frame_counter_++;
819   } else {
820     average_packets_per_frame_ = current_number_packets;
821     frame_counter_++;
822   }
823 }
824 
825 // Must be called under the critical section |mutex_|.
CleanUpOldOrEmptyFrames()826 void VCMJitterBuffer::CleanUpOldOrEmptyFrames() {
827   decodable_frames_.CleanUpOldOrEmptyFrames(&last_decoded_state_,
828                                             &free_frames_);
829   incomplete_frames_.CleanUpOldOrEmptyFrames(&last_decoded_state_,
830                                              &free_frames_);
831   if (!last_decoded_state_.in_initial_state()) {
832     DropPacketsFromNackList(last_decoded_state_.sequence_num());
833   }
834 }
835 
836 // Must be called from within |mutex_|.
IsPacketRetransmitted(const VCMPacket & packet) const837 bool VCMJitterBuffer::IsPacketRetransmitted(const VCMPacket& packet) const {
838   return missing_sequence_numbers_.find(packet.seqNum) !=
839          missing_sequence_numbers_.end();
840 }
841 
842 // Must be called under the critical section |mutex_|. Should never be
843 // called with retransmitted frames, they must be filtered out before this
844 // function is called.
UpdateJitterEstimate(const VCMJitterSample & sample,bool incomplete_frame)845 void VCMJitterBuffer::UpdateJitterEstimate(const VCMJitterSample& sample,
846                                            bool incomplete_frame) {
847   if (sample.latest_packet_time == -1) {
848     return;
849   }
850   UpdateJitterEstimate(sample.latest_packet_time, sample.timestamp,
851                        sample.frame_size, incomplete_frame);
852 }
853 
854 // Must be called under the critical section mutex_. Should never be
855 // called with retransmitted frames, they must be filtered out before this
856 // function is called.
UpdateJitterEstimate(const VCMFrameBuffer & frame,bool incomplete_frame)857 void VCMJitterBuffer::UpdateJitterEstimate(const VCMFrameBuffer& frame,
858                                            bool incomplete_frame) {
859   if (frame.LatestPacketTimeMs() == -1) {
860     return;
861   }
862   // No retransmitted frames should be a part of the jitter
863   // estimate.
864   UpdateJitterEstimate(frame.LatestPacketTimeMs(), frame.Timestamp(),
865                        frame.size(), incomplete_frame);
866 }
867 
868 // Must be called under the critical section |mutex_|. Should never be
869 // called with retransmitted frames, they must be filtered out before this
870 // function is called.
UpdateJitterEstimate(int64_t latest_packet_time_ms,uint32_t timestamp,unsigned int frame_size,bool incomplete_frame)871 void VCMJitterBuffer::UpdateJitterEstimate(int64_t latest_packet_time_ms,
872                                            uint32_t timestamp,
873                                            unsigned int frame_size,
874                                            bool incomplete_frame) {
875   if (latest_packet_time_ms == -1) {
876     return;
877   }
878   int64_t frame_delay;
879   bool not_reordered = inter_frame_delay_.CalculateDelay(
880       timestamp, &frame_delay, latest_packet_time_ms);
881   // Filter out frames which have been reordered in time by the network
882   if (not_reordered) {
883     // Update the jitter estimate with the new samples
884     jitter_estimate_.UpdateEstimate(frame_delay, frame_size, incomplete_frame);
885   }
886 }
887 
RecycleFrameBuffer(VCMFrameBuffer * frame)888 void VCMJitterBuffer::RecycleFrameBuffer(VCMFrameBuffer* frame) {
889   frame->Reset();
890   free_frames_.push_back(frame);
891 }
892 
893 }  // namespace webrtc
894