File: screenshare_layers_unittest.cc

package info (click to toggle)
chromium 138.0.7204.183-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,908 kB
  • sloc: cpp: 34,937,088; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (790 lines) | stat: -rw-r--r-- 27,874 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
/*
 *  Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "modules/video_coding/codecs/vp8/screenshare_layers.h"

#include <stdlib.h>
#include <string.h>

#include <cstdint>
#include <memory>
#include <optional>
#include <vector>

#include "api/units/time_delta.h"
#include "api/video_codecs/vp8_frame_buffer_controller.h"
#include "api/video_codecs/vp8_frame_config.h"
#include "modules/video_coding/codecs/interface/common_constants.h"
#include "modules/video_coding/codecs/vp8/libvpx_vp8_encoder.h"
#include "modules/video_coding/include/video_codec_interface.h"
#include "rtc_base/checks.h"
#include "rtc_base/fake_clock.h"
#include "rtc_base/time_utils.h"
#include "system_wrappers/include/metrics.h"
#include "test/gmock.h"
#include "test/gtest.h"
#include "vpx/vp8cx.h"

using ::testing::_;
using ::testing::ElementsAre;
using ::testing::NiceMock;

namespace webrtc {
namespace {
// 5 frames per second at 90 kHz.
const uint32_t kTimestampDelta5Fps = 90000 / 5;
const int kDefaultQp = 54;
const int kDefaultTl0BitrateKbps = 200;
const int kDefaultTl1BitrateKbps = 2000;
const int kFrameRate = 5;
const int kSyncPeriodSeconds = 2;
const int kMaxSyncPeriodSeconds = 4;

// Expected flags for corresponding temporal layers.
const int kTl0Flags = VP8_EFLAG_NO_UPD_GF | VP8_EFLAG_NO_UPD_ARF |
                      VP8_EFLAG_NO_REF_GF | VP8_EFLAG_NO_REF_ARF;
const int kTl1Flags =
    VP8_EFLAG_NO_REF_ARF | VP8_EFLAG_NO_UPD_ARF | VP8_EFLAG_NO_UPD_LAST;
const int kTl1SyncFlags = VP8_EFLAG_NO_REF_ARF | VP8_EFLAG_NO_REF_GF |
                          VP8_EFLAG_NO_UPD_ARF | VP8_EFLAG_NO_UPD_LAST;
const std::vector<uint32_t> kDefault2TlBitratesBps = {
    kDefaultTl0BitrateKbps * 1000,
    (kDefaultTl1BitrateKbps - kDefaultTl0BitrateKbps) * 1000};

}  // namespace

class ScreenshareLayerTest : public ::testing::Test {
 protected:
  ScreenshareLayerTest()
      : min_qp_(2),
        max_qp_(kDefaultQp),
        frame_size_(-1),
        timestamp_(90),
        config_updated_(false) {}
  virtual ~ScreenshareLayerTest() {}

  void SetUp() override {
    layers_.reset(new ScreenshareLayers(2));
    cfg_ = ConfigureBitrates();
  }

  int EncodeFrame(bool base_sync, CodecSpecificInfo* info = nullptr) {
    CodecSpecificInfo ignored_info;
    if (!info) {
      info = &ignored_info;
    }

    int flags = ConfigureFrame(base_sync);
    if (flags != -1)
      layers_->OnEncodeDone(0, timestamp_, frame_size_, base_sync, kDefaultQp,
                            info);
    return flags;
  }

  int ConfigureFrame(bool /* key_frame */) {
    tl_config_ = NextFrameConfig(0, timestamp_);
    EXPECT_EQ(0, tl_config_.encoder_layer_id)
        << "ScreenshareLayers always encodes using the bitrate allocator for "
           "layer 0, but may reference different buffers and packetize "
           "differently.";
    if (tl_config_.drop_frame) {
      return -1;
    }
    const uint32_t prev_rc_target_bitrate = cfg_.rc_target_bitrate.value_or(-1);
    const uint32_t prev_rc_max_quantizer = cfg_.rc_max_quantizer.value_or(-1);

    cfg_ = layers_->UpdateConfiguration(0);

    config_updated_ =
        cfg_.temporal_layer_config.has_value() ||
        (cfg_.rc_target_bitrate.has_value() &&
         cfg_.rc_target_bitrate.value() != prev_rc_target_bitrate) ||
        (cfg_.rc_max_quantizer.has_value() &&
         cfg_.rc_max_quantizer.value() != prev_rc_max_quantizer) ||
        cfg_.g_error_resilient.has_value();

    int flags = LibvpxVp8Encoder::EncodeFlags(tl_config_);
    EXPECT_NE(-1, frame_size_);
    return flags;
  }

  Vp8FrameConfig NextFrameConfig(size_t stream_index, uint32_t timestamp) {
    int64_t timestamp_ms = timestamp / 90;
    clock_.AdvanceTime(TimeDelta::Millis(timestamp_ms - TimeMillis()));
    return layers_->NextFrameConfig(stream_index, timestamp);
  }

  int FrameSizeForBitrate(int bitrate_kbps) {
    return ((bitrate_kbps * 1000) / 8) / kFrameRate;
  }

  Vp8EncoderConfig ConfigureBitrates() {
    layers_->SetQpLimits(0, min_qp_, max_qp_);
    layers_->OnRatesUpdated(0, kDefault2TlBitratesBps, kFrameRate);
    const Vp8EncoderConfig vp8_cfg = layers_->UpdateConfiguration(0);
    EXPECT_TRUE(vp8_cfg.rc_target_bitrate.has_value());
    frame_size_ = FrameSizeForBitrate(vp8_cfg.rc_target_bitrate.value());
    return vp8_cfg;
  }

  void WithQpLimits(int min_qp, int max_qp) {
    min_qp_ = min_qp;
    max_qp_ = max_qp;
  }

  // Runs a few initial frames and makes sure we have seen frames on both
  // temporal layers, including sync and non-sync frames.
  bool RunGracePeriod() {
    bool got_tl0 = false;
    bool got_tl1 = false;
    bool got_tl1_sync = false;
    for (int i = 0; i < 10; ++i) {
      CodecSpecificInfo info;
      EXPECT_NE(-1, EncodeFrame(false, &info));
      timestamp_ += kTimestampDelta5Fps;
      if (info.codecSpecific.VP8.temporalIdx == 0) {
        got_tl0 = true;
      } else if (info.codecSpecific.VP8.layerSync) {
        got_tl1_sync = true;
      } else {
        got_tl1 = true;
      }
      if (got_tl0 && got_tl1 && got_tl1_sync)
        return true;
    }
    return false;
  }

  // Adds frames until we get one in the specified temporal layer. The last
  // FrameEncoded() call will be omitted and needs to be done by the caller.
  // Returns the flags for the last frame.
  int SkipUntilTl(int layer) { return SkipUntilTlAndSync(layer, std::nullopt); }

  // Same as SkipUntilTl, but also waits until the sync bit condition is met.
  int SkipUntilTlAndSync(int layer, std::optional<bool> sync) {
    int flags = 0;
    const int kMaxFramesToSkip =
        1 + (sync.value_or(false) ? kMaxSyncPeriodSeconds : 1) * kFrameRate;
    for (int i = 0; i < kMaxFramesToSkip; ++i) {
      flags = ConfigureFrame(false);
      if (tl_config_.packetizer_temporal_idx != layer ||
          (sync && *sync != tl_config_.layer_sync)) {
        if (flags != -1) {
          // If flags do not request a frame drop, report some default values
          // for frame size etc.
          CodecSpecificInfo info;
          layers_->OnEncodeDone(0, timestamp_, frame_size_, false, kDefaultQp,
                                &info);
        }
        timestamp_ += kTimestampDelta5Fps;
      } else {
        // Found frame from sought after layer.
        return flags;
      }
    }
    ADD_FAILURE() << "Did not get a frame of TL" << layer << " in time.";
    return -1;
  }

  int min_qp_;
  uint32_t max_qp_;
  int frame_size_;
  ScopedFakeClock clock_;
  std::unique_ptr<ScreenshareLayers> layers_;

  uint32_t timestamp_;
  Vp8FrameConfig tl_config_;
  Vp8EncoderConfig cfg_;
  bool config_updated_;

  CodecSpecificInfo* IgnoredCodecSpecificInfo() {
    ignored_codec_specific_info_ = std::make_unique<CodecSpecificInfo>();
    return ignored_codec_specific_info_.get();
  }

 private:
  std::unique_ptr<CodecSpecificInfo> ignored_codec_specific_info_;
};

