aboutsummaryrefslogtreecommitdiff
path: root/call/adaptation/resource_adaptation_processor_unittest.cc
blob: 4e0f88524baa26a6e9167d49ef66741b52951ba2 (plain)
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
/*
 *  Copyright (c) 2020 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 "call/adaptation/resource_adaptation_processor.h"

#include "api/adaptation/resource.h"
#include "api/scoped_refptr.h"
#include "api/video/video_adaptation_counters.h"
#include "call/adaptation/resource_adaptation_processor_interface.h"
#include "call/adaptation/test/fake_adaptation_constraint.h"
#include "call/adaptation/test/fake_adaptation_listener.h"
#include "call/adaptation/test/fake_frame_rate_provider.h"
#include "call/adaptation/test/fake_resource.h"
#include "call/adaptation/video_source_restrictions.h"
#include "call/adaptation/video_stream_input_state_provider.h"
#include "rtc_base/critical_section.h"
#include "rtc_base/event.h"
#include "rtc_base/gunit.h"
#include "rtc_base/task_queue_for_test.h"
#include "test/gtest.h"

namespace webrtc {

namespace {

const int kDefaultFrameRate = 30;
const int kDefaultFrameSize = 1280 * 720;
const int kDefaultTimeoutMs = 5000;

class VideoSourceRestrictionsListenerForTesting
    : public VideoSourceRestrictionsListener {
 public:
  VideoSourceRestrictionsListenerForTesting()
      : restrictions_updated_count_(0),
        restrictions_(),
        adaptation_counters_(),
        reason_(nullptr) {}
  ~VideoSourceRestrictionsListenerForTesting() override {}

  size_t restrictions_updated_count() const {
    RTC_DCHECK_RUN_ON(&sequence_checker_);
    return restrictions_updated_count_;
  }
  VideoSourceRestrictions restrictions() const {
    RTC_DCHECK_RUN_ON(&sequence_checker_);
    return restrictions_;
  }
  VideoAdaptationCounters adaptation_counters() const {
    RTC_DCHECK_RUN_ON(&sequence_checker_);
    return adaptation_counters_;
  }
  rtc::scoped_refptr<Resource> reason() const {
    RTC_DCHECK_RUN_ON(&sequence_checker_);
    return reason_;
  }

  // VideoSourceRestrictionsListener implementation.
  void OnVideoSourceRestrictionsUpdated(
      VideoSourceRestrictions restrictions,
      const VideoAdaptationCounters& adaptation_counters,
      rtc::scoped_refptr<Resource> reason,
      const VideoSourceRestrictions& unfiltered_restrictions) override {
    RTC_DCHECK_RUN_ON(&sequence_checker_);
    ++restrictions_updated_count_;
    restrictions_ = restrictions;
    adaptation_counters_ = adaptation_counters;
    reason_ = reason;
  }

 private:
  SequenceChecker sequence_checker_;
  size_t restrictions_updated_count_ RTC_GUARDED_BY(&sequence_checker_);
  VideoSourceRestrictions restrictions_ RTC_GUARDED_BY(&sequence_checker_);
  VideoAdaptationCounters adaptation_counters_
      RTC_GUARDED_BY(&sequence_checker_);
  rtc::scoped_refptr<Resource> reason_ RTC_GUARDED_BY(&sequence_checker_);
};

class ResourceAdaptationProcessorTest : public ::testing::Test {
 public:
  ResourceAdaptationProcessorTest()
      : frame_rate_provider_(),
        input_state_provider_(&frame_rate_provider_),
        resource_(FakeResource::Create("FakeResource")),
        other_resource_(FakeResource::Create("OtherFakeResource")),
        adaptation_constraint_("FakeAdaptationConstraint"),
        adaptation_listener_(),
        video_stream_adapter_(
            std::make_unique<VideoStreamAdapter>(&input_state_provider_)),
        processor_(std::make_unique<ResourceAdaptationProcessor>(
            /*encoder_stats_observer=*/&frame_rate_provider_,
            video_stream_adapter_.get())) {
    processor_->SetResourceAdaptationQueue(TaskQueueBase::Current());
    video_stream_adapter_->AddRestrictionsListener(&restrictions_listener_);
    processor_->AddResource(resource_);
    processor_->AddResource(other_resource_);
    processor_->AddAdaptationConstraint(&adaptation_constraint_);
    processor_->AddAdaptationListener(&adaptation_listener_);
  }
  ~ResourceAdaptationProcessorTest() override {
    if (processor_) {
      DestroyProcessor();
    }
  }

  void SetInputStates(bool has_input, int fps, int frame_size) {
    input_state_provider_.OnHasInputChanged(has_input);
    frame_rate_provider_.set_fps(fps);
    input_state_provider_.OnFrameSizeObserved(frame_size);
  }

  void RestrictSource(VideoSourceRestrictions restrictions) {
    SetInputStates(
        true, restrictions.max_frame_rate().value_or(kDefaultFrameRate),
        restrictions.target_pixels_per_frame().has_value()
            ? restrictions.target_pixels_per_frame().value()
            : restrictions.max_pixels_per_frame().value_or(kDefaultFrameSize));
  }

  void DestroyProcessor() {
    if (resource_) {
      processor_->RemoveResource(resource_);
    }
    if (other_resource_) {
      processor_->RemoveResource(other_resource_);
    }
    processor_->RemoveAdaptationConstraint(&adaptation_constraint_);
    processor_->RemoveAdaptationListener(&adaptation_listener_);
    video_stream_adapter_->RemoveRestrictionsListener(&restrictions_listener_);
    processor_.reset();
  }

  static void WaitUntilTaskQueueIdle() {
    ASSERT_TRUE(rtc::Thread::Current()->ProcessMessages(0));
  }

 protected:
  FakeFrameRateProvider frame_rate_provider_;
  VideoStreamInputStateProvider input_state_provider_;
  rtc::scoped_refptr<FakeResource> resource_;
  rtc::scoped_refptr<FakeResource> other_resource_;
  FakeAdaptationConstraint adaptation_constraint_;
  FakeAdaptationListener adaptation_listener_;
  std::unique_ptr<VideoStreamAdapter> video_stream_adapter_;
  std::unique_ptr<ResourceAdaptationProcessor> processor_;
  VideoSourceRestrictionsListenerForTesting restrictions_listener_;
};

}  // namespace

