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