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 "webrtc/modules/remote_bitrate_estimator/remote_bitrate_estimator_unittest_helper.h"
11 
12 #include <algorithm>
13 #include <limits>
14 #include <utility>
15 
16 namespace webrtc {
17 
18 const size_t kMtu = 1200;
19 const unsigned int kAcceptedBitrateErrorBps = 50000;
20 
21 namespace testing {
22 
OnReceiveBitrateChanged(const std::vector<unsigned int> & ssrcs,unsigned int bitrate)23 void TestBitrateObserver::OnReceiveBitrateChanged(
24     const std::vector<unsigned int>& ssrcs,
25     unsigned int bitrate) {
26   latest_bitrate_ = bitrate;
27   updated_ = true;
28 }
29 
RtpStream(int fps,int bitrate_bps,unsigned int ssrc,unsigned int frequency,uint32_t timestamp_offset,int64_t rtcp_receive_time)30 RtpStream::RtpStream(int fps,
31                      int bitrate_bps,
32                      unsigned int ssrc,
33                      unsigned int frequency,
34                      uint32_t timestamp_offset,
35                      int64_t rtcp_receive_time)
36     : fps_(fps),
37       bitrate_bps_(bitrate_bps),
38       ssrc_(ssrc),
39       frequency_(frequency),
40       next_rtp_time_(0),
41       next_rtcp_time_(rtcp_receive_time),
42       rtp_timestamp_offset_(timestamp_offset),
43       kNtpFracPerMs(4.294967296E6) {
44   assert(fps_ > 0);
45 }
46 
set_rtp_timestamp_offset(uint32_t offset)47 void RtpStream::set_rtp_timestamp_offset(uint32_t offset) {
48   rtp_timestamp_offset_ = offset;
49 }
50 
51 // Generates a new frame for this stream. If called too soon after the
52 // previous frame, no frame will be generated. The frame is split into
53 // packets.
GenerateFrame(int64_t time_now_us,PacketList * packets)54 int64_t RtpStream::GenerateFrame(int64_t time_now_us, PacketList* packets) {
55   if (time_now_us < next_rtp_time_) {
56     return next_rtp_time_;
57   }
58   assert(packets != NULL);
59   size_t bits_per_frame = (bitrate_bps_ + fps_ / 2) / fps_;
60   size_t n_packets =
61       std::max<size_t>((bits_per_frame + 4 * kMtu) / (8 * kMtu), 1u);
62   size_t packet_size = (bits_per_frame + 4 * n_packets) / (8 * n_packets);
63   for (size_t i = 0; i < n_packets; ++i) {
64     RtpPacket* packet = new RtpPacket;
65     packet->send_time = time_now_us + kSendSideOffsetUs;
66     packet->size = packet_size;
67     packet->rtp_timestamp = rtp_timestamp_offset_ + static_cast<uint32_t>(
68         ((frequency_ / 1000) * packet->send_time + 500) / 1000);
69     packet->ssrc = ssrc_;
70     packets->push_back(packet);
71   }
72   next_rtp_time_ = time_now_us + (1000000 + fps_ / 2) / fps_;
73   return next_rtp_time_;
74 }
75 
76 // The send-side time when the next frame can be generated.
next_rtp_time() const77 double RtpStream::next_rtp_time() const {
78   return next_rtp_time_;
79 }
80 
81 // Generates an RTCP packet.
Rtcp(int64_t time_now_us)82 RtpStream::RtcpPacket* RtpStream::Rtcp(int64_t time_now_us) {
83   if (time_now_us < next_rtcp_time_) {
84     return NULL;
85   }
86   RtcpPacket* rtcp = new RtcpPacket;
87   int64_t send_time_us = time_now_us + kSendSideOffsetUs;
88   rtcp->timestamp = rtp_timestamp_offset_ + static_cast<uint32_t>(
89       ((frequency_ / 1000) * send_time_us + 500) / 1000);
90   rtcp->ntp_secs = send_time_us / 1000000;
91   rtcp->ntp_frac = static_cast<int64_t>((send_time_us % 1000000) *
92       kNtpFracPerMs);
93   rtcp->ssrc = ssrc_;
94   next_rtcp_time_ = time_now_us + kRtcpIntervalUs;
95   return rtcp;
96 }
97 
set_bitrate_bps(int bitrate_bps)98 void RtpStream::set_bitrate_bps(int bitrate_bps) {
99   ASSERT_GE(bitrate_bps, 0);
100   bitrate_bps_ = bitrate_bps;
101 }
102 
bitrate_bps() const103 int RtpStream::bitrate_bps() const {
104   return bitrate_bps_;
105 }
106 
ssrc() const107 unsigned int RtpStream::ssrc() const {
108   return ssrc_;
109 }
110 
Compare(const std::pair<unsigned int,RtpStream * > & left,const std::pair<unsigned int,RtpStream * > & right)111 bool RtpStream::Compare(const std::pair<unsigned int, RtpStream*>& left,
112                         const std::pair<unsigned int, RtpStream*>& right) {
113   return left.second->next_rtp_time_ < right.second->next_rtp_time_;
114 }
115 
StreamGenerator(int capacity,double time_now)116 StreamGenerator::StreamGenerator(int capacity, double time_now)
117     : capacity_(capacity),
118       prev_arrival_time_us_(time_now) {}
119 
~StreamGenerator()120 StreamGenerator::~StreamGenerator() {
121   for (StreamMap::iterator it = streams_.begin(); it != streams_.end();
122       ++it) {
123     delete it->second;
124   }
125   streams_.clear();
126 }
127 
128 // Add a new stream.
AddStream(RtpStream * stream)129 void StreamGenerator::AddStream(RtpStream* stream) {
130   streams_[stream->ssrc()] = stream;
131 }
132 
133 // Set the link capacity.
set_capacity_bps(int capacity_bps)134 void StreamGenerator::set_capacity_bps(int capacity_bps) {
135   ASSERT_GT(capacity_bps, 0);
136   capacity_ = capacity_bps;
137 }
138 
139 // Divides |bitrate_bps| among all streams. The allocated bitrate per stream
140 // is decided by the current allocation ratios.
SetBitrateBps(int bitrate_bps)141 void StreamGenerator::SetBitrateBps(int bitrate_bps) {
142   ASSERT_GE(streams_.size(), 0u);
143   int total_bitrate_before = 0;
144   for (StreamMap::iterator it = streams_.begin(); it != streams_.end(); ++it) {
145     total_bitrate_before += it->second->bitrate_bps();
146   }
147   int64_t bitrate_before = 0;
148   int total_bitrate_after = 0;
149   for (StreamMap::iterator it = streams_.begin(); it != streams_.end(); ++it) {
150     bitrate_before += it->second->bitrate_bps();
151     int64_t bitrate_after = (bitrate_before * bitrate_bps +
152         total_bitrate_before / 2) / total_bitrate_before;
153     it->second->set_bitrate_bps(bitrate_after - total_bitrate_after);
154     total_bitrate_after += it->second->bitrate_bps();
155   }
156   ASSERT_EQ(bitrate_before, total_bitrate_before);
157   EXPECT_EQ(total_bitrate_after, bitrate_bps);
158 }
159 
160 // Set the RTP timestamp offset for the stream identified by |ssrc|.
set_rtp_timestamp_offset(unsigned int ssrc,uint32_t offset)161 void StreamGenerator::set_rtp_timestamp_offset(unsigned int ssrc,
162                                                uint32_t offset) {
163   streams_[ssrc]->set_rtp_timestamp_offset(offset);
164 }
165 
166 // TODO(holmer): Break out the channel simulation part from this class to make
167 // it possible to simulate different types of channels.
GenerateFrame(RtpStream::PacketList * packets,int64_t time_now_us)168 int64_t StreamGenerator::GenerateFrame(RtpStream::PacketList* packets,
169                                        int64_t time_now_us) {
170   assert(packets != NULL);
171   assert(packets->empty());
172   assert(capacity_ > 0);
173   StreamMap::iterator it = std::min_element(streams_.begin(), streams_.end(),
174                                             RtpStream::Compare);
175   (*it).second->GenerateFrame(time_now_us, packets);
176   int i = 0;
177   for (RtpStream::PacketList::iterator packet_it = packets->begin();
178       packet_it != packets->end(); ++packet_it) {
179     int capacity_bpus = capacity_ / 1000;
180     int64_t required_network_time_us =
181         (8 * 1000 * (*packet_it)->size + capacity_bpus / 2) / capacity_bpus;
182     prev_arrival_time_us_ = std::max(time_now_us + required_network_time_us,
183         prev_arrival_time_us_ + required_network_time_us);
184     (*packet_it)->arrival_time = prev_arrival_time_us_;
185     ++i;
186   }
187   it = std::min_element(streams_.begin(), streams_.end(), RtpStream::Compare);
188   return (*it).second->next_rtp_time();
189 }
190 }  // namespace testing
191 
RemoteBitrateEstimatorTest()192 RemoteBitrateEstimatorTest::RemoteBitrateEstimatorTest()
193     : clock_(0),
194       bitrate_observer_(new testing::TestBitrateObserver),
195       stream_generator_(new testing::StreamGenerator(
196           1e6,  // Capacity.
197           clock_.TimeInMicroseconds())) {}
198 
~RemoteBitrateEstimatorTest()199 RemoteBitrateEstimatorTest::~RemoteBitrateEstimatorTest() {}
200 
AddDefaultStream()201 void RemoteBitrateEstimatorTest::AddDefaultStream() {
202   stream_generator_->AddStream(new testing::RtpStream(
203     30,          // Frames per second.
204     3e5,         // Bitrate.
205     1,           // SSRC.
206     90000,       // RTP frequency.
207     0xFFFFF000,  // Timestamp offset.
208     0));         // RTCP receive time.
209 }
210 
AbsSendTime(int64_t t,int64_t denom)211 uint32_t RemoteBitrateEstimatorTest::AbsSendTime(int64_t t, int64_t denom) {
212   return (((t << 18) + (denom >> 1)) / denom) & 0x00fffffful;
213 }
214 
AddAbsSendTime(uint32_t t1,uint32_t t2)215 uint32_t RemoteBitrateEstimatorTest::AddAbsSendTime(uint32_t t1, uint32_t t2) {
216   return (t1 + t2) & 0x00fffffful;
217 }
218 
219 const unsigned int RemoteBitrateEstimatorTest::kDefaultSsrc = 1;
220 
IncomingPacket(uint32_t ssrc,size_t payload_size,int64_t arrival_time,uint32_t rtp_timestamp,uint32_t absolute_send_time,bool was_paced)221 void RemoteBitrateEstimatorTest::IncomingPacket(uint32_t ssrc,
222                                                 size_t payload_size,
223                                                 int64_t arrival_time,
224                                                 uint32_t rtp_timestamp,
225                                                 uint32_t absolute_send_time,
226                                                 bool was_paced) {
227   RTPHeader header;
228   memset(&header, 0, sizeof(header));
229   header.ssrc = ssrc;
230   header.timestamp = rtp_timestamp;
231   header.extension.hasAbsoluteSendTime = true;
232   header.extension.absoluteSendTime = absolute_send_time;
233   bitrate_estimator_->IncomingPacket(arrival_time + kArrivalTimeClockOffsetMs,
234                                      payload_size, header, was_paced);
235 }
236 
237 // Generates a frame of packets belonging to a stream at a given bitrate and
238 // with a given ssrc. The stream is pushed through a very simple simulated
239 // network, and is then given to the receive-side bandwidth estimator.
240 // Returns true if an over-use was seen, false otherwise.
241 // The StreamGenerator::updated() should be used to check for any changes in
242 // target bitrate after the call to this function.
GenerateAndProcessFrame(unsigned int ssrc,unsigned int bitrate_bps)243 bool RemoteBitrateEstimatorTest::GenerateAndProcessFrame(unsigned int ssrc,
244     unsigned int bitrate_bps) {
245   stream_generator_->SetBitrateBps(bitrate_bps);
246   testing::RtpStream::PacketList packets;
247   int64_t next_time_us = stream_generator_->GenerateFrame(
248       &packets, clock_.TimeInMicroseconds());
249   bool overuse = false;
250   while (!packets.empty()) {
251     testing::RtpStream::RtpPacket* packet = packets.front();
252     bitrate_observer_->Reset();
253     // The simulated clock should match the time of packet->arrival_time
254     // since both are used in IncomingPacket().
255     clock_.AdvanceTimeMicroseconds(packet->arrival_time -
256                                    clock_.TimeInMicroseconds());
257     IncomingPacket(packet->ssrc, packet->size,
258                    (packet->arrival_time + 500) / 1000, packet->rtp_timestamp,
259                    AbsSendTime(packet->send_time, 1000000), true);
260     if (bitrate_observer_->updated()) {
261       // Verify that new estimates only are triggered by an overuse and a
262       // rate decrease.
263       overuse = true;
264       EXPECT_LE(bitrate_observer_->latest_bitrate(), bitrate_bps);
265     }
266     delete packet;
267     packets.pop_front();
268   }
269   bitrate_estimator_->Process();
270   clock_.AdvanceTimeMicroseconds(next_time_us - clock_.TimeInMicroseconds());
271   return overuse;
272 }
273 
274 // Run the bandwidth estimator with a stream of |number_of_frames| frames, or
275 // until it reaches |target_bitrate|.
276 // Can for instance be used to run the estimator for some time to get it
277 // into a steady state.
SteadyStateRun(unsigned int ssrc,int max_number_of_frames,unsigned int start_bitrate,unsigned int min_bitrate,unsigned int max_bitrate,unsigned int target_bitrate)278 unsigned int RemoteBitrateEstimatorTest::SteadyStateRun(
279     unsigned int ssrc,
280     int max_number_of_frames,
281     unsigned int start_bitrate,
282     unsigned int min_bitrate,
283     unsigned int max_bitrate,
284     unsigned int target_bitrate) {
285   unsigned int bitrate_bps = start_bitrate;
286   bool bitrate_update_seen = false;
287   // Produce |number_of_frames| frames and give them to the estimator.
288   for (int i = 0; i < max_number_of_frames; ++i) {
289     bool overuse = GenerateAndProcessFrame(ssrc, bitrate_bps);
290     if (overuse) {
291       EXPECT_LT(bitrate_observer_->latest_bitrate(), max_bitrate);
292       EXPECT_GT(bitrate_observer_->latest_bitrate(), min_bitrate);
293       bitrate_bps = bitrate_observer_->latest_bitrate();
294       bitrate_update_seen = true;
295     } else if (bitrate_observer_->updated()) {
296       bitrate_bps = bitrate_observer_->latest_bitrate();
297       bitrate_observer_->Reset();
298     }
299     if (bitrate_update_seen && bitrate_bps > target_bitrate) {
300       break;
301     }
302   }
303   EXPECT_TRUE(bitrate_update_seen);
304   return bitrate_bps;
305 }
306 
InitialBehaviorTestHelper(unsigned int expected_converge_bitrate)307 void RemoteBitrateEstimatorTest::InitialBehaviorTestHelper(
308     unsigned int expected_converge_bitrate) {
309   const int kFramerate = 50;  // 50 fps to avoid rounding errors.
310   const int kFrameIntervalMs = 1000 / kFramerate;
311   const uint32_t kFrameIntervalAbsSendTime = AbsSendTime(1, kFramerate);
312   unsigned int bitrate_bps = 0;
313   uint32_t timestamp = 0;
314   uint32_t absolute_send_time = 0;
315   std::vector<unsigned int> ssrcs;
316   EXPECT_FALSE(bitrate_estimator_->LatestEstimate(&ssrcs, &bitrate_bps));
317   EXPECT_EQ(0u, ssrcs.size());
318   clock_.AdvanceTimeMilliseconds(1000);
319   bitrate_estimator_->Process();
320   EXPECT_FALSE(bitrate_estimator_->LatestEstimate(&ssrcs, &bitrate_bps));
321   EXPECT_FALSE(bitrate_observer_->updated());
322   bitrate_observer_->Reset();
323   clock_.AdvanceTimeMilliseconds(1000);
324   // Inserting a packet. Still no valid estimate. We need to wait 5 seconds.
325   IncomingPacket(kDefaultSsrc, kMtu, clock_.TimeInMilliseconds(), timestamp,
326                  absolute_send_time, true);
327   bitrate_estimator_->Process();
328   EXPECT_FALSE(bitrate_estimator_->LatestEstimate(&ssrcs, &bitrate_bps));
329   EXPECT_EQ(0u, ssrcs.size());
330   EXPECT_FALSE(bitrate_observer_->updated());
331   bitrate_observer_->Reset();
332   // Inserting packets for 5 seconds to get a valid estimate.
333   for (int i = 0; i < 5 * kFramerate + 1; ++i) {
334     IncomingPacket(kDefaultSsrc, kMtu, clock_.TimeInMilliseconds(), timestamp,
335                    absolute_send_time, true);
336     clock_.AdvanceTimeMilliseconds(1000 / kFramerate);
337     timestamp += 90 * kFrameIntervalMs;
338     absolute_send_time = AddAbsSendTime(absolute_send_time,
339                                         kFrameIntervalAbsSendTime);
340   }
341   bitrate_estimator_->Process();
342   EXPECT_TRUE(bitrate_estimator_->LatestEstimate(&ssrcs, &bitrate_bps));
343   ASSERT_EQ(1u, ssrcs.size());
344   EXPECT_EQ(kDefaultSsrc, ssrcs.front());
345   EXPECT_NEAR(expected_converge_bitrate, bitrate_bps, kAcceptedBitrateErrorBps);
346   EXPECT_TRUE(bitrate_observer_->updated());
347   bitrate_observer_->Reset();
348   EXPECT_EQ(bitrate_observer_->latest_bitrate(), bitrate_bps);
349   bitrate_estimator_->RemoveStream(kDefaultSsrc);
350   EXPECT_TRUE(bitrate_estimator_->LatestEstimate(&ssrcs, &bitrate_bps));
351   ASSERT_EQ(0u, ssrcs.size());
352   EXPECT_EQ(0u, bitrate_bps);
353 }
354 
RateIncreaseReorderingTestHelper(uint32_t expected_bitrate_bps)355 void RemoteBitrateEstimatorTest::RateIncreaseReorderingTestHelper(
356     uint32_t expected_bitrate_bps) {
357   const int kFramerate = 50;  // 50 fps to avoid rounding errors.
358   const int kFrameIntervalMs = 1000 / kFramerate;
359   const uint32_t kFrameIntervalAbsSendTime = AbsSendTime(1, kFramerate);
360   uint32_t timestamp = 0;
361   uint32_t absolute_send_time = 0;
362   IncomingPacket(kDefaultSsrc, 1000, clock_.TimeInMilliseconds(), timestamp,
363                  absolute_send_time, true);
364   bitrate_estimator_->Process();
365   EXPECT_FALSE(bitrate_observer_->updated());  // No valid estimate.
366   // Inserting packets for one second to get a valid estimate.
367   for (int i = 0; i < 5 * kFramerate + 1; ++i) {
368     IncomingPacket(kDefaultSsrc, kMtu, clock_.TimeInMilliseconds(), timestamp,
369                    absolute_send_time, true);
370     clock_.AdvanceTimeMilliseconds(kFrameIntervalMs);
371     timestamp += 90 * kFrameIntervalMs;
372     absolute_send_time = AddAbsSendTime(absolute_send_time,
373                                         kFrameIntervalAbsSendTime);
374   }
375   bitrate_estimator_->Process();
376   EXPECT_TRUE(bitrate_observer_->updated());
377   EXPECT_NEAR(expected_bitrate_bps,
378               bitrate_observer_->latest_bitrate(),
379               kAcceptedBitrateErrorBps);
380   for (int i = 0; i < 10; ++i) {
381     clock_.AdvanceTimeMilliseconds(2 * kFrameIntervalMs);
382     timestamp += 2 * 90 * kFrameIntervalMs;
383     absolute_send_time = AddAbsSendTime(absolute_send_time,
384                                         2 * kFrameIntervalAbsSendTime);
385     IncomingPacket(kDefaultSsrc, 1000, clock_.TimeInMilliseconds(), timestamp,
386                    absolute_send_time, true);
387     IncomingPacket(kDefaultSsrc, 1000, clock_.TimeInMilliseconds(),
388                    timestamp - 90 * kFrameIntervalMs,
389                    AddAbsSendTime(absolute_send_time,
390                                   -static_cast<int>(kFrameIntervalAbsSendTime)),
391                    true);
392   }
393   bitrate_estimator_->Process();
394   EXPECT_TRUE(bitrate_observer_->updated());
395   EXPECT_NEAR(expected_bitrate_bps,
396               bitrate_observer_->latest_bitrate(),
397               kAcceptedBitrateErrorBps);
398 }
399 
400 // Make sure we initially increase the bitrate as expected.
RateIncreaseRtpTimestampsTestHelper(int expected_iterations)401 void RemoteBitrateEstimatorTest::RateIncreaseRtpTimestampsTestHelper(
402     int expected_iterations) {
403   // This threshold corresponds approximately to increasing linearly with
404   // bitrate(i) = 1.04 * bitrate(i-1) + 1000
405   // until bitrate(i) > 500000, with bitrate(1) ~= 30000.
406   unsigned int bitrate_bps = 30000;
407   int iterations = 0;
408   AddDefaultStream();
409   // Feed the estimator with a stream of packets and verify that it reaches
410   // 500 kbps at the expected time.
411   while (bitrate_bps < 5e5) {
412     bool overuse = GenerateAndProcessFrame(kDefaultSsrc, bitrate_bps);
413     if (overuse) {
414       EXPECT_GT(bitrate_observer_->latest_bitrate(), bitrate_bps);
415       bitrate_bps = bitrate_observer_->latest_bitrate();
416       bitrate_observer_->Reset();
417     } else if (bitrate_observer_->updated()) {
418       bitrate_bps = bitrate_observer_->latest_bitrate();
419       bitrate_observer_->Reset();
420     }
421     ++iterations;
422     ASSERT_LE(iterations, expected_iterations);
423   }
424   ASSERT_EQ(expected_iterations, iterations);
425 }
426 
CapacityDropTestHelper(int number_of_streams,bool wrap_time_stamp,unsigned int expected_bitrate_drop_delta)427 void RemoteBitrateEstimatorTest::CapacityDropTestHelper(
428     int number_of_streams,
429     bool wrap_time_stamp,
430     unsigned int expected_bitrate_drop_delta) {
431   const int kFramerate = 30;
432   const int kStartBitrate = 900e3;
433   const int kMinExpectedBitrate = 800e3;
434   const int kMaxExpectedBitrate = 1100e3;
435   const unsigned int kInitialCapacityBps = 1000e3;
436   const unsigned int kReducedCapacityBps = 500e3;
437 
438   int steady_state_time = 0;
439   if (number_of_streams <= 1) {
440     steady_state_time = 10;
441     AddDefaultStream();
442   } else {
443     steady_state_time = 10 * number_of_streams;
444     int bitrate_sum = 0;
445     int kBitrateDenom = number_of_streams * (number_of_streams - 1);
446     for (int i = 0; i < number_of_streams; i++) {
447       // First stream gets half available bitrate, while the rest share the
448       // remaining half i.e.: 1/2 = Sum[n/(N*(N-1))] for n=1..N-1 (rounded up)
449       int bitrate = kStartBitrate / 2;
450       if (i > 0) {
451         bitrate = (kStartBitrate * i + kBitrateDenom / 2) / kBitrateDenom;
452       }
453       stream_generator_->AddStream(new testing::RtpStream(
454           kFramerate,                     // Frames per second.
455           bitrate,                        // Bitrate.
456           kDefaultSsrc + i,               // SSRC.
457           90000,                          // RTP frequency.
458           0xFFFFF000 ^ (~0 << (32 - i)),  // Timestamp offset.
459           0));                            // RTCP receive time.
460       bitrate_sum += bitrate;
461     }
462     ASSERT_EQ(bitrate_sum, kStartBitrate);
463   }
464   if (wrap_time_stamp) {
465     stream_generator_->set_rtp_timestamp_offset(kDefaultSsrc,
466         std::numeric_limits<uint32_t>::max() - steady_state_time * 90000);
467   }
468 
469   // Run in steady state to make the estimator converge.
470   stream_generator_->set_capacity_bps(kInitialCapacityBps);
471   unsigned int bitrate_bps = SteadyStateRun(kDefaultSsrc,
472                                             steady_state_time * kFramerate,
473                                             kStartBitrate,
474                                             kMinExpectedBitrate,
475                                             kMaxExpectedBitrate,
476                                             kInitialCapacityBps);
477   EXPECT_NEAR(kInitialCapacityBps, bitrate_bps, 110000u);
478   bitrate_observer_->Reset();
479 
480   // Reduce the capacity and verify the decrease time.
481   stream_generator_->set_capacity_bps(kReducedCapacityBps);
482   int64_t overuse_start_time = clock_.TimeInMilliseconds();
483   int64_t bitrate_drop_time = -1;
484   for (int i = 0; i < 100 * number_of_streams; ++i) {
485     GenerateAndProcessFrame(kDefaultSsrc, bitrate_bps);
486     // Check for either increase or decrease.
487     if (bitrate_observer_->updated()) {
488       if (bitrate_drop_time == -1 &&
489           bitrate_observer_->latest_bitrate() <= kReducedCapacityBps) {
490         bitrate_drop_time = clock_.TimeInMilliseconds();
491       }
492       bitrate_bps = bitrate_observer_->latest_bitrate();
493       bitrate_observer_->Reset();
494     }
495   }
496 
497   EXPECT_NEAR(expected_bitrate_drop_delta,
498               bitrate_drop_time - overuse_start_time, 33);
499 
500   // Remove stream one by one.
501   unsigned int latest_bps = 0;
502   std::vector<unsigned int> ssrcs;
503   for (int i = 0; i < number_of_streams; i++) {
504     EXPECT_TRUE(bitrate_estimator_->LatestEstimate(&ssrcs, &latest_bps));
505     EXPECT_EQ(number_of_streams - i, static_cast<int>(ssrcs.size()));
506     EXPECT_EQ(bitrate_bps, latest_bps);
507     for (int j = i; j < number_of_streams; j++) {
508       EXPECT_EQ(kDefaultSsrc + j, ssrcs[j - i]);
509     }
510     bitrate_estimator_->RemoveStream(kDefaultSsrc + i);
511   }
512   EXPECT_TRUE(bitrate_estimator_->LatestEstimate(&ssrcs, &latest_bps));
513   EXPECT_EQ(0u, ssrcs.size());
514   EXPECT_EQ(0u, latest_bps);
515 }
516 
TestTimestampGroupingTestHelper()517 void RemoteBitrateEstimatorTest::TestTimestampGroupingTestHelper() {
518   const int kFramerate = 50;  // 50 fps to avoid rounding errors.
519   const int kFrameIntervalMs = 1000 / kFramerate;
520   const uint32_t kFrameIntervalAbsSendTime = AbsSendTime(1, kFramerate);
521   uint32_t timestamp = 0;
522   // Initialize absolute_send_time (24 bits) so that it will definitely wrap
523   // during the test.
524   uint32_t absolute_send_time = AddAbsSendTime(
525       (1 << 24), -static_cast<int>(50 * kFrameIntervalAbsSendTime));
526   // Initial set of frames to increase the bitrate. 6 seconds to have enough
527   // time for the first estimate to be generated and for Process() to be called.
528   for (int i = 0; i <= 6 * kFramerate; ++i) {
529     IncomingPacket(kDefaultSsrc, 1000, clock_.TimeInMilliseconds(), timestamp,
530                    absolute_send_time, true);
531     bitrate_estimator_->Process();
532     clock_.AdvanceTimeMilliseconds(kFrameIntervalMs);
533     timestamp += 90 * kFrameIntervalMs;
534     absolute_send_time = AddAbsSendTime(absolute_send_time,
535                                         kFrameIntervalAbsSendTime);
536   }
537   EXPECT_TRUE(bitrate_observer_->updated());
538   EXPECT_GE(bitrate_observer_->latest_bitrate(), 400000u);
539 
540   // Insert batches of frames which were sent very close in time. Also simulate
541   // capacity over-use to see that we back off correctly.
542   const int kTimestampGroupLength = 15;
543   const uint32_t kTimestampGroupLengthAbsSendTime =
544       AbsSendTime(kTimestampGroupLength, 90000);
545   const uint32_t kSingleRtpTickAbsSendTime = AbsSendTime(1, 90000);
546   for (int i = 0; i < 100; ++i) {
547     for (int j = 0; j < kTimestampGroupLength; ++j) {
548       // Insert |kTimestampGroupLength| frames with just 1 timestamp ticks in
549       // between. Should be treated as part of the same group by the estimator.
550       IncomingPacket(kDefaultSsrc, 100, clock_.TimeInMilliseconds(), timestamp,
551                      absolute_send_time, true);
552       clock_.AdvanceTimeMilliseconds(kFrameIntervalMs / kTimestampGroupLength);
553       timestamp += 1;
554       absolute_send_time = AddAbsSendTime(absolute_send_time,
555                                           kSingleRtpTickAbsSendTime);
556     }
557     // Increase time until next batch to simulate over-use.
558     clock_.AdvanceTimeMilliseconds(10);
559     timestamp += 90 * kFrameIntervalMs - kTimestampGroupLength;
560     absolute_send_time = AddAbsSendTime(
561         absolute_send_time,
562         AddAbsSendTime(kFrameIntervalAbsSendTime,
563                        -static_cast<int>(kTimestampGroupLengthAbsSendTime)));
564     bitrate_estimator_->Process();
565   }
566   EXPECT_TRUE(bitrate_observer_->updated());
567   // Should have reduced the estimate.
568   EXPECT_LT(bitrate_observer_->latest_bitrate(), 400000u);
569 }
570 
TestGetStatsHelper()571 void RemoteBitrateEstimatorTest::TestGetStatsHelper() {
572   const int kFramerate = 100;
573   const int kFrameIntervalMs = 1000 / kFramerate;
574   const int kBurstThresholdMs = 5;
575   const uint32_t kFrameIntervalAbsSendTime = AbsSendTime(1, kFramerate);
576   uint32_t timestamp = 0;
577   // Initialize absolute_send_time (24 bits) so that it will definitely wrap
578   // during the test.
579   uint32_t absolute_send_time =
580       AddAbsSendTime((1 << 24),
581       -(50 * static_cast<int>(kFrameIntervalAbsSendTime)));
582 
583   // Inject propagation_time_delta of kFrameIntervalMs.
584   for (size_t i = 0; i < 3; ++i) {
585     IncomingPacket(kDefaultSsrc, 1000, clock_.TimeInMilliseconds(), timestamp,
586                    absolute_send_time, true);
587     timestamp += kFrameIntervalMs;
588     // Insert a kFrameIntervalMs propagation_time_delta.
589     clock_.AdvanceTimeMilliseconds(kFrameIntervalMs * 2);
590     absolute_send_time = AddAbsSendTime(absolute_send_time,
591                                         kFrameIntervalAbsSendTime);
592   }
593   ReceiveBandwidthEstimatorStats stats;
594   EXPECT_TRUE(bitrate_estimator_->GetStats(&stats));
595   EXPECT_EQ(1U, stats.recent_propagation_time_delta_ms.size());
596   EXPECT_EQ(kFrameIntervalMs, stats.recent_propagation_time_delta_ms[0]);
597   EXPECT_EQ(1U, stats.recent_arrival_time_ms.size());
598   EXPECT_EQ(kFrameIntervalMs, stats.total_propagation_time_delta_ms);
599 
600   // Inject negative propagation_time_deltas. The total propagation_time_delta
601   // should be adjusted to 0.
602   for (size_t i = 0; i < 3; ++i) {
603     IncomingPacket(kDefaultSsrc, 1000, clock_.TimeInMilliseconds(), timestamp,
604                    absolute_send_time, true);
605     timestamp += 10 * kFrameIntervalMs;
606     clock_.AdvanceTimeMilliseconds(kBurstThresholdMs + 1);
607     absolute_send_time = AddAbsSendTime(absolute_send_time,
608                                         10 * kFrameIntervalAbsSendTime);
609   }
610   EXPECT_TRUE(bitrate_estimator_->GetStats(&stats));
611   EXPECT_EQ(0, stats.total_propagation_time_delta_ms);
612 
613   // Send more than 1000 frames and make sure the stats queues stays within
614   // limits.
615   for (size_t i = 0; i < 1001; ++i) {
616     IncomingPacket(kDefaultSsrc, 1000, clock_.TimeInMilliseconds(), timestamp,
617                    absolute_send_time, true);
618     timestamp += kFrameIntervalMs;
619     absolute_send_time = AddAbsSendTime(absolute_send_time,
620                                         kFrameIntervalAbsSendTime);
621   }
622   EXPECT_TRUE(bitrate_estimator_->GetStats(&stats));
623   EXPECT_LE(stats.recent_propagation_time_delta_ms.size(), 1000U);
624   EXPECT_LE(stats.recent_arrival_time_ms.size(), 1000U);
625 
626   // Move the clock over the 1000ms limit.
627   clock_.AdvanceTimeMilliseconds(2000);
628   EXPECT_TRUE(bitrate_estimator_->GetStats(&stats));
629   EXPECT_EQ(0U, stats.recent_propagation_time_delta_ms.size());
630 }
631 
TestWrappingHelper(int silence_time_s)632 void RemoteBitrateEstimatorTest::TestWrappingHelper(
633     int silence_time_s) {
634   const int kFramerate = 100;
635   const int kFrameIntervalMs = 1000 / kFramerate;
636   const uint32_t kFrameIntervalAbsSendTime = AbsSendTime(1, kFramerate);
637   uint32_t absolute_send_time = 0;
638   uint32_t timestamp = 0;
639 
640   for (size_t i = 0; i < 3000; ++i) {
641     IncomingPacket(kDefaultSsrc, 1000, clock_.TimeInMilliseconds(), timestamp,
642                    absolute_send_time, true);
643     timestamp += kFrameIntervalMs;
644     clock_.AdvanceTimeMilliseconds(kFrameIntervalMs);
645     absolute_send_time = AddAbsSendTime(absolute_send_time,
646                                         kFrameIntervalAbsSendTime);
647     bitrate_estimator_->Process();
648   }
649   unsigned int bitrate_before = 0;
650   std::vector<unsigned int> ssrcs;
651   bitrate_estimator_->LatestEstimate(&ssrcs, &bitrate_before);
652 
653   clock_.AdvanceTimeMilliseconds(silence_time_s * 1000);
654   absolute_send_time = AddAbsSendTime(absolute_send_time,
655                                       AbsSendTime(silence_time_s, 1));
656   bitrate_estimator_->Process();
657   for (size_t i = 0; i < 100; ++i) {
658     IncomingPacket(kDefaultSsrc, 1000, clock_.TimeInMilliseconds(), timestamp,
659                    absolute_send_time, true);
660     timestamp += kFrameIntervalMs;
661     clock_.AdvanceTimeMilliseconds(2 * kFrameIntervalMs);
662     absolute_send_time = AddAbsSendTime(absolute_send_time,
663                                         kFrameIntervalAbsSendTime);
664     bitrate_estimator_->Process();
665   }
666   unsigned int bitrate_after = 0;
667   bitrate_estimator_->LatestEstimate(&ssrcs, &bitrate_after);
668   EXPECT_LT(bitrate_after, bitrate_before);
669 }
670 }  // namespace webrtc
671