TEST_F(ResourceAdaptationProcessorTest, DisabledByDefault) {
  SetInputStates(true, kDefaultFrameRate, kDefaultFrameSize);
  // Adaptation does not happen when disabled.
  resource_->SetUsageState(ResourceUsageState::kOveruse);
  EXPECT_EQ(0u, restrictions_listener_.restrictions_updated_count());
}

TEST_F(ResourceAdaptationProcessorTest, InsufficientInput) {
  processor_->OnDegradationPreferenceUpdated(
      DegradationPreference::MAINTAIN_FRAMERATE);
  // Adaptation does not happen if input is insufficient.
  // When frame size is missing (OnFrameSizeObserved not called yet).
  input_state_provider_.OnHasInputChanged(true);
  resource_->SetUsageState(ResourceUsageState::kOveruse);
  EXPECT_EQ(0u, restrictions_listener_.restrictions_updated_count());
  // When "has input" is missing.
  SetInputStates(false, kDefaultFrameRate, kDefaultFrameSize);
  resource_->SetUsageState(ResourceUsageState::kOveruse);
  EXPECT_EQ(0u, restrictions_listener_.restrictions_updated_count());
  // Note: frame rate cannot be missing, if unset it is 0.
}

// These tests verify that restrictions are applied, but not exactly how much
// the source is restricted. This ensures that the VideoStreamAdapter is wired
// up correctly but not exactly how the VideoStreamAdapter generates
// restrictions. For that, see video_stream_adapter_unittest.cc.
TEST_F(ResourceAdaptationProcessorTest,
       OveruseTriggersRestrictingResolutionInMaintainFrameRate) {
  processor_->OnDegradationPreferenceUpdated(
      DegradationPreference::MAINTAIN_FRAMERATE);
  SetInputStates(true, kDefaultFrameRate, kDefaultFrameSize);
  resource_->SetUsageState(ResourceUsageState::kOveruse);
  EXPECT_EQ(1u, restrictions_listener_.restrictions_updated_count());
  EXPECT_TRUE(
      restrictions_listener_.restrictions().max_pixels_per_frame().has_value());
}

TEST_F(ResourceAdaptationProcessorTest,
       OveruseTriggersRestrictingFrameRateInMaintainResolution) {
  processor_->OnDegradationPreferenceUpdated(
      DegradationPreference::MAINTAIN_RESOLUTION);
  SetInputStates(true, kDefaultFrameRate, kDefaultFrameSize);
  resource_->SetUsageState(ResourceUsageState::kOveruse);
  EXPECT_EQ(1u, restrictions_listener_.restrictions_updated_count());
  EXPECT_TRUE(
      restrictions_listener_.restrictions().max_frame_rate().has_value());
}