TEST_F(ScreenshareLayerTest, 1Layer) {
  layers_.reset(new ScreenshareLayers(1));
  ConfigureBitrates();
  // One layer screenshare should not use the frame dropper as all frames will
  // belong to the base layer.
  const int kSingleLayerFlags = 0;
  auto info = std::make_unique<CodecSpecificInfo>();
  int flags = EncodeFrame(/*base_sync=*/false, info.get());
  timestamp_ += kTimestampDelta5Fps;
  EXPECT_EQ(static_cast<uint8_t>(kNoTemporalIdx),
            info->codecSpecific.VP8.temporalIdx);
  EXPECT_FALSE(info->codecSpecific.VP8.layerSync);
  EXPECT_EQ(info->generic_frame_info->temporal_id, 0);

  info = std::make_unique<CodecSpecificInfo>();
  flags = EncodeFrame(/*base_sync=*/false, info.get());
  EXPECT_EQ(kSingleLayerFlags, flags);
  EXPECT_EQ(static_cast<uint8_t>(kNoTemporalIdx),
            info->codecSpecific.VP8.temporalIdx);
  EXPECT_FALSE(info->codecSpecific.VP8.layerSync);
  EXPECT_EQ(info->generic_frame_info->temporal_id, 0);
}

TEST_F(ScreenshareLayerTest, 2LayersPeriodicSync) {
  std::vector<int> sync_times;
  const int kNumFrames = kSyncPeriodSeconds * kFrameRate * 2 - 1;
  for (int i = 0; i < kNumFrames; ++i) {
    CodecSpecificInfo info;
    EncodeFrame(false, &info);
    timestamp_ += kTimestampDelta5Fps;
    if (info.codecSpecific.VP8.temporalIdx == 1 &&
        info.codecSpecific.VP8.layerSync) {
      sync_times.push_back(timestamp_);
    }
  }

  ASSERT_EQ(2u, sync_times.size());
  EXPECT_GE(sync_times[1] - sync_times[0], 90000 * kSyncPeriodSeconds);
}