TEST_F(ResourceAdaptationProcessorTest,
       OveruseTriggersRestrictingFrameRateAndResolutionInBalanced) {
  processor_->OnDegradationPreferenceUpdated(DegradationPreference::BALANCED);
  SetInputStates(true, kDefaultFrameRate, kDefaultFrameSize);
  // Adapting multiple times eventually resticts both frame rate and
  // resolution. Exactly many times we need to adapt depends on
  // BalancedDegradationSettings, VideoStreamAdapter and default input
  // states. This test requires it to be achieved within 4 adaptations.
  for (size_t i = 0; i < 4; ++i) {
    resource_->SetUsageState(ResourceUsageState::kOveruse);
    EXPECT_EQ(i + 1, restrictions_listener_.restrictions_updated_count());
    RestrictSource(restrictions_listener_.restrictions());
  }
  EXPECT_TRUE(
      restrictions_listener_.restrictions().max_pixels_per_frame().has_value());
  EXPECT_TRUE(
      restrictions_listener_.restrictions().max_frame_rate().has_value());
}

TEST_F(ResourceAdaptationProcessorTest, AwaitingPreviousAdaptation) {
  processor_->OnDegradationPreferenceUpdated(
      DegradationPreference::MAINTAIN_FRAMERATE);
  SetInputStates(true, kDefaultFrameRate, kDefaultFrameSize);
  resource_->SetUsageState(ResourceUsageState::kOveruse);
  EXPECT_EQ(1u, restrictions_listener_.restrictions_updated_count());
  // If we don't restrict the source then adaptation will not happen again
  // due to "awaiting previous adaptation". This prevents "double-adapt".
  resource_->SetUsageState(ResourceUsageState::kOveruse);
  EXPECT_EQ(1u, restrictions_listener_.restrictions_updated_count());
}

TEST_F(ResourceAdaptationProcessorTest, CannotAdaptUpWhenUnrestricted) {
  processor_->OnDegradationPreferenceUpdated(
      DegradationPreference::MAINTAIN_FRAMERATE);
  SetInputStates(true, kDefaultFrameRate, kDefaultFrameSize);
  resource_->SetUsageState(ResourceUsageState::kUnderuse);
  EXPECT_EQ(0u, restrictions_listener_.restrictions_updated_count());
}

TEST_F(ResourceAdaptationProcessorTest, UnderuseTakesUsBackToUnrestricted) {
  processor_->OnDegradationPreferenceUpdated(
      DegradationPreference::MAINTAIN_FRAMERATE);
  SetInputStates(true, kDefaultFrameRate, kDefaultFrameSize);
  resource_->SetUsageState(ResourceUsageState::kOveruse);
  EXPECT_EQ(1u, restrictions_listener_.restrictions_updated_count());
  RestrictSource(restrictions_listener_.restrictions());
  resource_->SetUsageState(ResourceUsageState::kUnderuse);
  EXPECT_EQ(2u, restrictions_listener_.restrictions_updated_count());
  EXPECT_EQ(VideoSourceRestrictions(), restrictions_listener_.restrictions());
}

TEST_F(ResourceAdaptationProcessorTest, ResourcesCanPreventAdaptingUp) {
  processor_->OnDegradationPreferenceUpdated(
      DegradationPreference::MAINTAIN_FRAMERATE);
  SetInputStates(true, kDefaultFrameRate, kDefaultFrameSize);
  // Adapt down so that we can adapt up.
  resource_->SetUsageState(ResourceUsageState::kOveruse);
  EXPECT_EQ(1u, restrictions_listener_.restrictions_updated_count());
  RestrictSource(restrictions_listener_.restrictions());
  // Adapting up is prevented.
  adaptation_constraint_.set_is_adaptation_up_allowed(false);
  resource_->SetUsageState(ResourceUsageState::kUnderuse);
  EXPECT_EQ(1u, restrictions_listener_.restrictions_updated_count());
}

TEST_F(ResourceAdaptationProcessorTest,
       ResourcesCanNotAdaptUpIfNeverAdaptedDown) {
  processor_->OnDegradationPreferenceUpdated(
      DegradationPreference::MAINTAIN_FRAMERATE);
  SetInputStates(true, kDefaultFrameRate, kDefaultFrameSize);
  resource_->SetUsageState(ResourceUsageState::kOveruse);
  EXPECT_EQ(1u, restrictions_listener_.restrictions_updated_count());
  RestrictSource(restrictions_listener_.restrictions());

  // Other resource signals under-use
  other_resource_->SetUsageState(ResourceUsageState::kUnderuse);
  EXPECT_EQ(1u, restrictions_listener_.restrictions_updated_count());
}

TEST_F(ResourceAdaptationProcessorTest,
       ResourcesCanNotAdaptUpIfNotAdaptedDownAfterReset) {
  processor_->OnDegradationPreferenceUpdated(
      DegradationPreference::MAINTAIN_FRAMERATE);
  SetInputStates(true, kDefaultFrameRate, kDefaultFrameSize);
  resource_->SetUsageState(ResourceUsageState::kOveruse);
  EXPECT_EQ(1u, restrictions_listener_.restrictions_updated_count());

  video_stream_adapter_->ClearRestrictions();
  EXPECT_EQ(0, restrictions_listener_.adaptation_counters().Total());
  other_resource_->SetUsageState(ResourceUsageState::kOveruse);
  EXPECT_EQ(1, restrictions_listener_.adaptation_counters().Total());
  RestrictSource(restrictions_listener_.restrictions());

  // resource_ did not overuse after we reset the restrictions, so adapt
  // up should be disallowed.
  resource_->SetUsageState(ResourceUsageState::kUnderuse);
  EXPECT_EQ(1, restrictions_listener_.adaptation_counters().Total());
}

TEST_F(ResourceAdaptationProcessorTest, OnlyMostLimitedResourceMayAdaptUp) {
  processor_->OnDegradationPreferenceUpdated(
      DegradationPreference::MAINTAIN_FRAMERATE);
  SetInputStates(true, kDefaultFrameRate, kDefaultFrameSize);
  resource_->SetUsageState(ResourceUsageState::kOveruse);
  EXPECT_EQ(1, restrictions_listener_.adaptation_counters().Total());
  RestrictSource(restrictions_listener_.restrictions());
  other_resource_->SetUsageState(ResourceUsageState::kOveruse);
  EXPECT_EQ(2, restrictions_listener_.adaptation_counters().Total());
  RestrictSource(restrictions_listener_.restrictions());

  // |other_resource_| is most limited, resource_ can't adapt up.
  resource_->SetUsageState(ResourceUsageState::kUnderuse);
  EXPECT_EQ(2, restrictions_listener_.adaptation_counters().Total());
  RestrictSource(restrictions_listener_.restrictions());
  other_resource_->SetUsageState(ResourceUsageState::kUnderuse);
  EXPECT_EQ(1, restrictions_listener_.adaptation_counters().Total());
  RestrictSource(restrictions_listener_.restrictions());

  // |resource_| and |other_resource_| are now most limited, so both must
  // signal underuse to adapt up.
  other_resource_->SetUsageState(ResourceUsageState::kUnderuse);
  EXPECT_EQ(1, restrictions_listener_.adaptation_counters().Total());
  RestrictSource(restrictions_listener_.restrictions());
  resource_->SetUsageState(ResourceUsageState::kUnderuse);
  EXPECT_EQ(0, restrictions_listener_.adaptation_counters().Total());
  RestrictSource(restrictions_listener_.restrictions());
}

TEST_F(ResourceAdaptationProcessorTest,
       MultipleResourcesCanTriggerMultipleAdaptations) {
  processor_->OnDegradationPreferenceUpdated(
      DegradationPreference::MAINTAIN_FRAMERATE);
  SetInputStates(true, kDefaultFrameRate, kDefaultFrameSize);
  resource_->SetUsageState(ResourceUsageState::kOveruse);
  EXPECT_EQ(1, restrictions_listener_.adaptation_counters().Total());
  RestrictSource(restrictions_listener_.restrictions());
  other_resource_->SetUsageState(ResourceUsageState::kOveruse);
  EXPECT_EQ(2, restrictions_listener_.adaptation_counters().Total());
  RestrictSource(restrictions_listener_.restrictions());
  other_resource_->SetUsageState(ResourceUsageState::kOveruse);
  EXPECT_EQ(3, restrictions_listener_.adaptation_counters().Total());
  RestrictSource(restrictions_listener_.restrictions());

  // resource_ is not most limited so can't adapt from underuse.
  resource_->SetUsageState(ResourceUsageState::kUnderuse);
  EXPECT_EQ(3, restrictions_listener_.adaptation_counters().Total());
  RestrictSource(restrictions_listener_.restrictions());
  other_resource_->SetUsageState(ResourceUsageState::kUnderuse);
  EXPECT_EQ(2, restrictions_listener_.adaptation_counters().Total());
  RestrictSource(restrictions_listener_.restrictions());
  // resource_ is still not most limited so can't adapt from underuse.
  resource_->SetUsageState(ResourceUsageState::kUnderuse);
  EXPECT_EQ(2, restrictions_listener_.adaptation_counters().Total());
  RestrictSource(restrictions_listener_.restrictions());

  // However it will be after overuse
  resource_->SetUsageState(ResourceUsageState::kOveruse);
  EXPECT_EQ(3, restrictions_listener_.adaptation_counters().Total());
  RestrictSource(restrictions_listener_.restrictions());

  // Now other_resource_ can't adapt up as it is not most restricted.
  other_resource_->SetUsageState(ResourceUsageState::kUnderuse);
  EXPECT_EQ(3, restrictions_listener_.adaptation_counters().Total());
  RestrictSource(restrictions_listener_.restrictions());

  // resource_ is limited at 3 adaptations and other_resource_ 2.
  // With the most limited resource signalling underuse in the following
  // order we get back to unrestricted video.
  resource_->SetUsageState(ResourceUsageState::kUnderuse);
  EXPECT_EQ(2, restrictions_listener_.adaptation_counters().Total());
  RestrictSource(restrictions_listener_.restrictions());
  // Both resource_ and other_resource_ are most limited.
  other_resource_->SetUsageState(ResourceUsageState::kUnderuse);
  EXPECT_EQ(2, restrictions_listener_.adaptation_counters().Total());
  RestrictSource(restrictions_listener_.restrictions());
  resource_->SetUsageState(ResourceUsageState::kUnderuse);
  EXPECT_EQ(1, restrictions_listener_.adaptation_counters().Total());
  RestrictSource(restrictions_listener_.restrictions());
  // Again both are most limited.
  resource_->SetUsageState(ResourceUsageState::kUnderuse);
  EXPECT_EQ(1, restrictions_listener_.adaptation_counters().Total());
  RestrictSource(restrictions_listener_.restrictions());
  other_resource_->SetUsageState(ResourceUsageState::kUnderuse);
  EXPECT_EQ(0, restrictions_listener_.adaptation_counters().Total());
}