TEST_F(ScreenshareLayerTest, 2LayersSyncAfterTimeout) {
  std::vector<int> sync_times;
  const int kNumFrames = kMaxSyncPeriodSeconds * kFrameRate * 2 - 1;
  for (int i = 0; i < kNumFrames; ++i) {
    CodecSpecificInfo info;

    tl_config_ = NextFrameConfig(0, timestamp_);
    cfg_ = layers_->UpdateConfiguration(0);

    // Simulate TL1 being at least 8 qp steps better.
    if (tl_config_.packetizer_temporal_idx == 0) {
      layers_->OnEncodeDone(0, timestamp_, frame_size_, false, kDefaultQp,
                            &info);
    } else {
      layers_->OnEncodeDone(0, timestamp_, frame_size_, false, kDefaultQp - 8,
                            &info);
    }

    if (info.codecSpecific.VP8.temporalIdx == 1 &&
        info.codecSpecific.VP8.layerSync)
      sync_times.push_back(timestamp_);

    timestamp_ += kTimestampDelta5Fps;
  }

  ASSERT_EQ(2u, sync_times.size());
  EXPECT_GE(sync_times[1] - sync_times[0], 90000 * kMaxSyncPeriodSeconds);
}

TEST_F(ScreenshareLayerTest, 2LayersSyncAfterSimilarQP) {
  std::vector<int> sync_times;

  const int kNumFrames = (kSyncPeriodSeconds +
                          ((kMaxSyncPeriodSeconds - kSyncPeriodSeconds) / 2)) *
                         kFrameRate;
  for (int i = 0; i < kNumFrames; ++i) {
    CodecSpecificInfo info;

    ConfigureFrame(false);

    // Simulate TL1 being at least 8 qp steps better.
    if (tl_config_.packetizer_temporal_idx == 0) {
      layers_->OnEncodeDone(0, timestamp_, frame_size_, false, kDefaultQp,
                            &info);
    } else {
      layers_->OnEncodeDone(0, timestamp_, frame_size_, false, kDefaultQp - 8,
                            &info);
    }

    if (info.codecSpecific.VP8.temporalIdx == 1 &&
        info.codecSpecific.VP8.layerSync)
      sync_times.push_back(timestamp_);

    timestamp_ += kTimestampDelta5Fps;
  }

  ASSERT_EQ(1u, sync_times.size());

  bool bumped_tl0_quality = false;
  for (int i = 0; i < 3; ++i) {
    CodecSpecificInfo info;

    int flags = ConfigureFrame(false);
    layers_->OnEncodeDone(0, timestamp_, frame_size_, false, kDefaultQp - 8,
                          &info);
    if (info.codecSpecific.VP8.temporalIdx == 0) {
      // Bump TL0 to same quality as TL1.
      bumped_tl0_quality = true;
    } else {
      if (bumped_tl0_quality) {
        EXPECT_TRUE(info.codecSpecific.VP8.layerSync);
        EXPECT_EQ(kTl1SyncFlags, flags);
        return;
      }
    }
    timestamp_ += kTimestampDelta5Fps;
  }
  ADD_FAILURE() << "No TL1 frame arrived within time limit.";
}