TEST_F(ResourceAdaptationProcessorTest,
       MostLimitedResourceAdaptationWorksAfterChangingDegradataionPreference) {
  processor_->OnDegradationPreferenceUpdated(
      DegradationPreference::MAINTAIN_FRAMERATE);
  SetInputStates(true, kDefaultFrameRate, kDefaultFrameSize);
  // Adapt down until we can't anymore.
  resource_->SetUsageState(ResourceUsageState::kOveruse);
  RestrictSource(restrictions_listener_.restrictions());
  resource_->SetUsageState(ResourceUsageState::kOveruse);
  RestrictSource(restrictions_listener_.restrictions());
  resource_->SetUsageState(ResourceUsageState::kOveruse);
  RestrictSource(restrictions_listener_.restrictions());
  resource_->SetUsageState(ResourceUsageState::kOveruse);
  RestrictSource(restrictions_listener_.restrictions());
  resource_->SetUsageState(ResourceUsageState::kOveruse);
  RestrictSource(restrictions_listener_.restrictions());
  int last_total = restrictions_listener_.adaptation_counters().Total();

  processor_->OnDegradationPreferenceUpdated(
      DegradationPreference::MAINTAIN_RESOLUTION);
  // resource_ can not adapt up since we have never reduced FPS.
  resource_->SetUsageState(ResourceUsageState::kUnderuse);
  EXPECT_EQ(last_total, restrictions_listener_.adaptation_counters().Total());

  other_resource_->SetUsageState(ResourceUsageState::kOveruse);
  EXPECT_EQ(last_total + 1,
            restrictions_listener_.adaptation_counters().Total());
  RestrictSource(restrictions_listener_.restrictions());
  // other_resource_ is most limited so should be able to adapt up.
  other_resource_->SetUsageState(ResourceUsageState::kUnderuse);
  EXPECT_EQ(last_total, restrictions_listener_.adaptation_counters().Total());
}

TEST_F(ResourceAdaptationProcessorTest, AdaptingTriggersOnAdaptationApplied) {
  processor_->OnDegradationPreferenceUpdated(
      DegradationPreference::MAINTAIN_FRAMERATE);
  SetInputStates(true, kDefaultFrameRate, kDefaultFrameSize);
  resource_->SetUsageState(ResourceUsageState::kOveruse);
  EXPECT_EQ(1u, adaptation_listener_.num_adaptations_applied());
}

TEST_F(ResourceAdaptationProcessorTest,
       AdaptsDownWhenOtherResourceIsAlwaysUnderused) {
  processor_->OnDegradationPreferenceUpdated(
      DegradationPreference::MAINTAIN_FRAMERATE);
  SetInputStates(true, kDefaultFrameRate, kDefaultFrameSize);
  other_resource_->SetUsageState(ResourceUsageState::kUnderuse);
  // Does not trigger adapataion because there's no restriction.
  EXPECT_EQ(0, restrictions_listener_.adaptation_counters().Total());

  RestrictSource(restrictions_listener_.restrictions());
  resource_->SetUsageState(ResourceUsageState::kOveruse);
  // Adapts down even if other resource asked for adapting up.
  EXPECT_EQ(1, restrictions_listener_.adaptation_counters().Total());

  RestrictSource(restrictions_listener_.restrictions());
  other_resource_->SetUsageState(ResourceUsageState::kUnderuse);
  // Doesn't adapt up because adaptation is due to another resource.
  EXPECT_EQ(1, restrictions_listener_.adaptation_counters().Total());
  RestrictSource(restrictions_listener_.restrictions());
}

TEST_F(ResourceAdaptationProcessorTest,
       TriggerOveruseNotOnAdaptationTaskQueue) {
  processor_->OnDegradationPreferenceUpdated(
      DegradationPreference::MAINTAIN_FRAMERATE);
  SetInputStates(true, kDefaultFrameRate, kDefaultFrameSize);

  TaskQueueForTest resource_task_queue("ResourceTaskQueue");
  resource_task_queue.PostTask(ToQueuedTask(
      [&]() { resource_->SetUsageState(ResourceUsageState::kOveruse); }));

  EXPECT_EQ_WAIT(1u, restrictions_listener_.restrictions_updated_count(),
                 kDefaultTimeoutMs);
}

TEST_F(ResourceAdaptationProcessorTest,
       DestroyProcessorWhileResourceListenerDelegateHasTaskInFlight) {
  processor_->OnDegradationPreferenceUpdated(
      DegradationPreference::MAINTAIN_FRAMERATE);
  SetInputStates(true, kDefaultFrameRate, kDefaultFrameSize);

  // Wait for |resource_| to signal oversue first so we know that the delegate
  // has passed it on to the processor's task queue.
  rtc::Event resource_event;
  TaskQueueForTest resource_task_queue("ResourceTaskQueue");
  resource_task_queue.PostTask(ToQueuedTask([&]() {
    resource_->SetUsageState(ResourceUsageState::kOveruse);
    resource_event.Set();
  }));

  EXPECT_TRUE(resource_event.Wait(kDefaultTimeoutMs));
  // Now destroy the processor while handling the overuse is in flight.
  DestroyProcessor();

  // Because the processor was destroyed by the time the delegate's task ran,
  // the overuse signal must not have been handled.
  EXPECT_EQ(0u, restrictions_listener_.restrictions_updated_count());
}

TEST_F(ResourceAdaptationProcessorTest,
       ResourceOveruseIgnoredWhenSignalledDuringRemoval) {
  processor_->OnDegradationPreferenceUpdated(
      DegradationPreference::MAINTAIN_FRAMERATE);
  SetInputStates(true, kDefaultFrameRate, kDefaultFrameSize);

  rtc::Event overuse_event;
  TaskQueueForTest resource_task_queue("ResourceTaskQueue");
  // Queues task for |resource_| overuse while |processor_| is still listening.
  resource_task_queue.PostTask(ToQueuedTask([&]() {
    resource_->SetUsageState(ResourceUsageState::kOveruse);
    overuse_event.Set();
  }));
  EXPECT_TRUE(overuse_event.Wait(kDefaultTimeoutMs));
  // Once we know the overuse task is queued, remove |resource_| so that
  // |processor_| is not listening to it.
  processor_->RemoveResource(resource_);

  // Runs the queued task so |processor_| gets signalled kOveruse from
  // |resource_| even though |processor_| was not listening.
  WaitUntilTaskQueueIdle();

  // No restrictions should change even though |resource_| signaled |kOveruse|.
  EXPECT_EQ(0u, restrictions_listener_.restrictions_updated_count());

  // Delete |resource_| for cleanup.
  resource_ = nullptr;
}

TEST_F(ResourceAdaptationProcessorTest,
       RemovingOnlyAdaptedResourceResetsAdaptation) {
  processor_->OnDegradationPreferenceUpdated(
      DegradationPreference::MAINTAIN_FRAMERATE);
  SetInputStates(true, kDefaultFrameRate, kDefaultFrameSize);

  resource_->SetUsageState(ResourceUsageState::kOveruse);
  EXPECT_EQ(1, restrictions_listener_.adaptation_counters().Total());
  RestrictSource(restrictions_listener_.restrictions());

  processor_->RemoveResource(resource_);
  EXPECT_EQ(0, restrictions_listener_.adaptation_counters().Total());

  // Delete |resource_| for cleanup.
  resource_ = nullptr;
}