TEST_F(ScreenshareLayerTest, 2LayersToggling) {
  EXPECT_TRUE(RunGracePeriod());

  // Insert 50 frames. 2/5 should be TL0.
  int tl0_frames = 0;
  int tl1_frames = 0;
  for (int i = 0; i < 50; ++i) {
    CodecSpecificInfo info;
    EncodeFrame(/*base_sync=*/false, &info);
    EXPECT_EQ(info.codecSpecific.VP8.temporalIdx,
              info.generic_frame_info->temporal_id);
    timestamp_ += kTimestampDelta5Fps;
    switch (info.codecSpecific.VP8.temporalIdx) {
      case 0:
        ++tl0_frames;
        break;
      case 1:
        ++tl1_frames;
        break;
      default:
        abort();
    }
  }
  EXPECT_EQ(20, tl0_frames);
  EXPECT_EQ(30, tl1_frames);
}

TEST_F(ScreenshareLayerTest, AllFitsLayer0) {
  frame_size_ = FrameSizeForBitrate(kDefaultTl0BitrateKbps);

  // Insert 50 frames, small enough that all fits in TL0.
  for (int i = 0; i < 50; ++i) {
    CodecSpecificInfo info;
    int flags = EncodeFrame(false, &info);
    timestamp_ += kTimestampDelta5Fps;
    EXPECT_EQ(kTl0Flags, flags);
    EXPECT_EQ(0, info.codecSpecific.VP8.temporalIdx);
  }
}

TEST_F(ScreenshareLayerTest, TooHighBitrate) {
  frame_size_ = 2 * FrameSizeForBitrate(kDefaultTl1BitrateKbps);

  // Insert 100 frames. Half should be dropped.
  int tl0_frames = 0;
  int tl1_frames = 0;
  int dropped_frames = 0;
  for (int i = 0; i < 100; ++i) {
    CodecSpecificInfo info;
    int flags = EncodeFrame(false, &info);
    timestamp_ += kTimestampDelta5Fps;
    if (flags == -1) {
      ++dropped_frames;
    } else {
      switch (info.codecSpecific.VP8.temporalIdx) {
        case 0:
          ++tl0_frames;
          break;
        case 1:
          ++tl1_frames;
          break;
        default:
          ADD_FAILURE() << "Unexpected temporal id";
      }
    }
  }

  EXPECT_NEAR(50, tl0_frames + tl1_frames, 1);
  EXPECT_NEAR(50, dropped_frames, 1);
}

TEST_F(ScreenshareLayerTest, TargetBitrateCappedByTL0) {
  const int kTl0_kbps = 100;
  const int kTl1_kbps = 1000;
  const std::vector<uint32_t> layer_rates = {kTl0_kbps * 1000,
                                             (kTl1_kbps - kTl0_kbps) * 1000};
  layers_->OnRatesUpdated(0, layer_rates, kFrameRate);
  cfg_ = layers_->UpdateConfiguration(0);

  EXPECT_EQ(static_cast<unsigned int>(
                ScreenshareLayers::kMaxTL0FpsReduction * kTl0_kbps + 0.5),
            cfg_.rc_target_bitrate);
}

TEST_F(ScreenshareLayerTest, TargetBitrateCappedByTL1) {
  const int kTl0_kbps = 100;
  const int kTl1_kbps = 450;
  const std::vector<uint32_t> layer_rates = {kTl0_kbps * 1000,
                                             (kTl1_kbps - kTl0_kbps) * 1000};
  layers_->OnRatesUpdated(0, layer_rates, kFrameRate);
  cfg_ = layers_->UpdateConfiguration(0);

  EXPECT_EQ(static_cast<unsigned int>(
                kTl1_kbps / ScreenshareLayers::kAcceptableTargetOvershoot),
            cfg_.rc_target_bitrate);
}

TEST_F(ScreenshareLayerTest, TargetBitrateBelowTL0) {
  const int kTl0_kbps = 100;
  const std::vector<uint32_t> layer_rates = {kTl0_kbps * 1000};
  layers_->OnRatesUpdated(0, layer_rates, kFrameRate);
  cfg_ = layers_->UpdateConfiguration(0);

  EXPECT_EQ(static_cast<uint32_t>(kTl0_kbps), cfg_.rc_target_bitrate);
}

TEST_F(ScreenshareLayerTest, EncoderDrop) {
  EXPECT_TRUE(RunGracePeriod());
  SkipUntilTl(0);

  // Size 0 indicates dropped frame.
  layers_->OnEncodeDone(0, timestamp_, 0, false, 0, IgnoredCodecSpecificInfo());

  // Re-encode frame (so don't advance timestamp).
  int flags = EncodeFrame(false);
  timestamp_ += kTimestampDelta5Fps;
  EXPECT_FALSE(config_updated_);
  EXPECT_EQ(kTl0Flags, flags);

  // Next frame should have boosted quality...
  SkipUntilTl(0);
  EXPECT_TRUE(config_updated_);
  EXPECT_LT(cfg_.rc_max_quantizer, static_cast<unsigned int>(kDefaultQp));
  layers_->OnEncodeDone(0, timestamp_, frame_size_, false, kDefaultQp,
                        IgnoredCodecSpecificInfo());
  timestamp_ += kTimestampDelta5Fps;

  // ...then back to standard setup.
  SkipUntilTl(0);
  layers_->OnEncodeDone(0, timestamp_, frame_size_, false, kDefaultQp,
                        IgnoredCodecSpecificInfo());
  timestamp_ += kTimestampDelta5Fps;
  EXPECT_EQ(cfg_.rc_max_quantizer, static_cast<unsigned int>(kDefaultQp));

  // Next drop in TL1.
  SkipUntilTl(1);
  layers_->OnEncodeDone(0, timestamp_, 0, false, 0, IgnoredCodecSpecificInfo());

  // Re-encode frame (so don't advance timestamp).
  flags = EncodeFrame(false);
  timestamp_ += kTimestampDelta5Fps;
  EXPECT_FALSE(config_updated_);
  EXPECT_EQ(kTl1Flags, flags);

  // Next frame should have boosted QP.
  SkipUntilTl(1);
  EXPECT_TRUE(config_updated_);
  EXPECT_LT(cfg_.rc_max_quantizer, static_cast<unsigned int>(kDefaultQp));
  layers_->OnEncodeDone(0, timestamp_, frame_size_, false, kDefaultQp,
                        IgnoredCodecSpecificInfo());
  timestamp_ += kTimestampDelta5Fps;

  // ...and back to normal.
  SkipUntilTl(1);
  EXPECT_EQ(cfg_.rc_max_quantizer, static_cast<unsigned int>(kDefaultQp));
  layers_->OnEncodeDone(0, timestamp_, frame_size_, false, kDefaultQp,
                        IgnoredCodecSpecificInfo());
  timestamp_ += kTimestampDelta5Fps;
}

TEST_F(ScreenshareLayerTest, RespectsMaxIntervalBetweenFrames) {
  const int kLowBitrateKbps = 50;
  const int kLargeFrameSizeBytes = 100000;
  const uint32_t kStartTimestamp = 1234;

  const std::vector<uint32_t> layer_rates = {kLowBitrateKbps * 1000};
  layers_->OnRatesUpdated(0, layer_rates, kFrameRate);
  cfg_ = layers_->UpdateConfiguration(0);

  EXPECT_EQ(kTl0Flags,
            LibvpxVp8Encoder::EncodeFlags(NextFrameConfig(0, kStartTimestamp)));
  layers_->OnEncodeDone(0, kStartTimestamp, kLargeFrameSizeBytes, false,
                        kDefaultQp, IgnoredCodecSpecificInfo());

  const uint32_t kTwoSecondsLater =
      kStartTimestamp + (ScreenshareLayers::kMaxFrameIntervalMs * 90);

  // Sanity check, repayment time should exceed kMaxFrameIntervalMs.
  ASSERT_GT(kStartTimestamp + 90 * (kLargeFrameSizeBytes * 8) / kLowBitrateKbps,
            kStartTimestamp + (ScreenshareLayers::kMaxFrameIntervalMs * 90));

  // Expect drop one frame interval before the two second timeout. If we try
  // any later, the frame will be dropped anyway by the frame rate throttling
  // logic.
  EXPECT_TRUE(
      NextFrameConfig(0, kTwoSecondsLater - kTimestampDelta5Fps).drop_frame);

  // More than two seconds has passed since last frame, one should be emitted
  // even if bitrate target is then exceeded.
  EXPECT_EQ(kTl0Flags, LibvpxVp8Encoder::EncodeFlags(
                           NextFrameConfig(0, kTwoSecondsLater + 90)));
}