TEST_F(ResourceAdaptationProcessorTest,
       RemovingMostLimitedResourceSetsAdaptationToNextLimitedLevel) {
  processor_->OnDegradationPreferenceUpdated(DegradationPreference::BALANCED);
  SetInputStates(true, kDefaultFrameRate, kDefaultFrameSize);

  other_resource_->SetUsageState(ResourceUsageState::kOveruse);
  RestrictSource(restrictions_listener_.restrictions());
  EXPECT_EQ(1, restrictions_listener_.adaptation_counters().Total());
  VideoSourceRestrictions next_limited_restrictions =
      restrictions_listener_.restrictions();
  VideoAdaptationCounters next_limited_counters =
      restrictions_listener_.adaptation_counters();

  resource_->SetUsageState(ResourceUsageState::kOveruse);
  RestrictSource(restrictions_listener_.restrictions());
  EXPECT_EQ(2, restrictions_listener_.adaptation_counters().Total());

  // Removing most limited |resource_| should revert us back to
  processor_->RemoveResource(resource_);
  EXPECT_EQ(1, restrictions_listener_.adaptation_counters().Total());
  EXPECT_EQ(next_limited_restrictions, restrictions_listener_.restrictions());
  EXPECT_EQ(next_limited_counters,
            restrictions_listener_.adaptation_counters());

  // Delete |resource_| for cleanup.
  resource_ = nullptr;
}

TEST_F(ResourceAdaptationProcessorTest,
       RemovingMostLimitedResourceSetsAdaptationIfInputStateUnchanged) {
  processor_->OnDegradationPreferenceUpdated(
      DegradationPreference::MAINTAIN_FRAMERATE);
  SetInputStates(true, kDefaultFrameRate, kDefaultFrameSize);

  other_resource_->SetUsageState(ResourceUsageState::kOveruse);
  RestrictSource(restrictions_listener_.restrictions());
  EXPECT_EQ(1, restrictions_listener_.adaptation_counters().Total());
  VideoSourceRestrictions next_limited_restrictions =
      restrictions_listener_.restrictions();
  VideoAdaptationCounters next_limited_counters =
      restrictions_listener_.adaptation_counters();

  // Overuse twice and underuse once. After the underuse we don't restrict the
  // source. Normally this would block future underuses.
  resource_->SetUsageState(ResourceUsageState::kOveruse);
  RestrictSource(restrictions_listener_.restrictions());
  resource_->SetUsageState(ResourceUsageState::kOveruse);
  RestrictSource(restrictions_listener_.restrictions());
  resource_->SetUsageState(ResourceUsageState::kUnderuse);
  EXPECT_EQ(2, restrictions_listener_.adaptation_counters().Total());

  // Removing most limited |resource_| should revert us back to, even though we
  // did not call RestrictSource() after |resource_| was overused. Normally
  // adaptation for MAINTAIN_FRAMERATE would be blocked here but for removal we
  // allow this anyways.
  processor_->RemoveResource(resource_);
  EXPECT_EQ(1, restrictions_listener_.adaptation_counters().Total());
  EXPECT_EQ(next_limited_restrictions, restrictions_listener_.restrictions());
  EXPECT_EQ(next_limited_counters,
            restrictions_listener_.adaptation_counters());

  // Delete |resource_| for cleanup.
  resource_ = nullptr;
}

TEST_F(ResourceAdaptationProcessorTest,
       RemovingResourceNotMostLimitedHasNoEffectOnLimitations) {
  processor_->OnDegradationPreferenceUpdated(DegradationPreference::BALANCED);
  SetInputStates(true, kDefaultFrameRate, kDefaultFrameSize);

  other_resource_->SetUsageState(ResourceUsageState::kOveruse);
  RestrictSource(restrictions_listener_.restrictions());
  EXPECT_EQ(1, restrictions_listener_.adaptation_counters().Total());

  resource_->SetUsageState(ResourceUsageState::kOveruse);
  RestrictSource(restrictions_listener_.restrictions());
  VideoSourceRestrictions current_restrictions =
      restrictions_listener_.restrictions();
  VideoAdaptationCounters current_counters =
      restrictions_listener_.adaptation_counters();
  EXPECT_EQ(2, restrictions_listener_.adaptation_counters().Total());

  // Removing most limited |resource_| should revert us back to
  processor_->RemoveResource(other_resource_);
  EXPECT_EQ(current_restrictions, restrictions_listener_.restrictions());
  EXPECT_EQ(current_counters, restrictions_listener_.adaptation_counters());

  // Delete |other_resource_| for cleanup.
  other_resource_ = nullptr;
}