TEST_F(ScreenshareLayerTest, UpdatesHistograms) {
  metrics::Reset();
  bool trigger_drop = false;
  bool dropped_frame = false;
  bool overshoot = false;
  const int kTl0Qp = 35;
  const int kTl1Qp = 30;
  for (int64_t timestamp = 0;
       timestamp < kTimestampDelta5Fps * 5 * metrics::kMinRunTimeInSeconds;
       timestamp += kTimestampDelta5Fps) {
    tl_config_ = NextFrameConfig(0, timestamp);
    if (tl_config_.drop_frame) {
      dropped_frame = true;
      continue;
    }
    int flags = LibvpxVp8Encoder::EncodeFlags(tl_config_);
    if (flags != -1)
      cfg_ = layers_->UpdateConfiguration(0);

    if (timestamp >= kTimestampDelta5Fps * 5 && !overshoot && flags != -1) {
      // Simulate one overshoot.
      layers_->OnEncodeDone(0, timestamp, 0, false, 0, nullptr);
      overshoot = true;
    }

    if (flags == kTl0Flags) {
      if (timestamp >= kTimestampDelta5Fps * 20 && !trigger_drop) {
        // Simulate a too large frame, to cause frame drop.
        layers_->OnEncodeDone(0, timestamp, frame_size_ * 10, false, kTl0Qp,
                              IgnoredCodecSpecificInfo());
        trigger_drop = true;
      } else {
        layers_->OnEncodeDone(0, timestamp, frame_size_, false, kTl0Qp,
                              IgnoredCodecSpecificInfo());
      }
    } else if (flags == kTl1Flags || flags == kTl1SyncFlags) {
      layers_->OnEncodeDone(0, timestamp, frame_size_, false, kTl1Qp,
                            IgnoredCodecSpecificInfo());
    } else if (flags == -1) {
      dropped_frame = true;
    } else {
      RTC_DCHECK_NOTREACHED() << "Unexpected flags";
    }
    clock_.AdvanceTime(TimeDelta::Millis(1000 / 5));
  }

  EXPECT_TRUE(overshoot);
  EXPECT_TRUE(dropped_frame);

  layers_.reset();  // Histograms are reported on destruction.

  EXPECT_METRIC_EQ(
      1, metrics::NumSamples("WebRTC.Video.Screenshare.Layer0.FrameRate"));
  EXPECT_METRIC_EQ(
      1, metrics::NumSamples("WebRTC.Video.Screenshare.Layer1.FrameRate"));
  EXPECT_METRIC_EQ(
      1, metrics::NumSamples("WebRTC.Video.Screenshare.FramesPerDrop"));
  EXPECT_METRIC_EQ(
      1, metrics::NumSamples("WebRTC.Video.Screenshare.FramesPerOvershoot"));
  EXPECT_METRIC_EQ(1,
                   metrics::NumSamples("WebRTC.Video.Screenshare.Layer0.Qp"));
  EXPECT_METRIC_EQ(1,
                   metrics::NumSamples("WebRTC.Video.Screenshare.Layer1.Qp"));
  EXPECT_METRIC_EQ(
      1, metrics::NumSamples("WebRTC.Video.Screenshare.Layer0.TargetBitrate"));
  EXPECT_METRIC_EQ(
      1, metrics::NumSamples("WebRTC.Video.Screenshare.Layer1.TargetBitrate"));

  EXPECT_METRIC_GT(
      metrics::MinSample("WebRTC.Video.Screenshare.Layer0.FrameRate"), 1);
  EXPECT_METRIC_GT(
      metrics::MinSample("WebRTC.Video.Screenshare.Layer1.FrameRate"), 1);
  EXPECT_METRIC_GT(metrics::MinSample("WebRTC.Video.Screenshare.FramesPerDrop"),
                   1);
  EXPECT_METRIC_GT(
      metrics::MinSample("WebRTC.Video.Screenshare.FramesPerOvershoot"), 1);
  EXPECT_METRIC_EQ(
      1, metrics::NumEvents("WebRTC.Video.Screenshare.Layer0.Qp", kTl0Qp));
  EXPECT_METRIC_EQ(
      1, metrics::NumEvents("WebRTC.Video.Screenshare.Layer1.Qp", kTl1Qp));
  EXPECT_METRIC_EQ(
      1, metrics::NumEvents("WebRTC.Video.Screenshare.Layer0.TargetBitrate",
                            kDefaultTl0BitrateKbps));
  EXPECT_METRIC_EQ(
      1, metrics::NumEvents("WebRTC.Video.Screenshare.Layer1.TargetBitrate",
                            kDefaultTl1BitrateKbps));
}

TEST_F(ScreenshareLayerTest, RespectsConfiguredFramerate) {
  int64_t kTestSpanMs = 2000;
  int64_t kFrameIntervalsMs = 1000 / kFrameRate;

  uint32_t timestamp = 1234;
  int num_input_frames = 0;
  int num_discarded_frames = 0;

  // Send at regular rate - no drops expected.
  for (int64_t i = 0; i < kTestSpanMs; i += kFrameIntervalsMs) {
    if (NextFrameConfig(0, timestamp).drop_frame) {
      ++num_discarded_frames;
    } else {
      size_t frame_size_bytes = kDefaultTl0BitrateKbps * kFrameIntervalsMs / 8;
      layers_->OnEncodeDone(0, timestamp, frame_size_bytes, false, kDefaultQp,
                            IgnoredCodecSpecificInfo());
    }
    timestamp += kFrameIntervalsMs * 90;
    clock_.AdvanceTime(TimeDelta::Millis(kFrameIntervalsMs));

    ++num_input_frames;
  }
  EXPECT_EQ(0, num_discarded_frames);

  // Send at twice the configured rate - drop every other frame.
  num_input_frames = 0;
  num_discarded_frames = 0;
  for (int64_t i = 0; i < kTestSpanMs; i += kFrameIntervalsMs / 2) {
    if (NextFrameConfig(0, timestamp).drop_frame) {
      ++num_discarded_frames;
    } else {
      size_t frame_size_bytes = kDefaultTl0BitrateKbps * kFrameIntervalsMs / 8;
      layers_->OnEncodeDone(0, timestamp, frame_size_bytes, false, kDefaultQp,
                            IgnoredCodecSpecificInfo());
    }
    timestamp += kFrameIntervalsMs * 90 / 2;
    clock_.AdvanceTime(TimeDelta::Millis(kFrameIntervalsMs));
    ++num_input_frames;
  }

  // Allow for some rounding errors in the measurements.
  EXPECT_NEAR(num_discarded_frames, num_input_frames / 2, 2);
}

TEST_F(ScreenshareLayerTest, 2LayersSyncAtOvershootDrop) {
  // Run grace period so we have existing frames in both TL0 and Tl1.
  EXPECT_TRUE(RunGracePeriod());

  // Move ahead until we have a sync frame in TL1.
  EXPECT_EQ(kTl1SyncFlags, SkipUntilTlAndSync(1, true));
  ASSERT_TRUE(tl_config_.layer_sync);

  // Simulate overshoot of this frame.
  layers_->OnEncodeDone(0, timestamp_, 0, false, 0, nullptr);

  cfg_ = layers_->UpdateConfiguration(0);
  EXPECT_EQ(kTl1SyncFlags, LibvpxVp8Encoder::EncodeFlags(tl_config_));

  CodecSpecificInfo new_info;
  layers_->OnEncodeDone(0, timestamp_, frame_size_, false, kDefaultQp,
                        &new_info);
  EXPECT_TRUE(new_info.codecSpecific.VP8.layerSync);
}

TEST_F(ScreenshareLayerTest, DropOnTooShortFrameInterval) {
  // Run grace period so we have existing frames in both TL0 and Tl1.
  EXPECT_TRUE(RunGracePeriod());

  // Add a large gap, so there's plenty of room in the rate tracker.
  timestamp_ += kTimestampDelta5Fps * 3;
  EXPECT_FALSE(NextFrameConfig(0, timestamp_).drop_frame);
  layers_->OnEncodeDone(0, timestamp_, frame_size_, false, kDefaultQp,
                        IgnoredCodecSpecificInfo());

  // Frame interval below 90% if desired time is not allowed, try inserting
  // frame just before this limit.
  const int64_t kMinFrameInterval = (kTimestampDelta5Fps * 85) / 100;
  timestamp_ += kMinFrameInterval - 90;
  EXPECT_TRUE(NextFrameConfig(0, timestamp_).drop_frame);

  // Try again at the limit, now it should pass.
  timestamp_ += 90;
  EXPECT_FALSE(NextFrameConfig(0, timestamp_).drop_frame);
}