TEST_F(ResourceAdaptationProcessorTest,
       RemovingMostLimitedResourceAfterSwitchingDegradationPreferences) {
  processor_->OnDegradationPreferenceUpdated(
      DegradationPreference::MAINTAIN_FRAMERATE);
  SetInputStates(true, kDefaultFrameRate, kDefaultFrameSize);

  other_resource_->SetUsageState(ResourceUsageState::kOveruse);
  RestrictSource(restrictions_listener_.restrictions());
  EXPECT_EQ(1, restrictions_listener_.adaptation_counters().Total());
  VideoSourceRestrictions next_limited_restrictions =
      restrictions_listener_.restrictions();
  VideoAdaptationCounters next_limited_counters =
      restrictions_listener_.adaptation_counters();

  processor_->OnDegradationPreferenceUpdated(
      DegradationPreference::MAINTAIN_RESOLUTION);
  resource_->SetUsageState(ResourceUsageState::kOveruse);
  RestrictSource(restrictions_listener_.restrictions());
  EXPECT_EQ(2, restrictions_listener_.adaptation_counters().Total());

  // Revert to |other_resource_| when removing |resource_| even though the
  // degradation preference was different when it was overused.
  processor_->RemoveResource(resource_);
  EXPECT_EQ(next_limited_counters,
            restrictions_listener_.adaptation_counters());

  // After switching back to MAINTAIN_FRAMERATE, the next most limited settings
  // are restored.
  processor_->OnDegradationPreferenceUpdated(
      DegradationPreference::MAINTAIN_FRAMERATE);
  EXPECT_EQ(next_limited_restrictions, restrictions_listener_.restrictions());

  // Delete |resource_| for cleanup.
  resource_ = nullptr;
}

TEST_F(ResourceAdaptationProcessorTest,
       RemovingMostLimitedResourceSetsNextLimitationsInDisabled) {
  processor_->OnDegradationPreferenceUpdated(
      DegradationPreference::MAINTAIN_FRAMERATE);
  SetInputStates(true, kDefaultFrameRate, kDefaultFrameSize);

  other_resource_->SetUsageState(ResourceUsageState::kOveruse);
  RestrictSource(restrictions_listener_.restrictions());
  VideoSourceRestrictions next_limited_restrictions =
      restrictions_listener_.restrictions();
  VideoAdaptationCounters next_limited_counters =
      restrictions_listener_.adaptation_counters();
  EXPECT_EQ(1, restrictions_listener_.adaptation_counters().Total());
  resource_->SetUsageState(ResourceUsageState::kOveruse);
  RestrictSource(restrictions_listener_.restrictions());
  EXPECT_EQ(2, restrictions_listener_.adaptation_counters().Total());

  processor_->OnDegradationPreferenceUpdated(DegradationPreference::DISABLED);

  // Revert to |other_resource_| when removing |resource_| even though the
  // current degradataion preference is disabled.
  processor_->RemoveResource(resource_);

  // After switching back to MAINTAIN_FRAMERATE, the next most limited settings
  // are restored.
  processor_->OnDegradationPreferenceUpdated(
      DegradationPreference::MAINTAIN_FRAMERATE);
  EXPECT_EQ(next_limited_restrictions, restrictions_listener_.restrictions());
  EXPECT_EQ(next_limited_counters,
            restrictions_listener_.adaptation_counters());

  // Delete |resource_| for cleanup.
  resource_ = nullptr;
}

TEST_F(ResourceAdaptationProcessorTest,
       RemovedResourceSignalsIgnoredByProcessor) {
  processor_->OnDegradationPreferenceUpdated(
      DegradationPreference::MAINTAIN_FRAMERATE);
  SetInputStates(true, kDefaultFrameRate, kDefaultFrameSize);

  processor_->RemoveResource(resource_);
  resource_->SetUsageState(ResourceUsageState::kOveruse);
  EXPECT_EQ(0u, restrictions_listener_.restrictions_updated_count());

  // Delete |resource_| for cleanup.
  resource_ = nullptr;
}

TEST_F(ResourceAdaptationProcessorTest,
       RemovingResourceWhenMultipleMostLimtedHasNoEffect) {
  processor_->OnDegradationPreferenceUpdated(
      DegradationPreference::MAINTAIN_FRAMERATE);
  SetInputStates(true, kDefaultFrameRate, kDefaultFrameSize);

  other_resource_->SetUsageState(ResourceUsageState::kOveruse);
  RestrictSource(restrictions_listener_.restrictions());
  EXPECT_EQ(1, restrictions_listener_.adaptation_counters().Total());
  // Adapt |resource_| up and then down so that both resource's are most
  // limited at 1 adaptation.
  resource_->SetUsageState(ResourceUsageState::kOveruse);
  RestrictSource(restrictions_listener_.restrictions());
  resource_->SetUsageState(ResourceUsageState::kUnderuse);
  RestrictSource(restrictions_listener_.restrictions());
  EXPECT_EQ(1, restrictions_listener_.adaptation_counters().Total());

  // Removing |resource_| has no effect since both |resource_| and
  // |other_resource_| are most limited.
  processor_->RemoveResource(resource_);
  EXPECT_EQ(1, restrictions_listener_.adaptation_counters().Total());

  // Delete |resource_| for cleanup.
  resource_ = nullptr;
}

}  // namespace webrtc