TEST_F(ScreenshareLayerTest, AdjustsBitrateWhenDroppingFrames) {
  const uint32_t kTimestampDelta10Fps = kTimestampDelta5Fps / 2;
  const int kNumFrames = 30;
  ASSERT_TRUE(cfg_.rc_target_bitrate.has_value());
  const uint32_t default_bitrate = cfg_.rc_target_bitrate.value();
  layers_->OnRatesUpdated(0, kDefault2TlBitratesBps, 10);

  int num_dropped_frames = 0;
  for (int i = 0; i < kNumFrames; ++i) {
    if (EncodeFrame(false) == -1)
      ++num_dropped_frames;
    timestamp_ += kTimestampDelta10Fps;
  }
  cfg_ = layers_->UpdateConfiguration(0);

  EXPECT_EQ(num_dropped_frames, kNumFrames / 2);
  EXPECT_EQ(cfg_.rc_target_bitrate, default_bitrate * 2);
}

TEST_F(ScreenshareLayerTest, UpdatesConfigurationAfterRateChange) {
  // Set inital rate again, no need to update configuration.
  layers_->OnRatesUpdated(0, kDefault2TlBitratesBps, kFrameRate);
  cfg_ = layers_->UpdateConfiguration(0);

  // Rate changed, now update config.
  std::vector<uint32_t> bitrates = kDefault2TlBitratesBps;
  bitrates[1] -= 100000;
  layers_->OnRatesUpdated(0, bitrates, 5);
  cfg_ = layers_->UpdateConfiguration(0);

  // Changed rate, but then set changed rate again before trying to update
  // configuration, update should still apply.
  bitrates[1] -= 100000;
  layers_->OnRatesUpdated(0, bitrates, 5);
  layers_->OnRatesUpdated(0, bitrates, 5);
  cfg_ = layers_->UpdateConfiguration(0);
}

TEST_F(ScreenshareLayerTest, MaxQpRestoredAfterDoubleDrop) {
  // Run grace period so we have existing frames in both TL0 and Tl1.
  EXPECT_TRUE(RunGracePeriod());

  // Move ahead until we have a sync frame in TL1.
  EXPECT_EQ(kTl1SyncFlags, SkipUntilTlAndSync(1, true));
  ASSERT_TRUE(tl_config_.layer_sync);

  // Simulate overshoot of this frame.
  layers_->OnEncodeDone(0, timestamp_, 0, false, -1, nullptr);

  // Simulate re-encoded frame.
  layers_->OnEncodeDone(0, timestamp_, 1, false, max_qp_,
                        IgnoredCodecSpecificInfo());

  // Next frame, expect boosted quality.
  // Slightly alter bitrate between each frame.
  std::vector<uint32_t> kDefault2TlBitratesBpsAlt = kDefault2TlBitratesBps;
  kDefault2TlBitratesBpsAlt[1] += 4000;
  layers_->OnRatesUpdated(0, kDefault2TlBitratesBpsAlt, kFrameRate);
  EXPECT_EQ(kTl1Flags, SkipUntilTlAndSync(1, false));
  EXPECT_TRUE(config_updated_);
  EXPECT_LT(cfg_.rc_max_quantizer, max_qp_);
  ASSERT_TRUE(cfg_.rc_max_quantizer.has_value());
  const uint32_t adjusted_qp = cfg_.rc_max_quantizer.value();

  // Simulate overshoot of this frame.
  layers_->OnEncodeDone(0, timestamp_, 0, false, -1, nullptr);

  // Simulate re-encoded frame.
  layers_->OnEncodeDone(0, timestamp_, frame_size_, false, max_qp_,
                        IgnoredCodecSpecificInfo());

  // A third frame, expect boosted quality.
  layers_->OnRatesUpdated(0, kDefault2TlBitratesBps, kFrameRate);
  EXPECT_EQ(kTl1Flags, SkipUntilTlAndSync(1, false));
  EXPECT_TRUE(config_updated_);
  EXPECT_LT(cfg_.rc_max_quantizer, max_qp_);
  EXPECT_EQ(adjusted_qp, cfg_.rc_max_quantizer);

  // Frame encoded.
  layers_->OnEncodeDone(0, timestamp_, frame_size_, false, max_qp_,
                        IgnoredCodecSpecificInfo());

  // A fourth frame, max qp should be restored.
  layers_->OnRatesUpdated(0, kDefault2TlBitratesBpsAlt, kFrameRate);
  EXPECT_EQ(kTl1Flags, SkipUntilTlAndSync(1, false));
  EXPECT_EQ(cfg_.rc_max_quantizer, max_qp_);
}

}  // namespace webrtc