blob: 267169a2f2df4979af4a1fb073157a289ce05af2 [file] [log] [blame]
perkj26091b12016-09-01 08:17:401/*
2 * Copyright (c) 2016 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
Erik Språng4529fbc2018-10-12 08:30:3111#include "video/video_stream_encoder.h"
12
sprangfe627f32017-03-29 15:24:5913#include <algorithm>
perkj803d97f2016-11-01 18:45:4614#include <limits>
Danil Chapovalovd3ba2362019-04-10 15:01:2315#include <memory>
Per512ecb32016-09-23 13:52:0616#include <utility>
17
Mirta Dvornicic28f0eb22019-05-28 14:30:1618#include "absl/memory/memory.h"
Danil Chapovalovd3ba2362019-04-10 15:01:2319#include "api/task_queue/default_task_queue_factory.h"
Elad Alon45befc52019-07-02 09:20:0920#include "api/test/mock_fec_controller_override.h"
philipel9b058032020-02-10 10:30:0021#include "api/test/mock_video_encoder.h"
Jiawei Ouc2ebe212018-11-08 18:02:5622#include "api/video/builtin_video_bitrate_allocator_factory.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3123#include "api/video/i420_buffer.h"
Evan Shrubsole895556e2020-10-05 07:15:1324#include "api/video/nv12_buffer.h"
Evan Shrubsolece0a11d2020-04-16 09:36:5525#include "api/video/video_adaptation_reason.h"
Erik Språngf93eda12019-01-16 16:10:5726#include "api/video/video_bitrate_allocation.h"
Elad Alon370f93a2019-06-11 12:57:5727#include "api/video_codecs/video_encoder.h"
Erik Språng4529fbc2018-10-12 08:30:3128#include "api/video_codecs/vp8_temporal_layers.h"
Elad Aloncde8ab22019-03-20 10:56:2029#include "api/video_codecs/vp8_temporal_layers_factory.h"
Henrik Boström0f0aa9c2020-06-02 11:02:3630#include "call/adaptation/test/fake_adaptation_constraint.h"
Evan Shrubsoleaa6fbc12020-02-25 15:26:0131#include "call/adaptation/test/fake_resource.h"
Mirta Dvornicic28f0eb22019-05-28 14:30:1632#include "common_video/h264/h264_common.h"
Noah Richards51db4212019-06-12 13:59:1233#include "common_video/include/video_frame_buffer.h"
Steve Anton10542f22019-01-11 17:11:0034#include "media/base/video_adapter.h"
Åsa Perssonc5a74ff2020-09-20 15:50:0035#include "media/engine/webrtc_video_engine.h"
Sergey Silkin86684962018-03-28 17:32:3736#include "modules/video_coding/codecs/vp9/include/vp9_globals.h"
Henrik Boström91aa7322020-04-28 10:24:3337#include "modules/video_coding/utility/quality_scaler.h"
Åsa Perssonc29cb2c2019-03-25 11:06:5938#include "modules/video_coding/utility/simulcast_rate_allocator.h"
Tomas Gunnarsson612445e2020-09-21 12:31:2339#include "rtc_base/event.h"
Henrik Boström2671dac2020-05-19 14:29:0940#include "rtc_base/gunit.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3141#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 17:11:0042#include "rtc_base/ref_counted_object.h"
Markus Handella3765182020-07-08 11:13:3243#include "rtc_base/synchronization/mutex.h"
Erik Språng7ca375c2019-02-06 15:20:1744#include "system_wrappers/include/field_trial.h"
Mirko Bonadei17f48782018-09-28 06:51:1045#include "system_wrappers/include/metrics.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3146#include "test/encoder_settings.h"
47#include "test/fake_encoder.h"
Kári Tristan Helgason639602a2018-08-02 08:51:4048#include "test/field_trial.h"
Artem Titov33f9d2b2019-12-05 14:59:0049#include "test/frame_forwarder.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3150#include "test/gmock.h"
51#include "test/gtest.h"
Tomas Gunnarsson612445e2020-09-21 12:31:2352#include "test/time_controller/simulated_time_controller.h"
Niels Möllercbcbc222018-09-28 07:07:2453#include "test/video_encoder_proxy_factory.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3154#include "video/send_statistics_proxy.h"
perkj26091b12016-09-01 08:17:4055
56namespace webrtc {
57
sprang57c2fff2017-01-16 14:24:0258using ::testing::_;
philipeld9cc8c02019-09-16 12:53:4059using ::testing::AllOf;
Per Kjellanderd0a8f512020-10-07 09:28:4160using ::testing::AtLeast;
Evan Shrubsole5cd7eb82020-05-25 12:08:3961using ::testing::Eq;
philipeld9cc8c02019-09-16 12:53:4062using ::testing::Field;
Evan Shrubsole5cd7eb82020-05-25 12:08:3963using ::testing::Ge;
64using ::testing::Gt;
65using ::testing::Le;
66using ::testing::Lt;
philipel9b058032020-02-10 10:30:0067using ::testing::Matcher;
68using ::testing::NiceMock;
69using ::testing::Return;
philipeld9cc8c02019-09-16 12:53:4070using ::testing::StrictMock;
kthelgason876222f2016-11-29 09:44:1171
perkj803d97f2016-11-01 18:45:4672namespace {
Åsa Persson8c1bf952018-09-13 08:42:1973const int kMinPixelsPerFrame = 320 * 180;
Åsa Perssone644a032019-11-08 14:56:0074const int kQpLow = 1;
75const int kQpHigh = 2;
Åsa Persson8c1bf952018-09-13 08:42:1976const int kMinFramerateFps = 2;
77const int kMinBalancedFramerateFps = 7;
78const int64_t kFrameTimeoutMs = 100;
asapersson5f7226f2016-11-25 12:37:0079const size_t kMaxPayloadLength = 1440;
Erik Språngd7329ca2019-02-21 20:19:5380const uint32_t kTargetBitrateBps = 1000000;
Sergey Silkin5ee69672019-07-02 12:18:3481const uint32_t kStartBitrateBps = 600000;
Erik Språngd7329ca2019-02-21 20:19:5382const uint32_t kSimulcastTargetBitrateBps = 3150000;
83const uint32_t kLowTargetBitrateBps = kTargetBitrateBps / 10;
kthelgason2bc68642017-02-07 15:02:2284const int kMaxInitialFramedrop = 4;
sprangfda496a2017-06-15 11:21:0785const int kDefaultFramerate = 30;
Åsa Persson8c1bf952018-09-13 08:42:1986const int64_t kFrameIntervalMs = rtc::kNumMillisecsPerSec / kDefaultFramerate;
Niels Möllerfe407b72019-09-10 08:48:4887const int64_t kProcessIntervalMs = 1000;
Sergey Silkin41c650b2019-10-14 11:12:1988const VideoEncoder::ResolutionBitrateLimits
89 kEncoderBitrateLimits540p(960 * 540, 100 * 1000, 100 * 1000, 2000 * 1000);
90const VideoEncoder::ResolutionBitrateLimits
91 kEncoderBitrateLimits720p(1280 * 720, 200 * 1000, 200 * 1000, 4000 * 1000);
asapersson5f7226f2016-11-25 12:37:0092
Mirta Dvornicic28f0eb22019-05-28 14:30:1693uint8_t optimal_sps[] = {0, 0, 0, 1, H264::NaluType::kSps,
94 0x00, 0x00, 0x03, 0x03, 0xF4,
95 0x05, 0x03, 0xC7, 0xE0, 0x1B,
96 0x41, 0x10, 0x8D, 0x00};
97
perkj803d97f2016-11-01 18:45:4698class TestBuffer : public webrtc::I420Buffer {
99 public:
100 TestBuffer(rtc::Event* event, int width, int height)
101 : I420Buffer(width, height), event_(event) {}
102
103 private:
104 friend class rtc::RefCountedObject<TestBuffer>;
105 ~TestBuffer() override {
106 if (event_)
107 event_->Set();
108 }
109 rtc::Event* const event_;
110};
111
Noah Richards51db4212019-06-12 13:59:12112// A fake native buffer that can't be converted to I420.
113class FakeNativeBuffer : public webrtc::VideoFrameBuffer {
114 public:
115 FakeNativeBuffer(rtc::Event* event, int width, int height)
116 : event_(event), width_(width), height_(height) {}
117 webrtc::VideoFrameBuffer::Type type() const override { return Type::kNative; }
118 int width() const override { return width_; }
119 int height() const override { return height_; }
120 rtc::scoped_refptr<webrtc::I420BufferInterface> ToI420() override {
121 return nullptr;
122 }
123
124 private:
125 friend class rtc::RefCountedObject<FakeNativeBuffer>;
126 ~FakeNativeBuffer() override {
127 if (event_)
128 event_->Set();
129 }
130 rtc::Event* const event_;
131 const int width_;
132 const int height_;
133};
134
Evan Shrubsole895556e2020-10-05 07:15:13135// A fake native buffer that is backed by an NV12 buffer.
136class FakeNV12NativeBuffer : public webrtc::VideoFrameBuffer {
137 public:
138 FakeNV12NativeBuffer(rtc::Event* event, int width, int height)
139 : nv12_buffer_(NV12Buffer::Create(width, height)), event_(event) {}
140
141 webrtc::VideoFrameBuffer::Type type() const override { return Type::kNative; }
142 int width() const override { return nv12_buffer_->width(); }
143 int height() const override { return nv12_buffer_->height(); }
144 rtc::scoped_refptr<webrtc::I420BufferInterface> ToI420() override {
145 return nv12_buffer_->ToI420();
146 }
Evan Shrubsoleb556b082020-10-08 12:56:45147 rtc::scoped_refptr<VideoFrameBuffer> GetMappedFrameBuffer(
148 rtc::ArrayView<VideoFrameBuffer::Type> types) override {
149 if (absl::c_find(types, Type::kNV12) != types.end()) {
150 return nv12_buffer_;
151 }
152 return nullptr;
153 }
Evan Shrubsole895556e2020-10-05 07:15:13154 const NV12BufferInterface* GetNV12() const { return nv12_buffer_; }
155
156 private:
157 friend class rtc::RefCountedObject<FakeNV12NativeBuffer>;
158 ~FakeNV12NativeBuffer() override {
159 if (event_)
160 event_->Set();
161 }
162 rtc::scoped_refptr<NV12Buffer> nv12_buffer_;
163 rtc::Event* const event_;
164};
165
Niels Möller7dc26b72017-12-06 09:27:48166class CpuOveruseDetectorProxy : public OveruseFrameDetector {
167 public:
Niels Möllerd1f7eb62018-03-28 14:40:58168 explicit CpuOveruseDetectorProxy(CpuOveruseMetricsObserver* metrics_observer)
169 : OveruseFrameDetector(metrics_observer),
Henrik Boström381d1092020-05-12 16:49:07170 last_target_framerate_fps_(-1),
171 framerate_updated_event_(true /* manual_reset */,
172 false /* initially_signaled */) {}
Niels Möller7dc26b72017-12-06 09:27:48173 virtual ~CpuOveruseDetectorProxy() {}
174
175 void OnTargetFramerateUpdated(int framerate_fps) override {
Markus Handella3765182020-07-08 11:13:32176 MutexLock lock(&lock_);
Niels Möller7dc26b72017-12-06 09:27:48177 last_target_framerate_fps_ = framerate_fps;
178 OveruseFrameDetector::OnTargetFramerateUpdated(framerate_fps);
Henrik Boström381d1092020-05-12 16:49:07179 framerate_updated_event_.Set();
Niels Möller7dc26b72017-12-06 09:27:48180 }
181
182 int GetLastTargetFramerate() {
Markus Handella3765182020-07-08 11:13:32183 MutexLock lock(&lock_);
Niels Möller7dc26b72017-12-06 09:27:48184 return last_target_framerate_fps_;
185 }
186
Niels Möller4db138e2018-04-19 07:04:13187 CpuOveruseOptions GetOptions() { return options_; }
188
Henrik Boström381d1092020-05-12 16:49:07189 rtc::Event* framerate_updated_event() { return &framerate_updated_event_; }
190
Niels Möller7dc26b72017-12-06 09:27:48191 private:
Markus Handella3765182020-07-08 11:13:32192 Mutex lock_;
Niels Möller7dc26b72017-12-06 09:27:48193 int last_target_framerate_fps_ RTC_GUARDED_BY(lock_);
Henrik Boström381d1092020-05-12 16:49:07194 rtc::Event framerate_updated_event_;
Niels Möller7dc26b72017-12-06 09:27:48195};
196
Henrik Boström0f0aa9c2020-06-02 11:02:36197class FakeVideoSourceRestrictionsListener
198 : public VideoSourceRestrictionsListener {
Henrik Boström381d1092020-05-12 16:49:07199 public:
Henrik Boström0f0aa9c2020-06-02 11:02:36200 FakeVideoSourceRestrictionsListener()
Henrik Boström381d1092020-05-12 16:49:07201 : was_restrictions_updated_(false), restrictions_updated_event_() {}
Henrik Boström0f0aa9c2020-06-02 11:02:36202 ~FakeVideoSourceRestrictionsListener() override {
Henrik Boström381d1092020-05-12 16:49:07203 RTC_DCHECK(was_restrictions_updated_);
204 }
205
206 rtc::Event* restrictions_updated_event() {
207 return &restrictions_updated_event_;
208 }
209
Henrik Boström0f0aa9c2020-06-02 11:02:36210 // VideoSourceRestrictionsListener implementation.
Henrik Boström381d1092020-05-12 16:49:07211 void OnVideoSourceRestrictionsUpdated(
212 VideoSourceRestrictions restrictions,
213 const VideoAdaptationCounters& adaptation_counters,
Evan Shrubsoleec0af262020-07-01 09:47:46214 rtc::scoped_refptr<Resource> reason,
215 const VideoSourceRestrictions& unfiltered_restrictions) override {
Henrik Boström381d1092020-05-12 16:49:07216 was_restrictions_updated_ = true;
217 restrictions_updated_event_.Set();
218 }
219
220 private:
221 bool was_restrictions_updated_;
222 rtc::Event restrictions_updated_event_;
223};
224
Evan Shrubsole5fd40602020-05-25 14:19:54225auto WantsFps(Matcher<int> fps_matcher) {
226 return Field("max_framerate_fps", &rtc::VideoSinkWants::max_framerate_fps,
227 fps_matcher);
228}
229
230auto WantsMaxPixels(Matcher<int> max_pixel_matcher) {
231 return Field("max_pixel_count", &rtc::VideoSinkWants::max_pixel_count,
232 AllOf(max_pixel_matcher, Gt(0)));
233}
234
Evan Shrubsole5cd7eb82020-05-25 12:08:39235auto ResolutionMax() {
236 return AllOf(
Evan Shrubsole5fd40602020-05-25 14:19:54237 WantsMaxPixels(Eq(std::numeric_limits<int>::max())),
Evan Shrubsole5cd7eb82020-05-25 12:08:39238 Field("target_pixel_count", &rtc::VideoSinkWants::target_pixel_count,
239 Eq(absl::nullopt)));
240}
241
242auto FpsMax() {
Evan Shrubsole5fd40602020-05-25 14:19:54243 return WantsFps(Eq(kDefaultFramerate));
Evan Shrubsole5cd7eb82020-05-25 12:08:39244}
245
246auto FpsUnlimited() {
Evan Shrubsole5fd40602020-05-25 14:19:54247 return WantsFps(Eq(std::numeric_limits<int>::max()));
Evan Shrubsole5cd7eb82020-05-25 12:08:39248}
249
250auto FpsMatchesResolutionMax(Matcher<int> fps_matcher) {
Evan Shrubsole5fd40602020-05-25 14:19:54251 return AllOf(WantsFps(fps_matcher), ResolutionMax());
Evan Shrubsole5cd7eb82020-05-25 12:08:39252}
253
254auto FpsMaxResolutionMatches(Matcher<int> pixel_matcher) {
Evan Shrubsole5fd40602020-05-25 14:19:54255 return AllOf(FpsMax(), WantsMaxPixels(pixel_matcher));
Evan Shrubsole5cd7eb82020-05-25 12:08:39256}
257
258auto FpsMaxResolutionMax() {
259 return AllOf(FpsMax(), ResolutionMax());
260}
261
262auto UnlimitedSinkWants() {
263 return AllOf(FpsUnlimited(), ResolutionMax());
264}
265
266auto FpsInRangeForPixelsInBalanced(int last_frame_pixels) {
267 Matcher<int> fps_range_matcher;
268
269 if (last_frame_pixels <= 320 * 240) {
270 fps_range_matcher = AllOf(Ge(7), Le(10));
Åsa Perssonc5a74ff2020-09-20 15:50:00271 } else if (last_frame_pixels <= 480 * 360) {
Evan Shrubsole5cd7eb82020-05-25 12:08:39272 fps_range_matcher = AllOf(Ge(10), Le(15));
273 } else if (last_frame_pixels <= 640 * 480) {
274 fps_range_matcher = Ge(15);
275 } else {
276 fps_range_matcher = Eq(kDefaultFramerate);
277 }
278 return Field("max_framerate_fps", &rtc::VideoSinkWants::max_framerate_fps,
279 fps_range_matcher);
280}
281
Evan Shrubsole5fd40602020-05-25 14:19:54282auto FpsEqResolutionEqTo(const rtc::VideoSinkWants& other_wants) {
283 return AllOf(WantsFps(Eq(other_wants.max_framerate_fps)),
284 WantsMaxPixels(Eq(other_wants.max_pixel_count)));
285}
286
287auto FpsMaxResolutionLt(const rtc::VideoSinkWants& other_wants) {
288 return AllOf(FpsMax(), WantsMaxPixels(Lt(other_wants.max_pixel_count)));
289}
290
291auto FpsMaxResolutionGt(const rtc::VideoSinkWants& other_wants) {
292 return AllOf(FpsMax(), WantsMaxPixels(Gt(other_wants.max_pixel_count)));
293}
294
295auto FpsLtResolutionEq(const rtc::VideoSinkWants& other_wants) {
296 return AllOf(WantsFps(Lt(other_wants.max_framerate_fps)),
297 WantsMaxPixels(Eq(other_wants.max_pixel_count)));
298}
299
300auto FpsGtResolutionEq(const rtc::VideoSinkWants& other_wants) {
301 return AllOf(WantsFps(Gt(other_wants.max_framerate_fps)),
302 WantsMaxPixels(Eq(other_wants.max_pixel_count)));
303}
304
305auto FpsEqResolutionLt(const rtc::VideoSinkWants& other_wants) {
306 return AllOf(WantsFps(Eq(other_wants.max_framerate_fps)),
307 WantsMaxPixels(Lt(other_wants.max_pixel_count)));
308}
309
310auto FpsEqResolutionGt(const rtc::VideoSinkWants& other_wants) {
311 return AllOf(WantsFps(Eq(other_wants.max_framerate_fps)),
312 WantsMaxPixels(Gt(other_wants.max_pixel_count)));
313}
314
mflodmancc3d4422017-08-03 15:27:51315class VideoStreamEncoderUnderTest : public VideoStreamEncoder {
perkj803d97f2016-11-01 18:45:46316 public:
Tomas Gunnarsson612445e2020-09-21 12:31:23317 VideoStreamEncoderUnderTest(TimeController* time_controller,
318 TaskQueueFactory* task_queue_factory,
319 SendStatisticsProxy* stats_proxy,
320 const VideoStreamEncoderSettings& settings)
321 : VideoStreamEncoder(time_controller->GetClock(),
Sebastian Jansson572c60f2019-03-04 17:30:41322 1 /* number_of_cores */,
Yves Gerey665174f2018-06-19 13:03:05323 stats_proxy,
324 settings,
Yves Gerey665174f2018-06-19 13:03:05325 std::unique_ptr<OveruseFrameDetector>(
326 overuse_detector_proxy_ =
Sebastian Jansson74682c12019-03-01 10:50:20327 new CpuOveruseDetectorProxy(stats_proxy)),
Evan Shrubsoleaa6fbc12020-02-25 15:26:01328 task_queue_factory),
Tomas Gunnarsson612445e2020-09-21 12:31:23329 time_controller_(time_controller),
Henrik Boström5cc28b02020-06-01 15:59:05330 fake_cpu_resource_(FakeResource::Create("FakeResource[CPU]")),
Henrik Boström0f0aa9c2020-06-02 11:02:36331 fake_quality_resource_(FakeResource::Create("FakeResource[QP]")),
Evan Shrubsoledc4d4222020-07-09 09:47:10332 fake_adaptation_constraint_("FakeAdaptationConstraint") {
Henrik Boströmc55516d2020-05-11 14:29:22333 InjectAdaptationResource(fake_quality_resource_,
Evan Shrubsolece0a11d2020-04-16 09:36:55334 VideoAdaptationReason::kQuality);
Henrik Boströmc55516d2020-05-11 14:29:22335 InjectAdaptationResource(fake_cpu_resource_, VideoAdaptationReason::kCpu);
Henrik Boström0f0aa9c2020-06-02 11:02:36336 InjectAdaptationConstraint(&fake_adaptation_constraint_);
Evan Shrubsoleaa6fbc12020-02-25 15:26:01337 }
perkj803d97f2016-11-01 18:45:46338
Henrik Boström381d1092020-05-12 16:49:07339 void SetSourceAndWaitForRestrictionsUpdated(
340 rtc::VideoSourceInterface<VideoFrame>* source,
341 const DegradationPreference& degradation_preference) {
Henrik Boström0f0aa9c2020-06-02 11:02:36342 FakeVideoSourceRestrictionsListener listener;
343 AddRestrictionsListenerForTesting(&listener);
Henrik Boström381d1092020-05-12 16:49:07344 SetSource(source, degradation_preference);
345 listener.restrictions_updated_event()->Wait(5000);
Henrik Boström0f0aa9c2020-06-02 11:02:36346 RemoveRestrictionsListenerForTesting(&listener);
Henrik Boström381d1092020-05-12 16:49:07347 }
348
349 void SetSourceAndWaitForFramerateUpdated(
350 rtc::VideoSourceInterface<VideoFrame>* source,
351 const DegradationPreference& degradation_preference) {
352 overuse_detector_proxy_->framerate_updated_event()->Reset();
353 SetSource(source, degradation_preference);
354 overuse_detector_proxy_->framerate_updated_event()->Wait(5000);
355 }
356
357 void OnBitrateUpdatedAndWaitForManagedResources(
358 DataRate target_bitrate,
359 DataRate stable_target_bitrate,
360 DataRate link_allocation,
361 uint8_t fraction_lost,
362 int64_t round_trip_time_ms,
363 double cwnd_reduce_ratio) {
364 OnBitrateUpdated(target_bitrate, stable_target_bitrate, link_allocation,
365 fraction_lost, round_trip_time_ms, cwnd_reduce_ratio);
366 // Bitrate is updated on the encoder queue.
367 WaitUntilTaskQueueIsIdle();
Henrik Boström381d1092020-05-12 16:49:07368 }
369
kthelgason2fc52542017-03-03 08:24:41370 // This is used as a synchronisation mechanism, to make sure that the
371 // encoder queue is not blocked before we start sending it frames.
372 void WaitUntilTaskQueueIsIdle() {
Niels Möllerc572ff32018-11-07 07:43:50373 rtc::Event event;
Yves Gerey665174f2018-06-19 13:03:05374 encoder_queue()->PostTask([&event] { event.Set(); });
kthelgason2fc52542017-03-03 08:24:41375 ASSERT_TRUE(event.Wait(5000));
376 }
377
Henrik Boström91aa7322020-04-28 10:24:33378 // Triggers resource usage measurements on the fake CPU resource.
Åsa Perssonb67c44c2019-09-24 13:25:32379 void TriggerCpuOveruse() {
Henrik Boström91aa7322020-04-28 10:24:33380 rtc::Event event;
Evan Shrubsole85728412020-08-25 11:12:12381 encoder_queue()->PostTask([this, &event] {
Henrik Boström0f0aa9c2020-06-02 11:02:36382 fake_cpu_resource_->SetUsageState(ResourceUsageState::kOveruse);
Henrik Boström91aa7322020-04-28 10:24:33383 event.Set();
384 });
385 ASSERT_TRUE(event.Wait(5000));
Tomas Gunnarsson612445e2020-09-21 12:31:23386 time_controller_->AdvanceTime(TimeDelta::Millis(0));
Henrik Boström91aa7322020-04-28 10:24:33387 }
Tomas Gunnarsson612445e2020-09-21 12:31:23388
Henrik Boström91aa7322020-04-28 10:24:33389 void TriggerCpuUnderuse() {
390 rtc::Event event;
Evan Shrubsole85728412020-08-25 11:12:12391 encoder_queue()->PostTask([this, &event] {
Henrik Boström0f0aa9c2020-06-02 11:02:36392 fake_cpu_resource_->SetUsageState(ResourceUsageState::kUnderuse);
Henrik Boström91aa7322020-04-28 10:24:33393 event.Set();
394 });
395 ASSERT_TRUE(event.Wait(5000));
Tomas Gunnarsson612445e2020-09-21 12:31:23396 time_controller_->AdvanceTime(TimeDelta::Millis(0));
Åsa Perssonb67c44c2019-09-24 13:25:32397 }
kthelgason876222f2016-11-29 09:44:11398
Henrik Boström91aa7322020-04-28 10:24:33399 // Triggers resource usage measurements on the fake quality resource.
Åsa Perssonb67c44c2019-09-24 13:25:32400 void TriggerQualityLow() {
Henrik Boström91aa7322020-04-28 10:24:33401 rtc::Event event;
Evan Shrubsole85728412020-08-25 11:12:12402 encoder_queue()->PostTask([this, &event] {
Henrik Boström0f0aa9c2020-06-02 11:02:36403 fake_quality_resource_->SetUsageState(ResourceUsageState::kOveruse);
Henrik Boström91aa7322020-04-28 10:24:33404 event.Set();
405 });
406 ASSERT_TRUE(event.Wait(5000));
Tomas Gunnarsson612445e2020-09-21 12:31:23407 time_controller_->AdvanceTime(TimeDelta::Millis(0));
Åsa Perssonb67c44c2019-09-24 13:25:32408 }
Åsa Perssonb67c44c2019-09-24 13:25:32409 void TriggerQualityHigh() {
Henrik Boström91aa7322020-04-28 10:24:33410 rtc::Event event;
Evan Shrubsole85728412020-08-25 11:12:12411 encoder_queue()->PostTask([this, &event] {
Henrik Boström0f0aa9c2020-06-02 11:02:36412 fake_quality_resource_->SetUsageState(ResourceUsageState::kUnderuse);
Henrik Boström91aa7322020-04-28 10:24:33413 event.Set();
414 });
415 ASSERT_TRUE(event.Wait(5000));
Tomas Gunnarsson612445e2020-09-21 12:31:23416 time_controller_->AdvanceTime(TimeDelta::Millis(0));
Henrik Boström91aa7322020-04-28 10:24:33417 }
418
Tomas Gunnarsson612445e2020-09-21 12:31:23419 TimeController* const time_controller_;
Niels Möller7dc26b72017-12-06 09:27:48420 CpuOveruseDetectorProxy* overuse_detector_proxy_;
Henrik Boströmc55516d2020-05-11 14:29:22421 rtc::scoped_refptr<FakeResource> fake_cpu_resource_;
422 rtc::scoped_refptr<FakeResource> fake_quality_resource_;
Henrik Boström0f0aa9c2020-06-02 11:02:36423 FakeAdaptationConstraint fake_adaptation_constraint_;
perkj803d97f2016-11-01 18:45:46424};
425
Noah Richards51db4212019-06-12 13:59:12426// Simulates simulcast behavior and makes highest stream resolutions divisible
427// by 4.
428class CroppingVideoStreamFactory
429 : public VideoEncoderConfig::VideoStreamFactoryInterface {
430 public:
Åsa Persson17b29b92020-10-17 10:57:58431 CroppingVideoStreamFactory() {}
Noah Richards51db4212019-06-12 13:59:12432
433 private:
434 std::vector<VideoStream> CreateEncoderStreams(
435 int width,
436 int height,
437 const VideoEncoderConfig& encoder_config) override {
438 std::vector<VideoStream> streams = test::CreateVideoStreams(
439 width - width % 4, height - height % 4, encoder_config);
Noah Richards51db4212019-06-12 13:59:12440 return streams;
441 }
Noah Richards51db4212019-06-12 13:59:12442};
443
sprangb1ca0732017-02-01 16:38:12444class AdaptingFrameForwarder : public test::FrameForwarder {
445 public:
Tomas Gunnarsson612445e2020-09-21 12:31:23446 explicit AdaptingFrameForwarder(TimeController* time_controller)
447 : time_controller_(time_controller), adaptation_enabled_(false) {}
asaperssonfab67072017-04-04 12:51:49448 ~AdaptingFrameForwarder() override {}
sprangb1ca0732017-02-01 16:38:12449
450 void set_adaptation_enabled(bool enabled) {
Markus Handella3765182020-07-08 11:13:32451 MutexLock lock(&mutex_);
sprangb1ca0732017-02-01 16:38:12452 adaptation_enabled_ = enabled;
453 }
454
asaperssonfab67072017-04-04 12:51:49455 bool adaption_enabled() const {
Markus Handella3765182020-07-08 11:13:32456 MutexLock lock(&mutex_);
sprangb1ca0732017-02-01 16:38:12457 return adaptation_enabled_;
458 }
459
asapersson09f05612017-05-16 06:40:18460 rtc::VideoSinkWants last_wants() const {
Markus Handella3765182020-07-08 11:13:32461 MutexLock lock(&mutex_);
asapersson09f05612017-05-16 06:40:18462 return last_wants_;
463 }
464
Danil Chapovalovb9b146c2018-06-15 10:28:07465 absl::optional<int> last_sent_width() const { return last_width_; }
466 absl::optional<int> last_sent_height() const { return last_height_; }
Jonathan Yubc771b72017-12-09 01:04:29467
sprangb1ca0732017-02-01 16:38:12468 void IncomingCapturedFrame(const VideoFrame& video_frame) override {
Tomas Gunnarsson612445e2020-09-21 12:31:23469 RTC_DCHECK(time_controller_->GetMainThread()->IsCurrent());
470 time_controller_->AdvanceTime(TimeDelta::Millis(0));
471
sprangb1ca0732017-02-01 16:38:12472 int cropped_width = 0;
473 int cropped_height = 0;
474 int out_width = 0;
475 int out_height = 0;
sprangc5d62e22017-04-03 06:53:04476 if (adaption_enabled()) {
Tomas Gunnarsson612445e2020-09-21 12:31:23477 RTC_DLOG(INFO) << "IncomingCapturedFrame: AdaptFrameResolution()"
478 << "w=" << video_frame.width()
479 << "h=" << video_frame.height();
sprangc5d62e22017-04-03 06:53:04480 if (adapter_.AdaptFrameResolution(
481 video_frame.width(), video_frame.height(),
482 video_frame.timestamp_us() * 1000, &cropped_width,
483 &cropped_height, &out_width, &out_height)) {
Artem Titov1ebfb6a2019-01-03 22:49:37484 VideoFrame adapted_frame =
485 VideoFrame::Builder()
486 .set_video_frame_buffer(new rtc::RefCountedObject<TestBuffer>(
487 nullptr, out_width, out_height))
488 .set_timestamp_rtp(99)
489 .set_timestamp_ms(99)
490 .set_rotation(kVideoRotation_0)
491 .build();
sprangc5d62e22017-04-03 06:53:04492 adapted_frame.set_ntp_time_ms(video_frame.ntp_time_ms());
Ilya Nikolaevskiy648b9d72019-12-03 15:54:17493 if (video_frame.has_update_rect()) {
494 adapted_frame.set_update_rect(
495 video_frame.update_rect().ScaleWithFrame(
496 video_frame.width(), video_frame.height(), 0, 0,
497 video_frame.width(), video_frame.height(), out_width,
498 out_height));
499 }
sprangc5d62e22017-04-03 06:53:04500 test::FrameForwarder::IncomingCapturedFrame(adapted_frame);
Jonathan Yubc771b72017-12-09 01:04:29501 last_width_.emplace(adapted_frame.width());
502 last_height_.emplace(adapted_frame.height());
503 } else {
Danil Chapovalovb9b146c2018-06-15 10:28:07504 last_width_ = absl::nullopt;
505 last_height_ = absl::nullopt;
sprangc5d62e22017-04-03 06:53:04506 }
sprangb1ca0732017-02-01 16:38:12507 } else {
Tomas Gunnarsson612445e2020-09-21 12:31:23508 RTC_DLOG(INFO) << "IncomingCapturedFrame: adaptation not enabled";
sprangb1ca0732017-02-01 16:38:12509 test::FrameForwarder::IncomingCapturedFrame(video_frame);
Jonathan Yubc771b72017-12-09 01:04:29510 last_width_.emplace(video_frame.width());
511 last_height_.emplace(video_frame.height());
sprangb1ca0732017-02-01 16:38:12512 }
513 }
514
515 void AddOrUpdateSink(rtc::VideoSinkInterface<VideoFrame>* sink,
516 const rtc::VideoSinkWants& wants) override {
Markus Handella3765182020-07-08 11:13:32517 MutexLock lock(&mutex_);
Markus Handell16038ab2020-05-28 06:37:30518 last_wants_ = sink_wants_locked();
Rasmus Brandt287e4642019-11-15 15:56:01519 adapter_.OnSinkWants(wants);
Markus Handell16038ab2020-05-28 06:37:30520 test::FrameForwarder::AddOrUpdateSinkLocked(sink, wants);
sprangb1ca0732017-02-01 16:38:12521 }
Tomas Gunnarsson612445e2020-09-21 12:31:23522
523 TimeController* const time_controller_;
sprangb1ca0732017-02-01 16:38:12524 cricket::VideoAdapter adapter_;
Markus Handella3765182020-07-08 11:13:32525 bool adaptation_enabled_ RTC_GUARDED_BY(mutex_);
526 rtc::VideoSinkWants last_wants_ RTC_GUARDED_BY(mutex_);
Danil Chapovalovb9b146c2018-06-15 10:28:07527 absl::optional<int> last_width_;
528 absl::optional<int> last_height_;
sprangb1ca0732017-02-01 16:38:12529};
sprangc5d62e22017-04-03 06:53:04530
Niels Möller213618e2018-07-24 07:29:58531// TODO(nisse): Mock only VideoStreamEncoderObserver.
sprangc5d62e22017-04-03 06:53:04532class MockableSendStatisticsProxy : public SendStatisticsProxy {
533 public:
534 MockableSendStatisticsProxy(Clock* clock,
535 const VideoSendStream::Config& config,
536 VideoEncoderConfig::ContentType content_type)
537 : SendStatisticsProxy(clock, config, content_type) {}
538
539 VideoSendStream::Stats GetStats() override {
Markus Handella3765182020-07-08 11:13:32540 MutexLock lock(&lock_);
sprangc5d62e22017-04-03 06:53:04541 if (mock_stats_)
542 return *mock_stats_;
543 return SendStatisticsProxy::GetStats();
544 }
545
Niels Möller213618e2018-07-24 07:29:58546 int GetInputFrameRate() const override {
Markus Handella3765182020-07-08 11:13:32547 MutexLock lock(&lock_);
Niels Möller213618e2018-07-24 07:29:58548 if (mock_stats_)
549 return mock_stats_->input_frame_rate;
550 return SendStatisticsProxy::GetInputFrameRate();
551 }
sprangc5d62e22017-04-03 06:53:04552 void SetMockStats(const VideoSendStream::Stats& stats) {
Markus Handella3765182020-07-08 11:13:32553 MutexLock lock(&lock_);
sprangc5d62e22017-04-03 06:53:04554 mock_stats_.emplace(stats);
555 }
556
557 void ResetMockStats() {
Markus Handella3765182020-07-08 11:13:32558 MutexLock lock(&lock_);
sprangc5d62e22017-04-03 06:53:04559 mock_stats_.reset();
560 }
561
Tomas Gunnarsson612445e2020-09-21 12:31:23562 void SetDroppedFrameCallback(std::function<void(DropReason)> callback) {
563 on_frame_dropped_ = std::move(callback);
564 }
565
sprangc5d62e22017-04-03 06:53:04566 private:
Tomas Gunnarsson612445e2020-09-21 12:31:23567 void OnFrameDropped(DropReason reason) override {
568 SendStatisticsProxy::OnFrameDropped(reason);
569 if (on_frame_dropped_)
570 on_frame_dropped_(reason);
571 }
572
Markus Handella3765182020-07-08 11:13:32573 mutable Mutex lock_;
Danil Chapovalovb9b146c2018-06-15 10:28:07574 absl::optional<VideoSendStream::Stats> mock_stats_ RTC_GUARDED_BY(lock_);
Tomas Gunnarsson612445e2020-09-21 12:31:23575 std::function<void(DropReason)> on_frame_dropped_;
sprangc5d62e22017-04-03 06:53:04576};
577
philipel9b058032020-02-10 10:30:00578class MockEncoderSelector
579 : public VideoEncoderFactory::EncoderSelectorInterface {
580 public:
Danil Chapovalov91fdc602020-05-14 17:17:51581 MOCK_METHOD(void,
582 OnCurrentEncoder,
583 (const SdpVideoFormat& format),
584 (override));
585 MOCK_METHOD(absl::optional<SdpVideoFormat>,
586 OnAvailableBitrate,
587 (const DataRate& rate),
588 (override));
589 MOCK_METHOD(absl::optional<SdpVideoFormat>, OnEncoderBroken, (), (override));
philipel9b058032020-02-10 10:30:00590};
591
perkj803d97f2016-11-01 18:45:46592} // namespace
593
mflodmancc3d4422017-08-03 15:27:51594class VideoStreamEncoderTest : public ::testing::Test {
perkj26091b12016-09-01 08:17:40595 public:
Tomas Gunnarsson612445e2020-09-21 12:31:23596 static const int kDefaultTimeoutMs = 1000;
perkj26091b12016-09-01 08:17:40597
mflodmancc3d4422017-08-03 15:27:51598 VideoStreamEncoderTest()
perkj26091b12016-09-01 08:17:40599 : video_send_config_(VideoSendStream::Config(nullptr)),
perkjfa10b552016-10-03 06:45:26600 codec_width_(320),
601 codec_height_(240),
Åsa Persson8c1bf952018-09-13 08:42:19602 max_framerate_(kDefaultFramerate),
Tomas Gunnarsson612445e2020-09-21 12:31:23603 fake_encoder_(&time_controller_),
Niels Möller4db138e2018-04-19 07:04:13604 encoder_factory_(&fake_encoder_),
sprangc5d62e22017-04-03 06:53:04605 stats_proxy_(new MockableSendStatisticsProxy(
Tomas Gunnarsson612445e2020-09-21 12:31:23606 time_controller_.GetClock(),
perkj803d97f2016-11-01 18:45:46607 video_send_config_,
608 webrtc::VideoEncoderConfig::ContentType::kRealtimeVideo)),
Tomas Gunnarsson612445e2020-09-21 12:31:23609 sink_(&time_controller_, &fake_encoder_) {}
perkj26091b12016-09-01 08:17:40610
611 void SetUp() override {
perkj803d97f2016-11-01 18:45:46612 metrics::Reset();
perkj26091b12016-09-01 08:17:40613 video_send_config_ = VideoSendStream::Config(nullptr);
Niels Möller4db138e2018-04-19 07:04:13614 video_send_config_.encoder_settings.encoder_factory = &encoder_factory_;
Jiawei Ouc2ebe212018-11-08 18:02:56615 video_send_config_.encoder_settings.bitrate_allocator_factory =
Sergey Silkin5ee69672019-07-02 12:18:34616 &bitrate_allocator_factory_;
Niels Möller259a4972018-04-05 13:36:51617 video_send_config_.rtp.payload_name = "FAKE";
618 video_send_config_.rtp.payload_type = 125;
perkj26091b12016-09-01 08:17:40619
Per512ecb32016-09-23 13:52:06620 VideoEncoderConfig video_encoder_config;
Niels Möller259a4972018-04-05 13:36:51621 test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
Åsa Persson17107062020-10-08 06:57:51622 EXPECT_EQ(1u, video_encoder_config.simulcast_layers.size());
623 video_encoder_config.simulcast_layers[0].num_temporal_layers = 1;
624 video_encoder_config.simulcast_layers[0].max_framerate = max_framerate_;
Erik Språng08127a92016-11-16 15:41:30625 video_encoder_config_ = video_encoder_config.Copy();
sprang4847ae62017-06-27 14:06:52626
Niels Möllerf1338562018-04-26 07:51:47627 ConfigureEncoder(std::move(video_encoder_config));
asapersson5f7226f2016-11-25 12:37:00628 }
629
Niels Möllerf1338562018-04-26 07:51:47630 void ConfigureEncoder(VideoEncoderConfig video_encoder_config) {
mflodmancc3d4422017-08-03 15:27:51631 if (video_stream_encoder_)
632 video_stream_encoder_->Stop();
633 video_stream_encoder_.reset(new VideoStreamEncoderUnderTest(
Tomas Gunnarsson612445e2020-09-21 12:31:23634 &time_controller_, GetTaskQueueFactory(), stats_proxy_.get(),
635 video_send_config_.encoder_settings));
mflodmancc3d4422017-08-03 15:27:51636 video_stream_encoder_->SetSink(&sink_, false /* rotation_applied */);
637 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 21:20:41638 &video_source_, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
mflodmancc3d4422017-08-03 15:27:51639 video_stream_encoder_->SetStartBitrate(kTargetBitrateBps);
640 video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config),
Niels Möllerf1338562018-04-26 07:51:47641 kMaxPayloadLength);
mflodmancc3d4422017-08-03 15:27:51642 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
asapersson5f7226f2016-11-25 12:37:00643 }
644
Per Kjellanderdcef6412020-10-07 13:09:05645 void ResetEncoder(
646 const std::string& payload_name,
647 size_t num_streams,
648 size_t num_temporal_layers,
649 unsigned char num_spatial_layers,
650 bool screenshare,
651 VideoStreamEncoderSettings::BitrateAllocationCallbackType
652 allocation_cb_type =
653 VideoStreamEncoderSettings::BitrateAllocationCallbackType::
654 kVideoBitrateAllocationWhenScreenSharing) {
Niels Möller259a4972018-04-05 13:36:51655 video_send_config_.rtp.payload_name = payload_name;
Per Kjellanderdcef6412020-10-07 13:09:05656 video_send_config_.encoder_settings.allocation_cb_type = allocation_cb_type;
asapersson5f7226f2016-11-25 12:37:00657
658 VideoEncoderConfig video_encoder_config;
Åsa Persson17107062020-10-08 06:57:51659 test::FillEncoderConfiguration(PayloadStringToCodecType(payload_name),
660 num_streams, &video_encoder_config);
661 for (auto& layer : video_encoder_config.simulcast_layers) {
662 layer.num_temporal_layers = num_temporal_layers;
663 layer.max_framerate = kDefaultFramerate;
664 }
Erik Språngd7329ca2019-02-21 20:19:53665 video_encoder_config.max_bitrate_bps =
666 num_streams == 1 ? kTargetBitrateBps : kSimulcastTargetBitrateBps;
sprang4847ae62017-06-27 14:06:52667 video_encoder_config.content_type =
668 screenshare ? VideoEncoderConfig::ContentType::kScreen
669 : VideoEncoderConfig::ContentType::kRealtimeVideo;
emircanbbcc3562017-08-18 07:28:40670 if (payload_name == "VP9") {
671 VideoCodecVP9 vp9_settings = VideoEncoder::GetDefaultVp9Settings();
672 vp9_settings.numberOfSpatialLayers = num_spatial_layers;
Mirta Dvornicic97910da2020-07-14 13:29:23673 vp9_settings.automaticResizeOn = num_spatial_layers <= 1;
emircanbbcc3562017-08-18 07:28:40674 video_encoder_config.encoder_specific_settings =
675 new rtc::RefCountedObject<
676 VideoEncoderConfig::Vp9EncoderSpecificSettings>(vp9_settings);
677 }
Niels Möllerf1338562018-04-26 07:51:47678 ConfigureEncoder(std::move(video_encoder_config));
perkj26091b12016-09-01 08:17:40679 }
680
sprang57c2fff2017-01-16 14:24:02681 VideoFrame CreateFrame(int64_t ntp_time_ms,
682 rtc::Event* destruction_event) const {
Artem Titov1ebfb6a2019-01-03 22:49:37683 VideoFrame frame =
684 VideoFrame::Builder()
685 .set_video_frame_buffer(new rtc::RefCountedObject<TestBuffer>(
686 destruction_event, codec_width_, codec_height_))
687 .set_timestamp_rtp(99)
688 .set_timestamp_ms(99)
689 .set_rotation(kVideoRotation_0)
690 .build();
sprang57c2fff2017-01-16 14:24:02691 frame.set_ntp_time_ms(ntp_time_ms);
perkj26091b12016-09-01 08:17:40692 return frame;
693 }
694
Ilya Nikolaevskiy71aee3a2019-02-18 12:01:26695 VideoFrame CreateFrameWithUpdatedPixel(int64_t ntp_time_ms,
696 rtc::Event* destruction_event,
697 int offset_x) const {
698 VideoFrame frame =
699 VideoFrame::Builder()
700 .set_video_frame_buffer(new rtc::RefCountedObject<TestBuffer>(
701 destruction_event, codec_width_, codec_height_))
702 .set_timestamp_rtp(99)
703 .set_timestamp_ms(99)
704 .set_rotation(kVideoRotation_0)
Artem Titov5256d8b2019-12-02 09:34:12705 .set_update_rect(VideoFrame::UpdateRect{offset_x, 0, 1, 1})
Ilya Nikolaevskiy71aee3a2019-02-18 12:01:26706 .build();
707 frame.set_ntp_time_ms(ntp_time_ms);
708 return frame;
709 }
710
sprang57c2fff2017-01-16 14:24:02711 VideoFrame CreateFrame(int64_t ntp_time_ms, int width, int height) const {
Artem Titov1ebfb6a2019-01-03 22:49:37712 VideoFrame frame =
713 VideoFrame::Builder()
714 .set_video_frame_buffer(
715 new rtc::RefCountedObject<TestBuffer>(nullptr, width, height))
716 .set_timestamp_rtp(99)
717 .set_timestamp_ms(99)
718 .set_rotation(kVideoRotation_0)
719 .build();
sprang57c2fff2017-01-16 14:24:02720 frame.set_ntp_time_ms(ntp_time_ms);
sprangc5d62e22017-04-03 06:53:04721 frame.set_timestamp_us(ntp_time_ms * 1000);
perkj803d97f2016-11-01 18:45:46722 return frame;
723 }
724
Evan Shrubsole895556e2020-10-05 07:15:13725 VideoFrame CreateNV12Frame(int64_t ntp_time_ms, int width, int height) const {
726 VideoFrame frame =
727 VideoFrame::Builder()
728 .set_video_frame_buffer(NV12Buffer::Create(width, height))
729 .set_timestamp_rtp(99)
730 .set_timestamp_ms(99)
731 .set_rotation(kVideoRotation_0)
732 .build();
733 frame.set_ntp_time_ms(ntp_time_ms);
734 frame.set_timestamp_us(ntp_time_ms * 1000);
735 return frame;
736 }
737
Noah Richards51db4212019-06-12 13:59:12738 VideoFrame CreateFakeNativeFrame(int64_t ntp_time_ms,
739 rtc::Event* destruction_event,
740 int width,
741 int height) const {
742 VideoFrame frame =
743 VideoFrame::Builder()
744 .set_video_frame_buffer(new rtc::RefCountedObject<FakeNativeBuffer>(
745 destruction_event, width, height))
746 .set_timestamp_rtp(99)
747 .set_timestamp_ms(99)
748 .set_rotation(kVideoRotation_0)
749 .build();
750 frame.set_ntp_time_ms(ntp_time_ms);
751 return frame;
752 }
753
Evan Shrubsole895556e2020-10-05 07:15:13754 VideoFrame CreateFakeNV12NativeFrame(int64_t ntp_time_ms,
755 rtc::Event* destruction_event,
756 int width,
757 int height) const {
758 VideoFrame frame = VideoFrame::Builder()
759 .set_video_frame_buffer(
760 new rtc::RefCountedObject<FakeNV12NativeBuffer>(
761 destruction_event, width, height))
762 .set_timestamp_rtp(99)
763 .set_timestamp_ms(99)
764 .set_rotation(kVideoRotation_0)
765 .build();
766 frame.set_ntp_time_ms(ntp_time_ms);
767 return frame;
768 }
769
Noah Richards51db4212019-06-12 13:59:12770 VideoFrame CreateFakeNativeFrame(int64_t ntp_time_ms,
771 rtc::Event* destruction_event) const {
772 return CreateFakeNativeFrame(ntp_time_ms, destruction_event, codec_width_,
773 codec_height_);
774 }
775
Åsa Perssonc29cb2c2019-03-25 11:06:59776 void VerifyAllocatedBitrate(const VideoBitrateAllocation& expected_bitrate) {
Henrik Boström381d1092020-05-12 16:49:07777 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:07778 DataRate::BitsPerSec(kTargetBitrateBps),
779 DataRate::BitsPerSec(kTargetBitrateBps),
780 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Åsa Perssonc29cb2c2019-03-25 11:06:59781
782 video_source_.IncomingCapturedFrame(
783 CreateFrame(1, codec_width_, codec_height_));
784 WaitForEncodedFrame(1);
Per Kjellanderdcef6412020-10-07 13:09:05785 EXPECT_EQ(expected_bitrate, sink_.GetLastVideoBitrateAllocation());
Åsa Perssonc29cb2c2019-03-25 11:06:59786 }
787
sprang4847ae62017-06-27 14:06:52788 void WaitForEncodedFrame(int64_t expected_ntp_time) {
789 sink_.WaitForEncodedFrame(expected_ntp_time);
Tomas Gunnarsson612445e2020-09-21 12:31:23790 AdvanceTime(TimeDelta::Seconds(1) / max_framerate_);
sprang4847ae62017-06-27 14:06:52791 }
792
793 bool TimedWaitForEncodedFrame(int64_t expected_ntp_time, int64_t timeout_ms) {
794 bool ok = sink_.TimedWaitForEncodedFrame(expected_ntp_time, timeout_ms);
Tomas Gunnarsson612445e2020-09-21 12:31:23795 AdvanceTime(TimeDelta::Seconds(1) / max_framerate_);
sprang4847ae62017-06-27 14:06:52796 return ok;
797 }
798
799 void WaitForEncodedFrame(uint32_t expected_width, uint32_t expected_height) {
800 sink_.WaitForEncodedFrame(expected_width, expected_height);
Tomas Gunnarsson612445e2020-09-21 12:31:23801 AdvanceTime(TimeDelta::Seconds(1) / max_framerate_);
sprang4847ae62017-06-27 14:06:52802 }
803
804 void ExpectDroppedFrame() {
805 sink_.ExpectDroppedFrame();
Tomas Gunnarsson612445e2020-09-21 12:31:23806 AdvanceTime(TimeDelta::Seconds(1) / max_framerate_);
sprang4847ae62017-06-27 14:06:52807 }
808
809 bool WaitForFrame(int64_t timeout_ms) {
810 bool ok = sink_.WaitForFrame(timeout_ms);
Tomas Gunnarsson612445e2020-09-21 12:31:23811 AdvanceTime(TimeDelta::Seconds(1) / max_framerate_);
sprang4847ae62017-06-27 14:06:52812 return ok;
813 }
814
perkj26091b12016-09-01 08:17:40815 class TestEncoder : public test::FakeEncoder {
816 public:
Tomas Gunnarsson612445e2020-09-21 12:31:23817 explicit TestEncoder(TimeController* time_controller)
818 : FakeEncoder(time_controller->GetClock()),
819 time_controller_(time_controller) {
820 RTC_DCHECK(time_controller_);
821 }
perkj26091b12016-09-01 08:17:40822
asaperssonfab67072017-04-04 12:51:49823 VideoCodec codec_config() const {
Markus Handella3765182020-07-08 11:13:32824 MutexLock lock(&mutex_);
perkjfa10b552016-10-03 06:45:26825 return config_;
826 }
827
828 void BlockNextEncode() {
Markus Handella3765182020-07-08 11:13:32829 MutexLock lock(&local_mutex_);
perkjfa10b552016-10-03 06:45:26830 block_next_encode_ = true;
831 }
832
Erik Språngaed30702018-11-05 11:57:17833 VideoEncoder::EncoderInfo GetEncoderInfo() const override {
Markus Handella3765182020-07-08 11:13:32834 MutexLock lock(&local_mutex_);
Erik Språng9d69cbe2020-10-22 15:44:42835 EncoderInfo info = FakeEncoder::GetEncoderInfo();
Erik Språngb7cb7b52019-02-26 14:52:33836 if (initialized_ == EncoderState::kInitialized) {
Mirta Dvornicicccc1b572019-01-15 11:42:18837 if (quality_scaling_) {
Åsa Perssone644a032019-11-08 14:56:00838 info.scaling_settings = VideoEncoder::ScalingSettings(
839 kQpLow, kQpHigh, kMinPixelsPerFrame);
Mirta Dvornicicccc1b572019-01-15 11:42:18840 }
841 info.is_hardware_accelerated = is_hardware_accelerated_;
Åsa Perssonc29cb2c2019-03-25 11:06:59842 for (int i = 0; i < kMaxSpatialLayers; ++i) {
843 if (temporal_layers_supported_[i]) {
844 int num_layers = temporal_layers_supported_[i].value() ? 2 : 1;
845 info.fps_allocation[i].resize(num_layers);
846 }
847 }
Erik Språngaed30702018-11-05 11:57:17848 }
Sergey Silkin6456e352019-07-08 15:56:40849
850 info.resolution_bitrate_limits = resolution_bitrate_limits_;
Rasmus Brandt5cad55b2019-12-19 08:47:11851 info.requested_resolution_alignment = requested_resolution_alignment_;
Åsa Perssonc5a74ff2020-09-20 15:50:00852 info.apply_alignment_to_all_simulcast_layers =
853 apply_alignment_to_all_simulcast_layers_;
Evan Shrubsoleb556b082020-10-08 12:56:45854 info.preferred_pixel_formats = preferred_pixel_formats_;
Erik Språngaed30702018-11-05 11:57:17855 return info;
kthelgason876222f2016-11-29 09:44:11856 }
857
Erik Språngb7cb7b52019-02-26 14:52:33858 int32_t RegisterEncodeCompleteCallback(
859 EncodedImageCallback* callback) override {
Markus Handella3765182020-07-08 11:13:32860 MutexLock lock(&local_mutex_);
Erik Språngb7cb7b52019-02-26 14:52:33861 encoded_image_callback_ = callback;
862 return FakeEncoder::RegisterEncodeCompleteCallback(callback);
863 }
864
perkjfa10b552016-10-03 06:45:26865 void ContinueEncode() { continue_encode_event_.Set(); }
866
867 void CheckLastTimeStampsMatch(int64_t ntp_time_ms,
868 uint32_t timestamp) const {
Markus Handella3765182020-07-08 11:13:32869 MutexLock lock(&local_mutex_);
perkjfa10b552016-10-03 06:45:26870 EXPECT_EQ(timestamp_, timestamp);
871 EXPECT_EQ(ntp_time_ms_, ntp_time_ms);
872 }
873
kthelgason2fc52542017-03-03 08:24:41874 void SetQualityScaling(bool b) {
Markus Handella3765182020-07-08 11:13:32875 MutexLock lock(&local_mutex_);
kthelgason2fc52542017-03-03 08:24:41876 quality_scaling_ = b;
877 }
kthelgasonad9010c2017-02-14 08:46:51878
Rasmus Brandt5cad55b2019-12-19 08:47:11879 void SetRequestedResolutionAlignment(int requested_resolution_alignment) {
Markus Handella3765182020-07-08 11:13:32880 MutexLock lock(&local_mutex_);
Rasmus Brandt5cad55b2019-12-19 08:47:11881 requested_resolution_alignment_ = requested_resolution_alignment;
882 }
883
Åsa Perssonc5a74ff2020-09-20 15:50:00884 void SetApplyAlignmentToAllSimulcastLayers(bool b) {
885 MutexLock lock(&local_mutex_);
886 apply_alignment_to_all_simulcast_layers_ = b;
887 }
888
Mirta Dvornicicccc1b572019-01-15 11:42:18889 void SetIsHardwareAccelerated(bool is_hardware_accelerated) {
Markus Handella3765182020-07-08 11:13:32890 MutexLock lock(&local_mutex_);
Mirta Dvornicicccc1b572019-01-15 11:42:18891 is_hardware_accelerated_ = is_hardware_accelerated;
892 }
893
Åsa Perssonc29cb2c2019-03-25 11:06:59894 void SetTemporalLayersSupported(size_t spatial_idx, bool supported) {
895 RTC_DCHECK_LT(spatial_idx, kMaxSpatialLayers);
Markus Handella3765182020-07-08 11:13:32896 MutexLock lock(&local_mutex_);
Åsa Perssonc29cb2c2019-03-25 11:06:59897 temporal_layers_supported_[spatial_idx] = supported;
898 }
899
Sergey Silkin6456e352019-07-08 15:56:40900 void SetResolutionBitrateLimits(
901 std::vector<ResolutionBitrateLimits> thresholds) {
Markus Handella3765182020-07-08 11:13:32902 MutexLock lock(&local_mutex_);
Sergey Silkin6456e352019-07-08 15:56:40903 resolution_bitrate_limits_ = thresholds;
904 }
905
sprangfe627f32017-03-29 15:24:59906 void ForceInitEncodeFailure(bool force_failure) {
Markus Handella3765182020-07-08 11:13:32907 MutexLock lock(&local_mutex_);
sprangfe627f32017-03-29 15:24:59908 force_init_encode_failed_ = force_failure;
909 }
910
Niels Möller6bb5ab92019-01-11 10:11:10911 void SimulateOvershoot(double rate_factor) {
Markus Handella3765182020-07-08 11:13:32912 MutexLock lock(&local_mutex_);
Niels Möller6bb5ab92019-01-11 10:11:10913 rate_factor_ = rate_factor;
914 }
915
Erik Språngd7329ca2019-02-21 20:19:53916 uint32_t GetLastFramerate() const {
Markus Handella3765182020-07-08 11:13:32917 MutexLock lock(&local_mutex_);
Niels Möller6bb5ab92019-01-11 10:11:10918 return last_framerate_;
919 }
920
Erik Språngd7329ca2019-02-21 20:19:53921 VideoFrame::UpdateRect GetLastUpdateRect() const {
Markus Handella3765182020-07-08 11:13:32922 MutexLock lock(&local_mutex_);
Ilya Nikolaevskiy71aee3a2019-02-18 12:01:26923 return last_update_rect_;
924 }
925
Niels Möller87e2d782019-03-07 09:18:23926 const std::vector<VideoFrameType>& LastFrameTypes() const {
Markus Handella3765182020-07-08 11:13:32927 MutexLock lock(&local_mutex_);
Erik Språngd7329ca2019-02-21 20:19:53928 return last_frame_types_;
929 }
930
931 void InjectFrame(const VideoFrame& input_image, bool keyframe) {
Niels Möller87e2d782019-03-07 09:18:23932 const std::vector<VideoFrameType> frame_type = {
Niels Möller8f7ce222019-03-21 14:43:58933 keyframe ? VideoFrameType::kVideoFrameKey
934 : VideoFrameType::kVideoFrameDelta};
Erik Språngd7329ca2019-02-21 20:19:53935 {
Markus Handella3765182020-07-08 11:13:32936 MutexLock lock(&local_mutex_);
Erik Språngd7329ca2019-02-21 20:19:53937 last_frame_types_ = frame_type;
938 }
Niels Möllerb859b322019-03-07 11:40:01939 FakeEncoder::Encode(input_image, &frame_type);
Erik Språngd7329ca2019-02-21 20:19:53940 }
941
Erik Språngb7cb7b52019-02-26 14:52:33942 void InjectEncodedImage(const EncodedImage& image) {
Markus Handella3765182020-07-08 11:13:32943 MutexLock lock(&local_mutex_);
Danil Chapovalov2549f172020-08-12 15:30:36944 encoded_image_callback_->OnEncodedImage(image, nullptr);
Erik Språngb7cb7b52019-02-26 14:52:33945 }
946
Mirta Dvornicic97910da2020-07-14 13:29:23947 void SetEncodedImageData(
948 rtc::scoped_refptr<EncodedImageBufferInterface> encoded_image_data) {
Markus Handella3765182020-07-08 11:13:32949 MutexLock lock(&local_mutex_);
Mirta Dvornicic97910da2020-07-14 13:29:23950 encoded_image_data_ = encoded_image_data;
Mirta Dvornicic28f0eb22019-05-28 14:30:16951 }
952
Erik Språngd7329ca2019-02-21 20:19:53953 void ExpectNullFrame() {
Markus Handella3765182020-07-08 11:13:32954 MutexLock lock(&local_mutex_);
Erik Språngd7329ca2019-02-21 20:19:53955 expect_null_frame_ = true;
956 }
957
Erik Språng5056af02019-09-02 13:53:11958 absl::optional<VideoEncoder::RateControlParameters>
959 GetAndResetLastRateControlSettings() {
960 auto settings = last_rate_control_settings_;
961 last_rate_control_settings_.reset();
962 return settings;
Erik Språngd7329ca2019-02-21 20:19:53963 }
964
Evan Shrubsole895556e2020-10-05 07:15:13965 absl::optional<VideoFrameBuffer::Type> GetLastInputPixelFormat() {
966 MutexLock lock(&local_mutex_);
967 return last_input_pixel_format_;
968 }
969
Sergey Silkin5ee69672019-07-02 12:18:34970 int GetNumEncoderInitializations() const {
Markus Handella3765182020-07-08 11:13:32971 MutexLock lock(&local_mutex_);
Sergey Silkin5ee69672019-07-02 12:18:34972 return num_encoder_initializations_;
973 }
974
Evan Shrubsole7c079f62019-09-26 07:55:03975 int GetNumSetRates() const {
Markus Handella3765182020-07-08 11:13:32976 MutexLock lock(&local_mutex_);
Evan Shrubsole7c079f62019-09-26 07:55:03977 return num_set_rates_;
978 }
979
Åsa Perssonc5a74ff2020-09-20 15:50:00980 VideoCodec video_codec() const {
981 MutexLock lock(&local_mutex_);
982 return video_codec_;
983 }
984
Evan Shrubsoleb556b082020-10-08 12:56:45985 void SetPreferredPixelFormats(
986 absl::InlinedVector<VideoFrameBuffer::Type, kMaxPreferredPixelFormats>
987 pixel_formats) {
988 MutexLock lock(&local_mutex_);
989 preferred_pixel_formats_ = std::move(pixel_formats);
990 }
991
perkjfa10b552016-10-03 06:45:26992 private:
perkj26091b12016-09-01 08:17:40993 int32_t Encode(const VideoFrame& input_image,
Niels Möller87e2d782019-03-07 09:18:23994 const std::vector<VideoFrameType>* frame_types) override {
perkj26091b12016-09-01 08:17:40995 bool block_encode;
996 {
Markus Handella3765182020-07-08 11:13:32997 MutexLock lock(&local_mutex_);
Erik Språngd7329ca2019-02-21 20:19:53998 if (expect_null_frame_) {
999 EXPECT_EQ(input_image.timestamp(), 0u);
1000 EXPECT_EQ(input_image.width(), 1);
1001 last_frame_types_ = *frame_types;
1002 expect_null_frame_ = false;
1003 } else {
1004 EXPECT_GT(input_image.timestamp(), timestamp_);
1005 EXPECT_GT(input_image.ntp_time_ms(), ntp_time_ms_);
1006 EXPECT_EQ(input_image.timestamp(), input_image.ntp_time_ms() * 90);
1007 }
perkj26091b12016-09-01 08:17:401008
1009 timestamp_ = input_image.timestamp();
1010 ntp_time_ms_ = input_image.ntp_time_ms();
perkj803d97f2016-11-01 18:45:461011 last_input_width_ = input_image.width();
1012 last_input_height_ = input_image.height();
perkj26091b12016-09-01 08:17:401013 block_encode = block_next_encode_;
1014 block_next_encode_ = false;
Ilya Nikolaevskiy71aee3a2019-02-18 12:01:261015 last_update_rect_ = input_image.update_rect();
Erik Språngd7329ca2019-02-21 20:19:531016 last_frame_types_ = *frame_types;
Evan Shrubsole895556e2020-10-05 07:15:131017 last_input_pixel_format_ = input_image.video_frame_buffer()->type();
perkj26091b12016-09-01 08:17:401018 }
Niels Möllerb859b322019-03-07 11:40:011019 int32_t result = FakeEncoder::Encode(input_image, frame_types);
perkj26091b12016-09-01 08:17:401020 if (block_encode)
perkja49cbd32016-09-16 14:53:411021 EXPECT_TRUE(continue_encode_event_.Wait(kDefaultTimeoutMs));
Tomas Gunnarsson612445e2020-09-21 12:31:231022
perkj26091b12016-09-01 08:17:401023 return result;
1024 }
1025
Niels Möller08ae7ce2020-09-23 13:58:121026 CodecSpecificInfo EncodeHook(
1027 EncodedImage& encoded_image,
1028 rtc::scoped_refptr<EncodedImageBuffer> buffer) override {
Danil Chapovalov2549f172020-08-12 15:30:361029 CodecSpecificInfo codec_specific;
Mirta Dvornicic97910da2020-07-14 13:29:231030 {
1031 MutexLock lock(&mutex_);
Danil Chapovalov2549f172020-08-12 15:30:361032 codec_specific.codecType = config_.codecType;
Mirta Dvornicic97910da2020-07-14 13:29:231033 }
1034 MutexLock lock(&local_mutex_);
1035 if (encoded_image_data_) {
Danil Chapovalov2549f172020-08-12 15:30:361036 encoded_image.SetEncodedData(encoded_image_data_);
Mirta Dvornicic97910da2020-07-14 13:29:231037 }
Danil Chapovalov2549f172020-08-12 15:30:361038 return codec_specific;
Mirta Dvornicic97910da2020-07-14 13:29:231039 }
1040
sprangfe627f32017-03-29 15:24:591041 int32_t InitEncode(const VideoCodec* config,
Elad Alon370f93a2019-06-11 12:57:571042 const Settings& settings) override {
1043 int res = FakeEncoder::InitEncode(config, settings);
Sergey Silkin5ee69672019-07-02 12:18:341044
Markus Handella3765182020-07-08 11:13:321045 MutexLock lock(&local_mutex_);
Erik Språngb7cb7b52019-02-26 14:52:331046 EXPECT_EQ(initialized_, EncoderState::kUninitialized);
Sergey Silkin5ee69672019-07-02 12:18:341047
1048 ++num_encoder_initializations_;
Åsa Perssonc5a74ff2020-09-20 15:50:001049 video_codec_ = *config;
Sergey Silkin5ee69672019-07-02 12:18:341050
Erik Språng82fad3d2018-03-21 08:57:231051 if (config->codecType == kVideoCodecVP8) {
sprangfe627f32017-03-29 15:24:591052 // Simulate setting up temporal layers, in order to validate the life
1053 // cycle of these objects.
Elad Aloncde8ab22019-03-20 10:56:201054 Vp8TemporalLayersFactory factory;
Elad Alon45befc52019-07-02 09:20:091055 frame_buffer_controller_ =
1056 factory.Create(*config, settings, &fec_controller_override_);
sprangfe627f32017-03-29 15:24:591057 }
Erik Språngb7cb7b52019-02-26 14:52:331058 if (force_init_encode_failed_) {
1059 initialized_ = EncoderState::kInitializationFailed;
sprangfe627f32017-03-29 15:24:591060 return -1;
Erik Språngb7cb7b52019-02-26 14:52:331061 }
Mirta Dvornicicccc1b572019-01-15 11:42:181062
Erik Språngb7cb7b52019-02-26 14:52:331063 initialized_ = EncoderState::kInitialized;
sprangfe627f32017-03-29 15:24:591064 return res;
1065 }
1066
Erik Språngb7cb7b52019-02-26 14:52:331067 int32_t Release() override {
Markus Handella3765182020-07-08 11:13:321068 MutexLock lock(&local_mutex_);
Erik Språngb7cb7b52019-02-26 14:52:331069 EXPECT_NE(initialized_, EncoderState::kUninitialized);
1070 initialized_ = EncoderState::kUninitialized;
1071 return FakeEncoder::Release();
1072 }
1073
Erik Språng16cb8f52019-04-12 11:59:091074 void SetRates(const RateControlParameters& parameters) {
Markus Handella3765182020-07-08 11:13:321075 MutexLock lock(&local_mutex_);
Evan Shrubsole7c079f62019-09-26 07:55:031076 num_set_rates_++;
Niels Möller6bb5ab92019-01-11 10:11:101077 VideoBitrateAllocation adjusted_rate_allocation;
1078 for (size_t si = 0; si < kMaxSpatialLayers; ++si) {
1079 for (size_t ti = 0; ti < kMaxTemporalStreams; ++ti) {
Erik Språng16cb8f52019-04-12 11:59:091080 if (parameters.bitrate.HasBitrate(si, ti)) {
Niels Möller6bb5ab92019-01-11 10:11:101081 adjusted_rate_allocation.SetBitrate(
1082 si, ti,
Erik Språng16cb8f52019-04-12 11:59:091083 static_cast<uint32_t>(parameters.bitrate.GetBitrate(si, ti) *
Niels Möller6bb5ab92019-01-11 10:11:101084 rate_factor_));
1085 }
1086 }
1087 }
Erik Språng16cb8f52019-04-12 11:59:091088 last_framerate_ = static_cast<uint32_t>(parameters.framerate_fps + 0.5);
Erik Språng5056af02019-09-02 13:53:111089 last_rate_control_settings_ = parameters;
Erik Språng16cb8f52019-04-12 11:59:091090 RateControlParameters adjusted_paramters = parameters;
1091 adjusted_paramters.bitrate = adjusted_rate_allocation;
1092 FakeEncoder::SetRates(adjusted_paramters);
Niels Möller6bb5ab92019-01-11 10:11:101093 }
1094
Tomas Gunnarsson612445e2020-09-21 12:31:231095 TimeController* const time_controller_;
Markus Handella3765182020-07-08 11:13:321096 mutable Mutex local_mutex_;
Erik Språngb7cb7b52019-02-26 14:52:331097 enum class EncoderState {
1098 kUninitialized,
1099 kInitializationFailed,
1100 kInitialized
Markus Handella3765182020-07-08 11:13:321101 } initialized_ RTC_GUARDED_BY(local_mutex_) = EncoderState::kUninitialized;
1102 bool block_next_encode_ RTC_GUARDED_BY(local_mutex_) = false;
perkj26091b12016-09-01 08:17:401103 rtc::Event continue_encode_event_;
Markus Handella3765182020-07-08 11:13:321104 uint32_t timestamp_ RTC_GUARDED_BY(local_mutex_) = 0;
1105 int64_t ntp_time_ms_ RTC_GUARDED_BY(local_mutex_) = 0;
1106 int last_input_width_ RTC_GUARDED_BY(local_mutex_) = 0;
1107 int last_input_height_ RTC_GUARDED_BY(local_mutex_) = 0;
1108 bool quality_scaling_ RTC_GUARDED_BY(local_mutex_) = true;
1109 int requested_resolution_alignment_ RTC_GUARDED_BY(local_mutex_) = 1;
Åsa Perssonc5a74ff2020-09-20 15:50:001110 bool apply_alignment_to_all_simulcast_layers_ RTC_GUARDED_BY(local_mutex_) =
1111 false;
Markus Handella3765182020-07-08 11:13:321112 bool is_hardware_accelerated_ RTC_GUARDED_BY(local_mutex_) = false;
Mirta Dvornicic97910da2020-07-14 13:29:231113 rtc::scoped_refptr<EncodedImageBufferInterface> encoded_image_data_
1114 RTC_GUARDED_BY(local_mutex_);
Elad Aloncde8ab22019-03-20 10:56:201115 std::unique_ptr<Vp8FrameBufferController> frame_buffer_controller_
Markus Handella3765182020-07-08 11:13:321116 RTC_GUARDED_BY(local_mutex_);
Åsa Perssonc29cb2c2019-03-25 11:06:591117 absl::optional<bool>
1118 temporal_layers_supported_[kMaxSpatialLayers] RTC_GUARDED_BY(
Markus Handella3765182020-07-08 11:13:321119 local_mutex_);
1120 bool force_init_encode_failed_ RTC_GUARDED_BY(local_mutex_) = false;
1121 double rate_factor_ RTC_GUARDED_BY(local_mutex_) = 1.0;
1122 uint32_t last_framerate_ RTC_GUARDED_BY(local_mutex_) = 0;
Erik Språng5056af02019-09-02 13:53:111123 absl::optional<VideoEncoder::RateControlParameters>
1124 last_rate_control_settings_;
Markus Handella3765182020-07-08 11:13:321125 VideoFrame::UpdateRect last_update_rect_ RTC_GUARDED_BY(local_mutex_) = {
1126 0, 0, 0, 0};
Niels Möller87e2d782019-03-07 09:18:231127 std::vector<VideoFrameType> last_frame_types_;
Erik Språngd7329ca2019-02-21 20:19:531128 bool expect_null_frame_ = false;
Markus Handella3765182020-07-08 11:13:321129 EncodedImageCallback* encoded_image_callback_ RTC_GUARDED_BY(local_mutex_) =
1130 nullptr;
Evan Shrubsolefb862742020-03-16 15:18:361131 NiceMock<MockFecControllerOverride> fec_controller_override_;
Markus Handella3765182020-07-08 11:13:321132 int num_encoder_initializations_ RTC_GUARDED_BY(local_mutex_) = 0;
Sergey Silkin6456e352019-07-08 15:56:401133 std::vector<ResolutionBitrateLimits> resolution_bitrate_limits_
Markus Handella3765182020-07-08 11:13:321134 RTC_GUARDED_BY(local_mutex_);
1135 int num_set_rates_ RTC_GUARDED_BY(local_mutex_) = 0;
Åsa Perssonc5a74ff2020-09-20 15:50:001136 VideoCodec video_codec_ RTC_GUARDED_BY(local_mutex_);
Evan Shrubsole895556e2020-10-05 07:15:131137 absl::optional<VideoFrameBuffer::Type> last_input_pixel_format_
1138 RTC_GUARDED_BY(local_mutex_);
Evan Shrubsoleb556b082020-10-08 12:56:451139 absl::InlinedVector<VideoFrameBuffer::Type, kMaxPreferredPixelFormats>
1140 preferred_pixel_formats_ RTC_GUARDED_BY(local_mutex_);
perkj26091b12016-09-01 08:17:401141 };
1142
mflodmancc3d4422017-08-03 15:27:511143 class TestSink : public VideoStreamEncoder::EncoderSink {
perkj26091b12016-09-01 08:17:401144 public:
Tomas Gunnarsson612445e2020-09-21 12:31:231145 TestSink(TimeController* time_controller, TestEncoder* test_encoder)
1146 : time_controller_(time_controller), test_encoder_(test_encoder) {
1147 RTC_DCHECK(time_controller_);
1148 }
perkj26091b12016-09-01 08:17:401149
perkj26091b12016-09-01 08:17:401150 void WaitForEncodedFrame(int64_t expected_ntp_time) {
sprang4847ae62017-06-27 14:06:521151 EXPECT_TRUE(
1152 TimedWaitForEncodedFrame(expected_ntp_time, kDefaultTimeoutMs));
1153 }
1154
1155 bool TimedWaitForEncodedFrame(int64_t expected_ntp_time,
1156 int64_t timeout_ms) {
perkj26091b12016-09-01 08:17:401157 uint32_t timestamp = 0;
Tomas Gunnarsson612445e2020-09-21 12:31:231158 if (!WaitForFrame(timeout_ms))
sprang4847ae62017-06-27 14:06:521159 return false;
perkj26091b12016-09-01 08:17:401160 {
Markus Handella3765182020-07-08 11:13:321161 MutexLock lock(&mutex_);
sprangb1ca0732017-02-01 16:38:121162 timestamp = last_timestamp_;
perkj26091b12016-09-01 08:17:401163 }
1164 test_encoder_->CheckLastTimeStampsMatch(expected_ntp_time, timestamp);
sprang4847ae62017-06-27 14:06:521165 return true;
perkj26091b12016-09-01 08:17:401166 }
1167
sprangb1ca0732017-02-01 16:38:121168 void WaitForEncodedFrame(uint32_t expected_width,
1169 uint32_t expected_height) {
Tomas Gunnarsson612445e2020-09-21 12:31:231170 EXPECT_TRUE(WaitForFrame(kDefaultTimeoutMs));
Åsa Perssonc74d8da2017-12-04 13:13:561171 CheckLastFrameSizeMatches(expected_width, expected_height);
sprangc5d62e22017-04-03 06:53:041172 }
1173
Åsa Perssonc74d8da2017-12-04 13:13:561174 void CheckLastFrameSizeMatches(uint32_t expected_width,
sprangc5d62e22017-04-03 06:53:041175 uint32_t expected_height) {
sprangb1ca0732017-02-01 16:38:121176 uint32_t width = 0;
1177 uint32_t height = 0;
sprangb1ca0732017-02-01 16:38:121178 {
Markus Handella3765182020-07-08 11:13:321179 MutexLock lock(&mutex_);
sprangb1ca0732017-02-01 16:38:121180 width = last_width_;
1181 height = last_height_;
1182 }
1183 EXPECT_EQ(expected_height, height);
1184 EXPECT_EQ(expected_width, width);
1185 }
1186
Ilya Nikolaevskiyba96e2f2019-06-04 13:15:141187 void CheckLastFrameRotationMatches(VideoRotation expected_rotation) {
1188 VideoRotation rotation;
1189 {
Markus Handella3765182020-07-08 11:13:321190 MutexLock lock(&mutex_);
Ilya Nikolaevskiyba96e2f2019-06-04 13:15:141191 rotation = last_rotation_;
1192 }
1193 EXPECT_EQ(expected_rotation, rotation);
1194 }
1195
Tomas Gunnarsson612445e2020-09-21 12:31:231196 void ExpectDroppedFrame() { EXPECT_FALSE(WaitForFrame(100)); }
kthelgason2bc68642017-02-07 15:02:221197
sprangc5d62e22017-04-03 06:53:041198 bool WaitForFrame(int64_t timeout_ms) {
Tomas Gunnarsson612445e2020-09-21 12:31:231199 RTC_DCHECK(time_controller_->GetMainThread()->IsCurrent());
1200 bool ret = encoded_frame_event_.Wait(timeout_ms);
1201 time_controller_->AdvanceTime(TimeDelta::Millis(0));
1202 return ret;
sprangc5d62e22017-04-03 06:53:041203 }
1204
perkj26091b12016-09-01 08:17:401205 void SetExpectNoFrames() {
Markus Handella3765182020-07-08 11:13:321206 MutexLock lock(&mutex_);
perkj26091b12016-09-01 08:17:401207 expect_frames_ = false;
1208 }
1209
asaperssonfab67072017-04-04 12:51:491210 int number_of_reconfigurations() const {
Markus Handella3765182020-07-08 11:13:321211 MutexLock lock(&mutex_);
Per512ecb32016-09-23 13:52:061212 return number_of_reconfigurations_;
1213 }
1214
asaperssonfab67072017-04-04 12:51:491215 int last_min_transmit_bitrate() const {
Markus Handella3765182020-07-08 11:13:321216 MutexLock lock(&mutex_);
Per512ecb32016-09-23 13:52:061217 return min_transmit_bitrate_bps_;
1218 }
1219
Erik Språngd7329ca2019-02-21 20:19:531220 void SetNumExpectedLayers(size_t num_layers) {
Markus Handella3765182020-07-08 11:13:321221 MutexLock lock(&mutex_);
Erik Språngd7329ca2019-02-21 20:19:531222 num_expected_layers_ = num_layers;
1223 }
1224
Erik Språngb7cb7b52019-02-26 14:52:331225 int64_t GetLastCaptureTimeMs() const {
Markus Handella3765182020-07-08 11:13:321226 MutexLock lock(&mutex_);
Erik Språngb7cb7b52019-02-26 14:52:331227 return last_capture_time_ms_;
1228 }
1229
Mirta Dvornicic28f0eb22019-05-28 14:30:161230 std::vector<uint8_t> GetLastEncodedImageData() {
Markus Handella3765182020-07-08 11:13:321231 MutexLock lock(&mutex_);
Mirta Dvornicic28f0eb22019-05-28 14:30:161232 return std::move(last_encoded_image_data_);
1233 }
1234
Per Kjellanderdcef6412020-10-07 13:09:051235 VideoBitrateAllocation GetLastVideoBitrateAllocation() {
1236 MutexLock lock(&mutex_);
1237 return last_bitrate_allocation_;
1238 }
1239
1240 int number_of_bitrate_allocations() const {
1241 MutexLock lock(&mutex_);
1242 return number_of_bitrate_allocations_;
1243 }
1244
Per Kjellandera9434842020-10-15 15:53:221245 VideoLayersAllocation GetLastVideoLayersAllocation() {
1246 MutexLock lock(&mutex_);
1247 return last_layers_allocation_;
1248 }
1249
1250 int number_of_layers_allocations() const {
1251 MutexLock lock(&mutex_);
1252 return number_of_layers_allocations_;
1253 }
1254
perkj26091b12016-09-01 08:17:401255 private:
sergeyu2cb155a2016-11-04 18:39:291256 Result OnEncodedImage(
1257 const EncodedImage& encoded_image,
Danil Chapovalov2549f172020-08-12 15:30:361258 const CodecSpecificInfo* codec_specific_info) override {
Markus Handella3765182020-07-08 11:13:321259 MutexLock lock(&mutex_);
Per512ecb32016-09-23 13:52:061260 EXPECT_TRUE(expect_frames_);
Mirta Dvornicic28f0eb22019-05-28 14:30:161261 last_encoded_image_data_ = std::vector<uint8_t>(
1262 encoded_image.data(), encoded_image.data() + encoded_image.size());
Erik Språngd7329ca2019-02-21 20:19:531263 uint32_t timestamp = encoded_image.Timestamp();
1264 if (last_timestamp_ != timestamp) {
1265 num_received_layers_ = 1;
1266 } else {
1267 ++num_received_layers_;
1268 }
1269 last_timestamp_ = timestamp;
Erik Språngb7cb7b52019-02-26 14:52:331270 last_capture_time_ms_ = encoded_image.capture_time_ms_;
sprangb1ca0732017-02-01 16:38:121271 last_width_ = encoded_image._encodedWidth;
1272 last_height_ = encoded_image._encodedHeight;
Ilya Nikolaevskiyba96e2f2019-06-04 13:15:141273 last_rotation_ = encoded_image.rotation_;
Erik Språngd7329ca2019-02-21 20:19:531274 if (num_received_layers_ == num_expected_layers_) {
1275 encoded_frame_event_.Set();
1276 }
sprangb1ca0732017-02-01 16:38:121277 return Result(Result::OK, last_timestamp_);
Per512ecb32016-09-23 13:52:061278 }
1279
Rasmus Brandtc402dbe2019-02-04 10:09:461280 void OnEncoderConfigurationChanged(
1281 std::vector<VideoStream> streams,
Ilya Nikolaevskiy93be66c2020-04-02 12:10:271282 bool is_svc,
Rasmus Brandtc402dbe2019-02-04 10:09:461283 VideoEncoderConfig::ContentType content_type,
1284 int min_transmit_bitrate_bps) override {
Markus Handella3765182020-07-08 11:13:321285 MutexLock lock(&mutex_);
Per512ecb32016-09-23 13:52:061286 ++number_of_reconfigurations_;
1287 min_transmit_bitrate_bps_ = min_transmit_bitrate_bps;
1288 }
1289
Per Kjellanderdcef6412020-10-07 13:09:051290 void OnBitrateAllocationUpdated(
1291 const VideoBitrateAllocation& allocation) override {
1292 MutexLock lock(&mutex_);
1293 ++number_of_bitrate_allocations_;
1294 last_bitrate_allocation_ = allocation;
1295 }
1296
Per Kjellandera9434842020-10-15 15:53:221297 void OnVideoLayersAllocationUpdated(
1298 VideoLayersAllocation allocation) override {
1299 MutexLock lock(&mutex_);
1300 ++number_of_layers_allocations_;
1301 last_layers_allocation_ = allocation;
1302 rtc::StringBuilder log;
1303 for (const auto& layer : allocation.active_spatial_layers) {
1304 log << layer.width << "x" << layer.height << "@" << layer.frame_rate_fps
1305 << "[";
1306 for (const auto target_bitrate :
1307 layer.target_bitrate_per_temporal_layer) {
1308 log << target_bitrate.kbps() << ",";
1309 }
1310 log << "]";
1311 }
1312 RTC_DLOG(INFO) << "OnVideoLayersAllocationUpdated " << log.str();
1313 }
1314
Tomas Gunnarsson612445e2020-09-21 12:31:231315 TimeController* const time_controller_;
Markus Handella3765182020-07-08 11:13:321316 mutable Mutex mutex_;
perkj26091b12016-09-01 08:17:401317 TestEncoder* test_encoder_;
1318 rtc::Event encoded_frame_event_;
Mirta Dvornicic28f0eb22019-05-28 14:30:161319 std::vector<uint8_t> last_encoded_image_data_;
sprangb1ca0732017-02-01 16:38:121320 uint32_t last_timestamp_ = 0;
Erik Språngb7cb7b52019-02-26 14:52:331321 int64_t last_capture_time_ms_ = 0;
sprangb1ca0732017-02-01 16:38:121322 uint32_t last_height_ = 0;
1323 uint32_t last_width_ = 0;
Ilya Nikolaevskiyba96e2f2019-06-04 13:15:141324 VideoRotation last_rotation_ = kVideoRotation_0;
Erik Språngd7329ca2019-02-21 20:19:531325 size_t num_expected_layers_ = 1;
1326 size_t num_received_layers_ = 0;
perkj26091b12016-09-01 08:17:401327 bool expect_frames_ = true;
Per512ecb32016-09-23 13:52:061328 int number_of_reconfigurations_ = 0;
1329 int min_transmit_bitrate_bps_ = 0;
Per Kjellanderdcef6412020-10-07 13:09:051330 VideoBitrateAllocation last_bitrate_allocation_ RTC_GUARDED_BY(&mutex_);
1331 int number_of_bitrate_allocations_ RTC_GUARDED_BY(&mutex_) = 0;
Per Kjellandera9434842020-10-15 15:53:221332 VideoLayersAllocation last_layers_allocation_ RTC_GUARDED_BY(&mutex_);
1333 int number_of_layers_allocations_ RTC_GUARDED_BY(&mutex_) = 0;
perkj26091b12016-09-01 08:17:401334 };
1335
Sergey Silkin5ee69672019-07-02 12:18:341336 class VideoBitrateAllocatorProxyFactory
1337 : public VideoBitrateAllocatorFactory {
1338 public:
1339 VideoBitrateAllocatorProxyFactory()
1340 : bitrate_allocator_factory_(
1341 CreateBuiltinVideoBitrateAllocatorFactory()) {}
1342
1343 std::unique_ptr<VideoBitrateAllocator> CreateVideoBitrateAllocator(
1344 const VideoCodec& codec) override {
Markus Handella3765182020-07-08 11:13:321345 MutexLock lock(&mutex_);
Sergey Silkin5ee69672019-07-02 12:18:341346 codec_config_ = codec;
1347 return bitrate_allocator_factory_->CreateVideoBitrateAllocator(codec);
1348 }
1349
1350 VideoCodec codec_config() const {
Markus Handella3765182020-07-08 11:13:321351 MutexLock lock(&mutex_);
Sergey Silkin5ee69672019-07-02 12:18:341352 return codec_config_;
1353 }
1354
1355 private:
1356 std::unique_ptr<VideoBitrateAllocatorFactory> bitrate_allocator_factory_;
1357
Markus Handella3765182020-07-08 11:13:321358 mutable Mutex mutex_;
1359 VideoCodec codec_config_ RTC_GUARDED_BY(mutex_);
Sergey Silkin5ee69672019-07-02 12:18:341360 };
1361
Tomas Gunnarsson612445e2020-09-21 12:31:231362 Clock* clock() { return time_controller_.GetClock(); }
1363 void AdvanceTime(TimeDelta duration) {
1364 time_controller_.AdvanceTime(duration);
1365 }
1366
1367 int64_t CurrentTimeMs() { return clock()->CurrentTime().ms(); }
1368
1369 protected:
1370 virtual TaskQueueFactory* GetTaskQueueFactory() {
1371 return time_controller_.GetTaskQueueFactory();
1372 }
1373
1374 GlobalSimulatedTimeController time_controller_{Timestamp::Micros(1234)};
perkj26091b12016-09-01 08:17:401375 VideoSendStream::Config video_send_config_;
Erik Språng08127a92016-11-16 15:41:301376 VideoEncoderConfig video_encoder_config_;
Per512ecb32016-09-23 13:52:061377 int codec_width_;
1378 int codec_height_;
sprang4847ae62017-06-27 14:06:521379 int max_framerate_;
perkj26091b12016-09-01 08:17:401380 TestEncoder fake_encoder_;
Niels Möllercbcbc222018-09-28 07:07:241381 test::VideoEncoderProxyFactory encoder_factory_;
Sergey Silkin5ee69672019-07-02 12:18:341382 VideoBitrateAllocatorProxyFactory bitrate_allocator_factory_;
sprangc5d62e22017-04-03 06:53:041383 std::unique_ptr<MockableSendStatisticsProxy> stats_proxy_;
perkj26091b12016-09-01 08:17:401384 TestSink sink_;
Tomas Gunnarsson612445e2020-09-21 12:31:231385 AdaptingFrameForwarder video_source_{&time_controller_};
mflodmancc3d4422017-08-03 15:27:511386 std::unique_ptr<VideoStreamEncoderUnderTest> video_stream_encoder_;
perkj26091b12016-09-01 08:17:401387};
1388
mflodmancc3d4422017-08-03 15:27:511389TEST_F(VideoStreamEncoderTest, EncodeOneFrame) {
Henrik Boström381d1092020-05-12 16:49:071390 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:071391 DataRate::BitsPerSec(kTargetBitrateBps),
1392 DataRate::BitsPerSec(kTargetBitrateBps),
1393 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Niels Möllerc572ff32018-11-07 07:43:501394 rtc::Event frame_destroyed_event;
perkja49cbd32016-09-16 14:53:411395 video_source_.IncomingCapturedFrame(CreateFrame(1, &frame_destroyed_event));
sprang4847ae62017-06-27 14:06:521396 WaitForEncodedFrame(1);
perkja49cbd32016-09-16 14:53:411397 EXPECT_TRUE(frame_destroyed_event.Wait(kDefaultTimeoutMs));
mflodmancc3d4422017-08-03 15:27:511398 video_stream_encoder_->Stop();
perkj26091b12016-09-01 08:17:401399}
1400
mflodmancc3d4422017-08-03 15:27:511401TEST_F(VideoStreamEncoderTest, DropsFramesBeforeFirstOnBitrateUpdated) {
perkj26091b12016-09-01 08:17:401402 // Dropped since no target bitrate has been set.
Niels Möllerc572ff32018-11-07 07:43:501403 rtc::Event frame_destroyed_event;
Sebastian Janssona3177052018-04-10 11:05:491404 // The encoder will cache up to one frame for a short duration. Adding two
1405 // frames means that the first frame will be dropped and the second frame will
1406 // be sent when the encoder is enabled.
perkja49cbd32016-09-16 14:53:411407 video_source_.IncomingCapturedFrame(CreateFrame(1, &frame_destroyed_event));
Tomas Gunnarsson612445e2020-09-21 12:31:231408 AdvanceTime(TimeDelta::Millis(10));
Sebastian Janssona3177052018-04-10 11:05:491409 video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
perkja49cbd32016-09-16 14:53:411410 EXPECT_TRUE(frame_destroyed_event.Wait(kDefaultTimeoutMs));
perkj26091b12016-09-01 08:17:401411
Henrik Boström381d1092020-05-12 16:49:071412 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:071413 DataRate::BitsPerSec(kTargetBitrateBps),
1414 DataRate::BitsPerSec(kTargetBitrateBps),
1415 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
perkj26091b12016-09-01 08:17:401416
Sebastian Janssona3177052018-04-10 11:05:491417 // The pending frame should be received.
sprang4847ae62017-06-27 14:06:521418 WaitForEncodedFrame(2);
Sebastian Janssona3177052018-04-10 11:05:491419 video_source_.IncomingCapturedFrame(CreateFrame(3, nullptr));
1420
1421 WaitForEncodedFrame(3);
mflodmancc3d4422017-08-03 15:27:511422 video_stream_encoder_->Stop();
perkj26091b12016-09-01 08:17:401423}
1424
mflodmancc3d4422017-08-03 15:27:511425TEST_F(VideoStreamEncoderTest, DropsFramesWhenRateSetToZero) {
Henrik Boström381d1092020-05-12 16:49:071426 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:071427 DataRate::BitsPerSec(kTargetBitrateBps),
1428 DataRate::BitsPerSec(kTargetBitrateBps),
1429 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
perkja49cbd32016-09-16 14:53:411430 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
sprang4847ae62017-06-27 14:06:521431 WaitForEncodedFrame(1);
perkj26091b12016-09-01 08:17:401432
Henrik Boström381d1092020-05-12 16:49:071433 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
1434 DataRate::BitsPerSec(0), DataRate::BitsPerSec(0), DataRate::BitsPerSec(0),
1435 0, 0, 0);
Sebastian Janssona3177052018-04-10 11:05:491436 // The encoder will cache up to one frame for a short duration. Adding two
1437 // frames means that the first frame will be dropped and the second frame will
1438 // be sent when the encoder is resumed.
perkja49cbd32016-09-16 14:53:411439 video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
Sebastian Janssona3177052018-04-10 11:05:491440 video_source_.IncomingCapturedFrame(CreateFrame(3, nullptr));
perkj26091b12016-09-01 08:17:401441
Henrik Boström381d1092020-05-12 16:49:071442 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:071443 DataRate::BitsPerSec(kTargetBitrateBps),
1444 DataRate::BitsPerSec(kTargetBitrateBps),
1445 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
sprang4847ae62017-06-27 14:06:521446 WaitForEncodedFrame(3);
Sebastian Janssona3177052018-04-10 11:05:491447 video_source_.IncomingCapturedFrame(CreateFrame(4, nullptr));
1448 WaitForEncodedFrame(4);
mflodmancc3d4422017-08-03 15:27:511449 video_stream_encoder_->Stop();
perkj26091b12016-09-01 08:17:401450}
1451
mflodmancc3d4422017-08-03 15:27:511452TEST_F(VideoStreamEncoderTest, DropsFramesWithSameOrOldNtpTimestamp) {
Henrik Boström381d1092020-05-12 16:49:071453 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:071454 DataRate::BitsPerSec(kTargetBitrateBps),
1455 DataRate::BitsPerSec(kTargetBitrateBps),
1456 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
perkja49cbd32016-09-16 14:53:411457 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
sprang4847ae62017-06-27 14:06:521458 WaitForEncodedFrame(1);
perkj26091b12016-09-01 08:17:401459
1460 // This frame will be dropped since it has the same ntp timestamp.
perkja49cbd32016-09-16 14:53:411461 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
perkj26091b12016-09-01 08:17:401462
perkja49cbd32016-09-16 14:53:411463 video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
sprang4847ae62017-06-27 14:06:521464 WaitForEncodedFrame(2);
mflodmancc3d4422017-08-03 15:27:511465 video_stream_encoder_->Stop();
perkj26091b12016-09-01 08:17:401466}
1467
mflodmancc3d4422017-08-03 15:27:511468TEST_F(VideoStreamEncoderTest, DropsFrameAfterStop) {
Henrik Boström381d1092020-05-12 16:49:071469 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:071470 DataRate::BitsPerSec(kTargetBitrateBps),
1471 DataRate::BitsPerSec(kTargetBitrateBps),
1472 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
perkj26091b12016-09-01 08:17:401473
perkja49cbd32016-09-16 14:53:411474 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
sprang4847ae62017-06-27 14:06:521475 WaitForEncodedFrame(1);
perkj26091b12016-09-01 08:17:401476
mflodmancc3d4422017-08-03 15:27:511477 video_stream_encoder_->Stop();
perkj26091b12016-09-01 08:17:401478 sink_.SetExpectNoFrames();
Niels Möllerc572ff32018-11-07 07:43:501479 rtc::Event frame_destroyed_event;
perkja49cbd32016-09-16 14:53:411480 video_source_.IncomingCapturedFrame(CreateFrame(2, &frame_destroyed_event));
1481 EXPECT_TRUE(frame_destroyed_event.Wait(kDefaultTimeoutMs));
perkj26091b12016-09-01 08:17:401482}
1483
Tomas Gunnarsson612445e2020-09-21 12:31:231484class VideoStreamEncoderBlockedTest : public VideoStreamEncoderTest {
1485 public:
1486 VideoStreamEncoderBlockedTest() {}
1487
1488 TaskQueueFactory* GetTaskQueueFactory() override {
1489 return task_queue_factory_.get();
1490 }
1491
1492 private:
1493 std::unique_ptr<TaskQueueFactory> task_queue_factory_ =
1494 CreateDefaultTaskQueueFactory();
1495};
1496
1497TEST_F(VideoStreamEncoderBlockedTest, DropsPendingFramesOnSlowEncode) {
Henrik Boström381d1092020-05-12 16:49:071498 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:071499 DataRate::BitsPerSec(kTargetBitrateBps),
1500 DataRate::BitsPerSec(kTargetBitrateBps),
1501 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
perkj26091b12016-09-01 08:17:401502
Tomas Gunnarsson612445e2020-09-21 12:31:231503 int dropped_count = 0;
1504 stats_proxy_->SetDroppedFrameCallback(
1505 [&dropped_count](VideoStreamEncoderObserver::DropReason) {
1506 ++dropped_count;
1507 });
1508
perkj26091b12016-09-01 08:17:401509 fake_encoder_.BlockNextEncode();
perkja49cbd32016-09-16 14:53:411510 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
sprang4847ae62017-06-27 14:06:521511 WaitForEncodedFrame(1);
perkj26091b12016-09-01 08:17:401512 // Here, the encoder thread will be blocked in the TestEncoder waiting for a
1513 // call to ContinueEncode.
perkja49cbd32016-09-16 14:53:411514 video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
1515 video_source_.IncomingCapturedFrame(CreateFrame(3, nullptr));
perkj26091b12016-09-01 08:17:401516 fake_encoder_.ContinueEncode();
sprang4847ae62017-06-27 14:06:521517 WaitForEncodedFrame(3);
perkj26091b12016-09-01 08:17:401518
mflodmancc3d4422017-08-03 15:27:511519 video_stream_encoder_->Stop();
Tomas Gunnarsson612445e2020-09-21 12:31:231520
1521 EXPECT_EQ(1, dropped_count);
perkj26091b12016-09-01 08:17:401522}
1523
Noah Richards51db4212019-06-12 13:59:121524TEST_F(VideoStreamEncoderTest, DropFrameWithFailedI420Conversion) {
Henrik Boström381d1092020-05-12 16:49:071525 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:071526 DataRate::BitsPerSec(kTargetBitrateBps),
1527 DataRate::BitsPerSec(kTargetBitrateBps),
1528 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Noah Richards51db4212019-06-12 13:59:121529
1530 rtc::Event frame_destroyed_event;
1531 video_source_.IncomingCapturedFrame(
1532 CreateFakeNativeFrame(1, &frame_destroyed_event));
1533 ExpectDroppedFrame();
1534 EXPECT_TRUE(frame_destroyed_event.Wait(kDefaultTimeoutMs));
1535 video_stream_encoder_->Stop();
1536}
1537
1538TEST_F(VideoStreamEncoderTest, DropFrameWithFailedI420ConversionWithCrop) {
1539 // Use the cropping factory.
1540 video_encoder_config_.video_stream_factory =
Åsa Persson17b29b92020-10-17 10:57:581541 new rtc::RefCountedObject<CroppingVideoStreamFactory>();
Noah Richards51db4212019-06-12 13:59:121542 video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config_),
1543 kMaxPayloadLength);
1544 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
1545
1546 // Capture a frame at codec_width_/codec_height_.
Henrik Boström381d1092020-05-12 16:49:071547 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:071548 DataRate::BitsPerSec(kTargetBitrateBps),
1549 DataRate::BitsPerSec(kTargetBitrateBps),
1550 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Noah Richards51db4212019-06-12 13:59:121551 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
1552 WaitForEncodedFrame(1);
1553 // The encoder will have been configured once.
1554 EXPECT_EQ(1, sink_.number_of_reconfigurations());
1555 EXPECT_EQ(codec_width_, fake_encoder_.codec_config().width);
1556 EXPECT_EQ(codec_height_, fake_encoder_.codec_config().height);
1557
1558 // Now send in a fake frame that needs to be cropped as the width/height
1559 // aren't divisible by 4 (see CreateEncoderStreams above).
1560 rtc::Event frame_destroyed_event;
1561 video_source_.IncomingCapturedFrame(CreateFakeNativeFrame(
1562 2, &frame_destroyed_event, codec_width_ + 1, codec_height_ + 1));
1563 ExpectDroppedFrame();
1564 EXPECT_TRUE(frame_destroyed_event.Wait(kDefaultTimeoutMs));
1565 video_stream_encoder_->Stop();
1566}
1567
Evan Shrubsole895556e2020-10-05 07:15:131568TEST_F(VideoStreamEncoderTest, NonI420FramesShouldNotBeConvertedToI420) {
1569 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
1570 DataRate::BitsPerSec(kTargetBitrateBps),
1571 DataRate::BitsPerSec(kTargetBitrateBps),
1572 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
1573
1574 video_source_.IncomingCapturedFrame(
1575 CreateNV12Frame(1, codec_width_, codec_height_));
1576 WaitForEncodedFrame(1);
1577 EXPECT_EQ(VideoFrameBuffer::Type::kNV12,
1578 fake_encoder_.GetLastInputPixelFormat());
1579 video_stream_encoder_->Stop();
1580}
1581
Evan Shrubsoleb556b082020-10-08 12:56:451582TEST_F(VideoStreamEncoderTest,
1583 NativeFrameIsConvertedToI420IfNoFrameTypePreference) {
1584 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
1585 DataRate::BitsPerSec(kTargetBitrateBps),
1586 DataRate::BitsPerSec(kTargetBitrateBps),
1587 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
1588
1589 fake_encoder_.SetPreferredPixelFormats({});
1590
1591 rtc::Event frame_destroyed_event;
1592 video_source_.IncomingCapturedFrame(CreateFakeNV12NativeFrame(
1593 1, &frame_destroyed_event, codec_width_, codec_height_));
1594 WaitForEncodedFrame(1);
1595 EXPECT_EQ(VideoFrameBuffer::Type::kI420,
1596 fake_encoder_.GetLastInputPixelFormat());
1597 video_stream_encoder_->Stop();
1598}
1599
1600TEST_F(VideoStreamEncoderTest, NativeFrameMappedToPreferredPixelFormat) {
1601 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
1602 DataRate::BitsPerSec(kTargetBitrateBps),
1603 DataRate::BitsPerSec(kTargetBitrateBps),
1604 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
1605
1606 fake_encoder_.SetPreferredPixelFormats({VideoFrameBuffer::Type::kNV12});
1607
1608 rtc::Event frame_destroyed_event;
1609 video_source_.IncomingCapturedFrame(CreateFakeNV12NativeFrame(
1610 1, &frame_destroyed_event, codec_width_, codec_height_));
1611 WaitForEncodedFrame(1);
1612 EXPECT_EQ(VideoFrameBuffer::Type::kNV12,
1613 fake_encoder_.GetLastInputPixelFormat());
1614 video_stream_encoder_->Stop();
1615}
1616
1617TEST_F(VideoStreamEncoderTest, NativeFrameConvertedToI420IfMappingNotFeasible) {
1618 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
1619 DataRate::BitsPerSec(kTargetBitrateBps),
1620 DataRate::BitsPerSec(kTargetBitrateBps),
1621 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
1622
1623 // Fake NV12 native frame does not allow mapping to I444.
1624 fake_encoder_.SetPreferredPixelFormats({VideoFrameBuffer::Type::kI444});
1625
1626 rtc::Event frame_destroyed_event;
1627 video_source_.IncomingCapturedFrame(CreateFakeNV12NativeFrame(
1628 1, &frame_destroyed_event, codec_width_, codec_height_));
1629 WaitForEncodedFrame(1);
1630 EXPECT_EQ(VideoFrameBuffer::Type::kI420,
1631 fake_encoder_.GetLastInputPixelFormat());
1632 video_stream_encoder_->Stop();
1633}
1634
Evan Shrubsole895556e2020-10-05 07:15:131635TEST_F(VideoStreamEncoderTest, NativeFrameBackedByNV12FrameIsEncodedFromI420) {
1636 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
1637 DataRate::BitsPerSec(kTargetBitrateBps),
1638 DataRate::BitsPerSec(kTargetBitrateBps),
1639 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
1640
1641 rtc::Event frame_destroyed_event;
1642 video_source_.IncomingCapturedFrame(CreateFakeNV12NativeFrame(
1643 1, &frame_destroyed_event, codec_width_, codec_height_));
1644 WaitForEncodedFrame(1);
1645 EXPECT_EQ(VideoFrameBuffer::Type::kI420,
1646 fake_encoder_.GetLastInputPixelFormat());
1647 video_stream_encoder_->Stop();
1648}
1649
Ying Wang9b881ab2020-02-07 13:29:321650TEST_F(VideoStreamEncoderTest, DropsFramesWhenCongestionWindowPushbackSet) {
Henrik Boström381d1092020-05-12 16:49:071651 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:071652 DataRate::BitsPerSec(kTargetBitrateBps),
1653 DataRate::BitsPerSec(kTargetBitrateBps),
1654 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Ying Wang9b881ab2020-02-07 13:29:321655 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
1656 WaitForEncodedFrame(1);
1657
Henrik Boström381d1092020-05-12 16:49:071658 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:071659 DataRate::BitsPerSec(kTargetBitrateBps),
1660 DataRate::BitsPerSec(kTargetBitrateBps),
1661 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0.5);
Ying Wang9b881ab2020-02-07 13:29:321662 // The congestion window pushback is set to 0.5, which will drop 1/2 of
1663 // frames. Adding two frames means that the first frame will be dropped and
1664 // the second frame will be sent to the encoder.
1665 video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
1666 video_source_.IncomingCapturedFrame(CreateFrame(3, nullptr));
1667 WaitForEncodedFrame(3);
1668 video_source_.IncomingCapturedFrame(CreateFrame(4, nullptr));
1669 video_source_.IncomingCapturedFrame(CreateFrame(5, nullptr));
1670 WaitForEncodedFrame(5);
1671 EXPECT_EQ(2u, stats_proxy_->GetStats().frames_dropped_by_congestion_window);
1672 video_stream_encoder_->Stop();
1673}
1674
mflodmancc3d4422017-08-03 15:27:511675TEST_F(VideoStreamEncoderTest,
1676 ConfigureEncoderTriggersOnEncoderConfigurationChanged) {
Henrik Boström381d1092020-05-12 16:49:071677 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:071678 DataRate::BitsPerSec(kTargetBitrateBps),
1679 DataRate::BitsPerSec(kTargetBitrateBps),
1680 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Per21d45d22016-10-30 20:37:571681 EXPECT_EQ(0, sink_.number_of_reconfigurations());
Per512ecb32016-09-23 13:52:061682
1683 // Capture a frame and wait for it to synchronize with the encoder thread.
Perf8c5f2b2016-09-23 14:24:551684 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
sprang4847ae62017-06-27 14:06:521685 WaitForEncodedFrame(1);
Per21d45d22016-10-30 20:37:571686 // The encoder will have been configured once when the first frame is
1687 // received.
1688 EXPECT_EQ(1, sink_.number_of_reconfigurations());
Per512ecb32016-09-23 13:52:061689
1690 VideoEncoderConfig video_encoder_config;
Niels Möller259a4972018-04-05 13:36:511691 test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
Per512ecb32016-09-23 13:52:061692 video_encoder_config.min_transmit_bitrate_bps = 9999;
mflodmancc3d4422017-08-03 15:27:511693 video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config),
Niels Möllerf1338562018-04-26 07:51:471694 kMaxPayloadLength);
Per512ecb32016-09-23 13:52:061695
1696 // Capture a frame and wait for it to synchronize with the encoder thread.
Perf8c5f2b2016-09-23 14:24:551697 video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
sprang4847ae62017-06-27 14:06:521698 WaitForEncodedFrame(2);
Per21d45d22016-10-30 20:37:571699 EXPECT_EQ(2, sink_.number_of_reconfigurations());
perkj3b703ed2016-09-30 06:25:401700 EXPECT_EQ(9999, sink_.last_min_transmit_bitrate());
perkj26105b42016-09-30 05:39:101701
mflodmancc3d4422017-08-03 15:27:511702 video_stream_encoder_->Stop();
perkj26105b42016-09-30 05:39:101703}
1704
mflodmancc3d4422017-08-03 15:27:511705TEST_F(VideoStreamEncoderTest, FrameResolutionChangeReconfigureEncoder) {
Henrik Boström381d1092020-05-12 16:49:071706 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:071707 DataRate::BitsPerSec(kTargetBitrateBps),
1708 DataRate::BitsPerSec(kTargetBitrateBps),
1709 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
perkjfa10b552016-10-03 06:45:261710
1711 // Capture a frame and wait for it to synchronize with the encoder thread.
1712 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
sprang4847ae62017-06-27 14:06:521713 WaitForEncodedFrame(1);
Per21d45d22016-10-30 20:37:571714 // The encoder will have been configured once.
1715 EXPECT_EQ(1, sink_.number_of_reconfigurations());
perkjfa10b552016-10-03 06:45:261716 EXPECT_EQ(codec_width_, fake_encoder_.codec_config().width);
1717 EXPECT_EQ(codec_height_, fake_encoder_.codec_config().height);
1718
1719 codec_width_ *= 2;
1720 codec_height_ *= 2;
1721 // Capture a frame with a higher resolution and wait for it to synchronize
1722 // with the encoder thread.
1723 video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
sprang4847ae62017-06-27 14:06:521724 WaitForEncodedFrame(2);
perkjfa10b552016-10-03 06:45:261725 EXPECT_EQ(codec_width_, fake_encoder_.codec_config().width);
1726 EXPECT_EQ(codec_height_, fake_encoder_.codec_config().height);
Per21d45d22016-10-30 20:37:571727 EXPECT_EQ(2, sink_.number_of_reconfigurations());
perkjfa10b552016-10-03 06:45:261728
mflodmancc3d4422017-08-03 15:27:511729 video_stream_encoder_->Stop();
perkjfa10b552016-10-03 06:45:261730}
1731
Sergey Silkin443b7ee2019-06-28 10:53:071732TEST_F(VideoStreamEncoderTest,
1733 EncoderInstanceDestroyedBeforeAnotherInstanceCreated) {
Henrik Boström381d1092020-05-12 16:49:071734 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:071735 DataRate::BitsPerSec(kTargetBitrateBps),
1736 DataRate::BitsPerSec(kTargetBitrateBps),
1737 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Sergey Silkin443b7ee2019-06-28 10:53:071738
1739 // Capture a frame and wait for it to synchronize with the encoder thread.
1740 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
1741 WaitForEncodedFrame(1);
1742
1743 VideoEncoderConfig video_encoder_config;
1744 test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
1745 // Changing the max payload data length recreates encoder.
1746 video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config),
1747 kMaxPayloadLength / 2);
1748
1749 // Capture a frame and wait for it to synchronize with the encoder thread.
1750 video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
1751 WaitForEncodedFrame(2);
1752 EXPECT_EQ(1, encoder_factory_.GetMaxNumberOfSimultaneousEncoderInstances());
1753
1754 video_stream_encoder_->Stop();
1755}
1756
Sergey Silkin5ee69672019-07-02 12:18:341757TEST_F(VideoStreamEncoderTest, BitrateLimitsChangeReconfigureRateAllocator) {
Henrik Boström381d1092020-05-12 16:49:071758 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:071759 DataRate::BitsPerSec(kTargetBitrateBps),
1760 DataRate::BitsPerSec(kTargetBitrateBps),
1761 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Sergey Silkin5ee69672019-07-02 12:18:341762
1763 VideoEncoderConfig video_encoder_config;
1764 test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
1765 video_encoder_config.max_bitrate_bps = kTargetBitrateBps;
1766 video_stream_encoder_->SetStartBitrate(kStartBitrateBps);
1767 video_stream_encoder_->ConfigureEncoder(video_encoder_config.Copy(),
1768 kMaxPayloadLength);
1769
1770 // Capture a frame and wait for it to synchronize with the encoder thread.
1771 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
1772 WaitForEncodedFrame(1);
1773 // The encoder will have been configured once when the first frame is
1774 // received.
1775 EXPECT_EQ(1, sink_.number_of_reconfigurations());
1776 EXPECT_EQ(kTargetBitrateBps,
1777 bitrate_allocator_factory_.codec_config().maxBitrate * 1000);
1778 EXPECT_EQ(kStartBitrateBps,
1779 bitrate_allocator_factory_.codec_config().startBitrate * 1000);
1780
Sergey Silkin6456e352019-07-08 15:56:401781 test::FillEncoderConfiguration(kVideoCodecVP8, 1,
1782 &video_encoder_config); //???
Sergey Silkin5ee69672019-07-02 12:18:341783 video_encoder_config.max_bitrate_bps = kTargetBitrateBps * 2;
1784 video_stream_encoder_->SetStartBitrate(kStartBitrateBps * 2);
1785 video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config),
1786 kMaxPayloadLength);
1787
1788 // Capture a frame and wait for it to synchronize with the encoder thread.
1789 video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
1790 WaitForEncodedFrame(2);
1791 EXPECT_EQ(2, sink_.number_of_reconfigurations());
1792 // Bitrate limits have changed - rate allocator should be reconfigured,
1793 // encoder should not be reconfigured.
1794 EXPECT_EQ(kTargetBitrateBps * 2,
1795 bitrate_allocator_factory_.codec_config().maxBitrate * 1000);
1796 EXPECT_EQ(kStartBitrateBps * 2,
1797 bitrate_allocator_factory_.codec_config().startBitrate * 1000);
1798 EXPECT_EQ(1, fake_encoder_.GetNumEncoderInitializations());
1799
1800 video_stream_encoder_->Stop();
1801}
1802
Sergey Silkin6456e352019-07-08 15:56:401803TEST_F(VideoStreamEncoderTest,
Sergey Silkincd02eba2020-01-20 13:48:401804 IntersectionOfEncoderAndAppBitrateLimitsUsedWhenBothProvided) {
Henrik Boström381d1092020-05-12 16:49:071805 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:071806 DataRate::BitsPerSec(kTargetBitrateBps),
1807 DataRate::BitsPerSec(kTargetBitrateBps),
1808 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Sergey Silkin6456e352019-07-08 15:56:401809
Sergey Silkincd02eba2020-01-20 13:48:401810 const uint32_t kMinEncBitrateKbps = 100;
1811 const uint32_t kMaxEncBitrateKbps = 1000;
Sergey Silkin6b2cec12019-08-09 14:04:051812 const VideoEncoder::ResolutionBitrateLimits encoder_bitrate_limits(
Sergey Silkincd02eba2020-01-20 13:48:401813 /*frame_size_pixels=*/codec_width_ * codec_height_,
1814 /*min_start_bitrate_bps=*/0,
1815 /*min_bitrate_bps=*/kMinEncBitrateKbps * 1000,
1816 /*max_bitrate_bps=*/kMaxEncBitrateKbps * 1000);
Sergey Silkin6b2cec12019-08-09 14:04:051817 fake_encoder_.SetResolutionBitrateLimits({encoder_bitrate_limits});
1818
Sergey Silkincd02eba2020-01-20 13:48:401819 VideoEncoderConfig video_encoder_config;
1820 test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
1821 video_encoder_config.max_bitrate_bps = (kMaxEncBitrateKbps + 1) * 1000;
1822 video_encoder_config.simulcast_layers[0].min_bitrate_bps =
1823 (kMinEncBitrateKbps + 1) * 1000;
1824 video_stream_encoder_->ConfigureEncoder(video_encoder_config.Copy(),
1825 kMaxPayloadLength);
1826
1827 // When both encoder and app provide bitrate limits, the intersection of
1828 // provided sets should be used.
1829 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
1830 WaitForEncodedFrame(1);
1831 EXPECT_EQ(kMaxEncBitrateKbps,
1832 bitrate_allocator_factory_.codec_config().maxBitrate);
1833 EXPECT_EQ(kMinEncBitrateKbps + 1,
1834 bitrate_allocator_factory_.codec_config().minBitrate);
1835
1836 video_encoder_config.max_bitrate_bps = (kMaxEncBitrateKbps - 1) * 1000;
1837 video_encoder_config.simulcast_layers[0].min_bitrate_bps =
1838 (kMinEncBitrateKbps - 1) * 1000;
1839 video_stream_encoder_->ConfigureEncoder(video_encoder_config.Copy(),
1840 kMaxPayloadLength);
1841 video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
Sergey Silkin6b2cec12019-08-09 14:04:051842 WaitForEncodedFrame(2);
Sergey Silkincd02eba2020-01-20 13:48:401843 EXPECT_EQ(kMaxEncBitrateKbps - 1,
Sergey Silkin6b2cec12019-08-09 14:04:051844 bitrate_allocator_factory_.codec_config().maxBitrate);
Sergey Silkincd02eba2020-01-20 13:48:401845 EXPECT_EQ(kMinEncBitrateKbps,
Sergey Silkin6b2cec12019-08-09 14:04:051846 bitrate_allocator_factory_.codec_config().minBitrate);
1847
Sergey Silkincd02eba2020-01-20 13:48:401848 video_stream_encoder_->Stop();
1849}
1850
1851TEST_F(VideoStreamEncoderTest,
1852 EncoderAndAppLimitsDontIntersectEncoderLimitsIgnored) {
Henrik Boström381d1092020-05-12 16:49:071853 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:071854 DataRate::BitsPerSec(kTargetBitrateBps),
1855 DataRate::BitsPerSec(kTargetBitrateBps),
1856 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Sergey Silkincd02eba2020-01-20 13:48:401857
1858 const uint32_t kMinAppBitrateKbps = 100;
1859 const uint32_t kMaxAppBitrateKbps = 200;
1860 const uint32_t kMinEncBitrateKbps = kMaxAppBitrateKbps + 1;
1861 const uint32_t kMaxEncBitrateKbps = kMaxAppBitrateKbps * 2;
1862 const VideoEncoder::ResolutionBitrateLimits encoder_bitrate_limits(
1863 /*frame_size_pixels=*/codec_width_ * codec_height_,
1864 /*min_start_bitrate_bps=*/0,
1865 /*min_bitrate_bps=*/kMinEncBitrateKbps * 1000,
1866 /*max_bitrate_bps=*/kMaxEncBitrateKbps * 1000);
1867 fake_encoder_.SetResolutionBitrateLimits({encoder_bitrate_limits});
1868
1869 VideoEncoderConfig video_encoder_config;
1870 test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
1871 video_encoder_config.max_bitrate_bps = kMaxAppBitrateKbps * 1000;
1872 video_encoder_config.simulcast_layers[0].min_bitrate_bps =
1873 kMinAppBitrateKbps * 1000;
Sergey Silkin6b2cec12019-08-09 14:04:051874 video_stream_encoder_->ConfigureEncoder(video_encoder_config.Copy(),
1875 kMaxPayloadLength);
Sergey Silkin6b2cec12019-08-09 14:04:051876
Sergey Silkincd02eba2020-01-20 13:48:401877 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
1878 WaitForEncodedFrame(1);
1879 EXPECT_EQ(kMaxAppBitrateKbps,
Sergey Silkin6b2cec12019-08-09 14:04:051880 bitrate_allocator_factory_.codec_config().maxBitrate);
Sergey Silkincd02eba2020-01-20 13:48:401881 EXPECT_EQ(kMinAppBitrateKbps,
Sergey Silkin6b2cec12019-08-09 14:04:051882 bitrate_allocator_factory_.codec_config().minBitrate);
Sergey Silkin6456e352019-07-08 15:56:401883
1884 video_stream_encoder_->Stop();
1885}
1886
1887TEST_F(VideoStreamEncoderTest,
Sergey Silkin6b2cec12019-08-09 14:04:051888 EncoderRecommendedMaxAndMinBitratesUsedForGivenResolution) {
Henrik Boström381d1092020-05-12 16:49:071889 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:071890 DataRate::BitsPerSec(kTargetBitrateBps),
1891 DataRate::BitsPerSec(kTargetBitrateBps),
1892 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Sergey Silkin6456e352019-07-08 15:56:401893
1894 const VideoEncoder::ResolutionBitrateLimits encoder_bitrate_limits_270p(
Sergey Silkin6b2cec12019-08-09 14:04:051895 480 * 270, 34 * 1000, 12 * 1000, 1234 * 1000);
Sergey Silkin6456e352019-07-08 15:56:401896 const VideoEncoder::ResolutionBitrateLimits encoder_bitrate_limits_360p(
Sergey Silkin6b2cec12019-08-09 14:04:051897 640 * 360, 43 * 1000, 21 * 1000, 2345 * 1000);
Sergey Silkin6456e352019-07-08 15:56:401898 fake_encoder_.SetResolutionBitrateLimits(
1899 {encoder_bitrate_limits_270p, encoder_bitrate_limits_360p});
1900
1901 VideoEncoderConfig video_encoder_config;
1902 test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
1903 video_encoder_config.max_bitrate_bps = 0;
1904 video_stream_encoder_->ConfigureEncoder(video_encoder_config.Copy(),
1905 kMaxPayloadLength);
1906
Sergey Silkin6b2cec12019-08-09 14:04:051907 // 270p. The bitrate limits recommended by encoder for 270p should be used.
Sergey Silkin6456e352019-07-08 15:56:401908 video_source_.IncomingCapturedFrame(CreateFrame(1, 480, 270));
1909 WaitForEncodedFrame(1);
Sergey Silkin6b2cec12019-08-09 14:04:051910 EXPECT_EQ(static_cast<uint32_t>(encoder_bitrate_limits_270p.min_bitrate_bps),
1911 bitrate_allocator_factory_.codec_config().minBitrate * 1000);
Sergey Silkin6456e352019-07-08 15:56:401912 EXPECT_EQ(static_cast<uint32_t>(encoder_bitrate_limits_270p.max_bitrate_bps),
1913 bitrate_allocator_factory_.codec_config().maxBitrate * 1000);
1914
Sergey Silkin6b2cec12019-08-09 14:04:051915 // 360p. The bitrate limits recommended by encoder for 360p should be used.
Sergey Silkin6456e352019-07-08 15:56:401916 video_source_.IncomingCapturedFrame(CreateFrame(2, 640, 360));
1917 WaitForEncodedFrame(2);
Sergey Silkin6b2cec12019-08-09 14:04:051918 EXPECT_EQ(static_cast<uint32_t>(encoder_bitrate_limits_360p.min_bitrate_bps),
1919 bitrate_allocator_factory_.codec_config().minBitrate * 1000);
Sergey Silkin6456e352019-07-08 15:56:401920 EXPECT_EQ(static_cast<uint32_t>(encoder_bitrate_limits_360p.max_bitrate_bps),
1921 bitrate_allocator_factory_.codec_config().maxBitrate * 1000);
1922
Sergey Silkin6b2cec12019-08-09 14:04:051923 // Resolution between 270p and 360p. The bitrate limits recommended by
Sergey Silkin6456e352019-07-08 15:56:401924 // encoder for 360p should be used.
1925 video_source_.IncomingCapturedFrame(
1926 CreateFrame(3, (640 + 480) / 2, (360 + 270) / 2));
1927 WaitForEncodedFrame(3);
Sergey Silkin6b2cec12019-08-09 14:04:051928 EXPECT_EQ(static_cast<uint32_t>(encoder_bitrate_limits_360p.min_bitrate_bps),
1929 bitrate_allocator_factory_.codec_config().minBitrate * 1000);
Sergey Silkin6456e352019-07-08 15:56:401930 EXPECT_EQ(static_cast<uint32_t>(encoder_bitrate_limits_360p.max_bitrate_bps),
1931 bitrate_allocator_factory_.codec_config().maxBitrate * 1000);
1932
Sergey Silkin6b2cec12019-08-09 14:04:051933 // Resolution higher than 360p. The caps recommended by encoder should be
Sergey Silkin6456e352019-07-08 15:56:401934 // ignored.
1935 video_source_.IncomingCapturedFrame(CreateFrame(4, 960, 540));
1936 WaitForEncodedFrame(4);
Sergey Silkin6b2cec12019-08-09 14:04:051937 EXPECT_NE(static_cast<uint32_t>(encoder_bitrate_limits_270p.min_bitrate_bps),
1938 bitrate_allocator_factory_.codec_config().minBitrate * 1000);
Sergey Silkin6456e352019-07-08 15:56:401939 EXPECT_NE(static_cast<uint32_t>(encoder_bitrate_limits_270p.max_bitrate_bps),
1940 bitrate_allocator_factory_.codec_config().maxBitrate * 1000);
Sergey Silkin6b2cec12019-08-09 14:04:051941 EXPECT_NE(static_cast<uint32_t>(encoder_bitrate_limits_360p.min_bitrate_bps),
1942 bitrate_allocator_factory_.codec_config().minBitrate * 1000);
Sergey Silkin6456e352019-07-08 15:56:401943 EXPECT_NE(static_cast<uint32_t>(encoder_bitrate_limits_360p.max_bitrate_bps),
1944 bitrate_allocator_factory_.codec_config().maxBitrate * 1000);
1945
1946 // Resolution lower than 270p. The max bitrate limit recommended by encoder
1947 // for 270p should be used.
1948 video_source_.IncomingCapturedFrame(CreateFrame(5, 320, 180));
1949 WaitForEncodedFrame(5);
Sergey Silkin6b2cec12019-08-09 14:04:051950 EXPECT_EQ(static_cast<uint32_t>(encoder_bitrate_limits_270p.min_bitrate_bps),
1951 bitrate_allocator_factory_.codec_config().minBitrate * 1000);
Sergey Silkin6456e352019-07-08 15:56:401952 EXPECT_EQ(static_cast<uint32_t>(encoder_bitrate_limits_270p.max_bitrate_bps),
1953 bitrate_allocator_factory_.codec_config().maxBitrate * 1000);
1954
1955 video_stream_encoder_->Stop();
1956}
1957
Sergey Silkin6b2cec12019-08-09 14:04:051958TEST_F(VideoStreamEncoderTest, EncoderRecommendedMaxBitrateCapsTargetBitrate) {
Henrik Boström381d1092020-05-12 16:49:071959 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:071960 DataRate::BitsPerSec(kTargetBitrateBps),
1961 DataRate::BitsPerSec(kTargetBitrateBps),
1962 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Sergey Silkin6b2cec12019-08-09 14:04:051963
1964 VideoEncoderConfig video_encoder_config;
1965 test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
1966 video_encoder_config.max_bitrate_bps = 0;
1967 video_stream_encoder_->ConfigureEncoder(video_encoder_config.Copy(),
1968 kMaxPayloadLength);
1969
1970 // Encode 720p frame to get the default encoder target bitrate.
1971 video_source_.IncomingCapturedFrame(CreateFrame(1, 1280, 720));
1972 WaitForEncodedFrame(1);
1973 const uint32_t kDefaultTargetBitrateFor720pKbps =
1974 bitrate_allocator_factory_.codec_config()
1975 .simulcastStream[0]
1976 .targetBitrate;
1977
1978 // Set the max recommended encoder bitrate to something lower than the default
1979 // target bitrate.
1980 const VideoEncoder::ResolutionBitrateLimits encoder_bitrate_limits(
1981 1280 * 720, 10 * 1000, 10 * 1000,
1982 kDefaultTargetBitrateFor720pKbps / 2 * 1000);
1983 fake_encoder_.SetResolutionBitrateLimits({encoder_bitrate_limits});
1984
1985 // Change resolution to trigger encoder reinitialization.
1986 video_source_.IncomingCapturedFrame(CreateFrame(2, 640, 360));
1987 WaitForEncodedFrame(2);
1988 video_source_.IncomingCapturedFrame(CreateFrame(3, 1280, 720));
1989 WaitForEncodedFrame(3);
1990
1991 // Ensure the target bitrate is capped by the max bitrate.
1992 EXPECT_EQ(bitrate_allocator_factory_.codec_config().maxBitrate * 1000,
1993 static_cast<uint32_t>(encoder_bitrate_limits.max_bitrate_bps));
1994 EXPECT_EQ(bitrate_allocator_factory_.codec_config()
1995 .simulcastStream[0]
1996 .targetBitrate *
1997 1000,
1998 static_cast<uint32_t>(encoder_bitrate_limits.max_bitrate_bps));
1999
2000 video_stream_encoder_->Stop();
2001}
2002
mflodmancc3d4422017-08-03 15:27:512003TEST_F(VideoStreamEncoderTest, SwitchSourceDeregisterEncoderAsSink) {
perkj803d97f2016-11-01 18:45:462004 EXPECT_TRUE(video_source_.has_sinks());
2005 test::FrameForwarder new_video_source;
mflodmancc3d4422017-08-03 15:27:512006 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 21:20:412007 &new_video_source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
perkj803d97f2016-11-01 18:45:462008 EXPECT_FALSE(video_source_.has_sinks());
2009 EXPECT_TRUE(new_video_source.has_sinks());
2010
mflodmancc3d4422017-08-03 15:27:512011 video_stream_encoder_->Stop();
perkj803d97f2016-11-01 18:45:462012}
2013
mflodmancc3d4422017-08-03 15:27:512014TEST_F(VideoStreamEncoderTest, SinkWantsRotationApplied) {
perkj803d97f2016-11-01 18:45:462015 EXPECT_FALSE(video_source_.sink_wants().rotation_applied);
mflodmancc3d4422017-08-03 15:27:512016 video_stream_encoder_->SetSink(&sink_, true /*rotation_applied*/);
perkj803d97f2016-11-01 18:45:462017 EXPECT_TRUE(video_source_.sink_wants().rotation_applied);
mflodmancc3d4422017-08-03 15:27:512018 video_stream_encoder_->Stop();
perkj803d97f2016-11-01 18:45:462019}
2020
Åsa Perssonc5a74ff2020-09-20 15:50:002021class ResolutionAlignmentTest
2022 : public VideoStreamEncoderTest,
2023 public ::testing::WithParamInterface<
2024 ::testing::tuple<int, std::vector<double>>> {
2025 public:
2026 ResolutionAlignmentTest()
2027 : requested_alignment_(::testing::get<0>(GetParam())),
2028 scale_factors_(::testing::get<1>(GetParam())) {}
2029
2030 protected:
2031 const int requested_alignment_;
2032 const std::vector<double> scale_factors_;
2033};
2034
2035INSTANTIATE_TEST_SUITE_P(
2036 AlignmentAndScaleFactors,
2037 ResolutionAlignmentTest,
2038 ::testing::Combine(
2039 ::testing::Values(1, 2, 3, 4, 5, 6, 16, 22), // requested_alignment_
2040 ::testing::Values(std::vector<double>{-1.0}, // scale_factors_
2041 std::vector<double>{-1.0, -1.0},
2042 std::vector<double>{-1.0, -1.0, -1.0},
2043 std::vector<double>{4.0, 2.0, 1.0},
2044 std::vector<double>{9999.0, -1.0, 1.0},
2045 std::vector<double>{3.99, 2.01, 1.0},
2046 std::vector<double>{4.9, 1.7, 1.25},
2047 std::vector<double>{10.0, 4.0, 3.0},
2048 std::vector<double>{1.75, 3.5},
2049 std::vector<double>{1.5, 2.5},
2050 std::vector<double>{1.3, 1.0})));
2051
2052TEST_P(ResolutionAlignmentTest, SinkWantsAlignmentApplied) {
2053 // Set requested resolution alignment.
Rasmus Brandt5cad55b2019-12-19 08:47:112054 video_source_.set_adaptation_enabled(true);
Åsa Perssonc5a74ff2020-09-20 15:50:002055 fake_encoder_.SetRequestedResolutionAlignment(requested_alignment_);
2056 fake_encoder_.SetApplyAlignmentToAllSimulcastLayers(true);
2057
2058 // Fill config with the scaling factor by which to reduce encoding size.
2059 const int num_streams = scale_factors_.size();
2060 VideoEncoderConfig config;
2061 test::FillEncoderConfiguration(kVideoCodecVP8, num_streams, &config);
2062 for (int i = 0; i < num_streams; ++i) {
2063 config.simulcast_layers[i].scale_resolution_down_by = scale_factors_[i];
2064 }
2065 config.video_stream_factory =
2066 new rtc::RefCountedObject<cricket::EncoderStreamFactory>(
2067 "VP8", /*max qp*/ 56, /*screencast*/ false,
2068 /*screenshare enabled*/ false);
2069 video_stream_encoder_->ConfigureEncoder(std::move(config), kMaxPayloadLength);
2070
Henrik Boström381d1092020-05-12 16:49:072071 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Åsa Perssonc5a74ff2020-09-20 15:50:002072 DataRate::BitsPerSec(kSimulcastTargetBitrateBps),
2073 DataRate::BitsPerSec(kSimulcastTargetBitrateBps),
2074 DataRate::BitsPerSec(kSimulcastTargetBitrateBps), 0, 0, 0);
2075 // Wait for all layers before triggering event.
2076 sink_.SetNumExpectedLayers(num_streams);
Rasmus Brandt5cad55b2019-12-19 08:47:112077
2078 // On the 1st frame, we should have initialized the encoder and
2079 // asked for its resolution requirements.
Åsa Perssonc5a74ff2020-09-20 15:50:002080 int64_t timestamp_ms = kFrameIntervalMs;
2081 video_source_.IncomingCapturedFrame(CreateFrame(timestamp_ms, 1280, 720));
2082 WaitForEncodedFrame(timestamp_ms);
2083 EXPECT_EQ(1, fake_encoder_.GetNumEncoderInitializations());
Rasmus Brandt5cad55b2019-12-19 08:47:112084
2085 // On the 2nd frame, we should be receiving a correctly aligned resolution.
2086 // (It's up the to the encoder to potentially drop the previous frame,
2087 // to avoid coding back-to-back keyframes.)
Åsa Perssonc5a74ff2020-09-20 15:50:002088 timestamp_ms += kFrameIntervalMs;
2089 video_source_.IncomingCapturedFrame(CreateFrame(timestamp_ms, 1280, 720));
2090 WaitForEncodedFrame(timestamp_ms);
2091 EXPECT_GE(fake_encoder_.GetNumEncoderInitializations(), 1);
2092
2093 VideoCodec codec = fake_encoder_.video_codec();
2094 EXPECT_EQ(codec.numberOfSimulcastStreams, num_streams);
2095 // Frame size should be a multiple of the requested alignment.
2096 for (int i = 0; i < codec.numberOfSimulcastStreams; ++i) {
2097 EXPECT_EQ(codec.simulcastStream[i].width % requested_alignment_, 0);
2098 EXPECT_EQ(codec.simulcastStream[i].height % requested_alignment_, 0);
2099 // Aspect ratio should match.
2100 EXPECT_EQ(codec.width * codec.simulcastStream[i].height,
2101 codec.height * codec.simulcastStream[i].width);
2102 }
Rasmus Brandt5cad55b2019-12-19 08:47:112103
2104 video_stream_encoder_->Stop();
2105}
2106
Jonathan Yubc771b72017-12-09 01:04:292107TEST_F(VideoStreamEncoderTest, TestCpuDowngrades_BalancedMode) {
2108 const int kFramerateFps = 30;
asaperssonf7e294d2017-06-14 06:25:222109 const int kWidth = 1280;
2110 const int kHeight = 720;
Jonathan Yubc771b72017-12-09 01:04:292111
2112 // We rely on the automatic resolution adaptation, but we handle framerate
2113 // adaptation manually by mocking the stats proxy.
2114 video_source_.set_adaptation_enabled(true);
asaperssonf7e294d2017-06-14 06:25:222115
Taylor Brandstetter49fcc102018-05-16 21:20:412116 // Enable BALANCED preference, no initial limitation.
Henrik Boström381d1092020-05-12 16:49:072117 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:072118 DataRate::BitsPerSec(kTargetBitrateBps),
2119 DataRate::BitsPerSec(kTargetBitrateBps),
2120 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Taylor Brandstetter49fcc102018-05-16 21:20:412121 video_stream_encoder_->SetSource(&video_source_,
2122 webrtc::DegradationPreference::BALANCED);
Evan Shrubsole5cd7eb82020-05-25 12:08:392123 EXPECT_THAT(video_source_.sink_wants(), UnlimitedSinkWants());
asaperssonf7e294d2017-06-14 06:25:222124 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
Jonathan Yubc771b72017-12-09 01:04:292125 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
asaperssonf7e294d2017-06-14 06:25:222126 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
2127
Jonathan Yubc771b72017-12-09 01:04:292128 // Adapt down as far as possible.
2129 rtc::VideoSinkWants last_wants;
2130 int64_t t = 1;
2131 int loop_count = 0;
2132 do {
2133 ++loop_count;
2134 last_wants = video_source_.sink_wants();
2135
2136 // Simulate the framerate we've been asked to adapt to.
2137 const int fps = std::min(kFramerateFps, last_wants.max_framerate_fps);
2138 const int frame_interval_ms = rtc::kNumMillisecsPerSec / fps;
2139 VideoSendStream::Stats mock_stats = stats_proxy_->GetStats();
2140 mock_stats.input_frame_rate = fps;
2141 stats_proxy_->SetMockStats(mock_stats);
2142
2143 video_source_.IncomingCapturedFrame(CreateFrame(t, kWidth, kHeight));
2144 sink_.WaitForEncodedFrame(t);
2145 t += frame_interval_ms;
2146
mflodmancc3d4422017-08-03 15:27:512147 video_stream_encoder_->TriggerCpuOveruse();
Evan Shrubsole5cd7eb82020-05-25 12:08:392148 EXPECT_THAT(
Jonathan Yubc771b72017-12-09 01:04:292149 video_source_.sink_wants(),
Evan Shrubsole5cd7eb82020-05-25 12:08:392150 FpsInRangeForPixelsInBalanced(*video_source_.last_sent_width() *
2151 *video_source_.last_sent_height()));
Jonathan Yubc771b72017-12-09 01:04:292152 } while (video_source_.sink_wants().max_pixel_count <
2153 last_wants.max_pixel_count ||
2154 video_source_.sink_wants().max_framerate_fps <
2155 last_wants.max_framerate_fps);
asaperssonf7e294d2017-06-14 06:25:222156
Jonathan Yubc771b72017-12-09 01:04:292157 // Verify that we've adapted all the way down.
2158 stats_proxy_->ResetMockStats();
asaperssonf7e294d2017-06-14 06:25:222159 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
Jonathan Yubc771b72017-12-09 01:04:292160 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_framerate);
2161 EXPECT_EQ(loop_count - 1,
asaperssonf7e294d2017-06-14 06:25:222162 stats_proxy_->GetStats().number_of_cpu_adapt_changes);
Jonathan Yubc771b72017-12-09 01:04:292163 EXPECT_EQ(kMinPixelsPerFrame, *video_source_.last_sent_width() *
2164 *video_source_.last_sent_height());
2165 EXPECT_EQ(kMinBalancedFramerateFps,
2166 video_source_.sink_wants().max_framerate_fps);
asaperssonf7e294d2017-06-14 06:25:222167
Jonathan Yubc771b72017-12-09 01:04:292168 // Adapt back up the same number of times we adapted down.
2169 for (int i = 0; i < loop_count - 1; ++i) {
2170 last_wants = video_source_.sink_wants();
2171
2172 // Simulate the framerate we've been asked to adapt to.
2173 const int fps = std::min(kFramerateFps, last_wants.max_framerate_fps);
2174 const int frame_interval_ms = rtc::kNumMillisecsPerSec / fps;
2175 VideoSendStream::Stats mock_stats = stats_proxy_->GetStats();
2176 mock_stats.input_frame_rate = fps;
2177 stats_proxy_->SetMockStats(mock_stats);
2178
2179 video_source_.IncomingCapturedFrame(CreateFrame(t, kWidth, kHeight));
2180 sink_.WaitForEncodedFrame(t);
2181 t += frame_interval_ms;
2182
Henrik Boström91aa7322020-04-28 10:24:332183 video_stream_encoder_->TriggerCpuUnderuse();
Evan Shrubsole5cd7eb82020-05-25 12:08:392184 EXPECT_THAT(
Jonathan Yubc771b72017-12-09 01:04:292185 video_source_.sink_wants(),
Evan Shrubsole5cd7eb82020-05-25 12:08:392186 FpsInRangeForPixelsInBalanced(*video_source_.last_sent_width() *
2187 *video_source_.last_sent_height()));
Jonathan Yubc771b72017-12-09 01:04:292188 EXPECT_TRUE(video_source_.sink_wants().max_pixel_count >
2189 last_wants.max_pixel_count ||
2190 video_source_.sink_wants().max_framerate_fps >
2191 last_wants.max_framerate_fps);
asaperssonf7e294d2017-06-14 06:25:222192 }
2193
Evan Shrubsole5cd7eb82020-05-25 12:08:392194 EXPECT_THAT(video_source_.sink_wants(), FpsMaxResolutionMax());
Jonathan Yubc771b72017-12-09 01:04:292195 stats_proxy_->ResetMockStats();
asaperssonf7e294d2017-06-14 06:25:222196 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
Jonathan Yubc771b72017-12-09 01:04:292197 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
2198 EXPECT_EQ((loop_count - 1) * 2,
2199 stats_proxy_->GetStats().number_of_cpu_adapt_changes);
asaperssonf7e294d2017-06-14 06:25:222200
mflodmancc3d4422017-08-03 15:27:512201 video_stream_encoder_->Stop();
asaperssonf7e294d2017-06-14 06:25:222202}
Rasmus Brandt5cad55b2019-12-19 08:47:112203
Evan Shrubsole2e2f6742020-05-14 08:41:152204TEST_F(VideoStreamEncoderTest,
2205 SinkWantsNotChangedByResourceLimitedBeforeDegradationPreferenceChange) {
2206 video_stream_encoder_->OnBitrateUpdated(
2207 DataRate::BitsPerSec(kTargetBitrateBps),
2208 DataRate::BitsPerSec(kTargetBitrateBps),
2209 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Evan Shrubsole5cd7eb82020-05-25 12:08:392210 EXPECT_THAT(video_source_.sink_wants(), UnlimitedSinkWants());
Evan Shrubsole2e2f6742020-05-14 08:41:152211
2212 const int kFrameWidth = 1280;
2213 const int kFrameHeight = 720;
2214
2215 int64_t ntp_time = kFrameIntervalMs;
2216
2217 // Force an input frame rate to be available, or the adaptation call won't
2218 // know what framerate to adapt form.
2219 const int kInputFps = 30;
2220 VideoSendStream::Stats stats = stats_proxy_->GetStats();
2221 stats.input_frame_rate = kInputFps;
2222 stats_proxy_->SetMockStats(stats);
2223
2224 video_source_.set_adaptation_enabled(true);
2225 video_stream_encoder_->SetSource(
2226 &video_source_, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
Evan Shrubsole5cd7eb82020-05-25 12:08:392227 EXPECT_THAT(video_source_.sink_wants(), UnlimitedSinkWants());
Evan Shrubsole2e2f6742020-05-14 08:41:152228 video_source_.IncomingCapturedFrame(
2229 CreateFrame(ntp_time, kFrameWidth, kFrameHeight));
2230 sink_.WaitForEncodedFrame(ntp_time);
2231 ntp_time += kFrameIntervalMs;
2232
2233 // Trigger CPU overuse.
2234 video_stream_encoder_->TriggerCpuOveruse();
2235 video_source_.IncomingCapturedFrame(
2236 CreateFrame(ntp_time, kFrameWidth, kFrameHeight));
2237 sink_.WaitForEncodedFrame(ntp_time);
2238 ntp_time += kFrameIntervalMs;
2239
2240 EXPECT_FALSE(video_source_.sink_wants().target_pixel_count);
2241 EXPECT_EQ(std::numeric_limits<int>::max(),
2242 video_source_.sink_wants().max_pixel_count);
2243 // Some framerate constraint should be set.
2244 int restricted_fps = video_source_.sink_wants().max_framerate_fps;
2245 EXPECT_LT(restricted_fps, kInputFps);
2246 video_source_.IncomingCapturedFrame(
2247 CreateFrame(ntp_time, kFrameWidth, kFrameHeight));
2248 sink_.WaitForEncodedFrame(ntp_time);
2249 ntp_time += 100;
2250
Henrik Boström2671dac2020-05-19 14:29:092251 video_stream_encoder_->SetSourceAndWaitForRestrictionsUpdated(
Evan Shrubsole2e2f6742020-05-14 08:41:152252 &video_source_, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
2253 // Give the encoder queue time to process the change in degradation preference
2254 // by waiting for an encoded frame.
2255 video_source_.IncomingCapturedFrame(
2256 CreateFrame(ntp_time, kFrameWidth, kFrameHeight));
2257 sink_.WaitForEncodedFrame(ntp_time);
2258 ntp_time += kFrameIntervalMs;
2259
2260 video_stream_encoder_->TriggerQualityLow();
2261 video_source_.IncomingCapturedFrame(
2262 CreateFrame(ntp_time, kFrameWidth, kFrameHeight));
2263 sink_.WaitForEncodedFrame(ntp_time);
2264 ntp_time += kFrameIntervalMs;
2265
2266 // Some resolution constraint should be set.
2267 EXPECT_FALSE(video_source_.sink_wants().target_pixel_count);
2268 EXPECT_LT(video_source_.sink_wants().max_pixel_count,
2269 kFrameWidth * kFrameHeight);
2270 EXPECT_EQ(video_source_.sink_wants().max_framerate_fps, kInputFps);
2271
2272 int pixel_count = video_source_.sink_wants().max_pixel_count;
2273 // Triggering a CPU underuse should not change the sink wants since it has
2274 // not been overused for resolution since we changed degradation preference.
2275 video_stream_encoder_->TriggerCpuUnderuse();
2276 video_source_.IncomingCapturedFrame(
2277 CreateFrame(ntp_time, kFrameWidth, kFrameHeight));
2278 sink_.WaitForEncodedFrame(ntp_time);
2279 ntp_time += kFrameIntervalMs;
2280 EXPECT_EQ(video_source_.sink_wants().max_pixel_count, pixel_count);
2281 EXPECT_EQ(video_source_.sink_wants().max_framerate_fps, kInputFps);
2282
Evan Shrubsole64469032020-06-11 08:45:292283 // Change the degradation preference back. CPU underuse should not adapt since
2284 // QP is most limited.
Henrik Boström2671dac2020-05-19 14:29:092285 video_stream_encoder_->SetSourceAndWaitForRestrictionsUpdated(
Evan Shrubsole2e2f6742020-05-14 08:41:152286 &video_source_, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
2287 video_source_.IncomingCapturedFrame(
2288 CreateFrame(ntp_time, kFrameWidth, kFrameHeight));
2289 sink_.WaitForEncodedFrame(ntp_time);
2290 ntp_time += 100;
2291 // Resolution adaptations is gone after changing degradation preference.
2292 EXPECT_FALSE(video_source_.sink_wants().target_pixel_count);
2293 EXPECT_EQ(std::numeric_limits<int>::max(),
2294 video_source_.sink_wants().max_pixel_count);
2295 // The fps adaptation from above is now back.
2296 EXPECT_EQ(video_source_.sink_wants().max_framerate_fps, restricted_fps);
2297
2298 // Trigger CPU underuse.
2299 video_stream_encoder_->TriggerCpuUnderuse();
2300 video_source_.IncomingCapturedFrame(
2301 CreateFrame(ntp_time, kFrameWidth, kFrameHeight));
2302 sink_.WaitForEncodedFrame(ntp_time);
2303 ntp_time += kFrameIntervalMs;
Evan Shrubsole64469032020-06-11 08:45:292304 EXPECT_EQ(video_source_.sink_wants().max_framerate_fps, restricted_fps);
2305
2306 // Trigger QP underuse, fps should return to normal.
2307 video_stream_encoder_->TriggerQualityHigh();
2308 video_source_.IncomingCapturedFrame(
2309 CreateFrame(ntp_time, kFrameWidth, kFrameHeight));
2310 sink_.WaitForEncodedFrame(ntp_time);
2311 ntp_time += kFrameIntervalMs;
2312 EXPECT_THAT(video_source_.sink_wants(), FpsMax());
Evan Shrubsole2e2f6742020-05-14 08:41:152313
2314 video_stream_encoder_->Stop();
2315}
2316
mflodmancc3d4422017-08-03 15:27:512317TEST_F(VideoStreamEncoderTest, SinkWantsStoredByDegradationPreference) {
Henrik Boström381d1092020-05-12 16:49:072318 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:072319 DataRate::BitsPerSec(kTargetBitrateBps),
2320 DataRate::BitsPerSec(kTargetBitrateBps),
2321 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Evan Shrubsole5cd7eb82020-05-25 12:08:392322 EXPECT_THAT(video_source_.sink_wants(), UnlimitedSinkWants());
perkj803d97f2016-11-01 18:45:462323
sprangc5d62e22017-04-03 06:53:042324 const int kFrameWidth = 1280;
2325 const int kFrameHeight = 720;
sprangc5d62e22017-04-03 06:53:042326
Åsa Persson8c1bf952018-09-13 08:42:192327 int64_t frame_timestamp = 1;
perkj803d97f2016-11-01 18:45:462328
kthelgason5e13d412016-12-01 11:59:512329 video_source_.IncomingCapturedFrame(
sprangc5d62e22017-04-03 06:53:042330 CreateFrame(frame_timestamp, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 14:06:522331 WaitForEncodedFrame(frame_timestamp);
sprangc5d62e22017-04-03 06:53:042332 frame_timestamp += kFrameIntervalMs;
2333
perkj803d97f2016-11-01 18:45:462334 // Trigger CPU overuse.
mflodmancc3d4422017-08-03 15:27:512335 video_stream_encoder_->TriggerCpuOveruse();
perkj803d97f2016-11-01 18:45:462336 video_source_.IncomingCapturedFrame(
sprangc5d62e22017-04-03 06:53:042337 CreateFrame(frame_timestamp, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 14:06:522338 WaitForEncodedFrame(frame_timestamp);
sprangc5d62e22017-04-03 06:53:042339 frame_timestamp += kFrameIntervalMs;
sprang3ea3c772017-03-30 14:23:482340
asapersson0944a802017-04-07 07:57:582341 // Default degradation preference is maintain-framerate, so will lower max
sprangc5d62e22017-04-03 06:53:042342 // wanted resolution.
2343 EXPECT_FALSE(video_source_.sink_wants().target_pixel_count);
2344 EXPECT_LT(video_source_.sink_wants().max_pixel_count,
2345 kFrameWidth * kFrameHeight);
Åsa Persson8c1bf952018-09-13 08:42:192346 EXPECT_EQ(kDefaultFramerate, video_source_.sink_wants().max_framerate_fps);
sprangc5d62e22017-04-03 06:53:042347
2348 // Set new source, switch to maintain-resolution.
perkj803d97f2016-11-01 18:45:462349 test::FrameForwarder new_video_source;
Henrik Boström381d1092020-05-12 16:49:072350 video_stream_encoder_->SetSourceAndWaitForRestrictionsUpdated(
Taylor Brandstetter49fcc102018-05-16 21:20:412351 &new_video_source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
Henrik Boström07b17df2020-01-15 10:42:122352 // Give the encoder queue time to process the change in degradation preference
2353 // by waiting for an encoded frame.
2354 new_video_source.IncomingCapturedFrame(
2355 CreateFrame(frame_timestamp, kFrameWidth, kFrameWidth));
2356 sink_.WaitForEncodedFrame(frame_timestamp);
2357 frame_timestamp += kFrameIntervalMs;
sprangc5d62e22017-04-03 06:53:042358 // Initially no degradation registered.
Evan Shrubsole5cd7eb82020-05-25 12:08:392359 EXPECT_THAT(new_video_source.sink_wants(), FpsMaxResolutionMax());
perkj803d97f2016-11-01 18:45:462360
sprangc5d62e22017-04-03 06:53:042361 // Force an input frame rate to be available, or the adaptation call won't
2362 // know what framerate to adapt form.
asapersson02465b82017-04-10 08:12:522363 const int kInputFps = 30;
sprangc5d62e22017-04-03 06:53:042364 VideoSendStream::Stats stats = stats_proxy_->GetStats();
asapersson02465b82017-04-10 08:12:522365 stats.input_frame_rate = kInputFps;
sprangc5d62e22017-04-03 06:53:042366 stats_proxy_->SetMockStats(stats);
2367
mflodmancc3d4422017-08-03 15:27:512368 video_stream_encoder_->TriggerCpuOveruse();
perkj803d97f2016-11-01 18:45:462369 new_video_source.IncomingCapturedFrame(
sprangc5d62e22017-04-03 06:53:042370 CreateFrame(frame_timestamp, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 14:06:522371 WaitForEncodedFrame(frame_timestamp);
sprangc5d62e22017-04-03 06:53:042372 frame_timestamp += kFrameIntervalMs;
2373
2374 // Some framerate constraint should be set.
sprang84a37592017-02-10 15:04:272375 EXPECT_FALSE(new_video_source.sink_wants().target_pixel_count);
sprangc5d62e22017-04-03 06:53:042376 EXPECT_EQ(std::numeric_limits<int>::max(),
2377 new_video_source.sink_wants().max_pixel_count);
asapersson02465b82017-04-10 08:12:522378 EXPECT_LT(new_video_source.sink_wants().max_framerate_fps, kInputFps);
sprangc5d62e22017-04-03 06:53:042379
asapersson02465b82017-04-10 08:12:522380 // Turn off degradation completely.
Henrik Boström381d1092020-05-12 16:49:072381 video_stream_encoder_->SetSourceAndWaitForRestrictionsUpdated(
2382 &new_video_source, webrtc::DegradationPreference::DISABLED);
Henrik Boström07b17df2020-01-15 10:42:122383 // Give the encoder queue time to process the change in degradation preference
2384 // by waiting for an encoded frame.
2385 new_video_source.IncomingCapturedFrame(
2386 CreateFrame(frame_timestamp, kFrameWidth, kFrameWidth));
2387 sink_.WaitForEncodedFrame(frame_timestamp);
2388 frame_timestamp += kFrameIntervalMs;
Evan Shrubsole5cd7eb82020-05-25 12:08:392389 EXPECT_THAT(new_video_source.sink_wants(), FpsMaxResolutionMax());
sprangc5d62e22017-04-03 06:53:042390
mflodmancc3d4422017-08-03 15:27:512391 video_stream_encoder_->TriggerCpuOveruse();
sprangc5d62e22017-04-03 06:53:042392 new_video_source.IncomingCapturedFrame(
2393 CreateFrame(frame_timestamp, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 14:06:522394 WaitForEncodedFrame(frame_timestamp);
sprangc5d62e22017-04-03 06:53:042395 frame_timestamp += kFrameIntervalMs;
2396
2397 // Still no degradation.
Evan Shrubsole5cd7eb82020-05-25 12:08:392398 EXPECT_THAT(new_video_source.sink_wants(), FpsMaxResolutionMax());
perkj803d97f2016-11-01 18:45:462399
2400 // Calling SetSource with resolution scaling enabled apply the old SinkWants.
Henrik Boström381d1092020-05-12 16:49:072401 video_stream_encoder_->SetSourceAndWaitForRestrictionsUpdated(
Taylor Brandstetter49fcc102018-05-16 21:20:412402 &new_video_source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
Henrik Boström07b17df2020-01-15 10:42:122403 // Give the encoder queue time to process the change in degradation preference
2404 // by waiting for an encoded frame.
2405 new_video_source.IncomingCapturedFrame(
2406 CreateFrame(frame_timestamp, kFrameWidth, kFrameWidth));
2407 sink_.WaitForEncodedFrame(frame_timestamp);
2408 frame_timestamp += kFrameIntervalMs;
sprangc5d62e22017-04-03 06:53:042409 EXPECT_LT(new_video_source.sink_wants().max_pixel_count,
2410 kFrameWidth * kFrameHeight);
sprang84a37592017-02-10 15:04:272411 EXPECT_FALSE(new_video_source.sink_wants().target_pixel_count);
Åsa Persson8c1bf952018-09-13 08:42:192412 EXPECT_EQ(kDefaultFramerate, new_video_source.sink_wants().max_framerate_fps);
sprangc5d62e22017-04-03 06:53:042413
2414 // Calling SetSource with framerate scaling enabled apply the old SinkWants.
Henrik Boström381d1092020-05-12 16:49:072415 video_stream_encoder_->SetSourceAndWaitForRestrictionsUpdated(
Taylor Brandstetter49fcc102018-05-16 21:20:412416 &new_video_source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
Henrik Boström07b17df2020-01-15 10:42:122417 // Give the encoder queue time to process the change in degradation preference
2418 // by waiting for an encoded frame.
2419 new_video_source.IncomingCapturedFrame(
2420 CreateFrame(frame_timestamp, kFrameWidth, kFrameWidth));
2421 sink_.WaitForEncodedFrame(frame_timestamp);
2422 frame_timestamp += kFrameIntervalMs;
sprangc5d62e22017-04-03 06:53:042423 EXPECT_FALSE(new_video_source.sink_wants().target_pixel_count);
2424 EXPECT_EQ(std::numeric_limits<int>::max(),
2425 new_video_source.sink_wants().max_pixel_count);
asapersson02465b82017-04-10 08:12:522426 EXPECT_LT(new_video_source.sink_wants().max_framerate_fps, kInputFps);
perkj803d97f2016-11-01 18:45:462427
mflodmancc3d4422017-08-03 15:27:512428 video_stream_encoder_->Stop();
perkj803d97f2016-11-01 18:45:462429}
2430
mflodmancc3d4422017-08-03 15:27:512431TEST_F(VideoStreamEncoderTest, StatsTracksQualityAdaptationStats) {
Henrik Boström381d1092020-05-12 16:49:072432 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:072433 DataRate::BitsPerSec(kTargetBitrateBps),
2434 DataRate::BitsPerSec(kTargetBitrateBps),
2435 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
perkj803d97f2016-11-01 18:45:462436
asaperssonfab67072017-04-04 12:51:492437 const int kWidth = 1280;
2438 const int kHeight = 720;
asaperssonfab67072017-04-04 12:51:492439 video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:522440 WaitForEncodedFrame(1);
asaperssonfab67072017-04-04 12:51:492441 VideoSendStream::Stats stats = stats_proxy_->GetStats();
2442 EXPECT_FALSE(stats.bw_limited_resolution);
2443 EXPECT_EQ(0, stats.number_of_quality_adapt_changes);
2444
2445 // Trigger adapt down.
mflodmancc3d4422017-08-03 15:27:512446 video_stream_encoder_->TriggerQualityLow();
asaperssonfab67072017-04-04 12:51:492447 video_source_.IncomingCapturedFrame(CreateFrame(2, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:522448 WaitForEncodedFrame(2);
asaperssonfab67072017-04-04 12:51:492449
2450 stats = stats_proxy_->GetStats();
2451 EXPECT_TRUE(stats.bw_limited_resolution);
2452 EXPECT_EQ(1, stats.number_of_quality_adapt_changes);
2453
2454 // Trigger adapt up.
mflodmancc3d4422017-08-03 15:27:512455 video_stream_encoder_->TriggerQualityHigh();
asaperssonfab67072017-04-04 12:51:492456 video_source_.IncomingCapturedFrame(CreateFrame(3, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:522457 WaitForEncodedFrame(3);
asaperssonfab67072017-04-04 12:51:492458
2459 stats = stats_proxy_->GetStats();
2460 EXPECT_FALSE(stats.bw_limited_resolution);
2461 EXPECT_EQ(2, stats.number_of_quality_adapt_changes);
2462 EXPECT_EQ(0, stats.number_of_cpu_adapt_changes);
2463
mflodmancc3d4422017-08-03 15:27:512464 video_stream_encoder_->Stop();
asaperssonfab67072017-04-04 12:51:492465}
2466
mflodmancc3d4422017-08-03 15:27:512467TEST_F(VideoStreamEncoderTest, StatsTracksCpuAdaptationStats) {
Henrik Boström381d1092020-05-12 16:49:072468 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:072469 DataRate::BitsPerSec(kTargetBitrateBps),
2470 DataRate::BitsPerSec(kTargetBitrateBps),
2471 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asaperssonfab67072017-04-04 12:51:492472
2473 const int kWidth = 1280;
2474 const int kHeight = 720;
asaperssonfab67072017-04-04 12:51:492475 video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:522476 WaitForEncodedFrame(1);
perkj803d97f2016-11-01 18:45:462477 VideoSendStream::Stats stats = stats_proxy_->GetStats();
2478 EXPECT_FALSE(stats.cpu_limited_resolution);
2479 EXPECT_EQ(0, stats.number_of_cpu_adapt_changes);
2480
2481 // Trigger CPU overuse.
mflodmancc3d4422017-08-03 15:27:512482 video_stream_encoder_->TriggerCpuOveruse();
asaperssonfab67072017-04-04 12:51:492483 video_source_.IncomingCapturedFrame(CreateFrame(2, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:522484 WaitForEncodedFrame(2);
perkj803d97f2016-11-01 18:45:462485
2486 stats = stats_proxy_->GetStats();
2487 EXPECT_TRUE(stats.cpu_limited_resolution);
2488 EXPECT_EQ(1, stats.number_of_cpu_adapt_changes);
2489
2490 // Trigger CPU normal use.
Henrik Boström91aa7322020-04-28 10:24:332491 video_stream_encoder_->TriggerCpuUnderuse();
asaperssonfab67072017-04-04 12:51:492492 video_source_.IncomingCapturedFrame(CreateFrame(3, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:522493 WaitForEncodedFrame(3);
perkj803d97f2016-11-01 18:45:462494
2495 stats = stats_proxy_->GetStats();
2496 EXPECT_FALSE(stats.cpu_limited_resolution);
2497 EXPECT_EQ(2, stats.number_of_cpu_adapt_changes);
asaperssonfab67072017-04-04 12:51:492498 EXPECT_EQ(0, stats.number_of_quality_adapt_changes);
perkj803d97f2016-11-01 18:45:462499
mflodmancc3d4422017-08-03 15:27:512500 video_stream_encoder_->Stop();
perkj803d97f2016-11-01 18:45:462501}
2502
mflodmancc3d4422017-08-03 15:27:512503TEST_F(VideoStreamEncoderTest, SwitchingSourceKeepsCpuAdaptation) {
Henrik Boström381d1092020-05-12 16:49:072504 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:072505 DataRate::BitsPerSec(kTargetBitrateBps),
2506 DataRate::BitsPerSec(kTargetBitrateBps),
2507 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
kthelgason876222f2016-11-29 09:44:112508
asaperssonfab67072017-04-04 12:51:492509 const int kWidth = 1280;
2510 const int kHeight = 720;
2511 video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:522512 WaitForEncodedFrame(1);
kthelgason876222f2016-11-29 09:44:112513 VideoSendStream::Stats stats = stats_proxy_->GetStats();
asapersson09f05612017-05-16 06:40:182514 EXPECT_FALSE(stats.bw_limited_resolution);
kthelgason876222f2016-11-29 09:44:112515 EXPECT_FALSE(stats.cpu_limited_resolution);
2516 EXPECT_EQ(0, stats.number_of_cpu_adapt_changes);
2517
asaperssonfab67072017-04-04 12:51:492518 // Trigger CPU overuse.
mflodmancc3d4422017-08-03 15:27:512519 video_stream_encoder_->TriggerCpuOveruse();
asaperssonfab67072017-04-04 12:51:492520 video_source_.IncomingCapturedFrame(CreateFrame(2, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:522521 WaitForEncodedFrame(2);
kthelgason876222f2016-11-29 09:44:112522 stats = stats_proxy_->GetStats();
asapersson09f05612017-05-16 06:40:182523 EXPECT_FALSE(stats.bw_limited_resolution);
kthelgason876222f2016-11-29 09:44:112524 EXPECT_TRUE(stats.cpu_limited_resolution);
2525 EXPECT_EQ(1, stats.number_of_cpu_adapt_changes);
2526
2527 // Set new source with adaptation still enabled.
2528 test::FrameForwarder new_video_source;
mflodmancc3d4422017-08-03 15:27:512529 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 21:20:412530 &new_video_source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
kthelgason876222f2016-11-29 09:44:112531
asaperssonfab67072017-04-04 12:51:492532 new_video_source.IncomingCapturedFrame(CreateFrame(3, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:522533 WaitForEncodedFrame(3);
kthelgason876222f2016-11-29 09:44:112534 stats = stats_proxy_->GetStats();
asapersson09f05612017-05-16 06:40:182535 EXPECT_FALSE(stats.bw_limited_resolution);
kthelgason876222f2016-11-29 09:44:112536 EXPECT_TRUE(stats.cpu_limited_resolution);
2537 EXPECT_EQ(1, stats.number_of_cpu_adapt_changes);
2538
2539 // Set adaptation disabled.
Taylor Brandstetter49fcc102018-05-16 21:20:412540 video_stream_encoder_->SetSource(&new_video_source,
2541 webrtc::DegradationPreference::DISABLED);
kthelgason876222f2016-11-29 09:44:112542
asaperssonfab67072017-04-04 12:51:492543 new_video_source.IncomingCapturedFrame(CreateFrame(4, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:522544 WaitForEncodedFrame(4);
kthelgason876222f2016-11-29 09:44:112545 stats = stats_proxy_->GetStats();
asapersson09f05612017-05-16 06:40:182546 EXPECT_FALSE(stats.bw_limited_resolution);
kthelgason876222f2016-11-29 09:44:112547 EXPECT_FALSE(stats.cpu_limited_resolution);
2548 EXPECT_EQ(1, stats.number_of_cpu_adapt_changes);
2549
2550 // Set adaptation back to enabled.
mflodmancc3d4422017-08-03 15:27:512551 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 21:20:412552 &new_video_source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
kthelgason876222f2016-11-29 09:44:112553
asaperssonfab67072017-04-04 12:51:492554 new_video_source.IncomingCapturedFrame(CreateFrame(5, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:522555 WaitForEncodedFrame(5);
kthelgason876222f2016-11-29 09:44:112556 stats = stats_proxy_->GetStats();
asapersson09f05612017-05-16 06:40:182557 EXPECT_FALSE(stats.bw_limited_resolution);
kthelgason876222f2016-11-29 09:44:112558 EXPECT_TRUE(stats.cpu_limited_resolution);
2559 EXPECT_EQ(1, stats.number_of_cpu_adapt_changes);
2560
asaperssonfab67072017-04-04 12:51:492561 // Trigger CPU normal use.
Henrik Boström91aa7322020-04-28 10:24:332562 video_stream_encoder_->TriggerCpuUnderuse();
asaperssonfab67072017-04-04 12:51:492563 new_video_source.IncomingCapturedFrame(CreateFrame(6, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:522564 WaitForEncodedFrame(6);
kthelgason876222f2016-11-29 09:44:112565 stats = stats_proxy_->GetStats();
asapersson09f05612017-05-16 06:40:182566 EXPECT_FALSE(stats.bw_limited_resolution);
kthelgason876222f2016-11-29 09:44:112567 EXPECT_FALSE(stats.cpu_limited_resolution);
2568 EXPECT_EQ(2, stats.number_of_cpu_adapt_changes);
asapersson02465b82017-04-10 08:12:522569 EXPECT_EQ(0, stats.number_of_quality_adapt_changes);
kthelgason876222f2016-11-29 09:44:112570
mflodmancc3d4422017-08-03 15:27:512571 video_stream_encoder_->Stop();
kthelgason876222f2016-11-29 09:44:112572}
2573
mflodmancc3d4422017-08-03 15:27:512574TEST_F(VideoStreamEncoderTest, SwitchingSourceKeepsQualityAdaptation) {
Henrik Boström381d1092020-05-12 16:49:072575 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:072576 DataRate::BitsPerSec(kTargetBitrateBps),
2577 DataRate::BitsPerSec(kTargetBitrateBps),
2578 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
kthelgason876222f2016-11-29 09:44:112579
asaperssonfab67072017-04-04 12:51:492580 const int kWidth = 1280;
2581 const int kHeight = 720;
2582 video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:522583 WaitForEncodedFrame(1);
kthelgason876222f2016-11-29 09:44:112584 VideoSendStream::Stats stats = stats_proxy_->GetStats();
kthelgason876222f2016-11-29 09:44:112585 EXPECT_FALSE(stats.bw_limited_resolution);
asapersson13874762017-06-07 07:01:022586 EXPECT_FALSE(stats.bw_limited_framerate);
asaperssonfab67072017-04-04 12:51:492587 EXPECT_EQ(0, stats.number_of_quality_adapt_changes);
kthelgason876222f2016-11-29 09:44:112588
2589 // Set new source with adaptation still enabled.
2590 test::FrameForwarder new_video_source;
Taylor Brandstetter49fcc102018-05-16 21:20:412591 video_stream_encoder_->SetSource(&new_video_source,
2592 webrtc::DegradationPreference::BALANCED);
kthelgason876222f2016-11-29 09:44:112593
asaperssonfab67072017-04-04 12:51:492594 new_video_source.IncomingCapturedFrame(CreateFrame(2, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:522595 WaitForEncodedFrame(2);
kthelgason876222f2016-11-29 09:44:112596 stats = stats_proxy_->GetStats();
kthelgason876222f2016-11-29 09:44:112597 EXPECT_FALSE(stats.bw_limited_resolution);
asapersson13874762017-06-07 07:01:022598 EXPECT_FALSE(stats.bw_limited_framerate);
asaperssonfab67072017-04-04 12:51:492599 EXPECT_EQ(0, stats.number_of_quality_adapt_changes);
kthelgason876222f2016-11-29 09:44:112600
asaperssonfab67072017-04-04 12:51:492601 // Trigger adapt down.
mflodmancc3d4422017-08-03 15:27:512602 video_stream_encoder_->TriggerQualityLow();
asaperssonfab67072017-04-04 12:51:492603 new_video_source.IncomingCapturedFrame(CreateFrame(3, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:522604 WaitForEncodedFrame(3);
kthelgason876222f2016-11-29 09:44:112605 stats = stats_proxy_->GetStats();
kthelgason876222f2016-11-29 09:44:112606 EXPECT_TRUE(stats.bw_limited_resolution);
asapersson13874762017-06-07 07:01:022607 EXPECT_FALSE(stats.bw_limited_framerate);
asaperssonfab67072017-04-04 12:51:492608 EXPECT_EQ(1, stats.number_of_quality_adapt_changes);
kthelgason876222f2016-11-29 09:44:112609
asaperssonfab67072017-04-04 12:51:492610 // Set new source with adaptation still enabled.
Taylor Brandstetter49fcc102018-05-16 21:20:412611 video_stream_encoder_->SetSource(&new_video_source,
2612 webrtc::DegradationPreference::BALANCED);
kthelgason876222f2016-11-29 09:44:112613
asaperssonfab67072017-04-04 12:51:492614 new_video_source.IncomingCapturedFrame(CreateFrame(4, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:522615 WaitForEncodedFrame(4);
kthelgason876222f2016-11-29 09:44:112616 stats = stats_proxy_->GetStats();
kthelgason876222f2016-11-29 09:44:112617 EXPECT_TRUE(stats.bw_limited_resolution);
asapersson13874762017-06-07 07:01:022618 EXPECT_FALSE(stats.bw_limited_framerate);
asaperssonfab67072017-04-04 12:51:492619 EXPECT_EQ(1, stats.number_of_quality_adapt_changes);
kthelgason876222f2016-11-29 09:44:112620
asapersson02465b82017-04-10 08:12:522621 // Disable resolution scaling.
mflodmancc3d4422017-08-03 15:27:512622 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 21:20:412623 &new_video_source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
kthelgason876222f2016-11-29 09:44:112624
asaperssonfab67072017-04-04 12:51:492625 new_video_source.IncomingCapturedFrame(CreateFrame(5, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:522626 WaitForEncodedFrame(5);
kthelgason876222f2016-11-29 09:44:112627 stats = stats_proxy_->GetStats();
kthelgason876222f2016-11-29 09:44:112628 EXPECT_FALSE(stats.bw_limited_resolution);
asapersson13874762017-06-07 07:01:022629 EXPECT_FALSE(stats.bw_limited_framerate);
asaperssonfab67072017-04-04 12:51:492630 EXPECT_EQ(1, stats.number_of_quality_adapt_changes);
2631 EXPECT_EQ(0, stats.number_of_cpu_adapt_changes);
kthelgason876222f2016-11-29 09:44:112632
mflodmancc3d4422017-08-03 15:27:512633 video_stream_encoder_->Stop();
kthelgason876222f2016-11-29 09:44:112634}
2635
mflodmancc3d4422017-08-03 15:27:512636TEST_F(VideoStreamEncoderTest,
2637 QualityAdaptationStatsAreResetWhenScalerIsDisabled) {
Henrik Boström381d1092020-05-12 16:49:072638 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:072639 DataRate::BitsPerSec(kTargetBitrateBps),
2640 DataRate::BitsPerSec(kTargetBitrateBps),
2641 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asapersson36e9eb42017-03-31 12:29:122642
2643 const int kWidth = 1280;
2644 const int kHeight = 720;
Åsa Persson8c1bf952018-09-13 08:42:192645 int64_t timestamp_ms = kFrameIntervalMs;
asapersson36e9eb42017-03-31 12:29:122646 video_source_.set_adaptation_enabled(true);
Åsa Persson8c1bf952018-09-13 08:42:192647 video_source_.IncomingCapturedFrame(
2648 CreateFrame(timestamp_ms, kWidth, kHeight));
2649 WaitForEncodedFrame(timestamp_ms);
asapersson36e9eb42017-03-31 12:29:122650 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
2651 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
2652 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
2653
2654 // Trigger adapt down.
mflodmancc3d4422017-08-03 15:27:512655 video_stream_encoder_->TriggerQualityLow();
Åsa Persson8c1bf952018-09-13 08:42:192656 timestamp_ms += kFrameIntervalMs;
2657 video_source_.IncomingCapturedFrame(
2658 CreateFrame(timestamp_ms, kWidth, kHeight));
2659 WaitForEncodedFrame(timestamp_ms);
asapersson36e9eb42017-03-31 12:29:122660 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
2661 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
2662 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
2663
2664 // Trigger overuse.
mflodmancc3d4422017-08-03 15:27:512665 video_stream_encoder_->TriggerCpuOveruse();
Åsa Persson8c1bf952018-09-13 08:42:192666 timestamp_ms += kFrameIntervalMs;
2667 video_source_.IncomingCapturedFrame(
2668 CreateFrame(timestamp_ms, kWidth, kHeight));
2669 WaitForEncodedFrame(timestamp_ms);
asapersson36e9eb42017-03-31 12:29:122670 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
2671 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
2672 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
2673
Niels Möller4db138e2018-04-19 07:04:132674 // Leave source unchanged, but disable quality scaler.
asapersson36e9eb42017-03-31 12:29:122675 fake_encoder_.SetQualityScaling(false);
Niels Möller4db138e2018-04-19 07:04:132676
2677 VideoEncoderConfig video_encoder_config;
2678 test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
2679 // Make format different, to force recreation of encoder.
2680 video_encoder_config.video_format.parameters["foo"] = "foo";
2681 video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config),
Niels Möllerf1338562018-04-26 07:51:472682 kMaxPayloadLength);
Åsa Persson8c1bf952018-09-13 08:42:192683 timestamp_ms += kFrameIntervalMs;
2684 video_source_.IncomingCapturedFrame(
2685 CreateFrame(timestamp_ms, kWidth, kHeight));
2686 WaitForEncodedFrame(timestamp_ms);
asapersson36e9eb42017-03-31 12:29:122687 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
2688 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
2689 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
2690
mflodmancc3d4422017-08-03 15:27:512691 video_stream_encoder_->Stop();
asapersson36e9eb42017-03-31 12:29:122692}
2693
mflodmancc3d4422017-08-03 15:27:512694TEST_F(VideoStreamEncoderTest,
Evan Shrubsole33be9df2020-03-05 17:39:322695 StatsTracksCpuAdaptationStatsWhenSwitchingSource_Balanced) {
Henrik Boström381d1092020-05-12 16:49:072696 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Evan Shrubsole33be9df2020-03-05 17:39:322697 DataRate::BitsPerSec(kTargetBitrateBps),
2698 DataRate::BitsPerSec(kTargetBitrateBps),
2699 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
2700
2701 const int kWidth = 1280;
2702 const int kHeight = 720;
2703 int sequence = 1;
2704
2705 // Enable BALANCED preference, no initial limitation.
2706 test::FrameForwarder source;
2707 video_stream_encoder_->SetSource(&source,
2708 webrtc::DegradationPreference::BALANCED);
2709 source.IncomingCapturedFrame(CreateFrame(sequence, kWidth, kHeight));
2710 WaitForEncodedFrame(sequence++);
2711 VideoSendStream::Stats stats = stats_proxy_->GetStats();
2712 EXPECT_FALSE(stats.cpu_limited_resolution);
2713 EXPECT_FALSE(stats.cpu_limited_framerate);
2714 EXPECT_EQ(0, stats.number_of_cpu_adapt_changes);
2715
2716 // Trigger CPU overuse, should now adapt down.
2717 video_stream_encoder_->TriggerCpuOveruse();
2718 source.IncomingCapturedFrame(CreateFrame(sequence, kWidth, kHeight));
2719 WaitForEncodedFrame(sequence++);
2720 stats = stats_proxy_->GetStats();
2721 EXPECT_EQ(1, stats.number_of_cpu_adapt_changes);
2722
2723 // Set new degradation preference should clear restrictions since we changed
2724 // from BALANCED.
Evan Shrubsolede2049e2020-05-25 14:54:212725 video_stream_encoder_->SetSourceAndWaitForRestrictionsUpdated(
Evan Shrubsole33be9df2020-03-05 17:39:322726 &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
2727 source.IncomingCapturedFrame(CreateFrame(sequence, kWidth, kHeight));
2728 WaitForEncodedFrame(sequence++);
2729 stats = stats_proxy_->GetStats();
2730 EXPECT_FALSE(stats.cpu_limited_resolution);
2731 EXPECT_FALSE(stats.cpu_limited_framerate);
2732 EXPECT_EQ(1, stats.number_of_cpu_adapt_changes);
2733
2734 // Force an input frame rate to be available, or the adaptation call won't
2735 // know what framerate to adapt from.
2736 VideoSendStream::Stats mock_stats = stats_proxy_->GetStats();
2737 mock_stats.input_frame_rate = 30;
2738 stats_proxy_->SetMockStats(mock_stats);
2739 video_stream_encoder_->TriggerCpuOveruse();
2740 stats_proxy_->ResetMockStats();
2741 source.IncomingCapturedFrame(CreateFrame(sequence, kWidth, kHeight));
2742 WaitForEncodedFrame(sequence++);
2743
2744 // We have now adapted once.
2745 stats = stats_proxy_->GetStats();
2746 EXPECT_EQ(2, stats.number_of_cpu_adapt_changes);
2747
2748 // Back to BALANCED, should clear the restrictions again.
Evan Shrubsolede2049e2020-05-25 14:54:212749 video_stream_encoder_->SetSourceAndWaitForRestrictionsUpdated(
2750 &source, webrtc::DegradationPreference::BALANCED);
Evan Shrubsole33be9df2020-03-05 17:39:322751 source.IncomingCapturedFrame(CreateFrame(sequence, kWidth, kHeight));
2752 WaitForEncodedFrame(sequence++);
2753 stats = stats_proxy_->GetStats();
2754 EXPECT_FALSE(stats.cpu_limited_resolution);
2755 EXPECT_FALSE(stats.cpu_limited_framerate);
2756 EXPECT_EQ(2, stats.number_of_cpu_adapt_changes);
2757
2758 video_stream_encoder_->Stop();
2759}
2760
2761TEST_F(VideoStreamEncoderTest,
mflodmancc3d4422017-08-03 15:27:512762 StatsTracksCpuAdaptationStatsWhenSwitchingSource) {
Henrik Boström381d1092020-05-12 16:49:072763 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:072764 DataRate::BitsPerSec(kTargetBitrateBps),
2765 DataRate::BitsPerSec(kTargetBitrateBps),
2766 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
perkj803d97f2016-11-01 18:45:462767
asapersson0944a802017-04-07 07:57:582768 const int kWidth = 1280;
2769 const int kHeight = 720;
sprang84a37592017-02-10 15:04:272770 int sequence = 1;
perkj803d97f2016-11-01 18:45:462771
asaperssonfab67072017-04-04 12:51:492772 video_source_.IncomingCapturedFrame(CreateFrame(sequence, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:522773 WaitForEncodedFrame(sequence++);
perkj803d97f2016-11-01 18:45:462774 VideoSendStream::Stats stats = stats_proxy_->GetStats();
sprang84a37592017-02-10 15:04:272775 EXPECT_FALSE(stats.cpu_limited_resolution);
asapersson13874762017-06-07 07:01:022776 EXPECT_FALSE(stats.cpu_limited_framerate);
sprang84a37592017-02-10 15:04:272777 EXPECT_EQ(0, stats.number_of_cpu_adapt_changes);
2778
asapersson02465b82017-04-10 08:12:522779 // Trigger CPU overuse, should now adapt down.
mflodmancc3d4422017-08-03 15:27:512780 video_stream_encoder_->TriggerCpuOveruse();
asaperssonfab67072017-04-04 12:51:492781 video_source_.IncomingCapturedFrame(CreateFrame(sequence, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:522782 WaitForEncodedFrame(sequence++);
sprang84a37592017-02-10 15:04:272783 stats = stats_proxy_->GetStats();
perkj803d97f2016-11-01 18:45:462784 EXPECT_TRUE(stats.cpu_limited_resolution);
asapersson13874762017-06-07 07:01:022785 EXPECT_FALSE(stats.cpu_limited_framerate);
perkj803d97f2016-11-01 18:45:462786 EXPECT_EQ(1, stats.number_of_cpu_adapt_changes);
2787
2788 // Set new source with adaptation still enabled.
2789 test::FrameForwarder new_video_source;
mflodmancc3d4422017-08-03 15:27:512790 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 21:20:412791 &new_video_source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
perkj803d97f2016-11-01 18:45:462792
2793 new_video_source.IncomingCapturedFrame(
asaperssonfab67072017-04-04 12:51:492794 CreateFrame(sequence, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:522795 WaitForEncodedFrame(sequence++);
perkj803d97f2016-11-01 18:45:462796 stats = stats_proxy_->GetStats();
2797 EXPECT_TRUE(stats.cpu_limited_resolution);
asapersson09f05612017-05-16 06:40:182798 EXPECT_FALSE(stats.cpu_limited_framerate);
perkj803d97f2016-11-01 18:45:462799 EXPECT_EQ(1, stats.number_of_cpu_adapt_changes);
2800
sprangc5d62e22017-04-03 06:53:042801 // Set cpu adaptation by frame dropping.
mflodmancc3d4422017-08-03 15:27:512802 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 21:20:412803 &new_video_source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
perkj803d97f2016-11-01 18:45:462804 new_video_source.IncomingCapturedFrame(
asaperssonfab67072017-04-04 12:51:492805 CreateFrame(sequence, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:522806 WaitForEncodedFrame(sequence++);
perkj803d97f2016-11-01 18:45:462807 stats = stats_proxy_->GetStats();
sprangc5d62e22017-04-03 06:53:042808 // Not adapted at first.
perkj803d97f2016-11-01 18:45:462809 EXPECT_FALSE(stats.cpu_limited_resolution);
asapersson09f05612017-05-16 06:40:182810 EXPECT_FALSE(stats.cpu_limited_framerate);
perkj803d97f2016-11-01 18:45:462811 EXPECT_EQ(1, stats.number_of_cpu_adapt_changes);
2812
sprangc5d62e22017-04-03 06:53:042813 // Force an input frame rate to be available, or the adaptation call won't
asapersson09f05612017-05-16 06:40:182814 // know what framerate to adapt from.
sprangc5d62e22017-04-03 06:53:042815 VideoSendStream::Stats mock_stats = stats_proxy_->GetStats();
2816 mock_stats.input_frame_rate = 30;
2817 stats_proxy_->SetMockStats(mock_stats);
mflodmancc3d4422017-08-03 15:27:512818 video_stream_encoder_->TriggerCpuOveruse();
sprangc5d62e22017-04-03 06:53:042819 stats_proxy_->ResetMockStats();
2820
2821 new_video_source.IncomingCapturedFrame(
asaperssonfab67072017-04-04 12:51:492822 CreateFrame(sequence, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:522823 WaitForEncodedFrame(sequence++);
sprangc5d62e22017-04-03 06:53:042824
2825 // Framerate now adapted.
2826 stats = stats_proxy_->GetStats();
asapersson09f05612017-05-16 06:40:182827 EXPECT_FALSE(stats.cpu_limited_resolution);
2828 EXPECT_TRUE(stats.cpu_limited_framerate);
sprangc5d62e22017-04-03 06:53:042829 EXPECT_EQ(2, stats.number_of_cpu_adapt_changes);
2830
2831 // Disable CPU adaptation.
Taylor Brandstetter49fcc102018-05-16 21:20:412832 video_stream_encoder_->SetSource(&new_video_source,
2833 webrtc::DegradationPreference::DISABLED);
sprangc5d62e22017-04-03 06:53:042834 new_video_source.IncomingCapturedFrame(
asaperssonfab67072017-04-04 12:51:492835 CreateFrame(sequence, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:522836 WaitForEncodedFrame(sequence++);
sprangc5d62e22017-04-03 06:53:042837
2838 stats = stats_proxy_->GetStats();
2839 EXPECT_FALSE(stats.cpu_limited_resolution);
asapersson13874762017-06-07 07:01:022840 EXPECT_FALSE(stats.cpu_limited_framerate);
sprangc5d62e22017-04-03 06:53:042841 EXPECT_EQ(2, stats.number_of_cpu_adapt_changes);
2842
2843 // Try to trigger overuse. Should not succeed.
2844 stats_proxy_->SetMockStats(mock_stats);
mflodmancc3d4422017-08-03 15:27:512845 video_stream_encoder_->TriggerCpuOveruse();
sprangc5d62e22017-04-03 06:53:042846 stats_proxy_->ResetMockStats();
2847
2848 stats = stats_proxy_->GetStats();
2849 EXPECT_FALSE(stats.cpu_limited_resolution);
asapersson13874762017-06-07 07:01:022850 EXPECT_FALSE(stats.cpu_limited_framerate);
sprangc5d62e22017-04-03 06:53:042851 EXPECT_EQ(2, stats.number_of_cpu_adapt_changes);
2852
2853 // Switch back the source with resolution adaptation enabled.
mflodmancc3d4422017-08-03 15:27:512854 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 21:20:412855 &video_source_, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
asaperssonfab67072017-04-04 12:51:492856 video_source_.IncomingCapturedFrame(CreateFrame(sequence, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:522857 WaitForEncodedFrame(sequence++);
perkj803d97f2016-11-01 18:45:462858 stats = stats_proxy_->GetStats();
2859 EXPECT_TRUE(stats.cpu_limited_resolution);
asapersson13874762017-06-07 07:01:022860 EXPECT_FALSE(stats.cpu_limited_framerate);
sprangc5d62e22017-04-03 06:53:042861 EXPECT_EQ(2, stats.number_of_cpu_adapt_changes);
perkj803d97f2016-11-01 18:45:462862
2863 // Trigger CPU normal usage.
Henrik Boström91aa7322020-04-28 10:24:332864 video_stream_encoder_->TriggerCpuUnderuse();
asaperssonfab67072017-04-04 12:51:492865 video_source_.IncomingCapturedFrame(CreateFrame(sequence, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:522866 WaitForEncodedFrame(sequence++);
perkj803d97f2016-11-01 18:45:462867 stats = stats_proxy_->GetStats();
2868 EXPECT_FALSE(stats.cpu_limited_resolution);
asapersson13874762017-06-07 07:01:022869 EXPECT_FALSE(stats.cpu_limited_framerate);
sprangc5d62e22017-04-03 06:53:042870 EXPECT_EQ(3, stats.number_of_cpu_adapt_changes);
2871
2872 // Back to the source with adaptation off, set it back to maintain-resolution.
mflodmancc3d4422017-08-03 15:27:512873 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 21:20:412874 &new_video_source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
sprangc5d62e22017-04-03 06:53:042875 new_video_source.IncomingCapturedFrame(
asaperssonfab67072017-04-04 12:51:492876 CreateFrame(sequence, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:522877 WaitForEncodedFrame(sequence++);
sprangc5d62e22017-04-03 06:53:042878 stats = stats_proxy_->GetStats();
asapersson13874762017-06-07 07:01:022879 // Disabled, since we previously switched the source to disabled.
sprangc5d62e22017-04-03 06:53:042880 EXPECT_FALSE(stats.cpu_limited_resolution);
asapersson13874762017-06-07 07:01:022881 EXPECT_TRUE(stats.cpu_limited_framerate);
sprangc5d62e22017-04-03 06:53:042882 EXPECT_EQ(3, stats.number_of_cpu_adapt_changes);
2883
2884 // Trigger CPU normal usage.
Henrik Boström91aa7322020-04-28 10:24:332885 video_stream_encoder_->TriggerCpuUnderuse();
sprangc5d62e22017-04-03 06:53:042886 new_video_source.IncomingCapturedFrame(
asaperssonfab67072017-04-04 12:51:492887 CreateFrame(sequence, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:522888 WaitForEncodedFrame(sequence++);
sprangc5d62e22017-04-03 06:53:042889 stats = stats_proxy_->GetStats();
2890 EXPECT_FALSE(stats.cpu_limited_resolution);
asapersson13874762017-06-07 07:01:022891 EXPECT_FALSE(stats.cpu_limited_framerate);
sprangc5d62e22017-04-03 06:53:042892 EXPECT_EQ(4, stats.number_of_cpu_adapt_changes);
asapersson02465b82017-04-10 08:12:522893 EXPECT_EQ(0, stats.number_of_quality_adapt_changes);
perkj803d97f2016-11-01 18:45:462894
mflodmancc3d4422017-08-03 15:27:512895 video_stream_encoder_->Stop();
perkj803d97f2016-11-01 18:45:462896}
2897
mflodmancc3d4422017-08-03 15:27:512898TEST_F(VideoStreamEncoderTest,
2899 ScalingUpAndDownDoesNothingWithMaintainResolution) {
asaperssonfab67072017-04-04 12:51:492900 const int kWidth = 1280;
2901 const int kHeight = 720;
Henrik Boström381d1092020-05-12 16:49:072902 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:072903 DataRate::BitsPerSec(kTargetBitrateBps),
2904 DataRate::BitsPerSec(kTargetBitrateBps),
2905 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
kthelgason876222f2016-11-29 09:44:112906
asaperssonfab67072017-04-04 12:51:492907 // Expect no scaling to begin with.
Evan Shrubsole5cd7eb82020-05-25 12:08:392908 EXPECT_THAT(video_source_.sink_wants(), UnlimitedSinkWants());
kthelgason876222f2016-11-29 09:44:112909
asaperssonfab67072017-04-04 12:51:492910 video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:522911 WaitForEncodedFrame(1);
kthelgason876222f2016-11-29 09:44:112912
asaperssonfab67072017-04-04 12:51:492913 // Trigger scale down.
mflodmancc3d4422017-08-03 15:27:512914 video_stream_encoder_->TriggerQualityLow();
kthelgason5e13d412016-12-01 11:59:512915
asaperssonfab67072017-04-04 12:51:492916 video_source_.IncomingCapturedFrame(CreateFrame(2, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:522917 WaitForEncodedFrame(2);
kthelgason5e13d412016-12-01 11:59:512918
kthelgason876222f2016-11-29 09:44:112919 // Expect a scale down.
2920 EXPECT_TRUE(video_source_.sink_wants().max_pixel_count);
asaperssonfab67072017-04-04 12:51:492921 EXPECT_LT(video_source_.sink_wants().max_pixel_count, kWidth * kHeight);
kthelgason876222f2016-11-29 09:44:112922
asapersson02465b82017-04-10 08:12:522923 // Set resolution scaling disabled.
kthelgason876222f2016-11-29 09:44:112924 test::FrameForwarder new_video_source;
mflodmancc3d4422017-08-03 15:27:512925 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 21:20:412926 &new_video_source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
kthelgason876222f2016-11-29 09:44:112927
asaperssonfab67072017-04-04 12:51:492928 // Trigger scale down.
mflodmancc3d4422017-08-03 15:27:512929 video_stream_encoder_->TriggerQualityLow();
asaperssonfab67072017-04-04 12:51:492930 new_video_source.IncomingCapturedFrame(CreateFrame(3, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:522931 WaitForEncodedFrame(3);
kthelgason876222f2016-11-29 09:44:112932
asaperssonfab67072017-04-04 12:51:492933 // Expect no scaling.
sprangc5d62e22017-04-03 06:53:042934 EXPECT_EQ(std::numeric_limits<int>::max(),
2935 new_video_source.sink_wants().max_pixel_count);
kthelgason876222f2016-11-29 09:44:112936
asaperssonfab67072017-04-04 12:51:492937 // Trigger scale up.
mflodmancc3d4422017-08-03 15:27:512938 video_stream_encoder_->TriggerQualityHigh();
asaperssonfab67072017-04-04 12:51:492939 new_video_source.IncomingCapturedFrame(CreateFrame(4, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:522940 WaitForEncodedFrame(4);
kthelgason876222f2016-11-29 09:44:112941
asapersson02465b82017-04-10 08:12:522942 // Expect nothing to change, still no scaling.
sprangc5d62e22017-04-03 06:53:042943 EXPECT_EQ(std::numeric_limits<int>::max(),
2944 new_video_source.sink_wants().max_pixel_count);
kthelgason876222f2016-11-29 09:44:112945
mflodmancc3d4422017-08-03 15:27:512946 video_stream_encoder_->Stop();
kthelgason876222f2016-11-29 09:44:112947}
2948
mflodmancc3d4422017-08-03 15:27:512949TEST_F(VideoStreamEncoderTest,
2950 SkipsSameAdaptDownRequest_MaintainFramerateMode) {
asapersson02465b82017-04-10 08:12:522951 const int kWidth = 1280;
2952 const int kHeight = 720;
Henrik Boström381d1092020-05-12 16:49:072953 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:072954 DataRate::BitsPerSec(kTargetBitrateBps),
2955 DataRate::BitsPerSec(kTargetBitrateBps),
2956 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asapersson02465b82017-04-10 08:12:522957
Taylor Brandstetter49fcc102018-05-16 21:20:412958 // Enable MAINTAIN_FRAMERATE preference, no initial limitation.
asapersson02465b82017-04-10 08:12:522959 test::FrameForwarder source;
mflodmancc3d4422017-08-03 15:27:512960 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 21:20:412961 &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
asapersson02465b82017-04-10 08:12:522962
2963 source.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:522964 WaitForEncodedFrame(1);
Evan Shrubsole5cd7eb82020-05-25 12:08:392965 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asapersson02465b82017-04-10 08:12:522966 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
2967 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
2968
2969 // Trigger adapt down, expect scaled down resolution.
mflodmancc3d4422017-08-03 15:27:512970 video_stream_encoder_->TriggerCpuOveruse();
Evan Shrubsole5cd7eb82020-05-25 12:08:392971 EXPECT_THAT(source.sink_wants(),
2972 FpsMaxResolutionMatches(Lt(kWidth * kHeight)));
asapersson02465b82017-04-10 08:12:522973 const int kLastMaxPixelCount = source.sink_wants().max_pixel_count;
2974 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
2975 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
2976
2977 // Trigger adapt down for same input resolution, expect no change.
mflodmancc3d4422017-08-03 15:27:512978 video_stream_encoder_->TriggerCpuOveruse();
asapersson02465b82017-04-10 08:12:522979 EXPECT_EQ(kLastMaxPixelCount, source.sink_wants().max_pixel_count);
2980 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
2981 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
2982
mflodmancc3d4422017-08-03 15:27:512983 video_stream_encoder_->Stop();
asapersson02465b82017-04-10 08:12:522984}
2985
mflodmancc3d4422017-08-03 15:27:512986TEST_F(VideoStreamEncoderTest, SkipsSameOrLargerAdaptDownRequest_BalancedMode) {
asaperssonf7e294d2017-06-14 06:25:222987 const int kWidth = 1280;
2988 const int kHeight = 720;
Henrik Boström381d1092020-05-12 16:49:072989 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:072990 DataRate::BitsPerSec(kTargetBitrateBps),
2991 DataRate::BitsPerSec(kTargetBitrateBps),
2992 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asaperssonf7e294d2017-06-14 06:25:222993
Taylor Brandstetter49fcc102018-05-16 21:20:412994 // Enable BALANCED preference, no initial limitation.
asaperssonf7e294d2017-06-14 06:25:222995 test::FrameForwarder source;
Taylor Brandstetter49fcc102018-05-16 21:20:412996 video_stream_encoder_->SetSource(&source,
2997 webrtc::DegradationPreference::BALANCED);
asaperssonf7e294d2017-06-14 06:25:222998 source.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
2999 sink_.WaitForEncodedFrame(1);
Evan Shrubsole5cd7eb82020-05-25 12:08:393000 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-14 06:25:223001
3002 // Trigger adapt down, expect scaled down resolution.
mflodmancc3d4422017-08-03 15:27:513003 video_stream_encoder_->TriggerQualityLow();
Evan Shrubsole5cd7eb82020-05-25 12:08:393004 EXPECT_THAT(source.sink_wants(),
3005 FpsMaxResolutionMatches(Lt(kWidth * kHeight)));
asaperssonf7e294d2017-06-14 06:25:223006 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
3007 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3008 const int kLastMaxPixelCount = source.sink_wants().max_pixel_count;
3009
3010 // Trigger adapt down for same input resolution, expect no change.
3011 source.IncomingCapturedFrame(CreateFrame(2, kWidth, kHeight));
3012 sink_.WaitForEncodedFrame(2);
mflodmancc3d4422017-08-03 15:27:513013 video_stream_encoder_->TriggerQualityLow();
asaperssonf7e294d2017-06-14 06:25:223014 EXPECT_EQ(kLastMaxPixelCount, source.sink_wants().max_pixel_count);
3015 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
3016 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3017
3018 // Trigger adapt down for larger input resolution, expect no change.
3019 source.IncomingCapturedFrame(CreateFrame(3, kWidth + 1, kHeight + 1));
3020 sink_.WaitForEncodedFrame(3);
mflodmancc3d4422017-08-03 15:27:513021 video_stream_encoder_->TriggerQualityLow();
asaperssonf7e294d2017-06-14 06:25:223022 EXPECT_EQ(kLastMaxPixelCount, source.sink_wants().max_pixel_count);
3023 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
3024 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3025
mflodmancc3d4422017-08-03 15:27:513026 video_stream_encoder_->Stop();
asaperssonf7e294d2017-06-14 06:25:223027}
3028
mflodmancc3d4422017-08-03 15:27:513029TEST_F(VideoStreamEncoderTest,
3030 NoChangeForInitialNormalUsage_MaintainFramerateMode) {
asapersson02465b82017-04-10 08:12:523031 const int kWidth = 1280;
3032 const int kHeight = 720;
Henrik Boström381d1092020-05-12 16:49:073033 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:073034 DataRate::BitsPerSec(kTargetBitrateBps),
3035 DataRate::BitsPerSec(kTargetBitrateBps),
3036 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asapersson02465b82017-04-10 08:12:523037
Taylor Brandstetter49fcc102018-05-16 21:20:413038 // Enable MAINTAIN_FRAMERATE preference, no initial limitation.
asapersson02465b82017-04-10 08:12:523039 test::FrameForwarder source;
mflodmancc3d4422017-08-03 15:27:513040 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 21:20:413041 &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
asapersson02465b82017-04-10 08:12:523042
3043 source.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:523044 WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5cd7eb82020-05-25 12:08:393045 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asapersson02465b82017-04-10 08:12:523046 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
3047 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3048
3049 // Trigger adapt up, expect no change.
Henrik Boström91aa7322020-04-28 10:24:333050 video_stream_encoder_->TriggerCpuUnderuse();
Evan Shrubsole5cd7eb82020-05-25 12:08:393051 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asapersson02465b82017-04-10 08:12:523052 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
3053 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3054
mflodmancc3d4422017-08-03 15:27:513055 video_stream_encoder_->Stop();
asapersson02465b82017-04-10 08:12:523056}
3057
mflodmancc3d4422017-08-03 15:27:513058TEST_F(VideoStreamEncoderTest,
3059 NoChangeForInitialNormalUsage_MaintainResolutionMode) {
asapersson02465b82017-04-10 08:12:523060 const int kWidth = 1280;
3061 const int kHeight = 720;
Henrik Boström381d1092020-05-12 16:49:073062 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:073063 DataRate::BitsPerSec(kTargetBitrateBps),
3064 DataRate::BitsPerSec(kTargetBitrateBps),
3065 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asapersson02465b82017-04-10 08:12:523066
Taylor Brandstetter49fcc102018-05-16 21:20:413067 // Enable MAINTAIN_RESOLUTION preference, no initial limitation.
asapersson02465b82017-04-10 08:12:523068 test::FrameForwarder source;
mflodmancc3d4422017-08-03 15:27:513069 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 21:20:413070 &source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
asapersson02465b82017-04-10 08:12:523071
3072 source.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:523073 WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5cd7eb82020-05-25 12:08:393074 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asapersson09f05612017-05-16 06:40:183075 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
asapersson02465b82017-04-10 08:12:523076 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3077
3078 // Trigger adapt up, expect no change.
Henrik Boström91aa7322020-04-28 10:24:333079 video_stream_encoder_->TriggerCpuUnderuse();
Evan Shrubsole5cd7eb82020-05-25 12:08:393080 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asapersson09f05612017-05-16 06:40:183081 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
asapersson02465b82017-04-10 08:12:523082 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3083
mflodmancc3d4422017-08-03 15:27:513084 video_stream_encoder_->Stop();
asapersson02465b82017-04-10 08:12:523085}
3086
mflodmancc3d4422017-08-03 15:27:513087TEST_F(VideoStreamEncoderTest, NoChangeForInitialNormalUsage_BalancedMode) {
asaperssonf7e294d2017-06-14 06:25:223088 const int kWidth = 1280;
3089 const int kHeight = 720;
Henrik Boström381d1092020-05-12 16:49:073090 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:073091 DataRate::BitsPerSec(kTargetBitrateBps),
3092 DataRate::BitsPerSec(kTargetBitrateBps),
3093 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asaperssonf7e294d2017-06-14 06:25:223094
Taylor Brandstetter49fcc102018-05-16 21:20:413095 // Enable BALANCED preference, no initial limitation.
asaperssonf7e294d2017-06-14 06:25:223096 test::FrameForwarder source;
Taylor Brandstetter49fcc102018-05-16 21:20:413097 video_stream_encoder_->SetSource(&source,
3098 webrtc::DegradationPreference::BALANCED);
asaperssonf7e294d2017-06-14 06:25:223099
3100 source.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
3101 sink_.WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5cd7eb82020-05-25 12:08:393102 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-14 06:25:223103 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
3104 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
3105 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3106
3107 // Trigger adapt up, expect no change.
mflodmancc3d4422017-08-03 15:27:513108 video_stream_encoder_->TriggerQualityHigh();
Evan Shrubsole5cd7eb82020-05-25 12:08:393109 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-14 06:25:223110 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
3111 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
3112 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3113
mflodmancc3d4422017-08-03 15:27:513114 video_stream_encoder_->Stop();
asaperssonf7e294d2017-06-14 06:25:223115}
3116
mflodmancc3d4422017-08-03 15:27:513117TEST_F(VideoStreamEncoderTest, NoChangeForInitialNormalUsage_DisabledMode) {
asapersson09f05612017-05-16 06:40:183118 const int kWidth = 1280;
3119 const int kHeight = 720;
Henrik Boström381d1092020-05-12 16:49:073120 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:073121 DataRate::BitsPerSec(kTargetBitrateBps),
3122 DataRate::BitsPerSec(kTargetBitrateBps),
3123 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asapersson09f05612017-05-16 06:40:183124
Taylor Brandstetter49fcc102018-05-16 21:20:413125 // Enable DISABLED preference, no initial limitation.
asapersson09f05612017-05-16 06:40:183126 test::FrameForwarder source;
Taylor Brandstetter49fcc102018-05-16 21:20:413127 video_stream_encoder_->SetSource(&source,
3128 webrtc::DegradationPreference::DISABLED);
asapersson09f05612017-05-16 06:40:183129
3130 source.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
3131 sink_.WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5cd7eb82020-05-25 12:08:393132 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asapersson09f05612017-05-16 06:40:183133 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
3134 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
3135 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3136
3137 // Trigger adapt up, expect no change.
mflodmancc3d4422017-08-03 15:27:513138 video_stream_encoder_->TriggerQualityHigh();
Evan Shrubsole5cd7eb82020-05-25 12:08:393139 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asapersson09f05612017-05-16 06:40:183140 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
3141 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
3142 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3143
mflodmancc3d4422017-08-03 15:27:513144 video_stream_encoder_->Stop();
asapersson09f05612017-05-16 06:40:183145}
3146
mflodmancc3d4422017-08-03 15:27:513147TEST_F(VideoStreamEncoderTest,
3148 AdaptsResolutionForLowQuality_MaintainFramerateMode) {
asapersson02465b82017-04-10 08:12:523149 const int kWidth = 1280;
3150 const int kHeight = 720;
Henrik Boström381d1092020-05-12 16:49:073151 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:073152 DataRate::BitsPerSec(kTargetBitrateBps),
3153 DataRate::BitsPerSec(kTargetBitrateBps),
3154 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asapersson02465b82017-04-10 08:12:523155
Taylor Brandstetter49fcc102018-05-16 21:20:413156 // Enable MAINTAIN_FRAMERATE preference, no initial limitation.
Tomas Gunnarsson612445e2020-09-21 12:31:233157 AdaptingFrameForwarder source(&time_controller_);
asapersson02465b82017-04-10 08:12:523158 source.set_adaptation_enabled(true);
mflodmancc3d4422017-08-03 15:27:513159 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 21:20:413160 &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
asapersson02465b82017-04-10 08:12:523161
3162 source.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:523163 WaitForEncodedFrame(1);
Evan Shrubsole5cd7eb82020-05-25 12:08:393164 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asapersson02465b82017-04-10 08:12:523165 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
3166 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3167
3168 // Trigger adapt down, expect scaled down resolution.
mflodmancc3d4422017-08-03 15:27:513169 video_stream_encoder_->TriggerQualityLow();
asapersson02465b82017-04-10 08:12:523170 source.IncomingCapturedFrame(CreateFrame(2, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:523171 WaitForEncodedFrame(2);
Evan Shrubsole5cd7eb82020-05-25 12:08:393172 EXPECT_THAT(source.sink_wants(),
3173 FpsMaxResolutionMatches(Lt(kWidth * kHeight)));
asapersson02465b82017-04-10 08:12:523174 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
3175 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3176
3177 // Trigger adapt up, expect no restriction.
mflodmancc3d4422017-08-03 15:27:513178 video_stream_encoder_->TriggerQualityHigh();
Evan Shrubsole5cd7eb82020-05-25 12:08:393179 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asapersson02465b82017-04-10 08:12:523180 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
3181 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3182 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3183
mflodmancc3d4422017-08-03 15:27:513184 video_stream_encoder_->Stop();
asapersson02465b82017-04-10 08:12:523185}
3186
mflodmancc3d4422017-08-03 15:27:513187TEST_F(VideoStreamEncoderTest,
3188 AdaptsFramerateForLowQuality_MaintainResolutionMode) {
asapersson09f05612017-05-16 06:40:183189 const int kWidth = 1280;
3190 const int kHeight = 720;
3191 const int kInputFps = 30;
Henrik Boström381d1092020-05-12 16:49:073192 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:073193 DataRate::BitsPerSec(kTargetBitrateBps),
3194 DataRate::BitsPerSec(kTargetBitrateBps),
3195 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asapersson09f05612017-05-16 06:40:183196
3197 VideoSendStream::Stats stats = stats_proxy_->GetStats();
3198 stats.input_frame_rate = kInputFps;
3199 stats_proxy_->SetMockStats(stats);
3200
Taylor Brandstetter49fcc102018-05-16 21:20:413201 // Expect no scaling to begin with (preference: MAINTAIN_FRAMERATE).
asapersson09f05612017-05-16 06:40:183202 video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
3203 sink_.WaitForEncodedFrame(1);
Evan Shrubsole5cd7eb82020-05-25 12:08:393204 EXPECT_THAT(video_source_.sink_wants(), FpsMaxResolutionMax());
asapersson09f05612017-05-16 06:40:183205
3206 // Trigger adapt down, expect scaled down resolution.
mflodmancc3d4422017-08-03 15:27:513207 video_stream_encoder_->TriggerQualityLow();
asapersson09f05612017-05-16 06:40:183208 video_source_.IncomingCapturedFrame(CreateFrame(2, kWidth, kHeight));
3209 sink_.WaitForEncodedFrame(2);
Evan Shrubsole5cd7eb82020-05-25 12:08:393210 EXPECT_THAT(video_source_.sink_wants(),
3211 FpsMaxResolutionMatches(Lt(kWidth * kHeight)));
asapersson09f05612017-05-16 06:40:183212
Taylor Brandstetter49fcc102018-05-16 21:20:413213 // Enable MAINTAIN_RESOLUTION preference.
asapersson09f05612017-05-16 06:40:183214 test::FrameForwarder new_video_source;
Henrik Boström2671dac2020-05-19 14:29:093215 video_stream_encoder_->SetSourceAndWaitForRestrictionsUpdated(
Taylor Brandstetter49fcc102018-05-16 21:20:413216 &new_video_source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
Henrik Boström07b17df2020-01-15 10:42:123217 // Give the encoder queue time to process the change in degradation preference
3218 // by waiting for an encoded frame.
3219 new_video_source.IncomingCapturedFrame(CreateFrame(3, kWidth, kHeight));
3220 sink_.WaitForEncodedFrame(3);
Evan Shrubsole5cd7eb82020-05-25 12:08:393221 EXPECT_THAT(new_video_source.sink_wants(), FpsMaxResolutionMax());
asapersson09f05612017-05-16 06:40:183222
3223 // Trigger adapt down, expect reduced framerate.
mflodmancc3d4422017-08-03 15:27:513224 video_stream_encoder_->TriggerQualityLow();
Henrik Boström07b17df2020-01-15 10:42:123225 new_video_source.IncomingCapturedFrame(CreateFrame(4, kWidth, kHeight));
3226 sink_.WaitForEncodedFrame(4);
Evan Shrubsole5cd7eb82020-05-25 12:08:393227 EXPECT_THAT(new_video_source.sink_wants(),
3228 FpsMatchesResolutionMax(Lt(kInputFps)));
asapersson09f05612017-05-16 06:40:183229
3230 // Trigger adapt up, expect no restriction.
mflodmancc3d4422017-08-03 15:27:513231 video_stream_encoder_->TriggerQualityHigh();
Evan Shrubsole5cd7eb82020-05-25 12:08:393232 EXPECT_THAT(new_video_source.sink_wants(), FpsMaxResolutionMax());
asapersson09f05612017-05-16 06:40:183233
mflodmancc3d4422017-08-03 15:27:513234 video_stream_encoder_->Stop();
asapersson09f05612017-05-16 06:40:183235}
3236
mflodmancc3d4422017-08-03 15:27:513237TEST_F(VideoStreamEncoderTest, DoesNotScaleBelowSetResolutionLimit) {
asaperssond0de2952017-04-21 08:47:313238 const int kWidth = 1280;
3239 const int kHeight = 720;
3240 const size_t kNumFrames = 10;
3241
Henrik Boström381d1092020-05-12 16:49:073242 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:073243 DataRate::BitsPerSec(kTargetBitrateBps),
3244 DataRate::BitsPerSec(kTargetBitrateBps),
3245 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
kthelgason5e13d412016-12-01 11:59:513246
asaperssond0de2952017-04-21 08:47:313247 // Enable adapter, expected input resolutions when downscaling:
asapersson142fcc92017-08-17 15:58:543248 // 1280x720 -> 960x540 -> 640x360 -> 480x270 -> 320x180 (kMinPixelsPerFrame)
asaperssond0de2952017-04-21 08:47:313249 video_source_.set_adaptation_enabled(true);
3250
3251 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
3252 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3253
3254 int downscales = 0;
3255 for (size_t i = 1; i <= kNumFrames; i++) {
Åsa Persson8c1bf952018-09-13 08:42:193256 video_source_.IncomingCapturedFrame(
3257 CreateFrame(i * kFrameIntervalMs, kWidth, kHeight));
3258 WaitForEncodedFrame(i * kFrameIntervalMs);
asaperssond0de2952017-04-21 08:47:313259
asaperssonfab67072017-04-04 12:51:493260 // Trigger scale down.
asaperssond0de2952017-04-21 08:47:313261 rtc::VideoSinkWants last_wants = video_source_.sink_wants();
mflodmancc3d4422017-08-03 15:27:513262 video_stream_encoder_->TriggerQualityLow();
sprangc5d62e22017-04-03 06:53:043263 EXPECT_GE(video_source_.sink_wants().max_pixel_count, kMinPixelsPerFrame);
asaperssond0de2952017-04-21 08:47:313264
3265 if (video_source_.sink_wants().max_pixel_count < last_wants.max_pixel_count)
3266 ++downscales;
3267
3268 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
3269 EXPECT_EQ(downscales,
3270 stats_proxy_->GetStats().number_of_quality_adapt_changes);
3271 EXPECT_GT(downscales, 0);
kthelgason5e13d412016-12-01 11:59:513272 }
mflodmancc3d4422017-08-03 15:27:513273 video_stream_encoder_->Stop();
asaperssond0de2952017-04-21 08:47:313274}
3275
mflodmancc3d4422017-08-03 15:27:513276TEST_F(VideoStreamEncoderTest,
asaperssond0de2952017-04-21 08:47:313277 AdaptsResolutionUpAndDownTwiceOnOveruse_MaintainFramerateMode) {
3278 const int kWidth = 1280;
3279 const int kHeight = 720;
Henrik Boström381d1092020-05-12 16:49:073280 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:073281 DataRate::BitsPerSec(kTargetBitrateBps),
3282 DataRate::BitsPerSec(kTargetBitrateBps),
3283 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asaperssond0de2952017-04-21 08:47:313284
Taylor Brandstetter49fcc102018-05-16 21:20:413285 // Enable MAINTAIN_FRAMERATE preference, no initial limitation.
Tomas Gunnarsson612445e2020-09-21 12:31:233286 AdaptingFrameForwarder source(&time_controller_);
asaperssond0de2952017-04-21 08:47:313287 source.set_adaptation_enabled(true);
mflodmancc3d4422017-08-03 15:27:513288 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 21:20:413289 &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
asaperssond0de2952017-04-21 08:47:313290
Åsa Persson8c1bf952018-09-13 08:42:193291 int64_t timestamp_ms = kFrameIntervalMs;
3292 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:523293 WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5cd7eb82020-05-25 12:08:393294 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssond0de2952017-04-21 08:47:313295 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
3296 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3297
3298 // Trigger adapt down, expect scaled down resolution.
mflodmancc3d4422017-08-03 15:27:513299 video_stream_encoder_->TriggerCpuOveruse();
Åsa Persson8c1bf952018-09-13 08:42:193300 timestamp_ms += kFrameIntervalMs;
3301 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
3302 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5cd7eb82020-05-25 12:08:393303 EXPECT_THAT(source.sink_wants(),
3304 FpsMaxResolutionMatches(Lt(kWidth * kHeight)));
asaperssond0de2952017-04-21 08:47:313305 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
3306 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3307
3308 // Trigger adapt up, expect no restriction.
Henrik Boström91aa7322020-04-28 10:24:333309 video_stream_encoder_->TriggerCpuUnderuse();
Åsa Persson8c1bf952018-09-13 08:42:193310 timestamp_ms += kFrameIntervalMs;
3311 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:523312 WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5cd7eb82020-05-25 12:08:393313 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssond0de2952017-04-21 08:47:313314 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
3315 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3316
3317 // Trigger adapt down, expect scaled down resolution.
mflodmancc3d4422017-08-03 15:27:513318 video_stream_encoder_->TriggerCpuOveruse();
Åsa Persson8c1bf952018-09-13 08:42:193319 timestamp_ms += kFrameIntervalMs;
3320 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
3321 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5cd7eb82020-05-25 12:08:393322 EXPECT_THAT(source.sink_wants(),
3323 FpsMaxResolutionMatches(Lt(kWidth * kHeight)));
asaperssond0de2952017-04-21 08:47:313324 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
3325 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3326
3327 // Trigger adapt up, expect no restriction.
Henrik Boström91aa7322020-04-28 10:24:333328 video_stream_encoder_->TriggerCpuUnderuse();
Åsa Persson8c1bf952018-09-13 08:42:193329 timestamp_ms += kFrameIntervalMs;
3330 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
asapersson09f05612017-05-16 06:40:183331 sink_.WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5cd7eb82020-05-25 12:08:393332 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssond0de2952017-04-21 08:47:313333 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
3334 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3335
mflodmancc3d4422017-08-03 15:27:513336 video_stream_encoder_->Stop();
asaperssond0de2952017-04-21 08:47:313337}
3338
mflodmancc3d4422017-08-03 15:27:513339TEST_F(VideoStreamEncoderTest,
asaperssonf7e294d2017-06-14 06:25:223340 AdaptsResolutionUpAndDownTwiceForLowQuality_BalancedMode_NoFpsLimit) {
3341 const int kWidth = 1280;
3342 const int kHeight = 720;
Henrik Boström381d1092020-05-12 16:49:073343 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:073344 DataRate::BitsPerSec(kTargetBitrateBps),
3345 DataRate::BitsPerSec(kTargetBitrateBps),
3346 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asaperssonf7e294d2017-06-14 06:25:223347
Taylor Brandstetter49fcc102018-05-16 21:20:413348 // Enable BALANCED preference, no initial limitation.
Tomas Gunnarsson612445e2020-09-21 12:31:233349 AdaptingFrameForwarder source(&time_controller_);
asaperssonf7e294d2017-06-14 06:25:223350 source.set_adaptation_enabled(true);
Taylor Brandstetter49fcc102018-05-16 21:20:413351 video_stream_encoder_->SetSource(&source,
3352 webrtc::DegradationPreference::BALANCED);
asaperssonf7e294d2017-06-14 06:25:223353
Åsa Persson8c1bf952018-09-13 08:42:193354 int64_t timestamp_ms = kFrameIntervalMs;
3355 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
asaperssonf7e294d2017-06-14 06:25:223356 sink_.WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5cd7eb82020-05-25 12:08:393357 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-14 06:25:223358 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
3359 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3360
3361 // Trigger adapt down, expect scaled down resolution.
mflodmancc3d4422017-08-03 15:27:513362 video_stream_encoder_->TriggerQualityLow();
Åsa Persson8c1bf952018-09-13 08:42:193363 timestamp_ms += kFrameIntervalMs;
3364 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
3365 sink_.WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5cd7eb82020-05-25 12:08:393366 EXPECT_THAT(source.sink_wants(),
3367 FpsMaxResolutionMatches(Lt(kWidth * kHeight)));
asaperssonf7e294d2017-06-14 06:25:223368 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
3369 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3370
3371 // Trigger adapt up, expect no restriction.
mflodmancc3d4422017-08-03 15:27:513372 video_stream_encoder_->TriggerQualityHigh();
Åsa Persson8c1bf952018-09-13 08:42:193373 timestamp_ms += kFrameIntervalMs;
3374 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
asaperssonf7e294d2017-06-14 06:25:223375 sink_.WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5cd7eb82020-05-25 12:08:393376 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-14 06:25:223377 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
3378 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3379
3380 // Trigger adapt down, expect scaled down resolution.
mflodmancc3d4422017-08-03 15:27:513381 video_stream_encoder_->TriggerQualityLow();
Åsa Persson8c1bf952018-09-13 08:42:193382 timestamp_ms += kFrameIntervalMs;
3383 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
3384 sink_.WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5cd7eb82020-05-25 12:08:393385 EXPECT_THAT(source.sink_wants(),
3386 FpsMaxResolutionMatches(Lt(kWidth * kHeight)));
asaperssonf7e294d2017-06-14 06:25:223387 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
3388 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3389
3390 // Trigger adapt up, expect no restriction.
mflodmancc3d4422017-08-03 15:27:513391 video_stream_encoder_->TriggerQualityHigh();
Åsa Persson8c1bf952018-09-13 08:42:193392 timestamp_ms += kFrameIntervalMs;
3393 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
asaperssonf7e294d2017-06-14 06:25:223394 sink_.WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5cd7eb82020-05-25 12:08:393395 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-14 06:25:223396 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
3397 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3398
mflodmancc3d4422017-08-03 15:27:513399 video_stream_encoder_->Stop();
asaperssonf7e294d2017-06-14 06:25:223400}
3401
Sergey Silkin41c650b2019-10-14 11:12:193402TEST_F(VideoStreamEncoderTest, AdaptUpIfBwEstimateIsHigherThanMinBitrate) {
3403 fake_encoder_.SetResolutionBitrateLimits(
3404 {kEncoderBitrateLimits540p, kEncoderBitrateLimits720p});
3405
Henrik Boström381d1092020-05-12 16:49:073406 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:073407 DataRate::BitsPerSec(kEncoderBitrateLimits720p.min_start_bitrate_bps),
3408 DataRate::BitsPerSec(kEncoderBitrateLimits720p.min_start_bitrate_bps),
3409 DataRate::BitsPerSec(kEncoderBitrateLimits720p.min_start_bitrate_bps), 0,
3410 0, 0);
Sergey Silkin41c650b2019-10-14 11:12:193411
3412 // Enable MAINTAIN_FRAMERATE preference, no initial limitation.
Tomas Gunnarsson612445e2020-09-21 12:31:233413 AdaptingFrameForwarder source(&time_controller_);
Sergey Silkin41c650b2019-10-14 11:12:193414 source.set_adaptation_enabled(true);
3415 video_stream_encoder_->SetSource(
3416 &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
3417
3418 // Insert 720p frame.
3419 int64_t timestamp_ms = kFrameIntervalMs;
3420 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, 1280, 720));
3421 WaitForEncodedFrame(1280, 720);
3422
3423 // Reduce bitrate and trigger adapt down.
Henrik Boström381d1092020-05-12 16:49:073424 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:073425 DataRate::BitsPerSec(kEncoderBitrateLimits540p.min_start_bitrate_bps),
3426 DataRate::BitsPerSec(kEncoderBitrateLimits540p.min_start_bitrate_bps),
3427 DataRate::BitsPerSec(kEncoderBitrateLimits540p.min_start_bitrate_bps), 0,
3428 0, 0);
Sergey Silkin41c650b2019-10-14 11:12:193429 video_stream_encoder_->TriggerQualityLow();
3430
3431 // Insert 720p frame. It should be downscaled and encoded.
3432 timestamp_ms += kFrameIntervalMs;
3433 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, 1280, 720));
3434 WaitForEncodedFrame(960, 540);
3435
3436 // Trigger adapt up. Higher resolution should not be requested duo to lack
3437 // of bitrate.
3438 video_stream_encoder_->TriggerQualityHigh();
Evan Shrubsole5cd7eb82020-05-25 12:08:393439 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMatches(Lt(1280 * 720)));
Sergey Silkin41c650b2019-10-14 11:12:193440
3441 // Increase bitrate.
Henrik Boström381d1092020-05-12 16:49:073442 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:073443 DataRate::BitsPerSec(kEncoderBitrateLimits720p.min_start_bitrate_bps),
3444 DataRate::BitsPerSec(kEncoderBitrateLimits720p.min_start_bitrate_bps),
3445 DataRate::BitsPerSec(kEncoderBitrateLimits720p.min_start_bitrate_bps), 0,
3446 0, 0);
Sergey Silkin41c650b2019-10-14 11:12:193447
3448 // Trigger adapt up. Higher resolution should be requested.
3449 video_stream_encoder_->TriggerQualityHigh();
Evan Shrubsole5cd7eb82020-05-25 12:08:393450 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
Sergey Silkin41c650b2019-10-14 11:12:193451
3452 video_stream_encoder_->Stop();
3453}
3454
3455TEST_F(VideoStreamEncoderTest, DropFirstFramesIfBwEstimateIsTooLow) {
3456 fake_encoder_.SetResolutionBitrateLimits(
3457 {kEncoderBitrateLimits540p, kEncoderBitrateLimits720p});
3458
3459 // Set bitrate equal to min bitrate of 540p.
Henrik Boström381d1092020-05-12 16:49:073460 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:073461 DataRate::BitsPerSec(kEncoderBitrateLimits540p.min_start_bitrate_bps),
3462 DataRate::BitsPerSec(kEncoderBitrateLimits540p.min_start_bitrate_bps),
3463 DataRate::BitsPerSec(kEncoderBitrateLimits540p.min_start_bitrate_bps), 0,
3464 0, 0);
Sergey Silkin41c650b2019-10-14 11:12:193465
3466 // Enable MAINTAIN_FRAMERATE preference, no initial limitation.
Tomas Gunnarsson612445e2020-09-21 12:31:233467 AdaptingFrameForwarder source(&time_controller_);
Sergey Silkin41c650b2019-10-14 11:12:193468 source.set_adaptation_enabled(true);
3469 video_stream_encoder_->SetSource(
3470 &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
3471
3472 // Insert 720p frame. It should be dropped and lower resolution should be
3473 // requested.
3474 int64_t timestamp_ms = kFrameIntervalMs;
3475 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, 1280, 720));
3476 ExpectDroppedFrame();
Henrik Boström2671dac2020-05-19 14:29:093477 EXPECT_TRUE_WAIT(source.sink_wants().max_pixel_count < 1280 * 720, 5000);
Sergey Silkin41c650b2019-10-14 11:12:193478
3479 // Insert 720p frame. It should be downscaled and encoded.
3480 timestamp_ms += kFrameIntervalMs;
3481 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, 1280, 720));
3482 WaitForEncodedFrame(960, 540);
3483
3484 video_stream_encoder_->Stop();
3485}
3486
Åsa Perssonb67c44c2019-09-24 13:25:323487class BalancedDegradationTest : public VideoStreamEncoderTest {
3488 protected:
3489 void SetupTest() {
3490 // Reset encoder for field trials to take effect.
3491 ConfigureEncoder(video_encoder_config_.Copy());
Åsa Perssonccfb3402019-09-25 13:13:043492 OnBitrateUpdated(kTargetBitrateBps);
Åsa Perssonb67c44c2019-09-24 13:25:323493
3494 // Enable BALANCED preference.
3495 source_.set_adaptation_enabled(true);
Åsa Perssonccfb3402019-09-25 13:13:043496 video_stream_encoder_->SetSource(&source_, DegradationPreference::BALANCED);
3497 }
3498
3499 void OnBitrateUpdated(int bitrate_bps) {
Henrik Boström381d1092020-05-12 16:49:073500 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:073501 DataRate::BitsPerSec(bitrate_bps), DataRate::BitsPerSec(bitrate_bps),
3502 DataRate::BitsPerSec(bitrate_bps), 0, 0, 0);
Åsa Perssonb67c44c2019-09-24 13:25:323503 }
3504
Åsa Persson45b176f2019-09-30 09:19:053505 void InsertFrame() {
Åsa Perssonb67c44c2019-09-24 13:25:323506 timestamp_ms_ += kFrameIntervalMs;
3507 source_.IncomingCapturedFrame(CreateFrame(timestamp_ms_, kWidth, kHeight));
Åsa Persson45b176f2019-09-30 09:19:053508 }
3509
3510 void InsertFrameAndWaitForEncoded() {
3511 InsertFrame();
Åsa Perssonb67c44c2019-09-24 13:25:323512 sink_.WaitForEncodedFrame(timestamp_ms_);
3513 }
3514
3515 const int kWidth = 640; // pixels:640x360=230400
3516 const int kHeight = 360;
3517 const int64_t kFrameIntervalMs = 150; // Use low fps to not drop any frame.
3518 int64_t timestamp_ms_ = 0;
Tomas Gunnarsson612445e2020-09-21 12:31:233519 AdaptingFrameForwarder source_{&time_controller_};
Åsa Perssonb67c44c2019-09-24 13:25:323520};
3521
Evan Shrubsolea1c77f62020-08-10 09:01:063522TEST_F(BalancedDegradationTest, AdaptDownTwiceIfMinFpsDiffLtThreshold) {
Åsa Perssonb67c44c2019-09-24 13:25:323523 test::ScopedFieldTrials field_trials(
3524 "WebRTC-Video-BalancedDegradationSettings/"
3525 "pixels:57600|129600|230400,fps:7|10|24,fps_diff:1|1|1/");
3526 SetupTest();
3527
3528 // Force input frame rate.
3529 const int kInputFps = 24;
3530 VideoSendStream::Stats stats = stats_proxy_->GetStats();
3531 stats.input_frame_rate = kInputFps;
3532 stats_proxy_->SetMockStats(stats);
3533
Åsa Persson45b176f2019-09-30 09:19:053534 InsertFrameAndWaitForEncoded();
Evan Shrubsole5cd7eb82020-05-25 12:08:393535 EXPECT_THAT(source_.sink_wants(), FpsMaxResolutionMax());
Åsa Perssonb67c44c2019-09-24 13:25:323536
Evan Shrubsolea1c77f62020-08-10 09:01:063537 // Trigger adapt down, expect scaled down framerate and resolution,
3538 // since Fps diff (input-requested:0) < threshold.
3539 video_stream_encoder_->TriggerQualityLow();
3540 EXPECT_THAT(source_.sink_wants(),
3541 AllOf(WantsFps(Eq(24)), WantsMaxPixels(Le(230400))));
Åsa Perssonb67c44c2019-09-24 13:25:323542
3543 video_stream_encoder_->Stop();
3544}
3545
Evan Shrubsolea1c77f62020-08-10 09:01:063546TEST_F(BalancedDegradationTest, AdaptDownOnceIfFpsDiffGeThreshold) {
Åsa Perssonb67c44c2019-09-24 13:25:323547 test::ScopedFieldTrials field_trials(
3548 "WebRTC-Video-BalancedDegradationSettings/"
3549 "pixels:57600|129600|230400,fps:7|10|24,fps_diff:1|1|1/");
3550 SetupTest();
3551
3552 // Force input frame rate.
3553 const int kInputFps = 25;
3554 VideoSendStream::Stats stats = stats_proxy_->GetStats();
3555 stats.input_frame_rate = kInputFps;
3556 stats_proxy_->SetMockStats(stats);
3557
Åsa Persson45b176f2019-09-30 09:19:053558 InsertFrameAndWaitForEncoded();
Evan Shrubsole5cd7eb82020-05-25 12:08:393559 EXPECT_THAT(source_.sink_wants(), FpsMaxResolutionMax());
Åsa Perssonb67c44c2019-09-24 13:25:323560
Evan Shrubsolea1c77f62020-08-10 09:01:063561 // Trigger adapt down, expect scaled down framerate only (640x360@24fps).
3562 // Fps diff (input-requested:1) == threshold.
3563 video_stream_encoder_->TriggerQualityLow();
Evan Shrubsole5cd7eb82020-05-25 12:08:393564 EXPECT_THAT(source_.sink_wants(), FpsMatchesResolutionMax(Eq(24)));
Åsa Perssonb67c44c2019-09-24 13:25:323565
3566 video_stream_encoder_->Stop();
3567}
3568
3569TEST_F(BalancedDegradationTest, AdaptDownUsesCodecSpecificFps) {
3570 test::ScopedFieldTrials field_trials(
3571 "WebRTC-Video-BalancedDegradationSettings/"
3572 "pixels:57600|129600|230400,fps:7|10|24,vp8_fps:8|11|22/");
3573 SetupTest();
3574
3575 EXPECT_EQ(kVideoCodecVP8, video_encoder_config_.codec_type);
3576
Åsa Persson45b176f2019-09-30 09:19:053577 InsertFrameAndWaitForEncoded();
Evan Shrubsole5cd7eb82020-05-25 12:08:393578 EXPECT_THAT(source_.sink_wants(), FpsMaxResolutionMax());
Åsa Perssonb67c44c2019-09-24 13:25:323579
3580 // Trigger adapt down, expect scaled down framerate (640x360@22fps).
3581 video_stream_encoder_->TriggerQualityLow();
Evan Shrubsole5cd7eb82020-05-25 12:08:393582 EXPECT_THAT(source_.sink_wants(), FpsMatchesResolutionMax(Eq(22)));
Åsa Perssonb67c44c2019-09-24 13:25:323583
3584 video_stream_encoder_->Stop();
3585}
3586
Åsa Perssonccfb3402019-09-25 13:13:043587TEST_F(BalancedDegradationTest, NoAdaptUpIfBwEstimateIsLessThanMinBitrate) {
Åsa Perssonb67c44c2019-09-24 13:25:323588 test::ScopedFieldTrials field_trials(
Åsa Persson1b247f12019-08-14 15:26:393589 "WebRTC-Video-BalancedDegradationSettings/"
3590 "pixels:57600|129600|230400,fps:7|10|14,kbps:0|0|425/");
Åsa Perssonccfb3402019-09-25 13:13:043591 SetupTest();
Åsa Persson1b247f12019-08-14 15:26:393592
Åsa Persson1b247f12019-08-14 15:26:393593 const int kMinBitrateBps = 425000;
3594 const int kTooLowMinBitrateBps = 424000;
Åsa Perssonccfb3402019-09-25 13:13:043595 OnBitrateUpdated(kTooLowMinBitrateBps);
Åsa Persson1b247f12019-08-14 15:26:393596
Åsa Persson45b176f2019-09-30 09:19:053597 InsertFrameAndWaitForEncoded();
Evan Shrubsole5cd7eb82020-05-25 12:08:393598 EXPECT_THAT(source_.sink_wants(), FpsMaxResolutionMax());
Åsa Persson1b247f12019-08-14 15:26:393599 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3600
3601 // Trigger adapt down, expect scaled down framerate (640x360@14fps).
3602 video_stream_encoder_->TriggerQualityLow();
Åsa Persson45b176f2019-09-30 09:19:053603 InsertFrameAndWaitForEncoded();
Evan Shrubsole5cd7eb82020-05-25 12:08:393604 EXPECT_THAT(source_.sink_wants(), FpsMatchesResolutionMax(Eq(14)));
Åsa Persson1b247f12019-08-14 15:26:393605 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3606
3607 // Trigger adapt down, expect scaled down resolution (480x270@14fps).
3608 video_stream_encoder_->TriggerQualityLow();
Åsa Persson45b176f2019-09-30 09:19:053609 InsertFrameAndWaitForEncoded();
Evan Shrubsole5fd40602020-05-25 14:19:543610 EXPECT_THAT(source_.sink_wants(), FpsEqResolutionLt(source_.last_wants()));
Åsa Persson1b247f12019-08-14 15:26:393611 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3612
Åsa Persson30ab0152019-08-27 10:22:333613 // Trigger adapt down, expect scaled down framerate (480x270@10fps).
3614 video_stream_encoder_->TriggerQualityLow();
Åsa Persson45b176f2019-09-30 09:19:053615 InsertFrameAndWaitForEncoded();
Evan Shrubsole5fd40602020-05-25 14:19:543616 EXPECT_THAT(source_.sink_wants(), FpsLtResolutionEq(source_.last_wants()));
Åsa Perssonccfb3402019-09-25 13:13:043617 EXPECT_EQ(source_.sink_wants().max_framerate_fps, 10);
Åsa Persson30ab0152019-08-27 10:22:333618 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3619
3620 // Trigger adapt up, expect no upscale in fps (target bitrate < min bitrate).
Åsa Persson1b247f12019-08-14 15:26:393621 video_stream_encoder_->TriggerQualityHigh();
Åsa Persson45b176f2019-09-30 09:19:053622 InsertFrameAndWaitForEncoded();
Åsa Persson30ab0152019-08-27 10:22:333623 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_quality_adapt_changes);
Åsa Persson1b247f12019-08-14 15:26:393624
Åsa Persson30ab0152019-08-27 10:22:333625 // Trigger adapt up, expect upscaled fps (target bitrate == min bitrate).
Åsa Perssonccfb3402019-09-25 13:13:043626 OnBitrateUpdated(kMinBitrateBps);
Åsa Persson1b247f12019-08-14 15:26:393627 video_stream_encoder_->TriggerQualityHigh();
Åsa Persson45b176f2019-09-30 09:19:053628 InsertFrameAndWaitForEncoded();
Åsa Perssonccfb3402019-09-25 13:13:043629 EXPECT_EQ(source_.sink_wants().max_framerate_fps, 14);
Åsa Persson30ab0152019-08-27 10:22:333630 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3631
3632 video_stream_encoder_->Stop();
3633}
3634
Åsa Perssonccfb3402019-09-25 13:13:043635TEST_F(BalancedDegradationTest,
Åsa Persson45b176f2019-09-30 09:19:053636 InitialFrameDropAdaptsFpsAndResolutionInOneStep) {
3637 test::ScopedFieldTrials field_trials(
3638 "WebRTC-Video-BalancedDegradationSettings/"
3639 "pixels:57600|129600|230400,fps:7|24|24/");
3640 SetupTest();
3641 OnBitrateUpdated(kLowTargetBitrateBps);
3642
Evan Shrubsole5cd7eb82020-05-25 12:08:393643 EXPECT_THAT(source_.sink_wants(), UnlimitedSinkWants());
Åsa Persson45b176f2019-09-30 09:19:053644
3645 // Insert frame, expect scaled down:
3646 // framerate (640x360@24fps) -> resolution (480x270@24fps).
3647 InsertFrame();
3648 EXPECT_FALSE(WaitForFrame(1000));
3649 EXPECT_LT(source_.sink_wants().max_pixel_count, kWidth * kHeight);
3650 EXPECT_EQ(source_.sink_wants().max_framerate_fps, 24);
3651
3652 // Insert frame, expect scaled down:
3653 // resolution (320x180@24fps).
3654 InsertFrame();
3655 EXPECT_FALSE(WaitForFrame(1000));
3656 EXPECT_LT(source_.sink_wants().max_pixel_count,
3657 source_.last_wants().max_pixel_count);
3658 EXPECT_EQ(source_.sink_wants().max_framerate_fps, 24);
3659
3660 // Frame should not be dropped (min pixels per frame reached).
3661 InsertFrameAndWaitForEncoded();
3662
3663 video_stream_encoder_->Stop();
3664}
3665
3666TEST_F(BalancedDegradationTest,
Åsa Persson30ab0152019-08-27 10:22:333667 NoAdaptUpInResolutionIfBwEstimateIsLessThanMinBitrate) {
Åsa Perssonb67c44c2019-09-24 13:25:323668 test::ScopedFieldTrials field_trials(
Åsa Persson30ab0152019-08-27 10:22:333669 "WebRTC-Video-BalancedDegradationSettings/"
3670 "pixels:57600|129600|230400,fps:7|10|14,kbps_res:0|0|435/");
Åsa Perssonccfb3402019-09-25 13:13:043671 SetupTest();
Åsa Persson30ab0152019-08-27 10:22:333672
Åsa Persson30ab0152019-08-27 10:22:333673 const int kResolutionMinBitrateBps = 435000;
3674 const int kTooLowMinResolutionBitrateBps = 434000;
Åsa Perssonccfb3402019-09-25 13:13:043675 OnBitrateUpdated(kTooLowMinResolutionBitrateBps);
Åsa Persson30ab0152019-08-27 10:22:333676
Åsa Persson45b176f2019-09-30 09:19:053677 InsertFrameAndWaitForEncoded();
Evan Shrubsole5cd7eb82020-05-25 12:08:393678 EXPECT_THAT(source_.sink_wants(), FpsMaxResolutionMax());
Åsa Persson30ab0152019-08-27 10:22:333679 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3680
3681 // Trigger adapt down, expect scaled down framerate (640x360@14fps).
3682 video_stream_encoder_->TriggerQualityLow();
Åsa Persson45b176f2019-09-30 09:19:053683 InsertFrameAndWaitForEncoded();
Evan Shrubsole5cd7eb82020-05-25 12:08:393684 EXPECT_THAT(source_.sink_wants(), FpsMatchesResolutionMax(Eq(14)));
Åsa Persson30ab0152019-08-27 10:22:333685 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3686
3687 // Trigger adapt down, expect scaled down resolution (480x270@14fps).
3688 video_stream_encoder_->TriggerQualityLow();
Åsa Persson45b176f2019-09-30 09:19:053689 InsertFrameAndWaitForEncoded();
Evan Shrubsole5fd40602020-05-25 14:19:543690 EXPECT_THAT(source_.sink_wants(), FpsEqResolutionLt(source_.last_wants()));
Åsa Persson30ab0152019-08-27 10:22:333691 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3692
3693 // Trigger adapt down, expect scaled down framerate (480x270@10fps).
3694 video_stream_encoder_->TriggerQualityLow();
Åsa Persson45b176f2019-09-30 09:19:053695 InsertFrameAndWaitForEncoded();
Evan Shrubsole5fd40602020-05-25 14:19:543696 EXPECT_THAT(source_.sink_wants(), FpsLtResolutionEq(source_.last_wants()));
Åsa Persson1b247f12019-08-14 15:26:393697 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3698
Åsa Persson30ab0152019-08-27 10:22:333699 // Trigger adapt up, expect upscaled fps (no bitrate limit) (480x270@14fps).
3700 video_stream_encoder_->TriggerQualityHigh();
Åsa Persson45b176f2019-09-30 09:19:053701 InsertFrameAndWaitForEncoded();
Evan Shrubsole5fd40602020-05-25 14:19:543702 EXPECT_THAT(source_.sink_wants(), FpsGtResolutionEq(source_.last_wants()));
Åsa Persson30ab0152019-08-27 10:22:333703 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3704
3705 // Trigger adapt up, expect no upscale in res (target bitrate < min bitrate).
3706 video_stream_encoder_->TriggerQualityHigh();
Åsa Persson45b176f2019-09-30 09:19:053707 InsertFrameAndWaitForEncoded();
Åsa Persson30ab0152019-08-27 10:22:333708 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3709
3710 // Trigger adapt up, expect upscaled res (target bitrate == min bitrate).
Åsa Perssonccfb3402019-09-25 13:13:043711 OnBitrateUpdated(kResolutionMinBitrateBps);
Åsa Persson30ab0152019-08-27 10:22:333712 video_stream_encoder_->TriggerQualityHigh();
Åsa Persson45b176f2019-09-30 09:19:053713 InsertFrameAndWaitForEncoded();
Evan Shrubsole5fd40602020-05-25 14:19:543714 EXPECT_THAT(source_.sink_wants(), FpsEqResolutionGt(source_.last_wants()));
Åsa Persson30ab0152019-08-27 10:22:333715 EXPECT_EQ(5, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3716
3717 video_stream_encoder_->Stop();
3718}
3719
Åsa Perssonccfb3402019-09-25 13:13:043720TEST_F(BalancedDegradationTest,
Åsa Persson30ab0152019-08-27 10:22:333721 NoAdaptUpInFpsAndResolutionIfBwEstimateIsLessThanMinBitrate) {
Åsa Perssonb67c44c2019-09-24 13:25:323722 test::ScopedFieldTrials field_trials(
Åsa Persson30ab0152019-08-27 10:22:333723 "WebRTC-Video-BalancedDegradationSettings/"
3724 "pixels:57600|129600|230400,fps:7|10|14,kbps:0|0|425,kbps_res:0|0|435/");
Åsa Perssonccfb3402019-09-25 13:13:043725 SetupTest();
Åsa Persson30ab0152019-08-27 10:22:333726
Åsa Persson30ab0152019-08-27 10:22:333727 const int kMinBitrateBps = 425000;
3728 const int kTooLowMinBitrateBps = 424000;
3729 const int kResolutionMinBitrateBps = 435000;
3730 const int kTooLowMinResolutionBitrateBps = 434000;
Åsa Perssonccfb3402019-09-25 13:13:043731 OnBitrateUpdated(kTooLowMinBitrateBps);
Åsa Persson30ab0152019-08-27 10:22:333732
Åsa Persson45b176f2019-09-30 09:19:053733 InsertFrameAndWaitForEncoded();
Evan Shrubsole5cd7eb82020-05-25 12:08:393734 EXPECT_THAT(source_.sink_wants(), FpsMaxResolutionMax());
Åsa Persson30ab0152019-08-27 10:22:333735 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3736
3737 // Trigger adapt down, expect scaled down framerate (640x360@14fps).
3738 video_stream_encoder_->TriggerQualityLow();
Åsa Persson45b176f2019-09-30 09:19:053739 InsertFrameAndWaitForEncoded();
Evan Shrubsole5cd7eb82020-05-25 12:08:393740 EXPECT_THAT(source_.sink_wants(), FpsMatchesResolutionMax(Eq(14)));
Åsa Persson30ab0152019-08-27 10:22:333741 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3742
3743 // Trigger adapt down, expect scaled down resolution (480x270@14fps).
3744 video_stream_encoder_->TriggerQualityLow();
Åsa Persson45b176f2019-09-30 09:19:053745 InsertFrameAndWaitForEncoded();
Evan Shrubsole5fd40602020-05-25 14:19:543746 EXPECT_THAT(source_.sink_wants(), FpsEqResolutionLt(source_.last_wants()));
Åsa Persson30ab0152019-08-27 10:22:333747 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3748
3749 // Trigger adapt down, expect scaled down framerate (480x270@10fps).
3750 video_stream_encoder_->TriggerQualityLow();
Åsa Persson45b176f2019-09-30 09:19:053751 InsertFrameAndWaitForEncoded();
Evan Shrubsole5fd40602020-05-25 14:19:543752 EXPECT_THAT(source_.sink_wants(), FpsLtResolutionEq(source_.last_wants()));
Åsa Persson30ab0152019-08-27 10:22:333753 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3754
3755 // Trigger adapt up, expect no upscale (target bitrate < min bitrate).
3756 video_stream_encoder_->TriggerQualityHigh();
Åsa Persson45b176f2019-09-30 09:19:053757 InsertFrameAndWaitForEncoded();
Åsa Persson30ab0152019-08-27 10:22:333758 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3759
3760 // Trigger adapt up, expect upscaled fps (target bitrate == min bitrate).
Åsa Perssonccfb3402019-09-25 13:13:043761 OnBitrateUpdated(kMinBitrateBps);
Åsa Persson30ab0152019-08-27 10:22:333762 video_stream_encoder_->TriggerQualityHigh();
Åsa Persson45b176f2019-09-30 09:19:053763 InsertFrameAndWaitForEncoded();
Evan Shrubsole5fd40602020-05-25 14:19:543764 EXPECT_THAT(source_.sink_wants(), FpsGtResolutionEq(source_.last_wants()));
Åsa Persson30ab0152019-08-27 10:22:333765 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3766
3767 // Trigger adapt up, expect no upscale in res (target bitrate < min bitrate).
Åsa Perssonccfb3402019-09-25 13:13:043768 OnBitrateUpdated(kTooLowMinResolutionBitrateBps);
Åsa Persson30ab0152019-08-27 10:22:333769 video_stream_encoder_->TriggerQualityHigh();
Åsa Persson45b176f2019-09-30 09:19:053770 InsertFrameAndWaitForEncoded();
Åsa Persson30ab0152019-08-27 10:22:333771 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3772
3773 // Trigger adapt up, expect upscaled res (target bitrate == min bitrate).
Åsa Perssonccfb3402019-09-25 13:13:043774 OnBitrateUpdated(kResolutionMinBitrateBps);
Åsa Persson30ab0152019-08-27 10:22:333775 video_stream_encoder_->TriggerQualityHigh();
Åsa Persson45b176f2019-09-30 09:19:053776 InsertFrameAndWaitForEncoded();
Evan Shrubsole5fd40602020-05-25 14:19:543777 EXPECT_THAT(source_.sink_wants(), FpsEqResolutionGt(source_.last_wants()));
Åsa Persson30ab0152019-08-27 10:22:333778 EXPECT_EQ(5, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3779
Åsa Persson1b247f12019-08-14 15:26:393780 video_stream_encoder_->Stop();
3781}
3782
mflodmancc3d4422017-08-03 15:27:513783TEST_F(VideoStreamEncoderTest,
asaperssond0de2952017-04-21 08:47:313784 AdaptsResolutionOnOveruseAndLowQuality_MaintainFramerateMode) {
3785 const int kWidth = 1280;
3786 const int kHeight = 720;
Henrik Boström381d1092020-05-12 16:49:073787 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:073788 DataRate::BitsPerSec(kTargetBitrateBps),
3789 DataRate::BitsPerSec(kTargetBitrateBps),
3790 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asaperssond0de2952017-04-21 08:47:313791
Taylor Brandstetter49fcc102018-05-16 21:20:413792 // Enable MAINTAIN_FRAMERATE preference, no initial limitation.
Tomas Gunnarsson612445e2020-09-21 12:31:233793 AdaptingFrameForwarder source(&time_controller_);
asaperssond0de2952017-04-21 08:47:313794 source.set_adaptation_enabled(true);
mflodmancc3d4422017-08-03 15:27:513795 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 21:20:413796 &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
asaperssond0de2952017-04-21 08:47:313797
Åsa Persson8c1bf952018-09-13 08:42:193798 int64_t timestamp_ms = kFrameIntervalMs;
3799 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:523800 WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5cd7eb82020-05-25 12:08:393801 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssond0de2952017-04-21 08:47:313802 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
3803 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
3804 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3805 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3806
3807 // Trigger cpu adapt down, expect scaled down resolution (960x540).
mflodmancc3d4422017-08-03 15:27:513808 video_stream_encoder_->TriggerCpuOveruse();
Åsa Persson8c1bf952018-09-13 08:42:193809 timestamp_ms += kFrameIntervalMs;
3810 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
3811 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5cd7eb82020-05-25 12:08:393812 EXPECT_THAT(source.sink_wants(),
3813 FpsMaxResolutionMatches(Lt(kWidth * kHeight)));
asaperssond0de2952017-04-21 08:47:313814 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
3815 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
3816 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3817 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3818
3819 // Trigger cpu adapt down, expect scaled down resolution (640x360).
mflodmancc3d4422017-08-03 15:27:513820 video_stream_encoder_->TriggerCpuOveruse();
Åsa Persson8c1bf952018-09-13 08:42:193821 timestamp_ms += kFrameIntervalMs;
3822 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
3823 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 14:19:543824 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionLt(source.last_wants()));
asaperssond0de2952017-04-21 08:47:313825 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
3826 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
3827 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3828 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3829
Jonathan Yubc771b72017-12-09 01:04:293830 // Trigger cpu adapt down, expect scaled down resolution (480x270).
mflodmancc3d4422017-08-03 15:27:513831 video_stream_encoder_->TriggerCpuOveruse();
Åsa Persson8c1bf952018-09-13 08:42:193832 timestamp_ms += kFrameIntervalMs;
3833 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
3834 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 14:19:543835 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionLt(source.last_wants()));
asaperssond0de2952017-04-21 08:47:313836 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
3837 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
Jonathan Yubc771b72017-12-09 01:04:293838 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
asaperssond0de2952017-04-21 08:47:313839 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3840
Jonathan Yubc771b72017-12-09 01:04:293841 // Trigger quality adapt down, expect scaled down resolution (320x180).
mflodmancc3d4422017-08-03 15:27:513842 video_stream_encoder_->TriggerQualityLow();
Åsa Persson8c1bf952018-09-13 08:42:193843 timestamp_ms += kFrameIntervalMs;
3844 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
3845 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 14:19:543846 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionLt(source.last_wants()));
Jonathan Yubc771b72017-12-09 01:04:293847 rtc::VideoSinkWants last_wants = source.sink_wants();
asaperssond0de2952017-04-21 08:47:313848 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
3849 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
3850 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3851 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3852
Jonathan Yubc771b72017-12-09 01:04:293853 // Trigger quality adapt down, expect no change (min resolution reached).
3854 video_stream_encoder_->TriggerQualityLow();
Åsa Persson8c1bf952018-09-13 08:42:193855 timestamp_ms += kFrameIntervalMs;
3856 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
3857 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 14:19:543858 EXPECT_THAT(source.sink_wants(), FpsMax());
3859 EXPECT_EQ(source.sink_wants().max_pixel_count, last_wants.max_pixel_count);
Jonathan Yubc771b72017-12-09 01:04:293860 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
3861 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
3862 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3863 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3864
Evan Shrubsole64469032020-06-11 08:45:293865 // Trigger quality adapt up, expect upscaled resolution (480x270).
3866 video_stream_encoder_->TriggerQualityHigh();
3867 timestamp_ms += kFrameIntervalMs;
3868 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
3869 WaitForEncodedFrame(timestamp_ms);
3870 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionGt(source.last_wants()));
3871 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
3872 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
3873 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3874 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3875
3876 // Trigger quality and cpu adapt up since both are most limited, expect
3877 // upscaled resolution (640x360).
Henrik Boström91aa7322020-04-28 10:24:333878 video_stream_encoder_->TriggerCpuUnderuse();
Evan Shrubsole64469032020-06-11 08:45:293879 video_stream_encoder_->TriggerQualityHigh();
Åsa Persson8c1bf952018-09-13 08:42:193880 timestamp_ms += kFrameIntervalMs;
3881 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
3882 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 14:19:543883 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionGt(source.last_wants()));
Jonathan Yubc771b72017-12-09 01:04:293884 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
3885 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
3886 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
Evan Shrubsole64469032020-06-11 08:45:293887 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_quality_adapt_changes);
Jonathan Yubc771b72017-12-09 01:04:293888
Evan Shrubsole64469032020-06-11 08:45:293889 // Trigger quality and cpu adapt up since both are most limited, expect
3890 // upscaled resolution (960x540).
Henrik Boström91aa7322020-04-28 10:24:333891 video_stream_encoder_->TriggerCpuUnderuse();
Evan Shrubsole64469032020-06-11 08:45:293892 video_stream_encoder_->TriggerQualityHigh();
Åsa Persson8c1bf952018-09-13 08:42:193893 timestamp_ms += kFrameIntervalMs;
3894 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
3895 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 14:19:543896 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionGt(source.last_wants()));
asaperssond0de2952017-04-21 08:47:313897 last_wants = source.sink_wants();
Evan Shrubsole64469032020-06-11 08:45:293898 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
asaperssond0de2952017-04-21 08:47:313899 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
Evan Shrubsole64469032020-06-11 08:45:293900 EXPECT_EQ(5, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3901 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_quality_adapt_changes);
asaperssond0de2952017-04-21 08:47:313902
Evan Shrubsole64469032020-06-11 08:45:293903 // Trigger cpu adapt up, expect no change since not most limited (960x540).
3904 // However the stats will change since the CPU resource is no longer limited.
Henrik Boström91aa7322020-04-28 10:24:333905 video_stream_encoder_->TriggerCpuUnderuse();
Åsa Persson8c1bf952018-09-13 08:42:193906 timestamp_ms += kFrameIntervalMs;
3907 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
3908 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 14:19:543909 EXPECT_THAT(source.sink_wants(), FpsEqResolutionEqTo(last_wants));
asaperssond0de2952017-04-21 08:47:313910 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
3911 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
Jonathan Yubc771b72017-12-09 01:04:293912 EXPECT_EQ(6, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
Evan Shrubsole64469032020-06-11 08:45:293913 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_quality_adapt_changes);
asaperssond0de2952017-04-21 08:47:313914
3915 // Trigger quality adapt up, expect no restriction (1280x720).
mflodmancc3d4422017-08-03 15:27:513916 video_stream_encoder_->TriggerQualityHigh();
Åsa Persson8c1bf952018-09-13 08:42:193917 timestamp_ms += kFrameIntervalMs;
3918 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:523919 WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5fd40602020-05-25 14:19:543920 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionGt(source.last_wants()));
Evan Shrubsole5cd7eb82020-05-25 12:08:393921 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssond0de2952017-04-21 08:47:313922 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
3923 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
Jonathan Yubc771b72017-12-09 01:04:293924 EXPECT_EQ(6, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
Evan Shrubsole64469032020-06-11 08:45:293925 EXPECT_EQ(5, stats_proxy_->GetStats().number_of_quality_adapt_changes);
kthelgason5e13d412016-12-01 11:59:513926
mflodmancc3d4422017-08-03 15:27:513927 video_stream_encoder_->Stop();
kthelgason5e13d412016-12-01 11:59:513928}
3929
mflodmancc3d4422017-08-03 15:27:513930TEST_F(VideoStreamEncoderTest, CpuLimitedHistogramIsReported) {
asaperssonfab67072017-04-04 12:51:493931 const int kWidth = 640;
3932 const int kHeight = 360;
perkj803d97f2016-11-01 18:45:463933
Henrik Boström381d1092020-05-12 16:49:073934 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:073935 DataRate::BitsPerSec(kTargetBitrateBps),
3936 DataRate::BitsPerSec(kTargetBitrateBps),
3937 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
sprang4847ae62017-06-27 14:06:523938
perkj803d97f2016-11-01 18:45:463939 for (int i = 1; i <= SendStatisticsProxy::kMinRequiredMetricsSamples; ++i) {
asaperssonfab67072017-04-04 12:51:493940 video_source_.IncomingCapturedFrame(CreateFrame(i, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:523941 WaitForEncodedFrame(i);
perkj803d97f2016-11-01 18:45:463942 }
3943
mflodmancc3d4422017-08-03 15:27:513944 video_stream_encoder_->TriggerCpuOveruse();
perkj803d97f2016-11-01 18:45:463945 for (int i = 1; i <= SendStatisticsProxy::kMinRequiredMetricsSamples; ++i) {
asaperssonfab67072017-04-04 12:51:493946 video_source_.IncomingCapturedFrame(CreateFrame(
3947 SendStatisticsProxy::kMinRequiredMetricsSamples + i, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:523948 WaitForEncodedFrame(SendStatisticsProxy::kMinRequiredMetricsSamples + i);
perkj803d97f2016-11-01 18:45:463949 }
3950
mflodmancc3d4422017-08-03 15:27:513951 video_stream_encoder_->Stop();
3952 video_stream_encoder_.reset();
perkj803d97f2016-11-01 18:45:463953 stats_proxy_.reset();
sprangf8ee65e2017-02-28 16:49:333954
Ying Wangef3998f2019-12-09 12:06:533955 EXPECT_METRIC_EQ(
3956 1, metrics::NumSamples("WebRTC.Video.CpuLimitedResolutionInPercent"));
3957 EXPECT_METRIC_EQ(
perkj803d97f2016-11-01 18:45:463958 1, metrics::NumEvents("WebRTC.Video.CpuLimitedResolutionInPercent", 50));
3959}
3960
mflodmancc3d4422017-08-03 15:27:513961TEST_F(VideoStreamEncoderTest,
3962 CpuLimitedHistogramIsNotReportedForDisabledDegradation) {
Henrik Boström381d1092020-05-12 16:49:073963 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:073964 DataRate::BitsPerSec(kTargetBitrateBps),
3965 DataRate::BitsPerSec(kTargetBitrateBps),
3966 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asaperssonf4e44af2017-04-19 09:01:063967 const int kWidth = 640;
3968 const int kHeight = 360;
3969
Taylor Brandstetter49fcc102018-05-16 21:20:413970 video_stream_encoder_->SetSource(&video_source_,
3971 webrtc::DegradationPreference::DISABLED);
asaperssonf4e44af2017-04-19 09:01:063972
3973 for (int i = 1; i <= SendStatisticsProxy::kMinRequiredMetricsSamples; ++i) {
3974 video_source_.IncomingCapturedFrame(CreateFrame(i, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:523975 WaitForEncodedFrame(i);
asaperssonf4e44af2017-04-19 09:01:063976 }
3977
mflodmancc3d4422017-08-03 15:27:513978 video_stream_encoder_->Stop();
3979 video_stream_encoder_.reset();
asaperssonf4e44af2017-04-19 09:01:063980 stats_proxy_.reset();
3981
3982 EXPECT_EQ(0,
3983 metrics::NumSamples("WebRTC.Video.CpuLimitedResolutionInPercent"));
3984}
3985
Per Kjellanderdcef6412020-10-07 13:09:053986TEST_F(VideoStreamEncoderTest, ReportsVideoBitrateAllocation) {
3987 ResetEncoder("FAKE", 1, 1, 1, /*screenshare*/ false,
3988 VideoStreamEncoderSettings::BitrateAllocationCallbackType::
3989 kVideoBitrateAllocation);
sprang57c2fff2017-01-16 14:24:023990
3991 const int kDefaultFps = 30;
Erik Språng566124a2018-04-23 10:32:223992 const VideoBitrateAllocation expected_bitrate =
Mirta Dvornicic6799d732020-02-12 14:36:493993 SimulcastRateAllocator(fake_encoder_.codec_config())
Florent Castelli8bbdb5b2019-08-02 13:16:283994 .Allocate(VideoBitrateAllocationParameters(kLowTargetBitrateBps,
3995 kDefaultFps));
sprang57c2fff2017-01-16 14:24:023996
Henrik Boström381d1092020-05-12 16:49:073997 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:073998 DataRate::BitsPerSec(kLowTargetBitrateBps),
3999 DataRate::BitsPerSec(kLowTargetBitrateBps),
4000 DataRate::BitsPerSec(kLowTargetBitrateBps), 0, 0, 0);
sprang57c2fff2017-01-16 14:24:024001
sprang57c2fff2017-01-16 14:24:024002 video_source_.IncomingCapturedFrame(
Tomas Gunnarsson612445e2020-09-21 12:31:234003 CreateFrame(CurrentTimeMs(), codec_width_, codec_height_));
4004 WaitForEncodedFrame(CurrentTimeMs());
Per Kjellanderdcef6412020-10-07 13:09:054005 EXPECT_EQ(sink_.GetLastVideoBitrateAllocation(), expected_bitrate);
4006 EXPECT_EQ(sink_.number_of_bitrate_allocations(), 1);
4007
Erik Språngd7329ca2019-02-21 20:19:534008 // Check that encoder has been updated too, not just allocation observer.
Erik Språng9d69cbe2020-10-22 15:44:424009 EXPECT_TRUE(fake_encoder_.GetAndResetLastRateControlSettings().has_value());
Tomas Gunnarsson612445e2020-09-21 12:31:234010 AdvanceTime(TimeDelta::Seconds(1) / kDefaultFps);
sprang57c2fff2017-01-16 14:24:024011
Per Kjellanderdcef6412020-10-07 13:09:054012 // VideoBitrateAllocation not updated on second frame.
sprang57c2fff2017-01-16 14:24:024013 video_source_.IncomingCapturedFrame(
Tomas Gunnarsson612445e2020-09-21 12:31:234014 CreateFrame(CurrentTimeMs(), codec_width_, codec_height_));
4015 WaitForEncodedFrame(CurrentTimeMs());
Per Kjellanderdcef6412020-10-07 13:09:054016 EXPECT_EQ(sink_.number_of_bitrate_allocations(), 1);
Tomas Gunnarsson612445e2020-09-21 12:31:234017 AdvanceTime(TimeDelta::Millis(1) / kDefaultFps);
sprang57c2fff2017-01-16 14:24:024018
Per Kjellanderdcef6412020-10-07 13:09:054019 // VideoBitrateAllocation updated after a process interval.
Tomas Gunnarsson612445e2020-09-21 12:31:234020 const int64_t start_time_ms = CurrentTimeMs();
Per Kjellanderd0a8f512020-10-07 09:28:414021 while (CurrentTimeMs() - start_time_ms < 5 * kProcessIntervalMs) {
Erik Språngd7329ca2019-02-21 20:19:534022 video_source_.IncomingCapturedFrame(
Tomas Gunnarsson612445e2020-09-21 12:31:234023 CreateFrame(CurrentTimeMs(), codec_width_, codec_height_));
4024 WaitForEncodedFrame(CurrentTimeMs());
4025 AdvanceTime(TimeDelta::Millis(1) / kDefaultFps);
Erik Språngd7329ca2019-02-21 20:19:534026 }
Per Kjellanderdcef6412020-10-07 13:09:054027 EXPECT_GT(sink_.number_of_bitrate_allocations(), 3);
Erik Språngd7329ca2019-02-21 20:19:534028
mflodmancc3d4422017-08-03 15:27:514029 video_stream_encoder_->Stop();
sprang57c2fff2017-01-16 14:24:024030}
4031
Per Kjellandera9434842020-10-15 15:53:224032TEST_F(VideoStreamEncoderTest, ReportsVideoLayersAllocationForV8Simulcast) {
4033 ResetEncoder("VP8", /*num_streams*/ 2, 1, 1, /*screenshare*/ false,
4034 VideoStreamEncoderSettings::BitrateAllocationCallbackType::
4035 kVideoLayersAllocation);
4036
4037 const int kDefaultFps = 30;
4038
4039 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
4040 DataRate::BitsPerSec(kLowTargetBitrateBps),
4041 DataRate::BitsPerSec(kLowTargetBitrateBps),
4042 DataRate::BitsPerSec(kLowTargetBitrateBps), 0, 0, 0);
4043
4044 video_source_.IncomingCapturedFrame(
4045 CreateFrame(CurrentTimeMs(), codec_width_, codec_height_));
4046 WaitForEncodedFrame(CurrentTimeMs());
4047 EXPECT_EQ(sink_.number_of_layers_allocations(), 1);
4048 VideoLayersAllocation last_layer_allocation =
4049 sink_.GetLastVideoLayersAllocation();
4050 // kLowTargetBitrateBps is only enough for one spatial layer.
4051 ASSERT_EQ(last_layer_allocation.active_spatial_layers.size(), 1u);
4052
4053 VideoBitrateAllocation bitrate_allocation =
Erik Språng9d69cbe2020-10-22 15:44:424054 fake_encoder_.GetAndResetLastRateControlSettings()->target_bitrate;
Per Kjellandera9434842020-10-15 15:53:224055 // Check that encoder has been updated too, not just allocation observer.
4056 EXPECT_EQ(bitrate_allocation.get_sum_bps(), kLowTargetBitrateBps);
4057 AdvanceTime(TimeDelta::Seconds(1) / kDefaultFps);
4058
Erik Språng9d69cbe2020-10-22 15:44:424059 // VideoLayersAllocation might be updated if frame rate changes.
Per Kjellandera9434842020-10-15 15:53:224060 int number_of_layers_allocation = 1;
4061 const int64_t start_time_ms = CurrentTimeMs();
4062 while (CurrentTimeMs() - start_time_ms < 10 * kProcessIntervalMs) {
4063 video_source_.IncomingCapturedFrame(
4064 CreateFrame(CurrentTimeMs(), codec_width_, codec_height_));
4065 WaitForEncodedFrame(CurrentTimeMs());
Per Kjellandera9434842020-10-15 15:53:224066 if (number_of_layers_allocation != sink_.number_of_layers_allocations()) {
4067 number_of_layers_allocation = sink_.number_of_layers_allocations();
4068 VideoLayersAllocation new_allocation =
4069 sink_.GetLastVideoLayersAllocation();
4070 ASSERT_EQ(new_allocation.active_spatial_layers.size(), 1u);
4071 EXPECT_NE(new_allocation.active_spatial_layers[0].frame_rate_fps,
4072 last_layer_allocation.active_spatial_layers[0].frame_rate_fps);
4073 EXPECT_EQ(new_allocation.active_spatial_layers[0]
4074 .target_bitrate_per_temporal_layer,
4075 last_layer_allocation.active_spatial_layers[0]
4076 .target_bitrate_per_temporal_layer);
4077 last_layer_allocation = new_allocation;
4078 }
4079 }
4080 EXPECT_LE(sink_.number_of_layers_allocations(), 3);
4081 video_stream_encoder_->Stop();
4082}
4083
4084TEST_F(VideoStreamEncoderTest,
4085 ReportsUpdatedVideoLayersAllocationWhenBweChanges) {
4086 ResetEncoder("VP8", /*num_streams*/ 2, 1, 1, /*screenshare*/ false,
4087 VideoStreamEncoderSettings::BitrateAllocationCallbackType::
4088 kVideoLayersAllocation);
4089
4090 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
4091 DataRate::BitsPerSec(kLowTargetBitrateBps),
4092 DataRate::BitsPerSec(kLowTargetBitrateBps),
4093 DataRate::BitsPerSec(kLowTargetBitrateBps), 0, 0, 0);
4094
4095 video_source_.IncomingCapturedFrame(
4096 CreateFrame(CurrentTimeMs(), codec_width_, codec_height_));
4097 WaitForEncodedFrame(CurrentTimeMs());
4098 EXPECT_EQ(sink_.number_of_layers_allocations(), 1);
4099 VideoLayersAllocation last_layer_allocation =
4100 sink_.GetLastVideoLayersAllocation();
4101 // kLowTargetBitrateBps is only enough for one spatial layer.
4102 ASSERT_EQ(last_layer_allocation.active_spatial_layers.size(), 1u);
4103 EXPECT_EQ(last_layer_allocation.active_spatial_layers[0]
4104 .target_bitrate_per_temporal_layer[0],
4105 DataRate::BitsPerSec(kLowTargetBitrateBps));
4106
4107 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
4108 DataRate::BitsPerSec(kSimulcastTargetBitrateBps),
4109 DataRate::BitsPerSec(kSimulcastTargetBitrateBps),
4110 DataRate::BitsPerSec(kSimulcastTargetBitrateBps), 0, 0, 0);
4111 video_source_.IncomingCapturedFrame(
4112 CreateFrame(CurrentTimeMs(), codec_width_, codec_height_));
4113 WaitForEncodedFrame(CurrentTimeMs());
4114
4115 EXPECT_EQ(sink_.number_of_layers_allocations(), 2);
4116 last_layer_allocation = sink_.GetLastVideoLayersAllocation();
4117 ASSERT_EQ(last_layer_allocation.active_spatial_layers.size(), 2u);
4118 EXPECT_GT(last_layer_allocation.active_spatial_layers[1]
4119 .target_bitrate_per_temporal_layer[0],
4120 DataRate::Zero());
4121
4122 video_stream_encoder_->Stop();
4123}
4124
Åsa Perssonc29cb2c2019-03-25 11:06:594125TEST_F(VideoStreamEncoderTest, TemporalLayersNotDisabledIfSupported) {
4126 // 2 TLs configured, temporal layers supported by encoder.
4127 const int kNumTemporalLayers = 2;
Per Kjellanderdcef6412020-10-07 13:09:054128 ResetEncoder("VP8", 1, kNumTemporalLayers, 1, /*screenshare*/ false,
4129 VideoStreamEncoderSettings::BitrateAllocationCallbackType::
4130 kVideoBitrateAllocation);
Åsa Perssonc29cb2c2019-03-25 11:06:594131 fake_encoder_.SetTemporalLayersSupported(0, true);
4132
4133 // Bitrate allocated across temporal layers.
4134 const int kTl0Bps = kTargetBitrateBps *
4135 webrtc::SimulcastRateAllocator::GetTemporalRateAllocation(
Rasmus Brandt2b9317a2019-10-30 12:01:464136 kNumTemporalLayers, /*temporal_id*/ 0,
4137 /*base_heavy_tl3_alloc*/ false);
Åsa Perssonc29cb2c2019-03-25 11:06:594138 const int kTl1Bps = kTargetBitrateBps *
4139 webrtc::SimulcastRateAllocator::GetTemporalRateAllocation(
Rasmus Brandt2b9317a2019-10-30 12:01:464140 kNumTemporalLayers, /*temporal_id*/ 1,
4141 /*base_heavy_tl3_alloc*/ false);
Åsa Perssonc29cb2c2019-03-25 11:06:594142 VideoBitrateAllocation expected_bitrate;
4143 expected_bitrate.SetBitrate(/*si*/ 0, /*ti*/ 0, kTl0Bps);
4144 expected_bitrate.SetBitrate(/*si*/ 0, /*ti*/ 1, kTl1Bps - kTl0Bps);
4145
4146 VerifyAllocatedBitrate(expected_bitrate);
4147 video_stream_encoder_->Stop();
4148}
4149
4150TEST_F(VideoStreamEncoderTest, TemporalLayersDisabledIfNotSupported) {
4151 // 2 TLs configured, temporal layers not supported by encoder.
Per Kjellanderdcef6412020-10-07 13:09:054152 ResetEncoder("VP8", 1, /*num_temporal_layers*/ 2, 1, /*screenshare*/ false,
4153 VideoStreamEncoderSettings::BitrateAllocationCallbackType::
4154 kVideoBitrateAllocation);
Åsa Perssonc29cb2c2019-03-25 11:06:594155 fake_encoder_.SetTemporalLayersSupported(0, false);
4156
4157 // Temporal layers not supported by the encoder.
4158 // Total bitrate should be at ti:0.
4159 VideoBitrateAllocation expected_bitrate;
4160 expected_bitrate.SetBitrate(/*si*/ 0, /*ti*/ 0, kTargetBitrateBps);
4161
4162 VerifyAllocatedBitrate(expected_bitrate);
4163 video_stream_encoder_->Stop();
4164}
4165
4166TEST_F(VideoStreamEncoderTest, VerifyBitrateAllocationForTwoStreams) {
Per Kjellanderdcef6412020-10-07 13:09:054167 webrtc::test::ScopedFieldTrials field_trials(
4168 "WebRTC-Video-QualityScalerSettings/"
4169 "initial_bitrate_interval_ms:1000,initial_bitrate_factor:0.2/");
4170 // Reset encoder for field trials to take effect.
4171 ConfigureEncoder(video_encoder_config_.Copy());
4172
Åsa Perssonc29cb2c2019-03-25 11:06:594173 // 2 TLs configured, temporal layers only supported for first stream.
Per Kjellanderdcef6412020-10-07 13:09:054174 ResetEncoder("VP8", 2, /*num_temporal_layers*/ 2, 1, /*screenshare*/ false,
4175 VideoStreamEncoderSettings::BitrateAllocationCallbackType::
4176 kVideoBitrateAllocation);
Åsa Perssonc29cb2c2019-03-25 11:06:594177 fake_encoder_.SetTemporalLayersSupported(0, true);
4178 fake_encoder_.SetTemporalLayersSupported(1, false);
4179
4180 const int kS0Bps = 150000;
4181 const int kS0Tl0Bps =
Rasmus Brandt2b9317a2019-10-30 12:01:464182 kS0Bps *
4183 webrtc::SimulcastRateAllocator::GetTemporalRateAllocation(
4184 /*num_layers*/ 2, /*temporal_id*/ 0, /*base_heavy_tl3_alloc*/ false);
Åsa Perssonc29cb2c2019-03-25 11:06:594185 const int kS0Tl1Bps =
Rasmus Brandt2b9317a2019-10-30 12:01:464186 kS0Bps *
4187 webrtc::SimulcastRateAllocator::GetTemporalRateAllocation(
4188 /*num_layers*/ 2, /*temporal_id*/ 1, /*base_heavy_tl3_alloc*/ false);
Åsa Perssonc29cb2c2019-03-25 11:06:594189 const int kS1Bps = kTargetBitrateBps - kS0Tl1Bps;
4190 // Temporal layers not supported by si:1.
4191 VideoBitrateAllocation expected_bitrate;
4192 expected_bitrate.SetBitrate(/*si*/ 0, /*ti*/ 0, kS0Tl0Bps);
4193 expected_bitrate.SetBitrate(/*si*/ 0, /*ti*/ 1, kS0Tl1Bps - kS0Tl0Bps);
4194 expected_bitrate.SetBitrate(/*si*/ 1, /*ti*/ 0, kS1Bps);
4195
4196 VerifyAllocatedBitrate(expected_bitrate);
4197 video_stream_encoder_->Stop();
4198}
4199
Niels Möller7dc26b72017-12-06 09:27:484200TEST_F(VideoStreamEncoderTest, OveruseDetectorUpdatedOnReconfigureAndAdaption) {
4201 const int kFrameWidth = 1280;
4202 const int kFrameHeight = 720;
4203 const int kFramerate = 24;
4204
Henrik Boström381d1092020-05-12 16:49:074205 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:074206 DataRate::BitsPerSec(kTargetBitrateBps),
4207 DataRate::BitsPerSec(kTargetBitrateBps),
4208 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Niels Möller7dc26b72017-12-06 09:27:484209 test::FrameForwarder source;
4210 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 21:20:414211 &source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
Niels Möller7dc26b72017-12-06 09:27:484212
4213 // Insert a single frame, triggering initial configuration.
4214 source.IncomingCapturedFrame(CreateFrame(1, kFrameWidth, kFrameHeight));
4215 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
4216
4217 EXPECT_EQ(
4218 video_stream_encoder_->overuse_detector_proxy_->GetLastTargetFramerate(),
4219 kDefaultFramerate);
4220
4221 // Trigger reconfigure encoder (without resetting the entire instance).
4222 VideoEncoderConfig video_encoder_config;
Åsa Persson17107062020-10-08 06:57:514223 test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
4224 video_encoder_config.simulcast_layers[0].max_framerate = kFramerate;
Niels Möller7dc26b72017-12-06 09:27:484225 video_encoder_config.max_bitrate_bps = kTargetBitrateBps;
Niels Möller7dc26b72017-12-06 09:27:484226 video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config),
Niels Möllerf1338562018-04-26 07:51:474227 kMaxPayloadLength);
Niels Möller7dc26b72017-12-06 09:27:484228 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
4229
4230 // Detector should be updated with fps limit from codec config.
4231 EXPECT_EQ(
4232 video_stream_encoder_->overuse_detector_proxy_->GetLastTargetFramerate(),
4233 kFramerate);
4234
4235 // Trigger overuse, max framerate should be reduced.
4236 VideoSendStream::Stats stats = stats_proxy_->GetStats();
4237 stats.input_frame_rate = kFramerate;
4238 stats_proxy_->SetMockStats(stats);
4239 video_stream_encoder_->TriggerCpuOveruse();
4240 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
4241 int adapted_framerate =
4242 video_stream_encoder_->overuse_detector_proxy_->GetLastTargetFramerate();
4243 EXPECT_LT(adapted_framerate, kFramerate);
4244
4245 // Trigger underuse, max framerate should go back to codec configured fps.
4246 // Set extra low fps, to make sure it's actually reset, not just incremented.
4247 stats = stats_proxy_->GetStats();
4248 stats.input_frame_rate = adapted_framerate / 2;
4249 stats_proxy_->SetMockStats(stats);
Henrik Boström91aa7322020-04-28 10:24:334250 video_stream_encoder_->TriggerCpuUnderuse();
Niels Möller7dc26b72017-12-06 09:27:484251 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
4252 EXPECT_EQ(
4253 video_stream_encoder_->overuse_detector_proxy_->GetLastTargetFramerate(),
4254 kFramerate);
4255
4256 video_stream_encoder_->Stop();
4257}
4258
4259TEST_F(VideoStreamEncoderTest,
4260 OveruseDetectorUpdatedRespectsFramerateAfterUnderuse) {
4261 const int kFrameWidth = 1280;
4262 const int kFrameHeight = 720;
4263 const int kLowFramerate = 15;
4264 const int kHighFramerate = 25;
4265
Henrik Boström381d1092020-05-12 16:49:074266 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:074267 DataRate::BitsPerSec(kTargetBitrateBps),
4268 DataRate::BitsPerSec(kTargetBitrateBps),
4269 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Niels Möller7dc26b72017-12-06 09:27:484270 test::FrameForwarder source;
4271 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 21:20:414272 &source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
Niels Möller7dc26b72017-12-06 09:27:484273
4274 // Trigger initial configuration.
4275 VideoEncoderConfig video_encoder_config;
Åsa Persson17107062020-10-08 06:57:514276 test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
4277 video_encoder_config.simulcast_layers[0].max_framerate = kLowFramerate;
Niels Möller7dc26b72017-12-06 09:27:484278 video_encoder_config.max_bitrate_bps = kTargetBitrateBps;
Niels Möller7dc26b72017-12-06 09:27:484279 source.IncomingCapturedFrame(CreateFrame(1, kFrameWidth, kFrameHeight));
Åsa Persson17107062020-10-08 06:57:514280 video_stream_encoder_->ConfigureEncoder(video_encoder_config.Copy(),
Niels Möllerf1338562018-04-26 07:51:474281 kMaxPayloadLength);
Niels Möller7dc26b72017-12-06 09:27:484282 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
4283
4284 EXPECT_EQ(
4285 video_stream_encoder_->overuse_detector_proxy_->GetLastTargetFramerate(),
4286 kLowFramerate);
4287
4288 // Trigger overuse, max framerate should be reduced.
4289 VideoSendStream::Stats stats = stats_proxy_->GetStats();
4290 stats.input_frame_rate = kLowFramerate;
4291 stats_proxy_->SetMockStats(stats);
4292 video_stream_encoder_->TriggerCpuOveruse();
4293 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
4294 int adapted_framerate =
4295 video_stream_encoder_->overuse_detector_proxy_->GetLastTargetFramerate();
4296 EXPECT_LT(adapted_framerate, kLowFramerate);
4297
4298 // Reconfigure the encoder with a new (higher max framerate), max fps should
4299 // still respect the adaptation.
Åsa Persson17107062020-10-08 06:57:514300 video_encoder_config.simulcast_layers[0].max_framerate = kHighFramerate;
Niels Möller7dc26b72017-12-06 09:27:484301 source.IncomingCapturedFrame(CreateFrame(1, kFrameWidth, kFrameHeight));
4302 video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config),
Niels Möllerf1338562018-04-26 07:51:474303 kMaxPayloadLength);
Niels Möller7dc26b72017-12-06 09:27:484304 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
4305
4306 EXPECT_EQ(
4307 video_stream_encoder_->overuse_detector_proxy_->GetLastTargetFramerate(),
4308 adapted_framerate);
4309
4310 // Trigger underuse, max framerate should go back to codec configured fps.
4311 stats = stats_proxy_->GetStats();
4312 stats.input_frame_rate = adapted_framerate;
4313 stats_proxy_->SetMockStats(stats);
Henrik Boström91aa7322020-04-28 10:24:334314 video_stream_encoder_->TriggerCpuUnderuse();
Niels Möller7dc26b72017-12-06 09:27:484315 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
4316 EXPECT_EQ(
4317 video_stream_encoder_->overuse_detector_proxy_->GetLastTargetFramerate(),
4318 kHighFramerate);
4319
4320 video_stream_encoder_->Stop();
4321}
4322
mflodmancc3d4422017-08-03 15:27:514323TEST_F(VideoStreamEncoderTest,
4324 OveruseDetectorUpdatedOnDegradationPreferenceChange) {
sprangfda496a2017-06-15 11:21:074325 const int kFrameWidth = 1280;
4326 const int kFrameHeight = 720;
4327 const int kFramerate = 24;
4328
Henrik Boström381d1092020-05-12 16:49:074329 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:074330 DataRate::BitsPerSec(kTargetBitrateBps),
4331 DataRate::BitsPerSec(kTargetBitrateBps),
4332 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
sprangfda496a2017-06-15 11:21:074333 test::FrameForwarder source;
mflodmancc3d4422017-08-03 15:27:514334 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 21:20:414335 &source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
sprangfda496a2017-06-15 11:21:074336
4337 // Trigger initial configuration.
4338 VideoEncoderConfig video_encoder_config;
Åsa Persson17107062020-10-08 06:57:514339 test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
4340 video_encoder_config.simulcast_layers[0].max_framerate = kFramerate;
sprangfda496a2017-06-15 11:21:074341 video_encoder_config.max_bitrate_bps = kTargetBitrateBps;
sprangfda496a2017-06-15 11:21:074342 source.IncomingCapturedFrame(CreateFrame(1, kFrameWidth, kFrameHeight));
mflodmancc3d4422017-08-03 15:27:514343 video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config),
Niels Möllerf1338562018-04-26 07:51:474344 kMaxPayloadLength);
mflodmancc3d4422017-08-03 15:27:514345 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
sprangfda496a2017-06-15 11:21:074346
Niels Möller7dc26b72017-12-06 09:27:484347 EXPECT_EQ(
4348 video_stream_encoder_->overuse_detector_proxy_->GetLastTargetFramerate(),
4349 kFramerate);
sprangfda496a2017-06-15 11:21:074350
4351 // Trigger overuse, max framerate should be reduced.
4352 VideoSendStream::Stats stats = stats_proxy_->GetStats();
4353 stats.input_frame_rate = kFramerate;
4354 stats_proxy_->SetMockStats(stats);
mflodmancc3d4422017-08-03 15:27:514355 video_stream_encoder_->TriggerCpuOveruse();
4356 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
Niels Möller7dc26b72017-12-06 09:27:484357 int adapted_framerate =
4358 video_stream_encoder_->overuse_detector_proxy_->GetLastTargetFramerate();
sprangfda496a2017-06-15 11:21:074359 EXPECT_LT(adapted_framerate, kFramerate);
4360
4361 // Change degradation preference to not enable framerate scaling. Target
4362 // framerate should be changed to codec defined limit.
Henrik Boström381d1092020-05-12 16:49:074363 video_stream_encoder_->SetSourceAndWaitForFramerateUpdated(
Taylor Brandstetter49fcc102018-05-16 21:20:414364 &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
Niels Möller7dc26b72017-12-06 09:27:484365 EXPECT_EQ(
4366 video_stream_encoder_->overuse_detector_proxy_->GetLastTargetFramerate(),
4367 kFramerate);
sprangfda496a2017-06-15 11:21:074368
mflodmancc3d4422017-08-03 15:27:514369 video_stream_encoder_->Stop();
sprangfda496a2017-06-15 11:21:074370}
4371
mflodmancc3d4422017-08-03 15:27:514372TEST_F(VideoStreamEncoderTest, DropsFramesAndScalesWhenBitrateIsTooLow) {
asaperssonfab67072017-04-04 12:51:494373 const int kTooLowBitrateForFrameSizeBps = 10000;
Henrik Boström381d1092020-05-12 16:49:074374 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:074375 DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps),
4376 DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps),
4377 DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps), 0, 0, 0);
asaperssonfab67072017-04-04 12:51:494378 const int kWidth = 640;
4379 const int kHeight = 360;
kthelgason2bc68642017-02-07 15:02:224380
asaperssonfab67072017-04-04 12:51:494381 video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
kthelgason2bc68642017-02-07 15:02:224382
4383 // Expect to drop this frame, the wait should time out.
sprang4847ae62017-06-27 14:06:524384 ExpectDroppedFrame();
kthelgason2bc68642017-02-07 15:02:224385
4386 // Expect the sink_wants to specify a scaled frame.
Henrik Boström2671dac2020-05-19 14:29:094387 EXPECT_TRUE_WAIT(
4388 video_source_.sink_wants().max_pixel_count < kWidth * kHeight, 5000);
kthelgason2bc68642017-02-07 15:02:224389
sprangc5d62e22017-04-03 06:53:044390 int last_pixel_count = video_source_.sink_wants().max_pixel_count;
kthelgason2bc68642017-02-07 15:02:224391
asaperssonfab67072017-04-04 12:51:494392 // Next frame is scaled.
kthelgason2bc68642017-02-07 15:02:224393 video_source_.IncomingCapturedFrame(
asaperssonfab67072017-04-04 12:51:494394 CreateFrame(2, kWidth * 3 / 4, kHeight * 3 / 4));
kthelgason2bc68642017-02-07 15:02:224395
4396 // Expect to drop this frame, the wait should time out.
sprang4847ae62017-06-27 14:06:524397 ExpectDroppedFrame();
kthelgason2bc68642017-02-07 15:02:224398
Henrik Boström2671dac2020-05-19 14:29:094399 EXPECT_TRUE_WAIT(
4400 video_source_.sink_wants().max_pixel_count < last_pixel_count, 5000);
kthelgason2bc68642017-02-07 15:02:224401
mflodmancc3d4422017-08-03 15:27:514402 video_stream_encoder_->Stop();
kthelgason2bc68642017-02-07 15:02:224403}
4404
mflodmancc3d4422017-08-03 15:27:514405TEST_F(VideoStreamEncoderTest,
4406 NumberOfDroppedFramesLimitedWhenBitrateIsTooLow) {
asaperssonfab67072017-04-04 12:51:494407 const int kTooLowBitrateForFrameSizeBps = 10000;
Henrik Boström381d1092020-05-12 16:49:074408 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:074409 DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps),
4410 DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps),
4411 DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps), 0, 0, 0);
asaperssonfab67072017-04-04 12:51:494412 const int kWidth = 640;
4413 const int kHeight = 360;
kthelgason2bc68642017-02-07 15:02:224414
4415 // We expect the n initial frames to get dropped.
4416 int i;
4417 for (i = 1; i <= kMaxInitialFramedrop; ++i) {
asaperssonfab67072017-04-04 12:51:494418 video_source_.IncomingCapturedFrame(CreateFrame(i, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:524419 ExpectDroppedFrame();
kthelgason2bc68642017-02-07 15:02:224420 }
4421 // The n+1th frame should not be dropped, even though it's size is too large.
asaperssonfab67072017-04-04 12:51:494422 video_source_.IncomingCapturedFrame(CreateFrame(i, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:524423 WaitForEncodedFrame(i);
kthelgason2bc68642017-02-07 15:02:224424
4425 // Expect the sink_wants to specify a scaled frame.
asaperssonfab67072017-04-04 12:51:494426 EXPECT_LT(video_source_.sink_wants().max_pixel_count, kWidth * kHeight);
kthelgason2bc68642017-02-07 15:02:224427
mflodmancc3d4422017-08-03 15:27:514428 video_stream_encoder_->Stop();
kthelgason2bc68642017-02-07 15:02:224429}
4430
mflodmancc3d4422017-08-03 15:27:514431TEST_F(VideoStreamEncoderTest,
4432 InitialFrameDropOffWithMaintainResolutionPreference) {
asaperssonfab67072017-04-04 12:51:494433 const int kWidth = 640;
4434 const int kHeight = 360;
Henrik Boström381d1092020-05-12 16:49:074435 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:074436 DataRate::BitsPerSec(kLowTargetBitrateBps),
4437 DataRate::BitsPerSec(kLowTargetBitrateBps),
4438 DataRate::BitsPerSec(kLowTargetBitrateBps), 0, 0, 0);
kthelgason2bc68642017-02-07 15:02:224439
4440 // Set degradation preference.
mflodmancc3d4422017-08-03 15:27:514441 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 21:20:414442 &video_source_, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
kthelgason2bc68642017-02-07 15:02:224443
asaperssonfab67072017-04-04 12:51:494444 video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
kthelgason2bc68642017-02-07 15:02:224445 // Frame should not be dropped, even if it's too large.
sprang4847ae62017-06-27 14:06:524446 WaitForEncodedFrame(1);
kthelgason2bc68642017-02-07 15:02:224447
mflodmancc3d4422017-08-03 15:27:514448 video_stream_encoder_->Stop();
kthelgason2bc68642017-02-07 15:02:224449}
4450
mflodmancc3d4422017-08-03 15:27:514451TEST_F(VideoStreamEncoderTest, InitialFrameDropOffWhenEncoderDisabledScaling) {
asaperssonfab67072017-04-04 12:51:494452 const int kWidth = 640;
4453 const int kHeight = 360;
kthelgasonad9010c2017-02-14 08:46:514454 fake_encoder_.SetQualityScaling(false);
Niels Möller4db138e2018-04-19 07:04:134455
4456 VideoEncoderConfig video_encoder_config;
4457 test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
4458 // Make format different, to force recreation of encoder.
4459 video_encoder_config.video_format.parameters["foo"] = "foo";
4460 video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config),
Niels Möllerf1338562018-04-26 07:51:474461 kMaxPayloadLength);
Henrik Boström381d1092020-05-12 16:49:074462 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:074463 DataRate::BitsPerSec(kLowTargetBitrateBps),
4464 DataRate::BitsPerSec(kLowTargetBitrateBps),
4465 DataRate::BitsPerSec(kLowTargetBitrateBps), 0, 0, 0);
asapersson09f05612017-05-16 06:40:184466
kthelgasonb83797b2017-02-14 19:57:254467 // Force quality scaler reconfiguration by resetting the source.
Taylor Brandstetter49fcc102018-05-16 21:20:414468 video_stream_encoder_->SetSource(&video_source_,
4469 webrtc::DegradationPreference::BALANCED);
kthelgasonad9010c2017-02-14 08:46:514470
asaperssonfab67072017-04-04 12:51:494471 video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
kthelgasonad9010c2017-02-14 08:46:514472 // Frame should not be dropped, even if it's too large.
sprang4847ae62017-06-27 14:06:524473 WaitForEncodedFrame(1);
kthelgasonad9010c2017-02-14 08:46:514474
mflodmancc3d4422017-08-03 15:27:514475 video_stream_encoder_->Stop();
kthelgasonad9010c2017-02-14 08:46:514476 fake_encoder_.SetQualityScaling(true);
4477}
4478
Åsa Persson139f4dc2019-08-02 07:29:584479TEST_F(VideoStreamEncoderTest, InitialFrameDropActivatesWhenBweDrops) {
4480 webrtc::test::ScopedFieldTrials field_trials(
4481 "WebRTC-Video-QualityScalerSettings/"
4482 "initial_bitrate_interval_ms:1000,initial_bitrate_factor:0.2/");
4483 // Reset encoder for field trials to take effect.
4484 ConfigureEncoder(video_encoder_config_.Copy());
4485 const int kNotTooLowBitrateForFrameSizeBps = kTargetBitrateBps * 0.2;
4486 const int kTooLowBitrateForFrameSizeBps = kTargetBitrateBps * 0.19;
4487 const int kWidth = 640;
4488 const int kHeight = 360;
4489
Henrik Boström381d1092020-05-12 16:49:074490 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:074491 DataRate::BitsPerSec(kTargetBitrateBps),
4492 DataRate::BitsPerSec(kTargetBitrateBps),
4493 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Åsa Persson139f4dc2019-08-02 07:29:584494 video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
4495 // Frame should not be dropped.
4496 WaitForEncodedFrame(1);
4497
Henrik Boström381d1092020-05-12 16:49:074498 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:074499 DataRate::BitsPerSec(kNotTooLowBitrateForFrameSizeBps),
4500 DataRate::BitsPerSec(kNotTooLowBitrateForFrameSizeBps),
4501 DataRate::BitsPerSec(kNotTooLowBitrateForFrameSizeBps), 0, 0, 0);
Åsa Persson139f4dc2019-08-02 07:29:584502 video_source_.IncomingCapturedFrame(CreateFrame(2, kWidth, kHeight));
4503 // Frame should not be dropped.
4504 WaitForEncodedFrame(2);
4505
Henrik Boström381d1092020-05-12 16:49:074506 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:074507 DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps),
4508 DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps),
4509 DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps), 0, 0, 0);
Åsa Persson139f4dc2019-08-02 07:29:584510 video_source_.IncomingCapturedFrame(CreateFrame(3, kWidth, kHeight));
4511 // Expect to drop this frame, the wait should time out.
4512 ExpectDroppedFrame();
4513
4514 // Expect the sink_wants to specify a scaled frame.
Henrik Boström2671dac2020-05-19 14:29:094515 EXPECT_TRUE_WAIT(
4516 video_source_.sink_wants().max_pixel_count < kWidth * kHeight, 5000);
Åsa Persson139f4dc2019-08-02 07:29:584517 video_stream_encoder_->Stop();
4518}
4519
Evan Shrubsolee3da1d32020-08-14 13:58:334520TEST_F(VideoStreamEncoderTest,
4521 InitialFrameDropNotReactivatedWhenBweDropsWhenScalingDisabled) {
4522 webrtc::test::ScopedFieldTrials field_trials(
4523 "WebRTC-Video-QualityScalerSettings/"
4524 "initial_bitrate_interval_ms:1000,initial_bitrate_factor:0.2/");
4525 fake_encoder_.SetQualityScaling(false);
4526 ConfigureEncoder(video_encoder_config_.Copy());
4527 const int kNotTooLowBitrateForFrameSizeBps = kTargetBitrateBps * 0.2;
4528 const int kTooLowBitrateForFrameSizeBps = kTargetBitrateBps * 0.19;
4529 const int kWidth = 640;
4530 const int kHeight = 360;
4531
4532 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
4533 DataRate::BitsPerSec(kTargetBitrateBps),
4534 DataRate::BitsPerSec(kTargetBitrateBps),
4535 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
4536 video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
4537 // Frame should not be dropped.
4538 WaitForEncodedFrame(1);
4539
4540 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
4541 DataRate::BitsPerSec(kNotTooLowBitrateForFrameSizeBps),
4542 DataRate::BitsPerSec(kNotTooLowBitrateForFrameSizeBps),
4543 DataRate::BitsPerSec(kNotTooLowBitrateForFrameSizeBps), 0, 0, 0);
4544 video_source_.IncomingCapturedFrame(CreateFrame(2, kWidth, kHeight));
4545 // Frame should not be dropped.
4546 WaitForEncodedFrame(2);
4547
4548 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
4549 DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps),
4550 DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps),
4551 DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps), 0, 0, 0);
4552 video_source_.IncomingCapturedFrame(CreateFrame(3, kWidth, kHeight));
4553 // Not dropped since quality scaling is disabled.
4554 WaitForEncodedFrame(3);
4555
4556 // Expect the sink_wants to specify a scaled frame.
Evan Shrubsole85728412020-08-25 11:12:124557 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
Evan Shrubsolee3da1d32020-08-14 13:58:334558 EXPECT_THAT(video_source_.sink_wants(), ResolutionMax());
4559
4560 video_stream_encoder_->Stop();
4561}
4562
Ilya Nikolaevskiy84bc3482020-11-26 15:58:474563TEST_F(VideoStreamEncoderTest, InitialFrameDropActivatesWhenLayersChange) {
4564 const int kLowTargetBitrateBps = 400000;
4565 // Set simulcast.
4566 ResetEncoder("VP8", 3, 1, 1, false);
4567 fake_encoder_.SetQualityScaling(true);
4568 const int kWidth = 1280;
4569 const int kHeight = 720;
4570 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
4571 DataRate::BitsPerSec(kLowTargetBitrateBps),
4572 DataRate::BitsPerSec(kLowTargetBitrateBps),
4573 DataRate::BitsPerSec(kLowTargetBitrateBps), 0, 0, 0);
4574 video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
4575 // Frame should not be dropped.
4576 WaitForEncodedFrame(1);
4577
4578 // Trigger QVGA "singlecast"
4579 // Update the config.
4580 VideoEncoderConfig video_encoder_config;
4581 test::FillEncoderConfiguration(PayloadStringToCodecType("VP8"), 3,
4582 &video_encoder_config);
4583 for (auto& layer : video_encoder_config.simulcast_layers) {
4584 layer.num_temporal_layers = 1;
4585 layer.max_framerate = kDefaultFramerate;
4586 }
4587 video_encoder_config.max_bitrate_bps = kSimulcastTargetBitrateBps;
4588 video_encoder_config.content_type =
4589 VideoEncoderConfig::ContentType::kRealtimeVideo;
4590
4591 video_encoder_config.simulcast_layers[0].active = true;
4592 video_encoder_config.simulcast_layers[1].active = false;
4593 video_encoder_config.simulcast_layers[2].active = false;
4594
4595 video_stream_encoder_->ConfigureEncoder(video_encoder_config.Copy(),
4596 kMaxPayloadLength);
4597 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
4598
4599 video_source_.IncomingCapturedFrame(CreateFrame(2, kWidth, kHeight));
4600 // Frame should not be dropped.
4601 WaitForEncodedFrame(2);
4602
4603 // Trigger HD "singlecast"
4604 video_encoder_config.simulcast_layers[0].active = false;
4605 video_encoder_config.simulcast_layers[1].active = false;
4606 video_encoder_config.simulcast_layers[2].active = true;
4607
4608 video_stream_encoder_->ConfigureEncoder(video_encoder_config.Copy(),
4609 kMaxPayloadLength);
4610 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
4611
4612 video_source_.IncomingCapturedFrame(CreateFrame(3, kWidth, kHeight));
4613 // Frame should be dropped because of initial frame drop.
4614 ExpectDroppedFrame();
4615
4616 // Expect the sink_wants to specify a scaled frame.
4617 EXPECT_TRUE_WAIT(
4618 video_source_.sink_wants().max_pixel_count < kWidth * kHeight, 5000);
4619 video_stream_encoder_->Stop();
4620}
4621
Ilya Nikolaevskiycde4a9f2020-11-27 13:06:084622TEST_F(VideoStreamEncoderTest, InitialFrameDropActivatesWhenSVCLayersChange) {
4623 const int kLowTargetBitrateBps = 400000;
4624 // Set simulcast.
4625 ResetEncoder("VP9", 1, 1, 3, false);
4626 fake_encoder_.SetQualityScaling(true);
4627 const int kWidth = 1280;
4628 const int kHeight = 720;
4629 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
4630 DataRate::BitsPerSec(kLowTargetBitrateBps),
4631 DataRate::BitsPerSec(kLowTargetBitrateBps),
4632 DataRate::BitsPerSec(kLowTargetBitrateBps), 0, 0, 0);
4633 video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
4634 // Frame should not be dropped.
4635 WaitForEncodedFrame(1);
4636
4637 // Trigger QVGA "singlecast"
4638 // Update the config.
4639 VideoEncoderConfig video_encoder_config;
4640 test::FillEncoderConfiguration(PayloadStringToCodecType("VP9"), 1,
4641 &video_encoder_config);
4642 VideoCodecVP9 vp9_settings = VideoEncoder::GetDefaultVp9Settings();
4643 vp9_settings.numberOfSpatialLayers = 3;
4644 // Since only one layer is active - automatic resize should be enabled.
4645 vp9_settings.automaticResizeOn = true;
4646 video_encoder_config.encoder_specific_settings =
4647 new rtc::RefCountedObject<VideoEncoderConfig::Vp9EncoderSpecificSettings>(
4648 vp9_settings);
4649 video_encoder_config.max_bitrate_bps = kSimulcastTargetBitrateBps;
4650 video_encoder_config.content_type =
4651 VideoEncoderConfig::ContentType::kRealtimeVideo;
4652 // Currently simulcast layers |active| flags are used to inidicate
4653 // which SVC layers are active.
4654 video_encoder_config.simulcast_layers.resize(3);
4655
4656 video_encoder_config.simulcast_layers[0].active = true;
4657 video_encoder_config.simulcast_layers[1].active = false;
4658 video_encoder_config.simulcast_layers[2].active = false;
4659
4660 video_stream_encoder_->ConfigureEncoder(video_encoder_config.Copy(),
4661 kMaxPayloadLength);
4662 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
4663
4664 video_source_.IncomingCapturedFrame(CreateFrame(2, kWidth, kHeight));
4665 // Frame should not be dropped.
4666 WaitForEncodedFrame(2);
4667
4668 // Trigger HD "singlecast"
4669 video_encoder_config.simulcast_layers[0].active = false;
4670 video_encoder_config.simulcast_layers[1].active = false;
4671 video_encoder_config.simulcast_layers[2].active = true;
4672
4673 video_stream_encoder_->ConfigureEncoder(video_encoder_config.Copy(),
4674 kMaxPayloadLength);
4675 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
4676
4677 video_source_.IncomingCapturedFrame(CreateFrame(3, kWidth, kHeight));
4678 // Frame should be dropped because of initial frame drop.
4679 ExpectDroppedFrame();
4680
4681 // Expect the sink_wants to specify a scaled frame.
4682 EXPECT_TRUE_WAIT(
4683 video_source_.sink_wants().max_pixel_count < kWidth * kHeight, 5000);
4684 video_stream_encoder_->Stop();
4685}
4686
Ilya Nikolaevskiy84bc3482020-11-26 15:58:474687TEST_F(VideoStreamEncoderTest,
4688 InitialFrameDropActivatesWhenResolutionIncreases) {
4689 const int kWidth = 640;
4690 const int kHeight = 360;
4691
4692 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
4693 DataRate::BitsPerSec(kTargetBitrateBps),
4694 DataRate::BitsPerSec(kTargetBitrateBps),
4695 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
4696 video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth / 2, kHeight / 2));
4697 // Frame should not be dropped.
4698 WaitForEncodedFrame(1);
4699
4700 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
4701 DataRate::BitsPerSec(kLowTargetBitrateBps),
4702 DataRate::BitsPerSec(kLowTargetBitrateBps),
4703 DataRate::BitsPerSec(kLowTargetBitrateBps), 0, 0, 0);
4704 video_source_.IncomingCapturedFrame(CreateFrame(2, kWidth / 2, kHeight / 2));
4705 // Frame should not be dropped, bitrate not too low for frame.
4706 WaitForEncodedFrame(2);
4707
4708 // Incoming resolution increases.
4709 video_source_.IncomingCapturedFrame(CreateFrame(3, kWidth, kHeight));
4710 // Expect to drop this frame, bitrate too low for frame.
4711 ExpectDroppedFrame();
4712
4713 // Expect the sink_wants to specify a scaled frame.
4714 EXPECT_TRUE_WAIT(
4715 video_source_.sink_wants().max_pixel_count < kWidth * kHeight, 5000);
4716 video_stream_encoder_->Stop();
4717}
4718
4719TEST_F(VideoStreamEncoderTest, InitialFrameDropIsNotReactivatedWhenAdaptingUp) {
4720 const int kWidth = 640;
4721 const int kHeight = 360;
4722 // So that quality scaling doesn't happen by itself.
4723 fake_encoder_.SetQp(kQpHigh);
4724
4725 AdaptingFrameForwarder source(&time_controller_);
4726 source.set_adaptation_enabled(true);
4727 video_stream_encoder_->SetSource(
4728 &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
4729
4730 int timestamp = 1;
4731
4732 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
4733 DataRate::BitsPerSec(kTargetBitrateBps),
4734 DataRate::BitsPerSec(kTargetBitrateBps),
4735 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
4736 source.IncomingCapturedFrame(CreateFrame(timestamp, kWidth, kHeight));
4737 WaitForEncodedFrame(timestamp);
4738 timestamp += 9000;
4739 // Long pause to disable all first BWE drop logic.
4740 AdvanceTime(TimeDelta::Millis(1000));
4741
4742 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
4743 DataRate::BitsPerSec(kLowTargetBitrateBps),
4744 DataRate::BitsPerSec(kLowTargetBitrateBps),
4745 DataRate::BitsPerSec(kLowTargetBitrateBps), 0, 0, 0);
4746 source.IncomingCapturedFrame(CreateFrame(timestamp, kWidth, kHeight));
4747 // Not dropped frame, as initial frame drop is disabled by now.
4748 WaitForEncodedFrame(timestamp);
4749 timestamp += 9000;
4750 AdvanceTime(TimeDelta::Millis(100));
4751
4752 // Quality adaptation down.
4753 video_stream_encoder_->TriggerQualityLow();
4754
4755 // Adaptation has an effect.
4756 EXPECT_TRUE_WAIT(source.sink_wants().max_pixel_count < kWidth * kHeight,
4757 5000);
4758
4759 // Frame isn't dropped as initial frame dropper is disabled.
4760 source.IncomingCapturedFrame(CreateFrame(timestamp, kWidth, kHeight));
4761 WaitForEncodedFrame(timestamp);
4762 timestamp += 9000;
4763 AdvanceTime(TimeDelta::Millis(100));
4764
4765 // Quality adaptation up.
4766 video_stream_encoder_->TriggerQualityHigh();
4767
4768 // Adaptation has an effect.
4769 EXPECT_TRUE_WAIT(source.sink_wants().max_pixel_count > kWidth * kHeight,
4770 5000);
4771
4772 source.IncomingCapturedFrame(CreateFrame(timestamp, kWidth, kHeight));
4773 // Frame should not be dropped, as initial framedropper is off.
4774 WaitForEncodedFrame(timestamp);
4775
4776 video_stream_encoder_->Stop();
4777}
4778
Åsa Perssone644a032019-11-08 14:56:004779TEST_F(VideoStreamEncoderTest, RampsUpInQualityWhenBwIsHigh) {
4780 webrtc::test::ScopedFieldTrials field_trials(
4781 "WebRTC-Video-QualityRampupSettings/min_pixels:1,min_duration_ms:2000/");
4782
4783 // Reset encoder for field trials to take effect.
4784 VideoEncoderConfig config = video_encoder_config_.Copy();
4785 config.max_bitrate_bps = kTargetBitrateBps;
Evan Shrubsoledff79252020-04-16 09:34:324786 DataRate max_bitrate = DataRate::BitsPerSec(config.max_bitrate_bps);
Åsa Perssone644a032019-11-08 14:56:004787 ConfigureEncoder(std::move(config));
4788 fake_encoder_.SetQp(kQpLow);
4789
4790 // Enable MAINTAIN_FRAMERATE preference.
Tomas Gunnarsson612445e2020-09-21 12:31:234791 AdaptingFrameForwarder source(&time_controller_);
Åsa Perssone644a032019-11-08 14:56:004792 source.set_adaptation_enabled(true);
4793 video_stream_encoder_->SetSource(&source,
4794 DegradationPreference::MAINTAIN_FRAMERATE);
4795
4796 // Start at low bitrate.
4797 const int kLowBitrateBps = 200000;
Henrik Boström381d1092020-05-12 16:49:074798 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
4799 DataRate::BitsPerSec(kLowBitrateBps),
4800 DataRate::BitsPerSec(kLowBitrateBps),
4801 DataRate::BitsPerSec(kLowBitrateBps), 0, 0, 0);
Åsa Perssone644a032019-11-08 14:56:004802
4803 // Expect first frame to be dropped and resolution to be limited.
4804 const int kWidth = 1280;
4805 const int kHeight = 720;
4806 const int64_t kFrameIntervalMs = 100;
4807 int64_t timestamp_ms = kFrameIntervalMs;
4808 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
4809 ExpectDroppedFrame();
Henrik Boström2671dac2020-05-19 14:29:094810 EXPECT_TRUE_WAIT(source.sink_wants().max_pixel_count < kWidth * kHeight,
4811 5000);
Åsa Perssone644a032019-11-08 14:56:004812
4813 // Increase bitrate to encoder max.
Henrik Boström381d1092020-05-12 16:49:074814 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
4815 max_bitrate, max_bitrate, max_bitrate, 0, 0, 0);
Åsa Perssone644a032019-11-08 14:56:004816
4817 // Insert frames and advance |min_duration_ms|.
4818 for (size_t i = 1; i <= 10; i++) {
4819 timestamp_ms += kFrameIntervalMs;
4820 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
4821 WaitForEncodedFrame(timestamp_ms);
4822 }
4823 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
4824 EXPECT_LT(source.sink_wants().max_pixel_count, kWidth * kHeight);
4825
Tomas Gunnarsson612445e2020-09-21 12:31:234826 AdvanceTime(TimeDelta::Millis(2000));
Åsa Perssone644a032019-11-08 14:56:004827
4828 // Insert frame should trigger high BW and release quality limitation.
4829 timestamp_ms += kFrameIntervalMs;
4830 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
4831 WaitForEncodedFrame(timestamp_ms);
Henrik Boström381d1092020-05-12 16:49:074832 // The ramp-up code involves the adaptation queue, give it time to execute.
4833 // TODO(hbos): Can we await an appropriate event instead?
Evan Shrubsole85728412020-08-25 11:12:124834 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
Evan Shrubsole5cd7eb82020-05-25 12:08:394835 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
Åsa Perssone644a032019-11-08 14:56:004836
4837 // Frame should not be adapted.
4838 timestamp_ms += kFrameIntervalMs;
4839 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
4840 WaitForEncodedFrame(kWidth, kHeight);
4841 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
4842
4843 video_stream_encoder_->Stop();
4844}
4845
mflodmancc3d4422017-08-03 15:27:514846TEST_F(VideoStreamEncoderTest,
Evan Shrubsole99b0f8d2020-08-25 11:12:284847 QualityScalerAdaptationsRemovedWhenQualityScalingDisabled) {
Tomas Gunnarsson612445e2020-09-21 12:31:234848 AdaptingFrameForwarder source(&time_controller_);
Evan Shrubsole99b0f8d2020-08-25 11:12:284849 source.set_adaptation_enabled(true);
4850 video_stream_encoder_->SetSource(&source,
4851 DegradationPreference::MAINTAIN_FRAMERATE);
4852 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
4853 DataRate::BitsPerSec(kTargetBitrateBps),
4854 DataRate::BitsPerSec(kTargetBitrateBps),
4855 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
4856 fake_encoder_.SetQp(kQpHigh + 1);
4857 const int kWidth = 1280;
4858 const int kHeight = 720;
4859 const int64_t kFrameIntervalMs = 100;
4860 int64_t timestamp_ms = kFrameIntervalMs;
4861 for (size_t i = 1; i <= 100; i++) {
4862 timestamp_ms += kFrameIntervalMs;
4863 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
4864 WaitForEncodedFrame(timestamp_ms);
4865 }
4866 // Wait for QualityScaler, which will wait for 2000*2.5 ms until checking QP
4867 // for the first time.
4868 // TODO(eshr): We should avoid these waits by using threads with simulated
4869 // time.
4870 EXPECT_TRUE_WAIT(stats_proxy_->GetStats().bw_limited_resolution,
4871 2000 * 2.5 * 2);
4872 timestamp_ms += kFrameIntervalMs;
4873 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
4874 WaitForEncodedFrame(timestamp_ms);
4875 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
4876 EXPECT_THAT(source.sink_wants(), WantsMaxPixels(Lt(kWidth * kHeight)));
4877 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
4878
4879 // Disable Quality scaling by turning off scaler on the encoder and
4880 // reconfiguring.
4881 fake_encoder_.SetQualityScaling(false);
4882 video_stream_encoder_->ConfigureEncoder(video_encoder_config_.Copy(),
4883 kMaxPayloadLength);
4884 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
Tomas Gunnarsson612445e2020-09-21 12:31:234885 AdvanceTime(TimeDelta::Millis(0));
Evan Shrubsole99b0f8d2020-08-25 11:12:284886 // Since we turned off the quality scaler, the adaptations made by it are
4887 // removed.
4888 EXPECT_THAT(source.sink_wants(), ResolutionMax());
4889 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
4890
4891 video_stream_encoder_->Stop();
4892}
4893
4894TEST_F(VideoStreamEncoderTest,
asaperssond0de2952017-04-21 08:47:314895 ResolutionNotAdaptedForTooSmallFrame_MaintainFramerateMode) {
4896 const int kTooSmallWidth = 10;
4897 const int kTooSmallHeight = 10;
Henrik Boström381d1092020-05-12 16:49:074898 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:074899 DataRate::BitsPerSec(kTargetBitrateBps),
4900 DataRate::BitsPerSec(kTargetBitrateBps),
4901 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asaperssond0de2952017-04-21 08:47:314902
Taylor Brandstetter49fcc102018-05-16 21:20:414903 // Enable MAINTAIN_FRAMERATE preference, no initial limitation.
asaperssond0de2952017-04-21 08:47:314904 test::FrameForwarder source;
mflodmancc3d4422017-08-03 15:27:514905 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 21:20:414906 &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
Evan Shrubsole5cd7eb82020-05-25 12:08:394907 EXPECT_THAT(source.sink_wants(), UnlimitedSinkWants());
asaperssond0de2952017-04-21 08:47:314908 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
4909
4910 // Trigger adapt down, too small frame, expect no change.
4911 source.IncomingCapturedFrame(CreateFrame(1, kTooSmallWidth, kTooSmallHeight));
sprang4847ae62017-06-27 14:06:524912 WaitForEncodedFrame(1);
mflodmancc3d4422017-08-03 15:27:514913 video_stream_encoder_->TriggerCpuOveruse();
Evan Shrubsole5cd7eb82020-05-25 12:08:394914 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssond0de2952017-04-21 08:47:314915 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
4916 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
4917
mflodmancc3d4422017-08-03 15:27:514918 video_stream_encoder_->Stop();
asaperssond0de2952017-04-21 08:47:314919}
4920
mflodmancc3d4422017-08-03 15:27:514921TEST_F(VideoStreamEncoderTest,
4922 ResolutionNotAdaptedForTooSmallFrame_BalancedMode) {
asaperssonf7e294d2017-06-14 06:25:224923 const int kTooSmallWidth = 10;
4924 const int kTooSmallHeight = 10;
4925 const int kFpsLimit = 7;
Henrik Boström381d1092020-05-12 16:49:074926 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:074927 DataRate::BitsPerSec(kTargetBitrateBps),
4928 DataRate::BitsPerSec(kTargetBitrateBps),
4929 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asaperssonf7e294d2017-06-14 06:25:224930
Taylor Brandstetter49fcc102018-05-16 21:20:414931 // Enable BALANCED preference, no initial limitation.
asaperssonf7e294d2017-06-14 06:25:224932 test::FrameForwarder source;
Taylor Brandstetter49fcc102018-05-16 21:20:414933 video_stream_encoder_->SetSource(&source,
4934 webrtc::DegradationPreference::BALANCED);
Evan Shrubsole5cd7eb82020-05-25 12:08:394935 EXPECT_THAT(source.sink_wants(), UnlimitedSinkWants());
asaperssonf7e294d2017-06-14 06:25:224936 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
4937 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
4938
4939 // Trigger adapt down, expect limited framerate.
4940 source.IncomingCapturedFrame(CreateFrame(1, kTooSmallWidth, kTooSmallHeight));
sprang4847ae62017-06-27 14:06:524941 WaitForEncodedFrame(1);
mflodmancc3d4422017-08-03 15:27:514942 video_stream_encoder_->TriggerQualityLow();
Evan Shrubsole5cd7eb82020-05-25 12:08:394943 EXPECT_THAT(source.sink_wants(), FpsMatchesResolutionMax(Eq(kFpsLimit)));
asaperssonf7e294d2017-06-14 06:25:224944 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
4945 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
4946 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
4947
4948 // Trigger adapt down, too small frame, expect no change.
4949 source.IncomingCapturedFrame(CreateFrame(2, kTooSmallWidth, kTooSmallHeight));
sprang4847ae62017-06-27 14:06:524950 WaitForEncodedFrame(2);
mflodmancc3d4422017-08-03 15:27:514951 video_stream_encoder_->TriggerQualityLow();
Evan Shrubsole5cd7eb82020-05-25 12:08:394952 EXPECT_THAT(source.sink_wants(), FpsMatchesResolutionMax(Eq(kFpsLimit)));
asaperssonf7e294d2017-06-14 06:25:224953 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
4954 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
4955 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
4956
mflodmancc3d4422017-08-03 15:27:514957 video_stream_encoder_->Stop();
asaperssonf7e294d2017-06-14 06:25:224958}
4959
mflodmancc3d4422017-08-03 15:27:514960TEST_F(VideoStreamEncoderTest, FailingInitEncodeDoesntCauseCrash) {
asapersson02465b82017-04-10 08:12:524961 fake_encoder_.ForceInitEncodeFailure(true);
Henrik Boström381d1092020-05-12 16:49:074962 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:074963 DataRate::BitsPerSec(kTargetBitrateBps),
4964 DataRate::BitsPerSec(kTargetBitrateBps),
4965 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Niels Möllerf1338562018-04-26 07:51:474966 ResetEncoder("VP8", 2, 1, 1, false);
asapersson02465b82017-04-10 08:12:524967 const int kFrameWidth = 1280;
4968 const int kFrameHeight = 720;
4969 video_source_.IncomingCapturedFrame(
4970 CreateFrame(1, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 14:06:524971 ExpectDroppedFrame();
mflodmancc3d4422017-08-03 15:27:514972 video_stream_encoder_->Stop();
asapersson02465b82017-04-10 08:12:524973}
4974
sprangb1ca0732017-02-01 16:38:124975// TODO(sprang): Extend this with fps throttling and any "balanced" extensions.
mflodmancc3d4422017-08-03 15:27:514976TEST_F(VideoStreamEncoderTest,
4977 AdaptsResolutionOnOveruse_MaintainFramerateMode) {
Henrik Boström381d1092020-05-12 16:49:074978 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:074979 DataRate::BitsPerSec(kTargetBitrateBps),
4980 DataRate::BitsPerSec(kTargetBitrateBps),
4981 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
sprangb1ca0732017-02-01 16:38:124982
4983 const int kFrameWidth = 1280;
4984 const int kFrameHeight = 720;
4985 // Enabled default VideoAdapter downscaling. First step is 3/4, not 3/5 as
mflodmancc3d4422017-08-03 15:27:514986 // requested by
4987 // VideoStreamEncoder::VideoSourceProxy::RequestResolutionLowerThan().
sprangb1ca0732017-02-01 16:38:124988 video_source_.set_adaptation_enabled(true);
4989
4990 video_source_.IncomingCapturedFrame(
Åsa Persson8c1bf952018-09-13 08:42:194991 CreateFrame(1 * kFrameIntervalMs, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 14:06:524992 WaitForEncodedFrame(kFrameWidth, kFrameHeight);
sprangb1ca0732017-02-01 16:38:124993
4994 // Trigger CPU overuse, downscale by 3/4.
mflodmancc3d4422017-08-03 15:27:514995 video_stream_encoder_->TriggerCpuOveruse();
sprangb1ca0732017-02-01 16:38:124996 video_source_.IncomingCapturedFrame(
Åsa Persson8c1bf952018-09-13 08:42:194997 CreateFrame(2 * kFrameIntervalMs, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 14:06:524998 WaitForEncodedFrame((kFrameWidth * 3) / 4, (kFrameHeight * 3) / 4);
sprangb1ca0732017-02-01 16:38:124999
asaperssonfab67072017-04-04 12:51:495000 // Trigger CPU normal use, return to original resolution.
Henrik Boström91aa7322020-04-28 10:24:335001 video_stream_encoder_->TriggerCpuUnderuse();
sprangb1ca0732017-02-01 16:38:125002 video_source_.IncomingCapturedFrame(
Åsa Persson8c1bf952018-09-13 08:42:195003 CreateFrame(3 * kFrameIntervalMs, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 14:06:525004 WaitForEncodedFrame(kFrameWidth, kFrameHeight);
sprangb1ca0732017-02-01 16:38:125005
mflodmancc3d4422017-08-03 15:27:515006 video_stream_encoder_->Stop();
sprangb1ca0732017-02-01 16:38:125007}
sprangfe627f32017-03-29 15:24:595008
mflodmancc3d4422017-08-03 15:27:515009TEST_F(VideoStreamEncoderTest,
5010 AdaptsFramerateOnOveruse_MaintainResolutionMode) {
sprangc5d62e22017-04-03 06:53:045011 const int kFrameWidth = 1280;
5012 const int kFrameHeight = 720;
sprangc5d62e22017-04-03 06:53:045013
Henrik Boström381d1092020-05-12 16:49:075014 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:075015 DataRate::BitsPerSec(kTargetBitrateBps),
5016 DataRate::BitsPerSec(kTargetBitrateBps),
5017 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
mflodmancc3d4422017-08-03 15:27:515018 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 21:20:415019 &video_source_, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
sprangc5d62e22017-04-03 06:53:045020 video_source_.set_adaptation_enabled(true);
5021
Tomas Gunnarsson612445e2020-09-21 12:31:235022 int64_t timestamp_ms = CurrentTimeMs();
sprangc5d62e22017-04-03 06:53:045023
5024 video_source_.IncomingCapturedFrame(
5025 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 14:06:525026 WaitForEncodedFrame(timestamp_ms);
sprangc5d62e22017-04-03 06:53:045027
5028 // Try to trigger overuse. No fps estimate available => no effect.
mflodmancc3d4422017-08-03 15:27:515029 video_stream_encoder_->TriggerCpuOveruse();
sprangc5d62e22017-04-03 06:53:045030
5031 // Insert frames for one second to get a stable estimate.
sprang4847ae62017-06-27 14:06:525032 for (int i = 0; i < max_framerate_; ++i) {
sprangc5d62e22017-04-03 06:53:045033 timestamp_ms += kFrameIntervalMs;
sprangc5d62e22017-04-03 06:53:045034 video_source_.IncomingCapturedFrame(
5035 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 14:06:525036 WaitForEncodedFrame(timestamp_ms);
sprangc5d62e22017-04-03 06:53:045037 }
5038
5039 // Trigger CPU overuse, reduce framerate by 2/3.
mflodmancc3d4422017-08-03 15:27:515040 video_stream_encoder_->TriggerCpuOveruse();
sprangc5d62e22017-04-03 06:53:045041 int num_frames_dropped = 0;
sprang4847ae62017-06-27 14:06:525042 for (int i = 0; i < max_framerate_; ++i) {
sprangc5d62e22017-04-03 06:53:045043 timestamp_ms += kFrameIntervalMs;
sprangc5d62e22017-04-03 06:53:045044 video_source_.IncomingCapturedFrame(
5045 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 14:06:525046 if (!WaitForFrame(kFrameTimeoutMs)) {
sprangc5d62e22017-04-03 06:53:045047 ++num_frames_dropped;
5048 } else {
Åsa Perssonc74d8da2017-12-04 13:13:565049 sink_.CheckLastFrameSizeMatches(kFrameWidth, kFrameHeight);
sprangc5d62e22017-04-03 06:53:045050 }
5051 }
5052
sprang4847ae62017-06-27 14:06:525053 // Add some slack to account for frames dropped by the frame dropper.
5054 const int kErrorMargin = 1;
5055 EXPECT_NEAR(num_frames_dropped, max_framerate_ - (max_framerate_ * 2 / 3),
sprangc5d62e22017-04-03 06:53:045056 kErrorMargin);
5057
5058 // Trigger CPU overuse, reduce framerate by 2/3 again.
mflodmancc3d4422017-08-03 15:27:515059 video_stream_encoder_->TriggerCpuOveruse();
sprangc5d62e22017-04-03 06:53:045060 num_frames_dropped = 0;
Åsa Persson8c1bf952018-09-13 08:42:195061 for (int i = 0; i <= max_framerate_; ++i) {
sprangc5d62e22017-04-03 06:53:045062 timestamp_ms += kFrameIntervalMs;
sprangc5d62e22017-04-03 06:53:045063 video_source_.IncomingCapturedFrame(
5064 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 14:06:525065 if (!WaitForFrame(kFrameTimeoutMs)) {
sprangc5d62e22017-04-03 06:53:045066 ++num_frames_dropped;
5067 } else {
Åsa Perssonc74d8da2017-12-04 13:13:565068 sink_.CheckLastFrameSizeMatches(kFrameWidth, kFrameHeight);
sprangc5d62e22017-04-03 06:53:045069 }
5070 }
sprang4847ae62017-06-27 14:06:525071 EXPECT_NEAR(num_frames_dropped, max_framerate_ - (max_framerate_ * 4 / 9),
sprangc5d62e22017-04-03 06:53:045072 kErrorMargin);
5073
5074 // Go back up one step.
Henrik Boström91aa7322020-04-28 10:24:335075 video_stream_encoder_->TriggerCpuUnderuse();
sprangc5d62e22017-04-03 06:53:045076 num_frames_dropped = 0;
sprang4847ae62017-06-27 14:06:525077 for (int i = 0; i < max_framerate_; ++i) {
sprangc5d62e22017-04-03 06:53:045078 timestamp_ms += kFrameIntervalMs;
sprangc5d62e22017-04-03 06:53:045079 video_source_.IncomingCapturedFrame(
5080 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 14:06:525081 if (!WaitForFrame(kFrameTimeoutMs)) {
sprangc5d62e22017-04-03 06:53:045082 ++num_frames_dropped;
5083 } else {
Åsa Perssonc74d8da2017-12-04 13:13:565084 sink_.CheckLastFrameSizeMatches(kFrameWidth, kFrameHeight);
sprangc5d62e22017-04-03 06:53:045085 }
5086 }
sprang4847ae62017-06-27 14:06:525087 EXPECT_NEAR(num_frames_dropped, max_framerate_ - (max_framerate_ * 2 / 3),
sprangc5d62e22017-04-03 06:53:045088 kErrorMargin);
5089
5090 // Go back up to original mode.
Henrik Boström91aa7322020-04-28 10:24:335091 video_stream_encoder_->TriggerCpuUnderuse();
sprangc5d62e22017-04-03 06:53:045092 num_frames_dropped = 0;
sprang4847ae62017-06-27 14:06:525093 for (int i = 0; i < max_framerate_; ++i) {
sprangc5d62e22017-04-03 06:53:045094 timestamp_ms += kFrameIntervalMs;
sprangc5d62e22017-04-03 06:53:045095 video_source_.IncomingCapturedFrame(
5096 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 14:06:525097 if (!WaitForFrame(kFrameTimeoutMs)) {
sprangc5d62e22017-04-03 06:53:045098 ++num_frames_dropped;
5099 } else {
Åsa Perssonc74d8da2017-12-04 13:13:565100 sink_.CheckLastFrameSizeMatches(kFrameWidth, kFrameHeight);
sprangc5d62e22017-04-03 06:53:045101 }
5102 }
5103 EXPECT_NEAR(num_frames_dropped, 0, kErrorMargin);
5104
mflodmancc3d4422017-08-03 15:27:515105 video_stream_encoder_->Stop();
sprangc5d62e22017-04-03 06:53:045106}
5107
mflodmancc3d4422017-08-03 15:27:515108TEST_F(VideoStreamEncoderTest, DoesntAdaptDownPastMinFramerate) {
sprangc5d62e22017-04-03 06:53:045109 const int kFramerateFps = 5;
5110 const int kFrameIntervalMs = rtc::kNumMillisecsPerSec / kFramerateFps;
sprangc5d62e22017-04-03 06:53:045111 const int kFrameWidth = 1280;
5112 const int kFrameHeight = 720;
5113
sprang4847ae62017-06-27 14:06:525114 // Reconfigure encoder with two temporal layers and screensharing, which will
5115 // disable frame dropping and make testing easier.
Niels Möllerf1338562018-04-26 07:51:475116 ResetEncoder("VP8", 1, 2, 1, true);
sprang4847ae62017-06-27 14:06:525117
Henrik Boström381d1092020-05-12 16:49:075118 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:075119 DataRate::BitsPerSec(kTargetBitrateBps),
5120 DataRate::BitsPerSec(kTargetBitrateBps),
5121 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
mflodmancc3d4422017-08-03 15:27:515122 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 21:20:415123 &video_source_, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
sprangc5d62e22017-04-03 06:53:045124 video_source_.set_adaptation_enabled(true);
5125
Tomas Gunnarsson612445e2020-09-21 12:31:235126 int64_t timestamp_ms = CurrentTimeMs();
sprangc5d62e22017-04-03 06:53:045127
5128 // Trigger overuse as much as we can.
Jonathan Yubc771b72017-12-09 01:04:295129 rtc::VideoSinkWants last_wants;
5130 do {
5131 last_wants = video_source_.sink_wants();
5132
sprangc5d62e22017-04-03 06:53:045133 // Insert frames to get a new fps estimate...
5134 for (int j = 0; j < kFramerateFps; ++j) {
5135 video_source_.IncomingCapturedFrame(
5136 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
Jonathan Yubc771b72017-12-09 01:04:295137 if (video_source_.last_sent_width()) {
5138 sink_.WaitForEncodedFrame(timestamp_ms);
5139 }
sprangc5d62e22017-04-03 06:53:045140 timestamp_ms += kFrameIntervalMs;
Tomas Gunnarsson612445e2020-09-21 12:31:235141 AdvanceTime(TimeDelta::Millis(kFrameIntervalMs));
sprangc5d62e22017-04-03 06:53:045142 }
5143 // ...and then try to adapt again.
mflodmancc3d4422017-08-03 15:27:515144 video_stream_encoder_->TriggerCpuOveruse();
Jonathan Yubc771b72017-12-09 01:04:295145 } while (video_source_.sink_wants().max_framerate_fps <
5146 last_wants.max_framerate_fps);
sprangc5d62e22017-04-03 06:53:045147
Evan Shrubsole5cd7eb82020-05-25 12:08:395148 EXPECT_THAT(video_source_.sink_wants(),
5149 FpsMatchesResolutionMax(Eq(kMinFramerateFps)));
asaperssonf7e294d2017-06-14 06:25:225150
mflodmancc3d4422017-08-03 15:27:515151 video_stream_encoder_->Stop();
sprangc5d62e22017-04-03 06:53:045152}
asaperssonf7e294d2017-06-14 06:25:225153
mflodmancc3d4422017-08-03 15:27:515154TEST_F(VideoStreamEncoderTest,
5155 AdaptsResolutionAndFramerateForLowQuality_BalancedMode) {
asaperssonf7e294d2017-06-14 06:25:225156 const int kWidth = 1280;
5157 const int kHeight = 720;
5158 const int64_t kFrameIntervalMs = 150;
5159 int64_t timestamp_ms = kFrameIntervalMs;
Henrik Boström381d1092020-05-12 16:49:075160 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:075161 DataRate::BitsPerSec(kTargetBitrateBps),
5162 DataRate::BitsPerSec(kTargetBitrateBps),
5163 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asaperssonf7e294d2017-06-14 06:25:225164
Taylor Brandstetter49fcc102018-05-16 21:20:415165 // Enable BALANCED preference, no initial limitation.
Tomas Gunnarsson612445e2020-09-21 12:31:235166 AdaptingFrameForwarder source(&time_controller_);
asaperssonf7e294d2017-06-14 06:25:225167 source.set_adaptation_enabled(true);
Taylor Brandstetter49fcc102018-05-16 21:20:415168 video_stream_encoder_->SetSource(&source,
5169 webrtc::DegradationPreference::BALANCED);
asaperssonf7e294d2017-06-14 06:25:225170 timestamp_ms += kFrameIntervalMs;
5171 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:525172 WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5cd7eb82020-05-25 12:08:395173 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-14 06:25:225174 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
5175 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
5176 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5177
5178 // Trigger adapt down, expect scaled down resolution (960x540@30fps).
mflodmancc3d4422017-08-03 15:27:515179 video_stream_encoder_->TriggerQualityLow();
asaperssonf7e294d2017-06-14 06:25:225180 timestamp_ms += kFrameIntervalMs;
5181 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:525182 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5cd7eb82020-05-25 12:08:395183 EXPECT_THAT(source.sink_wants(),
5184 FpsMaxResolutionMatches(Lt(kWidth * kHeight)));
asaperssonf7e294d2017-06-14 06:25:225185 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5186 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
5187 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5188
5189 // Trigger adapt down, expect scaled down resolution (640x360@30fps).
mflodmancc3d4422017-08-03 15:27:515190 video_stream_encoder_->TriggerQualityLow();
asaperssonf7e294d2017-06-14 06:25:225191 timestamp_ms += kFrameIntervalMs;
5192 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:525193 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 14:19:545194 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionLt(source.last_wants()));
asaperssonf7e294d2017-06-14 06:25:225195 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5196 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
5197 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5198
5199 // Trigger adapt down, expect reduced fps (640x360@15fps).
mflodmancc3d4422017-08-03 15:27:515200 video_stream_encoder_->TriggerQualityLow();
asaperssonf7e294d2017-06-14 06:25:225201 timestamp_ms += kFrameIntervalMs;
5202 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:525203 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 14:19:545204 EXPECT_THAT(source.sink_wants(), FpsLtResolutionEq(source.last_wants()));
asaperssonf7e294d2017-06-14 06:25:225205 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5206 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
5207 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5208
5209 // Trigger adapt down, expect scaled down resolution (480x270@15fps).
mflodmancc3d4422017-08-03 15:27:515210 video_stream_encoder_->TriggerQualityLow();
asaperssonf7e294d2017-06-14 06:25:225211 timestamp_ms += kFrameIntervalMs;
5212 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:525213 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 14:19:545214 EXPECT_THAT(source.sink_wants(), FpsEqResolutionLt(source.last_wants()));
asaperssonf7e294d2017-06-14 06:25:225215 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5216 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
5217 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5218
5219 // Restrict bitrate, trigger adapt down, expect reduced fps (480x270@10fps).
mflodmancc3d4422017-08-03 15:27:515220 video_stream_encoder_->TriggerQualityLow();
asaperssonf7e294d2017-06-14 06:25:225221 timestamp_ms += kFrameIntervalMs;
5222 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:525223 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 14:19:545224 EXPECT_THAT(source.sink_wants(), FpsLtResolutionEq(source.last_wants()));
asaperssonf7e294d2017-06-14 06:25:225225 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5226 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
5227 EXPECT_EQ(5, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5228
5229 // Trigger adapt down, expect scaled down resolution (320x180@10fps).
mflodmancc3d4422017-08-03 15:27:515230 video_stream_encoder_->TriggerQualityLow();
asaperssonf7e294d2017-06-14 06:25:225231 timestamp_ms += kFrameIntervalMs;
5232 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:525233 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 14:19:545234 EXPECT_THAT(source.sink_wants(), FpsEqResolutionLt(source.last_wants()));
asaperssonf7e294d2017-06-14 06:25:225235 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5236 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
5237 EXPECT_EQ(6, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5238
5239 // Trigger adapt down, expect reduced fps (320x180@7fps).
mflodmancc3d4422017-08-03 15:27:515240 video_stream_encoder_->TriggerQualityLow();
asaperssonf7e294d2017-06-14 06:25:225241 timestamp_ms += kFrameIntervalMs;
5242 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:525243 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 14:19:545244 EXPECT_THAT(source.sink_wants(), FpsLtResolutionEq(source.last_wants()));
asaperssonf7e294d2017-06-14 06:25:225245 rtc::VideoSinkWants last_wants = source.sink_wants();
5246 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5247 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
5248 EXPECT_EQ(7, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5249
5250 // Trigger adapt down, min resolution reached, expect no change.
mflodmancc3d4422017-08-03 15:27:515251 video_stream_encoder_->TriggerQualityLow();
asaperssonf7e294d2017-06-14 06:25:225252 timestamp_ms += kFrameIntervalMs;
5253 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:525254 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 14:19:545255 EXPECT_THAT(source.sink_wants(), FpsEqResolutionEqTo(last_wants));
asaperssonf7e294d2017-06-14 06:25:225256 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5257 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
5258 EXPECT_EQ(7, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5259
Evan Shrubsole64469032020-06-11 08:45:295260 // Trigger adapt up, expect expect increased fps (320x180@10fps).
mflodmancc3d4422017-08-03 15:27:515261 video_stream_encoder_->TriggerQualityHigh();
asaperssonf7e294d2017-06-14 06:25:225262 timestamp_ms += kFrameIntervalMs;
5263 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:525264 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 14:19:545265 EXPECT_THAT(source.sink_wants(), FpsGtResolutionEq(source.last_wants()));
asaperssonf7e294d2017-06-14 06:25:225266 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5267 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
5268 EXPECT_EQ(8, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5269
5270 // Trigger adapt up, expect upscaled resolution (480x270@10fps).
mflodmancc3d4422017-08-03 15:27:515271 video_stream_encoder_->TriggerQualityHigh();
asaperssonf7e294d2017-06-14 06:25:225272 timestamp_ms += kFrameIntervalMs;
5273 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:525274 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 14:19:545275 EXPECT_THAT(source.sink_wants(), FpsEqResolutionGt(source.last_wants()));
asaperssonf7e294d2017-06-14 06:25:225276 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5277 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
5278 EXPECT_EQ(9, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5279
5280 // Increase bitrate, trigger adapt up, expect increased fps (480x270@15fps).
mflodmancc3d4422017-08-03 15:27:515281 video_stream_encoder_->TriggerQualityHigh();
asaperssonf7e294d2017-06-14 06:25:225282 timestamp_ms += kFrameIntervalMs;
5283 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:525284 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 14:19:545285 EXPECT_THAT(source.sink_wants(), FpsGtResolutionEq(source.last_wants()));
asaperssonf7e294d2017-06-14 06:25:225286 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5287 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
5288 EXPECT_EQ(10, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5289
5290 // Trigger adapt up, expect upscaled resolution (640x360@15fps).
mflodmancc3d4422017-08-03 15:27:515291 video_stream_encoder_->TriggerQualityHigh();
asaperssonf7e294d2017-06-14 06:25:225292 timestamp_ms += kFrameIntervalMs;
5293 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:525294 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 14:19:545295 EXPECT_THAT(source.sink_wants(), FpsEqResolutionGt(source.last_wants()));
asaperssonf7e294d2017-06-14 06:25:225296 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5297 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
5298 EXPECT_EQ(11, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5299
5300 // Trigger adapt up, expect increased fps (640x360@30fps).
mflodmancc3d4422017-08-03 15:27:515301 video_stream_encoder_->TriggerQualityHigh();
asaperssonf7e294d2017-06-14 06:25:225302 timestamp_ms += kFrameIntervalMs;
5303 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:525304 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 14:19:545305 EXPECT_THAT(source.sink_wants(), FpsMax());
5306 EXPECT_EQ(source.sink_wants().max_pixel_count,
5307 source.last_wants().max_pixel_count);
asaperssonf7e294d2017-06-14 06:25:225308 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5309 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
5310 EXPECT_EQ(12, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5311
5312 // Trigger adapt up, expect upscaled resolution (960x540@30fps).
mflodmancc3d4422017-08-03 15:27:515313 video_stream_encoder_->TriggerQualityHigh();
asaperssonf7e294d2017-06-14 06:25:225314 timestamp_ms += kFrameIntervalMs;
5315 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:525316 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 14:19:545317 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionGt(source.last_wants()));
asaperssonf7e294d2017-06-14 06:25:225318 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5319 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
5320 EXPECT_EQ(13, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5321
Åsa Persson30ab0152019-08-27 10:22:335322 // Trigger adapt up, expect no restriction (1280x720fps@30fps).
mflodmancc3d4422017-08-03 15:27:515323 video_stream_encoder_->TriggerQualityHigh();
asaperssonf7e294d2017-06-14 06:25:225324 timestamp_ms += kFrameIntervalMs;
5325 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:525326 WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5fd40602020-05-25 14:19:545327 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionGt(source.last_wants()));
Evan Shrubsole5cd7eb82020-05-25 12:08:395328 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-14 06:25:225329 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
5330 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
5331 EXPECT_EQ(14, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5332
5333 // Trigger adapt up, expect no change.
mflodmancc3d4422017-08-03 15:27:515334 video_stream_encoder_->TriggerQualityHigh();
Evan Shrubsole5cd7eb82020-05-25 12:08:395335 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-14 06:25:225336 EXPECT_EQ(14, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5337
mflodmancc3d4422017-08-03 15:27:515338 video_stream_encoder_->Stop();
asaperssonf7e294d2017-06-14 06:25:225339}
5340
mflodmancc3d4422017-08-03 15:27:515341TEST_F(VideoStreamEncoderTest, AdaptWithTwoReasonsAndDifferentOrder_Framerate) {
asaperssonf7e294d2017-06-14 06:25:225342 const int kWidth = 1280;
5343 const int kHeight = 720;
5344 const int64_t kFrameIntervalMs = 150;
5345 int64_t timestamp_ms = kFrameIntervalMs;
Henrik Boström381d1092020-05-12 16:49:075346 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:075347 DataRate::BitsPerSec(kTargetBitrateBps),
5348 DataRate::BitsPerSec(kTargetBitrateBps),
5349 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asaperssonf7e294d2017-06-14 06:25:225350
Taylor Brandstetter49fcc102018-05-16 21:20:415351 // Enable BALANCED preference, no initial limitation.
Tomas Gunnarsson612445e2020-09-21 12:31:235352 AdaptingFrameForwarder source(&time_controller_);
asaperssonf7e294d2017-06-14 06:25:225353 source.set_adaptation_enabled(true);
Taylor Brandstetter49fcc102018-05-16 21:20:415354 video_stream_encoder_->SetSource(&source,
5355 webrtc::DegradationPreference::BALANCED);
asaperssonf7e294d2017-06-14 06:25:225356 timestamp_ms += kFrameIntervalMs;
5357 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:525358 WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5cd7eb82020-05-25 12:08:395359 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-14 06:25:225360 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
5361 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
5362 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
5363 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
5364 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
5365 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5366
5367 // Trigger cpu adapt down, expect scaled down resolution (960x540@30fps).
mflodmancc3d4422017-08-03 15:27:515368 video_stream_encoder_->TriggerCpuOveruse();
asaperssonf7e294d2017-06-14 06:25:225369 timestamp_ms += kFrameIntervalMs;
5370 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:525371 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5cd7eb82020-05-25 12:08:395372 EXPECT_THAT(source.sink_wants(),
5373 FpsMaxResolutionMatches(Lt(kWidth * kHeight)));
asaperssonf7e294d2017-06-14 06:25:225374 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
5375 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
5376 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
5377 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
5378 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
5379 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5380
5381 // Trigger cpu adapt down, expect scaled down resolution (640x360@30fps).
mflodmancc3d4422017-08-03 15:27:515382 video_stream_encoder_->TriggerCpuOveruse();
asaperssonf7e294d2017-06-14 06:25:225383 timestamp_ms += kFrameIntervalMs;
5384 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:525385 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 14:19:545386 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionLt(source.last_wants()));
asaperssonf7e294d2017-06-14 06:25:225387 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
5388 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
5389 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
5390 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
5391 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
5392 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5393
5394 // Trigger quality adapt down, expect reduced fps (640x360@15fps).
mflodmancc3d4422017-08-03 15:27:515395 video_stream_encoder_->TriggerQualityLow();
asaperssonf7e294d2017-06-14 06:25:225396 timestamp_ms += kFrameIntervalMs;
5397 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:525398 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 14:19:545399 EXPECT_THAT(source.sink_wants(), FpsLtResolutionEq(source.last_wants()));
Evan Shrubsole64469032020-06-11 08:45:295400 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
asaperssonf7e294d2017-06-14 06:25:225401 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
5402 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
5403 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
5404 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
5405 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5406
Evan Shrubsole64469032020-06-11 08:45:295407 // Trigger cpu adapt up, expect no change since QP is most limited.
5408 {
5409 // Store current sink wants since we expect no change and if there is no
5410 // change then last_wants() is not updated.
5411 auto previous_sink_wants = source.sink_wants();
5412 video_stream_encoder_->TriggerCpuUnderuse();
5413 timestamp_ms += kFrameIntervalMs;
5414 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
5415 WaitForEncodedFrame(timestamp_ms);
5416 EXPECT_THAT(source.sink_wants(), FpsEqResolutionEqTo(previous_sink_wants));
5417 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
5418 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5419 }
5420
5421 // Trigger quality adapt up, expect increased fps (640x360@30fps).
5422 video_stream_encoder_->TriggerQualityHigh();
5423 timestamp_ms += kFrameIntervalMs;
5424 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
5425 WaitForEncodedFrame(timestamp_ms);
5426 EXPECT_THAT(source.sink_wants(), FpsGtResolutionEq(source.last_wants()));
5427 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5428 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
5429 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
5430 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
5431 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
5432 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5433
5434 // Trigger quality adapt up and Cpu adapt up since both are most limited,
5435 // expect increased resolution (960x540@30fps).
5436 video_stream_encoder_->TriggerQualityHigh();
Henrik Boström91aa7322020-04-28 10:24:335437 video_stream_encoder_->TriggerCpuUnderuse();
asaperssonf7e294d2017-06-14 06:25:225438 timestamp_ms += kFrameIntervalMs;
5439 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:525440 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole64469032020-06-11 08:45:295441 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionGt(source.last_wants()));
asaperssonf7e294d2017-06-14 06:25:225442 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5443 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
5444 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
5445 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
5446 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
Evan Shrubsole64469032020-06-11 08:45:295447 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_quality_adapt_changes);
asaperssonf7e294d2017-06-14 06:25:225448
Evan Shrubsole64469032020-06-11 08:45:295449 // Trigger quality adapt up and Cpu adapt up since both are most limited,
5450 // expect no restriction (1280x720fps@30fps).
mflodmancc3d4422017-08-03 15:27:515451 video_stream_encoder_->TriggerQualityHigh();
Henrik Boström91aa7322020-04-28 10:24:335452 video_stream_encoder_->TriggerCpuUnderuse();
asaperssonf7e294d2017-06-14 06:25:225453 timestamp_ms += kFrameIntervalMs;
5454 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:525455 WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5fd40602020-05-25 14:19:545456 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionGt(source.last_wants()));
Evan Shrubsole5cd7eb82020-05-25 12:08:395457 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-14 06:25:225458 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
5459 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
5460 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
5461 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
5462 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
Evan Shrubsole64469032020-06-11 08:45:295463 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_quality_adapt_changes);
asaperssonf7e294d2017-06-14 06:25:225464
5465 // Trigger adapt up, expect no change.
mflodmancc3d4422017-08-03 15:27:515466 video_stream_encoder_->TriggerQualityHigh();
Evan Shrubsole5cd7eb82020-05-25 12:08:395467 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-14 06:25:225468 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
Evan Shrubsole64469032020-06-11 08:45:295469 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_quality_adapt_changes);
asaperssonf7e294d2017-06-14 06:25:225470
mflodmancc3d4422017-08-03 15:27:515471 video_stream_encoder_->Stop();
asaperssonf7e294d2017-06-14 06:25:225472}
5473
mflodmancc3d4422017-08-03 15:27:515474TEST_F(VideoStreamEncoderTest,
5475 AdaptWithTwoReasonsAndDifferentOrder_Resolution) {
asaperssonf7e294d2017-06-14 06:25:225476 const int kWidth = 640;
5477 const int kHeight = 360;
5478 const int kFpsLimit = 15;
5479 const int64_t kFrameIntervalMs = 150;
5480 int64_t timestamp_ms = kFrameIntervalMs;
Henrik Boström381d1092020-05-12 16:49:075481 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:075482 DataRate::BitsPerSec(kTargetBitrateBps),
5483 DataRate::BitsPerSec(kTargetBitrateBps),
5484 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asaperssonf7e294d2017-06-14 06:25:225485
Taylor Brandstetter49fcc102018-05-16 21:20:415486 // Enable BALANCED preference, no initial limitation.
Tomas Gunnarsson612445e2020-09-21 12:31:235487 AdaptingFrameForwarder source(&time_controller_);
asaperssonf7e294d2017-06-14 06:25:225488 source.set_adaptation_enabled(true);
Taylor Brandstetter49fcc102018-05-16 21:20:415489 video_stream_encoder_->SetSource(&source,
5490 webrtc::DegradationPreference::BALANCED);
asaperssonf7e294d2017-06-14 06:25:225491 timestamp_ms += kFrameIntervalMs;
5492 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:525493 WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5cd7eb82020-05-25 12:08:395494 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-14 06:25:225495 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
5496 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
5497 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
5498 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
5499 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
5500 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5501
5502 // Trigger cpu adapt down, expect scaled down framerate (640x360@15fps).
mflodmancc3d4422017-08-03 15:27:515503 video_stream_encoder_->TriggerCpuOveruse();
asaperssonf7e294d2017-06-14 06:25:225504 timestamp_ms += kFrameIntervalMs;
5505 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:525506 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5cd7eb82020-05-25 12:08:395507 EXPECT_THAT(source.sink_wants(), FpsMatchesResolutionMax(Eq(kFpsLimit)));
asaperssonf7e294d2017-06-14 06:25:225508 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
5509 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
5510 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
5511 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_framerate);
5512 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
5513 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5514
5515 // Trigger quality adapt down, expect scaled down resolution (480x270@15fps).
mflodmancc3d4422017-08-03 15:27:515516 video_stream_encoder_->TriggerQualityLow();
asaperssonf7e294d2017-06-14 06:25:225517 timestamp_ms += kFrameIntervalMs;
5518 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:525519 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 14:19:545520 EXPECT_THAT(source.sink_wants(), FpsEqResolutionLt(source.last_wants()));
asaperssonf7e294d2017-06-14 06:25:225521 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
Evan Shrubsole64469032020-06-11 08:45:295522 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
asaperssonf7e294d2017-06-14 06:25:225523 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
5524 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_framerate);
5525 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
5526 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5527
Evan Shrubsole64469032020-06-11 08:45:295528 // Trigger cpu adapt up, expect no change because quality is most limited.
5529 {
5530 auto previous_sink_wants = source.sink_wants();
5531 // Store current sink wants since we expect no change ind if there is no
5532 // change then last__wants() is not updated.
5533 video_stream_encoder_->TriggerCpuUnderuse();
5534 timestamp_ms += kFrameIntervalMs;
5535 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
5536 WaitForEncodedFrame(timestamp_ms);
5537 EXPECT_THAT(source.sink_wants(), FpsEqResolutionEqTo(previous_sink_wants));
5538 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
5539 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5540 }
5541
5542 // Trigger quality adapt up, expect upscaled resolution (640x360@15fps).
5543 video_stream_encoder_->TriggerQualityHigh();
asaperssonf7e294d2017-06-14 06:25:225544 timestamp_ms += kFrameIntervalMs;
5545 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:525546 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 14:19:545547 EXPECT_THAT(source.sink_wants(), FpsEqResolutionGt(source.last_wants()));
asaperssonf7e294d2017-06-14 06:25:225548 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
5549 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
5550 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
Evan Shrubsole64469032020-06-11 08:45:295551 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_framerate);
5552 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
5553 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_quality_adapt_changes);
asaperssonf7e294d2017-06-14 06:25:225554
Evan Shrubsole64469032020-06-11 08:45:295555 // Trigger quality and cpu adapt up, expect increased fps (640x360@30fps).
mflodmancc3d4422017-08-03 15:27:515556 video_stream_encoder_->TriggerQualityHigh();
Evan Shrubsole64469032020-06-11 08:45:295557 video_stream_encoder_->TriggerCpuUnderuse();
asaperssonf7e294d2017-06-14 06:25:225558 timestamp_ms += kFrameIntervalMs;
5559 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 14:06:525560 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5cd7eb82020-05-25 12:08:395561 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-14 06:25:225562 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
5563 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
5564 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
5565 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
5566 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
Evan Shrubsole64469032020-06-11 08:45:295567 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_quality_adapt_changes);
asaperssonf7e294d2017-06-14 06:25:225568
5569 // Trigger adapt up, expect no change.
mflodmancc3d4422017-08-03 15:27:515570 video_stream_encoder_->TriggerQualityHigh();
Evan Shrubsole5cd7eb82020-05-25 12:08:395571 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-14 06:25:225572 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
Evan Shrubsole64469032020-06-11 08:45:295573 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_quality_adapt_changes);
asaperssonf7e294d2017-06-14 06:25:225574
mflodmancc3d4422017-08-03 15:27:515575 video_stream_encoder_->Stop();
asaperssonf7e294d2017-06-14 06:25:225576}
5577
mflodmancc3d4422017-08-03 15:27:515578TEST_F(VideoStreamEncoderTest, AcceptsFullHdAdaptedDownSimulcastFrames) {
ilnik6b826ef2017-06-16 13:53:485579 const int kFrameWidth = 1920;
5580 const int kFrameHeight = 1080;
5581 // 3/4 of 1920.
5582 const int kAdaptedFrameWidth = 1440;
5583 // 3/4 of 1080 rounded down to multiple of 4.
5584 const int kAdaptedFrameHeight = 808;
5585 const int kFramerate = 24;
5586
Henrik Boström381d1092020-05-12 16:49:075587 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:075588 DataRate::BitsPerSec(kTargetBitrateBps),
5589 DataRate::BitsPerSec(kTargetBitrateBps),
5590 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
ilnik6b826ef2017-06-16 13:53:485591 // Trigger reconfigure encoder (without resetting the entire instance).
5592 VideoEncoderConfig video_encoder_config;
Åsa Persson17b29b92020-10-17 10:57:585593 test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
5594 video_encoder_config.simulcast_layers[0].max_framerate = kFramerate;
ilnik6b826ef2017-06-16 13:53:485595 video_encoder_config.max_bitrate_bps = kTargetBitrateBps;
ilnik6b826ef2017-06-16 13:53:485596 video_encoder_config.video_stream_factory =
Åsa Persson17b29b92020-10-17 10:57:585597 new rtc::RefCountedObject<CroppingVideoStreamFactory>();
mflodmancc3d4422017-08-03 15:27:515598 video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config),
Niels Möllerf1338562018-04-26 07:51:475599 kMaxPayloadLength);
mflodmancc3d4422017-08-03 15:27:515600 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
ilnik6b826ef2017-06-16 13:53:485601
5602 video_source_.set_adaptation_enabled(true);
5603
5604 video_source_.IncomingCapturedFrame(
5605 CreateFrame(1, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 14:06:525606 WaitForEncodedFrame(kFrameWidth, kFrameHeight);
ilnik6b826ef2017-06-16 13:53:485607
5608 // Trigger CPU overuse, downscale by 3/4.
mflodmancc3d4422017-08-03 15:27:515609 video_stream_encoder_->TriggerCpuOveruse();
ilnik6b826ef2017-06-16 13:53:485610 video_source_.IncomingCapturedFrame(
5611 CreateFrame(2, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 14:06:525612 WaitForEncodedFrame(kAdaptedFrameWidth, kAdaptedFrameHeight);
ilnik6b826ef2017-06-16 13:53:485613
mflodmancc3d4422017-08-03 15:27:515614 video_stream_encoder_->Stop();
ilnik6b826ef2017-06-16 13:53:485615}
5616
mflodmancc3d4422017-08-03 15:27:515617TEST_F(VideoStreamEncoderTest, PeriodicallyUpdatesChannelParameters) {
sprang4847ae62017-06-27 14:06:525618 const int kFrameWidth = 1280;
5619 const int kFrameHeight = 720;
5620 const int kLowFps = 2;
5621 const int kHighFps = 30;
5622
Henrik Boström381d1092020-05-12 16:49:075623 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:075624 DataRate::BitsPerSec(kTargetBitrateBps),
5625 DataRate::BitsPerSec(kTargetBitrateBps),
5626 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
sprang4847ae62017-06-27 14:06:525627
Tomas Gunnarsson612445e2020-09-21 12:31:235628 int64_t timestamp_ms = CurrentTimeMs();
sprang4847ae62017-06-27 14:06:525629 max_framerate_ = kLowFps;
5630
5631 // Insert 2 seconds of 2fps video.
5632 for (int i = 0; i < kLowFps * 2; ++i) {
5633 video_source_.IncomingCapturedFrame(
5634 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
5635 WaitForEncodedFrame(timestamp_ms);
5636 timestamp_ms += 1000 / kLowFps;
5637 }
5638
5639 // Make sure encoder is updated with new target.
Henrik Boström381d1092020-05-12 16:49:075640 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:075641 DataRate::BitsPerSec(kTargetBitrateBps),
5642 DataRate::BitsPerSec(kTargetBitrateBps),
5643 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
sprang4847ae62017-06-27 14:06:525644 video_source_.IncomingCapturedFrame(
5645 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
5646 WaitForEncodedFrame(timestamp_ms);
5647 timestamp_ms += 1000 / kLowFps;
5648
5649 EXPECT_EQ(kLowFps, fake_encoder_.GetConfiguredInputFramerate());
5650
5651 // Insert 30fps frames for just a little more than the forced update period.
Niels Möllerfe407b72019-09-10 08:48:485652 const int kVcmTimerIntervalFrames = (kProcessIntervalMs * kHighFps) / 1000;
sprang4847ae62017-06-27 14:06:525653 const int kFrameIntervalMs = 1000 / kHighFps;
5654 max_framerate_ = kHighFps;
5655 for (int i = 0; i < kVcmTimerIntervalFrames + 2; ++i) {
5656 video_source_.IncomingCapturedFrame(
5657 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
5658 // Wait for encoded frame, but skip ahead if it doesn't arrive as it might
5659 // be dropped if the encoder hans't been updated with the new higher target
5660 // framerate yet, causing it to overshoot the target bitrate and then
5661 // suffering the wrath of the media optimizer.
5662 TimedWaitForEncodedFrame(timestamp_ms, 2 * kFrameIntervalMs);
5663 timestamp_ms += kFrameIntervalMs;
5664 }
5665
5666 // Don expect correct measurement just yet, but it should be higher than
5667 // before.
5668 EXPECT_GT(fake_encoder_.GetConfiguredInputFramerate(), kLowFps);
5669
mflodmancc3d4422017-08-03 15:27:515670 video_stream_encoder_->Stop();
sprang4847ae62017-06-27 14:06:525671}
5672
mflodmancc3d4422017-08-03 15:27:515673TEST_F(VideoStreamEncoderTest, DoesNotUpdateBitrateAllocationWhenSuspended) {
sprang4847ae62017-06-27 14:06:525674 const int kFrameWidth = 1280;
5675 const int kFrameHeight = 720;
5676 const int kTargetBitrateBps = 1000000;
Per Kjellanderdcef6412020-10-07 13:09:055677 ResetEncoder("FAKE", 1, 1, 1, false,
5678 VideoStreamEncoderSettings::BitrateAllocationCallbackType::
5679 kVideoBitrateAllocation);
sprang4847ae62017-06-27 14:06:525680
Henrik Boström381d1092020-05-12 16:49:075681 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:075682 DataRate::BitsPerSec(kTargetBitrateBps),
5683 DataRate::BitsPerSec(kTargetBitrateBps),
5684 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
mflodmancc3d4422017-08-03 15:27:515685 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
sprang4847ae62017-06-27 14:06:525686
5687 // Insert a first video frame, causes another bitrate update.
Tomas Gunnarsson612445e2020-09-21 12:31:235688 int64_t timestamp_ms = CurrentTimeMs();
sprang4847ae62017-06-27 14:06:525689 video_source_.IncomingCapturedFrame(
5690 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
5691 WaitForEncodedFrame(timestamp_ms);
Per Kjellanderdcef6412020-10-07 13:09:055692 EXPECT_EQ(sink_.number_of_bitrate_allocations(), 1);
sprang4847ae62017-06-27 14:06:525693
5694 // Next, simulate video suspension due to pacer queue overrun.
Henrik Boström381d1092020-05-12 16:49:075695 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
5696 DataRate::BitsPerSec(0), DataRate::BitsPerSec(0), DataRate::BitsPerSec(0),
5697 0, 1, 0);
sprang4847ae62017-06-27 14:06:525698
5699 // Skip ahead until a new periodic parameter update should have occured.
Niels Möllerfe407b72019-09-10 08:48:485700 timestamp_ms += kProcessIntervalMs;
Tomas Gunnarsson612445e2020-09-21 12:31:235701 AdvanceTime(TimeDelta::Millis(kProcessIntervalMs));
sprang4847ae62017-06-27 14:06:525702
Per Kjellanderdcef6412020-10-07 13:09:055703 // No more allocations has been made.
sprang4847ae62017-06-27 14:06:525704 video_source_.IncomingCapturedFrame(
5705 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
5706 ExpectDroppedFrame();
Per Kjellanderdcef6412020-10-07 13:09:055707 EXPECT_EQ(sink_.number_of_bitrate_allocations(), 1);
sprang4847ae62017-06-27 14:06:525708
mflodmancc3d4422017-08-03 15:27:515709 video_stream_encoder_->Stop();
sprang4847ae62017-06-27 14:06:525710}
ilnik6b826ef2017-06-16 13:53:485711
Niels Möller4db138e2018-04-19 07:04:135712TEST_F(VideoStreamEncoderTest,
5713 DefaultCpuAdaptationThresholdsForSoftwareEncoder) {
5714 const int kFrameWidth = 1280;
5715 const int kFrameHeight = 720;
5716 const CpuOveruseOptions default_options;
Henrik Boström381d1092020-05-12 16:49:075717 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:075718 DataRate::BitsPerSec(kTargetBitrateBps),
5719 DataRate::BitsPerSec(kTargetBitrateBps),
5720 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Niels Möller4db138e2018-04-19 07:04:135721 video_source_.IncomingCapturedFrame(
5722 CreateFrame(1, kFrameWidth, kFrameHeight));
5723 WaitForEncodedFrame(1);
5724 EXPECT_EQ(video_stream_encoder_->overuse_detector_proxy_->GetOptions()
5725 .low_encode_usage_threshold_percent,
5726 default_options.low_encode_usage_threshold_percent);
5727 EXPECT_EQ(video_stream_encoder_->overuse_detector_proxy_->GetOptions()
5728 .high_encode_usage_threshold_percent,
5729 default_options.high_encode_usage_threshold_percent);
5730 video_stream_encoder_->Stop();
5731}
5732
5733TEST_F(VideoStreamEncoderTest,
5734 HigherCpuAdaptationThresholdsForHardwareEncoder) {
5735 const int kFrameWidth = 1280;
5736 const int kFrameHeight = 720;
5737 CpuOveruseOptions hardware_options;
5738 hardware_options.low_encode_usage_threshold_percent = 150;
5739 hardware_options.high_encode_usage_threshold_percent = 200;
Mirta Dvornicicccc1b572019-01-15 11:42:185740 fake_encoder_.SetIsHardwareAccelerated(true);
Niels Möller4db138e2018-04-19 07:04:135741
Henrik Boström381d1092020-05-12 16:49:075742 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:075743 DataRate::BitsPerSec(kTargetBitrateBps),
5744 DataRate::BitsPerSec(kTargetBitrateBps),
5745 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Niels Möller4db138e2018-04-19 07:04:135746 video_source_.IncomingCapturedFrame(
5747 CreateFrame(1, kFrameWidth, kFrameHeight));
5748 WaitForEncodedFrame(1);
5749 EXPECT_EQ(video_stream_encoder_->overuse_detector_proxy_->GetOptions()
5750 .low_encode_usage_threshold_percent,
5751 hardware_options.low_encode_usage_threshold_percent);
5752 EXPECT_EQ(video_stream_encoder_->overuse_detector_proxy_->GetOptions()
5753 .high_encode_usage_threshold_percent,
5754 hardware_options.high_encode_usage_threshold_percent);
5755 video_stream_encoder_->Stop();
5756}
5757
Niels Möller6bb5ab92019-01-11 10:11:105758TEST_F(VideoStreamEncoderTest, DropsFramesWhenEncoderOvershoots) {
5759 const int kFrameWidth = 320;
5760 const int kFrameHeight = 240;
5761 const int kFps = 30;
5762 const int kTargetBitrateBps = 120000;
5763 const int kNumFramesInRun = kFps * 5; // Runs of five seconds.
5764
Henrik Boström381d1092020-05-12 16:49:075765 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:075766 DataRate::BitsPerSec(kTargetBitrateBps),
5767 DataRate::BitsPerSec(kTargetBitrateBps),
5768 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Niels Möller6bb5ab92019-01-11 10:11:105769
Tomas Gunnarsson612445e2020-09-21 12:31:235770 int64_t timestamp_ms = CurrentTimeMs();
Niels Möller6bb5ab92019-01-11 10:11:105771 max_framerate_ = kFps;
5772
5773 // Insert 3 seconds of video, verify number of drops with normal bitrate.
5774 fake_encoder_.SimulateOvershoot(1.0);
5775 int num_dropped = 0;
5776 for (int i = 0; i < kNumFramesInRun; ++i) {
5777 video_source_.IncomingCapturedFrame(
5778 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
5779 // Wait up to two frame durations for a frame to arrive.
5780 if (!TimedWaitForEncodedFrame(timestamp_ms, 2 * 1000 / kFps)) {
5781 ++num_dropped;
5782 }
5783 timestamp_ms += 1000 / kFps;
5784 }
5785
Erik Språnga8d48ab2019-02-08 13:17:405786 // Framerate should be measured to be near the expected target rate.
5787 EXPECT_NEAR(fake_encoder_.GetLastFramerate(), kFps, 1);
5788
5789 // Frame drops should be within 5% of expected 0%.
5790 EXPECT_NEAR(num_dropped, 0, 5 * kNumFramesInRun / 100);
Niels Möller6bb5ab92019-01-11 10:11:105791
5792 // Make encoder produce frames at double the expected bitrate during 3 seconds
5793 // of video, verify number of drops. Rate needs to be slightly changed in
5794 // order to force the rate to be reconfigured.
Erik Språng7ca375c2019-02-06 15:20:175795 double overshoot_factor = 2.0;
Erik Språng9d69cbe2020-10-22 15:44:425796 const RateControlSettings trials =
5797 RateControlSettings::ParseFromFieldTrials();
5798 if (trials.UseEncoderBitrateAdjuster()) {
Erik Språng7ca375c2019-02-06 15:20:175799 // With bitrate adjuster, when need to overshoot even more to trigger
Erik Språng9d69cbe2020-10-22 15:44:425800 // frame dropping since the adjuter will try to just lower the target
5801 // bitrate rather than drop frames. If network headroom can be used, it
5802 // doesn't push back as hard so we don't need quite as much overshoot.
5803 // These numbers are unfortunately a bit magical but there's not trivial
5804 // way to algebraically infer them.
5805 if (trials.BitrateAdjusterCanUseNetworkHeadroom()) {
5806 overshoot_factor = 2.4;
5807 } else {
5808 overshoot_factor = 4.0;
5809 }
Erik Språng7ca375c2019-02-06 15:20:175810 }
5811 fake_encoder_.SimulateOvershoot(overshoot_factor);
Henrik Boström381d1092020-05-12 16:49:075812 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:075813 DataRate::BitsPerSec(kTargetBitrateBps + 1000),
5814 DataRate::BitsPerSec(kTargetBitrateBps + 1000),
5815 DataRate::BitsPerSec(kTargetBitrateBps + 1000), 0, 0, 0);
Niels Möller6bb5ab92019-01-11 10:11:105816 num_dropped = 0;
5817 for (int i = 0; i < kNumFramesInRun; ++i) {
5818 video_source_.IncomingCapturedFrame(
5819 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
5820 // Wait up to two frame durations for a frame to arrive.
5821 if (!TimedWaitForEncodedFrame(timestamp_ms, 2 * 1000 / kFps)) {
5822 ++num_dropped;
5823 }
5824 timestamp_ms += 1000 / kFps;
5825 }
5826
Henrik Boström381d1092020-05-12 16:49:075827 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:075828 DataRate::BitsPerSec(kTargetBitrateBps),
5829 DataRate::BitsPerSec(kTargetBitrateBps),
5830 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Erik Språnga8d48ab2019-02-08 13:17:405831
5832 // Target framerate should be still be near the expected target, despite
5833 // the frame drops.
5834 EXPECT_NEAR(fake_encoder_.GetLastFramerate(), kFps, 1);
5835
5836 // Frame drops should be within 5% of expected 50%.
5837 EXPECT_NEAR(num_dropped, kNumFramesInRun / 2, 5 * kNumFramesInRun / 100);
Niels Möller6bb5ab92019-01-11 10:11:105838
5839 video_stream_encoder_->Stop();
5840}
5841
5842TEST_F(VideoStreamEncoderTest, ConfiguresCorrectFrameRate) {
5843 const int kFrameWidth = 320;
5844 const int kFrameHeight = 240;
5845 const int kActualInputFps = 24;
5846 const int kTargetBitrateBps = 120000;
5847
5848 ASSERT_GT(max_framerate_, kActualInputFps);
5849
Tomas Gunnarsson612445e2020-09-21 12:31:235850 int64_t timestamp_ms = CurrentTimeMs();
Niels Möller6bb5ab92019-01-11 10:11:105851 max_framerate_ = kActualInputFps;
Henrik Boström381d1092020-05-12 16:49:075852 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:075853 DataRate::BitsPerSec(kTargetBitrateBps),
5854 DataRate::BitsPerSec(kTargetBitrateBps),
5855 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Niels Möller6bb5ab92019-01-11 10:11:105856
5857 // Insert 3 seconds of video, with an input fps lower than configured max.
5858 for (int i = 0; i < kActualInputFps * 3; ++i) {
5859 video_source_.IncomingCapturedFrame(
5860 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
5861 // Wait up to two frame durations for a frame to arrive.
5862 WaitForEncodedFrame(timestamp_ms);
5863 timestamp_ms += 1000 / kActualInputFps;
5864 }
5865
5866 EXPECT_NEAR(kActualInputFps, fake_encoder_.GetLastFramerate(), 1);
5867
5868 video_stream_encoder_->Stop();
5869}
5870
Tomas Gunnarsson612445e2020-09-21 12:31:235871TEST_F(VideoStreamEncoderBlockedTest, AccumulatesUpdateRectOnDroppedFrames) {
Ilya Nikolaevskiy71aee3a2019-02-18 12:01:265872 VideoFrame::UpdateRect rect;
Henrik Boström381d1092020-05-12 16:49:075873 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:075874 DataRate::BitsPerSec(kTargetBitrateBps),
5875 DataRate::BitsPerSec(kTargetBitrateBps),
5876 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Ilya Nikolaevskiy71aee3a2019-02-18 12:01:265877
5878 fake_encoder_.BlockNextEncode();
5879 video_source_.IncomingCapturedFrame(
5880 CreateFrameWithUpdatedPixel(1, nullptr, 0));
5881 WaitForEncodedFrame(1);
5882 // On the very first frame full update should be forced.
5883 rect = fake_encoder_.GetLastUpdateRect();
5884 EXPECT_EQ(rect.offset_x, 0);
5885 EXPECT_EQ(rect.offset_y, 0);
5886 EXPECT_EQ(rect.height, codec_height_);
5887 EXPECT_EQ(rect.width, codec_width_);
5888 // Here, the encoder thread will be blocked in the TestEncoder waiting for a
5889 // call to ContinueEncode.
5890 video_source_.IncomingCapturedFrame(
5891 CreateFrameWithUpdatedPixel(2, nullptr, 1));
5892 ExpectDroppedFrame();
5893 video_source_.IncomingCapturedFrame(
5894 CreateFrameWithUpdatedPixel(3, nullptr, 10));
5895 ExpectDroppedFrame();
5896 fake_encoder_.ContinueEncode();
5897 WaitForEncodedFrame(3);
5898 // Updates to pixels 1 and 10 should be accumulated to one 10x1 rect.
5899 rect = fake_encoder_.GetLastUpdateRect();
5900 EXPECT_EQ(rect.offset_x, 1);
5901 EXPECT_EQ(rect.offset_y, 0);
5902 EXPECT_EQ(rect.width, 10);
5903 EXPECT_EQ(rect.height, 1);
5904
5905 video_source_.IncomingCapturedFrame(
5906 CreateFrameWithUpdatedPixel(4, nullptr, 0));
5907 WaitForEncodedFrame(4);
5908 // Previous frame was encoded, so no accumulation should happen.
5909 rect = fake_encoder_.GetLastUpdateRect();
5910 EXPECT_EQ(rect.offset_x, 0);
5911 EXPECT_EQ(rect.offset_y, 0);
5912 EXPECT_EQ(rect.width, 1);
5913 EXPECT_EQ(rect.height, 1);
5914
5915 video_stream_encoder_->Stop();
5916}
5917
Erik Språngd7329ca2019-02-21 20:19:535918TEST_F(VideoStreamEncoderTest, SetsFrameTypes) {
Henrik Boström381d1092020-05-12 16:49:075919 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:075920 DataRate::BitsPerSec(kTargetBitrateBps),
5921 DataRate::BitsPerSec(kTargetBitrateBps),
5922 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Erik Språngd7329ca2019-02-21 20:19:535923
5924 // First frame is always keyframe.
5925 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
5926 WaitForEncodedFrame(1);
Niels Möller8f7ce222019-03-21 14:43:585927 EXPECT_THAT(
5928 fake_encoder_.LastFrameTypes(),
Mirko Bonadei6a489f22019-04-09 13:11:125929 ::testing::ElementsAre(VideoFrameType{VideoFrameType::kVideoFrameKey}));
Erik Språngd7329ca2019-02-21 20:19:535930
5931 // Insert delta frame.
5932 video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
5933 WaitForEncodedFrame(2);
Niels Möller8f7ce222019-03-21 14:43:585934 EXPECT_THAT(
5935 fake_encoder_.LastFrameTypes(),
Mirko Bonadei6a489f22019-04-09 13:11:125936 ::testing::ElementsAre(VideoFrameType{VideoFrameType::kVideoFrameDelta}));
Erik Språngd7329ca2019-02-21 20:19:535937
5938 // Request next frame be a key-frame.
5939 video_stream_encoder_->SendKeyFrame();
5940 video_source_.IncomingCapturedFrame(CreateFrame(3, nullptr));
5941 WaitForEncodedFrame(3);
Niels Möller8f7ce222019-03-21 14:43:585942 EXPECT_THAT(
5943 fake_encoder_.LastFrameTypes(),
Mirko Bonadei6a489f22019-04-09 13:11:125944 ::testing::ElementsAre(VideoFrameType{VideoFrameType::kVideoFrameKey}));
Erik Språngd7329ca2019-02-21 20:19:535945
5946 video_stream_encoder_->Stop();
5947}
5948
5949TEST_F(VideoStreamEncoderTest, SetsFrameTypesSimulcast) {
5950 // Setup simulcast with three streams.
5951 ResetEncoder("VP8", 3, 1, 1, false);
Henrik Boström381d1092020-05-12 16:49:075952 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:075953 DataRate::BitsPerSec(kSimulcastTargetBitrateBps),
5954 DataRate::BitsPerSec(kSimulcastTargetBitrateBps),
5955 DataRate::BitsPerSec(kSimulcastTargetBitrateBps), 0, 0, 0);
Erik Språngd7329ca2019-02-21 20:19:535956 // Wait for all three layers before triggering event.
5957 sink_.SetNumExpectedLayers(3);
5958
5959 // First frame is always keyframe.
5960 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
5961 WaitForEncodedFrame(1);
5962 EXPECT_THAT(fake_encoder_.LastFrameTypes(),
Mirko Bonadei6a489f22019-04-09 13:11:125963 ::testing::ElementsAreArray({VideoFrameType::kVideoFrameKey,
5964 VideoFrameType::kVideoFrameKey,
5965 VideoFrameType::kVideoFrameKey}));
Erik Språngd7329ca2019-02-21 20:19:535966
5967 // Insert delta frame.
5968 video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
5969 WaitForEncodedFrame(2);
5970 EXPECT_THAT(fake_encoder_.LastFrameTypes(),
Mirko Bonadei6a489f22019-04-09 13:11:125971 ::testing::ElementsAreArray({VideoFrameType::kVideoFrameDelta,
5972 VideoFrameType::kVideoFrameDelta,
5973 VideoFrameType::kVideoFrameDelta}));
Erik Språngd7329ca2019-02-21 20:19:535974
5975 // Request next frame be a key-frame.
5976 // Only first stream is configured to produce key-frame.
5977 video_stream_encoder_->SendKeyFrame();
5978 video_source_.IncomingCapturedFrame(CreateFrame(3, nullptr));
5979 WaitForEncodedFrame(3);
Sergey Silkine62a08a2019-05-13 11:45:395980
5981 // TODO(webrtc:10615): Map keyframe request to spatial layer. Currently
5982 // keyframe request on any layer triggers keyframe on all layers.
Erik Språngd7329ca2019-02-21 20:19:535983 EXPECT_THAT(fake_encoder_.LastFrameTypes(),
Mirko Bonadei6a489f22019-04-09 13:11:125984 ::testing::ElementsAreArray({VideoFrameType::kVideoFrameKey,
Sergey Silkine62a08a2019-05-13 11:45:395985 VideoFrameType::kVideoFrameKey,
5986 VideoFrameType::kVideoFrameKey}));
Erik Språngd7329ca2019-02-21 20:19:535987
5988 video_stream_encoder_->Stop();
5989}
5990
5991TEST_F(VideoStreamEncoderTest, RequestKeyframeInternalSource) {
5992 // Configure internal source factory and setup test again.
5993 encoder_factory_.SetHasInternalSource(true);
5994 ResetEncoder("VP8", 1, 1, 1, false);
Henrik Boström381d1092020-05-12 16:49:075995 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:075996 DataRate::BitsPerSec(kTargetBitrateBps),
5997 DataRate::BitsPerSec(kTargetBitrateBps),
5998 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Erik Språngd7329ca2019-02-21 20:19:535999
6000 // Call encoder directly, simulating internal source where encoded frame
6001 // callback in VideoStreamEncoder is called despite no OnFrame().
6002 fake_encoder_.InjectFrame(CreateFrame(1, nullptr), true);
6003 EXPECT_TRUE(WaitForFrame(kDefaultTimeoutMs));
Niels Möller8f7ce222019-03-21 14:43:586004 EXPECT_THAT(
6005 fake_encoder_.LastFrameTypes(),
Mirko Bonadei6a489f22019-04-09 13:11:126006 ::testing::ElementsAre(VideoFrameType{VideoFrameType::kVideoFrameKey}));
Erik Språngd7329ca2019-02-21 20:19:536007
Niels Möller8f7ce222019-03-21 14:43:586008 const std::vector<VideoFrameType> kDeltaFrame = {
6009 VideoFrameType::kVideoFrameDelta};
Erik Språngd7329ca2019-02-21 20:19:536010 // Need to set timestamp manually since manually for injected frame.
6011 VideoFrame frame = CreateFrame(101, nullptr);
6012 frame.set_timestamp(101);
6013 fake_encoder_.InjectFrame(frame, false);
6014 EXPECT_TRUE(WaitForFrame(kDefaultTimeoutMs));
Niels Möller8f7ce222019-03-21 14:43:586015 EXPECT_THAT(
6016 fake_encoder_.LastFrameTypes(),
Mirko Bonadei6a489f22019-04-09 13:11:126017 ::testing::ElementsAre(VideoFrameType{VideoFrameType::kVideoFrameDelta}));
Erik Språngd7329ca2019-02-21 20:19:536018
6019 // Request key-frame. The forces a dummy frame down into the encoder.
6020 fake_encoder_.ExpectNullFrame();
6021 video_stream_encoder_->SendKeyFrame();
6022 EXPECT_TRUE(WaitForFrame(kDefaultTimeoutMs));
Niels Möller8f7ce222019-03-21 14:43:586023 EXPECT_THAT(
6024 fake_encoder_.LastFrameTypes(),
Mirko Bonadei6a489f22019-04-09 13:11:126025 ::testing::ElementsAre(VideoFrameType{VideoFrameType::kVideoFrameKey}));
Erik Språngd7329ca2019-02-21 20:19:536026
6027 video_stream_encoder_->Stop();
6028}
Erik Språngb7cb7b52019-02-26 14:52:336029
6030TEST_F(VideoStreamEncoderTest, AdjustsTimestampInternalSource) {
6031 // Configure internal source factory and setup test again.
6032 encoder_factory_.SetHasInternalSource(true);
6033 ResetEncoder("VP8", 1, 1, 1, false);
Henrik Boström381d1092020-05-12 16:49:076034 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:076035 DataRate::BitsPerSec(kTargetBitrateBps),
6036 DataRate::BitsPerSec(kTargetBitrateBps),
6037 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Erik Språngb7cb7b52019-02-26 14:52:336038
6039 int64_t timestamp = 1;
6040 EncodedImage image;
Niels Möller4d504c72019-06-18 13:56:566041 image.SetEncodedData(
6042 EncodedImageBuffer::Create(kTargetBitrateBps / kDefaultFramerate / 8));
Erik Språngb7cb7b52019-02-26 14:52:336043 image.capture_time_ms_ = ++timestamp;
6044 image.SetTimestamp(static_cast<uint32_t>(timestamp * 90));
6045 const int64_t kEncodeFinishDelayMs = 10;
6046 image.timing_.encode_start_ms = timestamp;
6047 image.timing_.encode_finish_ms = timestamp + kEncodeFinishDelayMs;
6048 fake_encoder_.InjectEncodedImage(image);
6049 // Wait for frame without incrementing clock.
6050 EXPECT_TRUE(sink_.WaitForFrame(kDefaultTimeoutMs));
6051 // Frame is captured kEncodeFinishDelayMs before it's encoded, so restored
6052 // capture timestamp should be kEncodeFinishDelayMs in the past.
6053 EXPECT_EQ(sink_.GetLastCaptureTimeMs(),
Tomas Gunnarsson612445e2020-09-21 12:31:236054 CurrentTimeMs() - kEncodeFinishDelayMs);
Erik Språngb7cb7b52019-02-26 14:52:336055
6056 video_stream_encoder_->Stop();
6057}
Mirta Dvornicic28f0eb22019-05-28 14:30:166058
6059TEST_F(VideoStreamEncoderTest, DoesNotRewriteH264BitstreamWithOptimalSps) {
Mirta Dvornicic97910da2020-07-14 13:29:236060 // SPS contains VUI with restrictions on the maximum number of reordered
6061 // pictures, there is no need to rewrite the bitstream to enable faster
6062 // decoding.
Mirta Dvornicic28f0eb22019-05-28 14:30:166063 ResetEncoder("H264", 1, 1, 1, false);
6064
Mirta Dvornicic97910da2020-07-14 13:29:236065 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
6066 DataRate::BitsPerSec(kTargetBitrateBps),
6067 DataRate::BitsPerSec(kTargetBitrateBps),
6068 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
6069 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
Mirta Dvornicic28f0eb22019-05-28 14:30:166070
Mirta Dvornicic97910da2020-07-14 13:29:236071 fake_encoder_.SetEncodedImageData(
6072 EncodedImageBuffer::Create(optimal_sps, sizeof(optimal_sps)));
Mirta Dvornicic28f0eb22019-05-28 14:30:166073
Mirta Dvornicic97910da2020-07-14 13:29:236074 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
6075 WaitForEncodedFrame(1);
Mirta Dvornicic28f0eb22019-05-28 14:30:166076
6077 EXPECT_THAT(sink_.GetLastEncodedImageData(),
6078 testing::ElementsAreArray(optimal_sps));
Mirta Dvornicic28f0eb22019-05-28 14:30:166079
6080 video_stream_encoder_->Stop();
6081}
6082
6083TEST_F(VideoStreamEncoderTest, RewritesH264BitstreamWithNonOptimalSps) {
Mirta Dvornicic97910da2020-07-14 13:29:236084 // SPS does not contain VUI, the bitstream is will be rewritten with added
6085 // VUI with restrictions on the maximum number of reordered pictures to
6086 // enable faster decoding.
Mirta Dvornicic28f0eb22019-05-28 14:30:166087 uint8_t original_sps[] = {0, 0, 0, 1, H264::NaluType::kSps,
6088 0x00, 0x00, 0x03, 0x03, 0xF4,
6089 0x05, 0x03, 0xC7, 0xC0};
Mirta Dvornicic28f0eb22019-05-28 14:30:166090 ResetEncoder("H264", 1, 1, 1, false);
6091
Mirta Dvornicic97910da2020-07-14 13:29:236092 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
6093 DataRate::BitsPerSec(kTargetBitrateBps),
6094 DataRate::BitsPerSec(kTargetBitrateBps),
6095 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
6096 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
Mirta Dvornicic28f0eb22019-05-28 14:30:166097
Mirta Dvornicic97910da2020-07-14 13:29:236098 fake_encoder_.SetEncodedImageData(
6099 EncodedImageBuffer::Create(original_sps, sizeof(original_sps)));
Mirta Dvornicic28f0eb22019-05-28 14:30:166100
Mirta Dvornicic97910da2020-07-14 13:29:236101 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
6102 WaitForEncodedFrame(1);
Mirta Dvornicic28f0eb22019-05-28 14:30:166103
6104 EXPECT_THAT(sink_.GetLastEncodedImageData(),
6105 testing::ElementsAreArray(optimal_sps));
Mirta Dvornicic28f0eb22019-05-28 14:30:166106
6107 video_stream_encoder_->Stop();
6108}
6109
Ilya Nikolaevskiyba96e2f2019-06-04 13:15:146110TEST_F(VideoStreamEncoderTest, CopiesVideoFrameMetadataAfterDownscale) {
6111 const int kFrameWidth = 1280;
6112 const int kFrameHeight = 720;
6113 const int kTargetBitrateBps = 300000; // To low for HD resolution.
6114
Henrik Boström381d1092020-05-12 16:49:076115 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:076116 DataRate::BitsPerSec(kTargetBitrateBps),
6117 DataRate::BitsPerSec(kTargetBitrateBps),
6118 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Ilya Nikolaevskiyba96e2f2019-06-04 13:15:146119 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
6120
6121 // Insert a first video frame. It should be dropped because of downscale in
6122 // resolution.
Tomas Gunnarsson612445e2020-09-21 12:31:236123 int64_t timestamp_ms = CurrentTimeMs();
Ilya Nikolaevskiyba96e2f2019-06-04 13:15:146124 VideoFrame frame = CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight);
6125 frame.set_rotation(kVideoRotation_270);
6126 video_source_.IncomingCapturedFrame(frame);
6127
6128 ExpectDroppedFrame();
6129
6130 // Second frame is downscaled.
Tomas Gunnarsson612445e2020-09-21 12:31:236131 timestamp_ms = CurrentTimeMs();
Ilya Nikolaevskiyba96e2f2019-06-04 13:15:146132 frame = CreateFrame(timestamp_ms, kFrameWidth / 2, kFrameHeight / 2);
6133 frame.set_rotation(kVideoRotation_90);
6134 video_source_.IncomingCapturedFrame(frame);
6135
6136 WaitForEncodedFrame(timestamp_ms);
6137 sink_.CheckLastFrameRotationMatches(kVideoRotation_90);
6138
6139 // Insert another frame, also downscaled.
Tomas Gunnarsson612445e2020-09-21 12:31:236140 timestamp_ms = CurrentTimeMs();
Ilya Nikolaevskiyba96e2f2019-06-04 13:15:146141 frame = CreateFrame(timestamp_ms, kFrameWidth / 2, kFrameHeight / 2);
6142 frame.set_rotation(kVideoRotation_180);
6143 video_source_.IncomingCapturedFrame(frame);
6144
6145 WaitForEncodedFrame(timestamp_ms);
6146 sink_.CheckLastFrameRotationMatches(kVideoRotation_180);
6147
6148 video_stream_encoder_->Stop();
6149}
6150
Erik Språng5056af02019-09-02 13:53:116151TEST_F(VideoStreamEncoderTest, BandwidthAllocationLowerBound) {
6152 const int kFrameWidth = 320;
6153 const int kFrameHeight = 180;
6154
6155 // Initial rate.
Henrik Boström381d1092020-05-12 16:49:076156 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:076157 /*target_bitrate=*/DataRate::KilobitsPerSec(300),
6158 /*stable_target_bitrate=*/DataRate::KilobitsPerSec(300),
6159 /*link_allocation=*/DataRate::KilobitsPerSec(300),
Erik Språng5056af02019-09-02 13:53:116160 /*fraction_lost=*/0,
Ying Wang9b881ab2020-02-07 13:29:326161 /*rtt_ms=*/0,
6162 /*cwnd_reduce_ratio=*/0);
Erik Språng5056af02019-09-02 13:53:116163
6164 // Insert a first video frame so that encoder gets configured.
Tomas Gunnarsson612445e2020-09-21 12:31:236165 int64_t timestamp_ms = CurrentTimeMs();
Erik Språng5056af02019-09-02 13:53:116166 VideoFrame frame = CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight);
6167 frame.set_rotation(kVideoRotation_270);
6168 video_source_.IncomingCapturedFrame(frame);
6169 WaitForEncodedFrame(timestamp_ms);
6170
6171 // Set a target rate below the minimum allowed by the codec settings.
6172 VideoCodec codec_config = fake_encoder_.codec_config();
Danil Chapovalovcad3e0e2020-02-17 17:46:076173 DataRate min_rate = DataRate::KilobitsPerSec(codec_config.minBitrate);
6174 DataRate target_rate = min_rate - DataRate::KilobitsPerSec(1);
Henrik Boström381d1092020-05-12 16:49:076175 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Erik Språng5056af02019-09-02 13:53:116176 /*target_bitrate=*/target_rate,
Florent Castellia8336d32019-09-09 11:36:556177 /*stable_target_bitrate=*/target_rate,
Erik Språng5056af02019-09-02 13:53:116178 /*link_allocation=*/target_rate,
6179 /*fraction_lost=*/0,
Ying Wang9b881ab2020-02-07 13:29:326180 /*rtt_ms=*/0,
6181 /*cwnd_reduce_ratio=*/0);
Erik Språng5056af02019-09-02 13:53:116182 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
6183
6184 // Target bitrate and bandwidth allocation should both be capped at min_rate.
6185 auto rate_settings = fake_encoder_.GetAndResetLastRateControlSettings();
6186 ASSERT_TRUE(rate_settings.has_value());
Danil Chapovalovcad3e0e2020-02-17 17:46:076187 DataRate allocation_sum =
6188 DataRate::BitsPerSec(rate_settings->bitrate.get_sum_bps());
Erik Språng5056af02019-09-02 13:53:116189 EXPECT_EQ(min_rate, allocation_sum);
6190 EXPECT_EQ(rate_settings->bandwidth_allocation, min_rate);
6191
6192 video_stream_encoder_->Stop();
6193}
6194
Rasmus Brandt5cad55b2019-12-19 08:47:116195TEST_F(VideoStreamEncoderTest, EncoderRatesPropagatedOnReconfigure) {
Henrik Boström381d1092020-05-12 16:49:076196 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:076197 DataRate::BitsPerSec(kTargetBitrateBps),
6198 DataRate::BitsPerSec(kTargetBitrateBps),
6199 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Evan Shrubsolee32ae4f2019-09-25 10:50:236200 // Capture a frame and wait for it to synchronize with the encoder thread.
Tomas Gunnarsson612445e2020-09-21 12:31:236201 int64_t timestamp_ms = CurrentTimeMs();
Evan Shrubsolee32ae4f2019-09-25 10:50:236202 video_source_.IncomingCapturedFrame(CreateFrame(timestamp_ms, nullptr));
6203 WaitForEncodedFrame(1);
6204
6205 auto prev_rate_settings = fake_encoder_.GetAndResetLastRateControlSettings();
6206 ASSERT_TRUE(prev_rate_settings.has_value());
6207 EXPECT_EQ(static_cast<int>(prev_rate_settings->framerate_fps),
6208 kDefaultFramerate);
6209
6210 // Send 1s of video to ensure the framerate is stable at kDefaultFramerate.
6211 for (int i = 0; i < 2 * kDefaultFramerate; i++) {
6212 timestamp_ms += 1000 / kDefaultFramerate;
6213 video_source_.IncomingCapturedFrame(CreateFrame(timestamp_ms, nullptr));
6214 WaitForEncodedFrame(timestamp_ms);
6215 }
6216 EXPECT_EQ(static_cast<int>(fake_encoder_.GetLastFramerate()),
6217 kDefaultFramerate);
6218 // Capture larger frame to trigger a reconfigure.
6219 codec_height_ *= 2;
6220 codec_width_ *= 2;
6221 timestamp_ms += 1000 / kDefaultFramerate;
6222 video_source_.IncomingCapturedFrame(CreateFrame(timestamp_ms, nullptr));
6223 WaitForEncodedFrame(timestamp_ms);
6224
6225 EXPECT_EQ(2, sink_.number_of_reconfigurations());
6226 auto current_rate_settings =
6227 fake_encoder_.GetAndResetLastRateControlSettings();
6228 // Ensure we have actually reconfigured twice
6229 // The rate settings should have been set again even though
6230 // they haven't changed.
6231 ASSERT_TRUE(current_rate_settings.has_value());
Evan Shrubsole7c079f62019-09-26 07:55:036232 EXPECT_EQ(prev_rate_settings, current_rate_settings);
Evan Shrubsolee32ae4f2019-09-25 10:50:236233
6234 video_stream_encoder_->Stop();
6235}
6236
philipeld9cc8c02019-09-16 12:53:406237struct MockEncoderSwitchRequestCallback : public EncoderSwitchRequestCallback {
Danil Chapovalov91fdc602020-05-14 17:17:516238 MOCK_METHOD(void, RequestEncoderFallback, (), (override));
6239 MOCK_METHOD(void, RequestEncoderSwitch, (const Config& conf), (override));
6240 MOCK_METHOD(void,
6241 RequestEncoderSwitch,
6242 (const webrtc::SdpVideoFormat& format),
6243 (override));
philipeld9cc8c02019-09-16 12:53:406244};
6245
6246TEST_F(VideoStreamEncoderTest, BitrateEncoderSwitch) {
6247 constexpr int kDontCare = 100;
6248
6249 StrictMock<MockEncoderSwitchRequestCallback> switch_callback;
6250 video_send_config_.encoder_settings.encoder_switch_request_callback =
6251 &switch_callback;
6252 VideoEncoderConfig encoder_config = video_encoder_config_.Copy();
6253 encoder_config.codec_type = kVideoCodecVP8;
6254 webrtc::test::ScopedFieldTrials field_trial(
6255 "WebRTC-NetworkCondition-EncoderSwitch/"
6256 "codec_thresholds:VP8;100;-1|H264;-1;30000,"
6257 "to_codec:AV1,to_param:ping,to_value:pong,window:2.0/");
6258
6259 // Reset encoder for new configuration to take effect.
6260 ConfigureEncoder(std::move(encoder_config));
6261
6262 // Send one frame to trigger ReconfigureEncoder.
6263 video_source_.IncomingCapturedFrame(
6264 CreateFrame(kDontCare, kDontCare, kDontCare));
6265
6266 using Config = EncoderSwitchRequestCallback::Config;
philipel9b058032020-02-10 10:30:006267 EXPECT_CALL(switch_callback, RequestEncoderSwitch(Matcher<const Config&>(
6268 AllOf(Field(&Config::codec_name, "AV1"),
philipeld9cc8c02019-09-16 12:53:406269 Field(&Config::param, "ping"),
philipel9b058032020-02-10 10:30:006270 Field(&Config::value, "pong")))));
philipeld9cc8c02019-09-16 12:53:406271
Henrik Boström381d1092020-05-12 16:49:076272 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:076273 /*target_bitrate=*/DataRate::KilobitsPerSec(50),
6274 /*stable_target_bitrate=*/DataRate::KilobitsPerSec(kDontCare),
6275 /*link_allocation=*/DataRate::KilobitsPerSec(kDontCare),
philipeld9cc8c02019-09-16 12:53:406276 /*fraction_lost=*/0,
Ying Wang9b881ab2020-02-07 13:29:326277 /*rtt_ms=*/0,
6278 /*cwnd_reduce_ratio=*/0);
Tomas Gunnarssond41c2a62020-09-21 13:56:426279 AdvanceTime(TimeDelta::Millis(0));
philipeld9cc8c02019-09-16 12:53:406280
6281 video_stream_encoder_->Stop();
6282}
6283
Mirta Dvornicic5ed40cf2020-02-21 15:35:516284TEST_F(VideoStreamEncoderTest, VideoSuspendedNoEncoderSwitch) {
6285 constexpr int kDontCare = 100;
6286
6287 StrictMock<MockEncoderSwitchRequestCallback> switch_callback;
6288 video_send_config_.encoder_settings.encoder_switch_request_callback =
6289 &switch_callback;
6290 VideoEncoderConfig encoder_config = video_encoder_config_.Copy();
6291 encoder_config.codec_type = kVideoCodecVP8;
6292 webrtc::test::ScopedFieldTrials field_trial(
6293 "WebRTC-NetworkCondition-EncoderSwitch/"
6294 "codec_thresholds:VP8;100;-1|H264;-1;30000,"
6295 "to_codec:AV1,to_param:ping,to_value:pong,window:2.0/");
6296
6297 // Reset encoder for new configuration to take effect.
6298 ConfigureEncoder(std::move(encoder_config));
6299
6300 // Send one frame to trigger ReconfigureEncoder.
6301 video_source_.IncomingCapturedFrame(
6302 CreateFrame(kDontCare, kDontCare, kDontCare));
6303
6304 using Config = EncoderSwitchRequestCallback::Config;
6305 EXPECT_CALL(switch_callback, RequestEncoderSwitch(Matcher<const Config&>(_)))
6306 .Times(0);
6307
Henrik Boström381d1092020-05-12 16:49:076308 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Mirta Dvornicic5ed40cf2020-02-21 15:35:516309 /*target_bitrate=*/DataRate::KilobitsPerSec(0),
6310 /*stable_target_bitrate=*/DataRate::KilobitsPerSec(0),
6311 /*link_allocation=*/DataRate::KilobitsPerSec(kDontCare),
6312 /*fraction_lost=*/0,
6313 /*rtt_ms=*/0,
6314 /*cwnd_reduce_ratio=*/0);
6315
6316 video_stream_encoder_->Stop();
6317}
6318
philipeld9cc8c02019-09-16 12:53:406319TEST_F(VideoStreamEncoderTest, ResolutionEncoderSwitch) {
6320 constexpr int kSufficientBitrateToNotDrop = 1000;
6321 constexpr int kHighRes = 500;
6322 constexpr int kLowRes = 100;
6323
6324 StrictMock<MockEncoderSwitchRequestCallback> switch_callback;
6325 video_send_config_.encoder_settings.encoder_switch_request_callback =
6326 &switch_callback;
6327 webrtc::test::ScopedFieldTrials field_trial(
6328 "WebRTC-NetworkCondition-EncoderSwitch/"
6329 "codec_thresholds:VP8;120;-1|H264;-1;30000,"
6330 "to_codec:AV1,to_param:ping,to_value:pong,window:2.0/");
6331 VideoEncoderConfig encoder_config = video_encoder_config_.Copy();
6332 encoder_config.codec_type = kVideoCodecH264;
6333
6334 // Reset encoder for new configuration to take effect.
6335 ConfigureEncoder(std::move(encoder_config));
6336
6337 // The VideoStreamEncoder needs some bitrate before it can start encoding,
6338 // setting some bitrate so that subsequent calls to WaitForEncodedFrame does
6339 // not fail.
Henrik Boström381d1092020-05-12 16:49:076340 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:076341 /*target_bitrate=*/DataRate::KilobitsPerSec(kSufficientBitrateToNotDrop),
6342 /*stable_target_bitrate=*/
6343 DataRate::KilobitsPerSec(kSufficientBitrateToNotDrop),
6344 /*link_allocation=*/DataRate::KilobitsPerSec(kSufficientBitrateToNotDrop),
philipeld9cc8c02019-09-16 12:53:406345 /*fraction_lost=*/0,
Ying Wang9b881ab2020-02-07 13:29:326346 /*rtt_ms=*/0,
6347 /*cwnd_reduce_ratio=*/0);
philipeld9cc8c02019-09-16 12:53:406348
6349 // Send one frame to trigger ReconfigureEncoder.
6350 video_source_.IncomingCapturedFrame(CreateFrame(1, kHighRes, kHighRes));
6351 WaitForEncodedFrame(1);
6352
6353 using Config = EncoderSwitchRequestCallback::Config;
philipel9b058032020-02-10 10:30:006354 EXPECT_CALL(switch_callback, RequestEncoderSwitch(Matcher<const Config&>(
6355 AllOf(Field(&Config::codec_name, "AV1"),
philipeld9cc8c02019-09-16 12:53:406356 Field(&Config::param, "ping"),
philipel9b058032020-02-10 10:30:006357 Field(&Config::value, "pong")))));
philipeld9cc8c02019-09-16 12:53:406358
6359 video_source_.IncomingCapturedFrame(CreateFrame(2, kLowRes, kLowRes));
6360 WaitForEncodedFrame(2);
6361
6362 video_stream_encoder_->Stop();
6363}
6364
philipel9b058032020-02-10 10:30:006365TEST_F(VideoStreamEncoderTest, EncoderSelectorCurrentEncoderIsSignaled) {
6366 constexpr int kDontCare = 100;
6367 StrictMock<MockEncoderSelector> encoder_selector;
6368 auto encoder_factory = std::make_unique<test::VideoEncoderProxyFactory>(
6369 &fake_encoder_, &encoder_selector);
6370 video_send_config_.encoder_settings.encoder_factory = encoder_factory.get();
6371
6372 // Reset encoder for new configuration to take effect.
6373 ConfigureEncoder(video_encoder_config_.Copy());
6374
6375 EXPECT_CALL(encoder_selector, OnCurrentEncoder(_));
6376
6377 video_source_.IncomingCapturedFrame(
6378 CreateFrame(kDontCare, kDontCare, kDontCare));
6379 video_stream_encoder_->Stop();
6380
6381 // The encoders produces by the VideoEncoderProxyFactory have a pointer back
6382 // to it's factory, so in order for the encoder instance in the
6383 // |video_stream_encoder_| to be destroyed before the |encoder_factory| we
6384 // reset the |video_stream_encoder_| here.
6385 video_stream_encoder_.reset();
6386}
6387
6388TEST_F(VideoStreamEncoderTest, EncoderSelectorBitrateSwitch) {
6389 constexpr int kDontCare = 100;
6390
6391 NiceMock<MockEncoderSelector> encoder_selector;
6392 StrictMock<MockEncoderSwitchRequestCallback> switch_callback;
6393 video_send_config_.encoder_settings.encoder_switch_request_callback =
6394 &switch_callback;
6395 auto encoder_factory = std::make_unique<test::VideoEncoderProxyFactory>(
6396 &fake_encoder_, &encoder_selector);
6397 video_send_config_.encoder_settings.encoder_factory = encoder_factory.get();
6398
6399 // Reset encoder for new configuration to take effect.
6400 ConfigureEncoder(video_encoder_config_.Copy());
6401
Mirta Dvornicic4f34d782020-02-26 12:01:196402 ON_CALL(encoder_selector, OnAvailableBitrate(_))
philipel9b058032020-02-10 10:30:006403 .WillByDefault(Return(SdpVideoFormat("AV1")));
6404 EXPECT_CALL(switch_callback,
6405 RequestEncoderSwitch(Matcher<const SdpVideoFormat&>(
6406 Field(&SdpVideoFormat::name, "AV1"))));
6407
Henrik Boström381d1092020-05-12 16:49:076408 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:076409 /*target_bitrate=*/DataRate::KilobitsPerSec(50),
6410 /*stable_target_bitrate=*/DataRate::KilobitsPerSec(kDontCare),
6411 /*link_allocation=*/DataRate::KilobitsPerSec(kDontCare),
philipel9b058032020-02-10 10:30:006412 /*fraction_lost=*/0,
6413 /*rtt_ms=*/0,
6414 /*cwnd_reduce_ratio=*/0);
Tomas Gunnarssond41c2a62020-09-21 13:56:426415 AdvanceTime(TimeDelta::Millis(0));
philipel9b058032020-02-10 10:30:006416
6417 video_stream_encoder_->Stop();
6418}
6419
6420TEST_F(VideoStreamEncoderTest, EncoderSelectorBrokenEncoderSwitch) {
6421 constexpr int kSufficientBitrateToNotDrop = 1000;
6422 constexpr int kDontCare = 100;
6423
6424 NiceMock<MockVideoEncoder> video_encoder;
6425 NiceMock<MockEncoderSelector> encoder_selector;
6426 StrictMock<MockEncoderSwitchRequestCallback> switch_callback;
6427 video_send_config_.encoder_settings.encoder_switch_request_callback =
6428 &switch_callback;
6429 auto encoder_factory = std::make_unique<test::VideoEncoderProxyFactory>(
6430 &video_encoder, &encoder_selector);
6431 video_send_config_.encoder_settings.encoder_factory = encoder_factory.get();
6432
6433 // Reset encoder for new configuration to take effect.
6434 ConfigureEncoder(video_encoder_config_.Copy());
6435
6436 // The VideoStreamEncoder needs some bitrate before it can start encoding,
6437 // setting some bitrate so that subsequent calls to WaitForEncodedFrame does
6438 // not fail.
Henrik Boström381d1092020-05-12 16:49:076439 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:076440 /*target_bitrate=*/DataRate::KilobitsPerSec(kSufficientBitrateToNotDrop),
6441 /*stable_target_bitrate=*/
6442 DataRate::KilobitsPerSec(kSufficientBitrateToNotDrop),
6443 /*link_allocation=*/DataRate::KilobitsPerSec(kSufficientBitrateToNotDrop),
philipel9b058032020-02-10 10:30:006444 /*fraction_lost=*/0,
6445 /*rtt_ms=*/0,
6446 /*cwnd_reduce_ratio=*/0);
6447
6448 ON_CALL(video_encoder, Encode(_, _))
6449 .WillByDefault(Return(WEBRTC_VIDEO_CODEC_ENCODER_FAILURE));
6450 ON_CALL(encoder_selector, OnEncoderBroken())
6451 .WillByDefault(Return(SdpVideoFormat("AV2")));
6452
6453 rtc::Event encode_attempted;
6454 EXPECT_CALL(switch_callback,
6455 RequestEncoderSwitch(Matcher<const SdpVideoFormat&>(_)))
6456 .WillOnce([&encode_attempted](const SdpVideoFormat& format) {
6457 EXPECT_EQ(format.name, "AV2");
6458 encode_attempted.Set();
6459 });
6460
6461 video_source_.IncomingCapturedFrame(CreateFrame(1, kDontCare, kDontCare));
6462 encode_attempted.Wait(3000);
6463
Tomas Gunnarssond41c2a62020-09-21 13:56:426464 AdvanceTime(TimeDelta::Millis(0));
6465
philipel9b058032020-02-10 10:30:006466 video_stream_encoder_->Stop();
6467
6468 // The encoders produces by the VideoEncoderProxyFactory have a pointer back
6469 // to it's factory, so in order for the encoder instance in the
6470 // |video_stream_encoder_| to be destroyed before the |encoder_factory| we
6471 // reset the |video_stream_encoder_| here.
6472 video_stream_encoder_.reset();
6473}
6474
Evan Shrubsole7c079f62019-09-26 07:55:036475TEST_F(VideoStreamEncoderTest,
Rasmus Brandt5cad55b2019-12-19 08:47:116476 AllocationPropagatedToEncoderWhenTargetRateChanged) {
Evan Shrubsole7c079f62019-09-26 07:55:036477 const int kFrameWidth = 320;
6478 const int kFrameHeight = 180;
6479
6480 // Set initial rate.
Danil Chapovalovcad3e0e2020-02-17 17:46:076481 auto rate = DataRate::KilobitsPerSec(100);
Henrik Boström381d1092020-05-12 16:49:076482 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Evan Shrubsole7c079f62019-09-26 07:55:036483 /*target_bitrate=*/rate,
6484 /*stable_target_bitrate=*/rate,
6485 /*link_allocation=*/rate,
6486 /*fraction_lost=*/0,
Ying Wang9b881ab2020-02-07 13:29:326487 /*rtt_ms=*/0,
6488 /*cwnd_reduce_ratio=*/0);
Evan Shrubsole7c079f62019-09-26 07:55:036489
6490 // Insert a first video frame so that encoder gets configured.
Tomas Gunnarsson612445e2020-09-21 12:31:236491 int64_t timestamp_ms = CurrentTimeMs();
Evan Shrubsole7c079f62019-09-26 07:55:036492 VideoFrame frame = CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight);
6493 frame.set_rotation(kVideoRotation_270);
6494 video_source_.IncomingCapturedFrame(frame);
6495 WaitForEncodedFrame(timestamp_ms);
6496 EXPECT_EQ(1, fake_encoder_.GetNumSetRates());
6497
6498 // Change of target bitrate propagates to the encoder.
Danil Chapovalovcad3e0e2020-02-17 17:46:076499 auto new_stable_rate = rate - DataRate::KilobitsPerSec(5);
Henrik Boström381d1092020-05-12 16:49:076500 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Evan Shrubsole7c079f62019-09-26 07:55:036501 /*target_bitrate=*/new_stable_rate,
6502 /*stable_target_bitrate=*/new_stable_rate,
6503 /*link_allocation=*/rate,
6504 /*fraction_lost=*/0,
Ying Wang9b881ab2020-02-07 13:29:326505 /*rtt_ms=*/0,
6506 /*cwnd_reduce_ratio=*/0);
Evan Shrubsole7c079f62019-09-26 07:55:036507 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
6508 EXPECT_EQ(2, fake_encoder_.GetNumSetRates());
6509 video_stream_encoder_->Stop();
6510}
6511
6512TEST_F(VideoStreamEncoderTest,
Rasmus Brandt5cad55b2019-12-19 08:47:116513 AllocationNotPropagatedToEncoderWhenTargetRateUnchanged) {
Evan Shrubsole7c079f62019-09-26 07:55:036514 const int kFrameWidth = 320;
6515 const int kFrameHeight = 180;
6516
6517 // Set initial rate.
Danil Chapovalovcad3e0e2020-02-17 17:46:076518 auto rate = DataRate::KilobitsPerSec(100);
Henrik Boström381d1092020-05-12 16:49:076519 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Evan Shrubsole7c079f62019-09-26 07:55:036520 /*target_bitrate=*/rate,
6521 /*stable_target_bitrate=*/rate,
6522 /*link_allocation=*/rate,
6523 /*fraction_lost=*/0,
Ying Wang9b881ab2020-02-07 13:29:326524 /*rtt_ms=*/0,
6525 /*cwnd_reduce_ratio=*/0);
Evan Shrubsole7c079f62019-09-26 07:55:036526
6527 // Insert a first video frame so that encoder gets configured.
Tomas Gunnarsson612445e2020-09-21 12:31:236528 int64_t timestamp_ms = CurrentTimeMs();
Evan Shrubsole7c079f62019-09-26 07:55:036529 VideoFrame frame = CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight);
6530 frame.set_rotation(kVideoRotation_270);
6531 video_source_.IncomingCapturedFrame(frame);
6532 WaitForEncodedFrame(timestamp_ms);
6533 EXPECT_EQ(1, fake_encoder_.GetNumSetRates());
6534
6535 // Set a higher target rate without changing the link_allocation. Should not
6536 // reset encoder's rate.
Danil Chapovalovcad3e0e2020-02-17 17:46:076537 auto new_stable_rate = rate - DataRate::KilobitsPerSec(5);
Henrik Boström381d1092020-05-12 16:49:076538 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Evan Shrubsole7c079f62019-09-26 07:55:036539 /*target_bitrate=*/rate,
6540 /*stable_target_bitrate=*/new_stable_rate,
6541 /*link_allocation=*/rate,
6542 /*fraction_lost=*/0,
Ying Wang9b881ab2020-02-07 13:29:326543 /*rtt_ms=*/0,
6544 /*cwnd_reduce_ratio=*/0);
Evan Shrubsole7c079f62019-09-26 07:55:036545 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
6546 EXPECT_EQ(1, fake_encoder_.GetNumSetRates());
6547 video_stream_encoder_->Stop();
6548}
6549
Ilya Nikolaevskiy648b9d72019-12-03 15:54:176550TEST_F(VideoStreamEncoderTest, AutomaticAnimationDetection) {
6551 test::ScopedFieldTrials field_trials(
6552 "WebRTC-AutomaticAnimationDetectionScreenshare/"
6553 "enabled:true,min_fps:20,min_duration_ms:1000,min_area_ratio:0.8/");
6554 const int kFramerateFps = 30;
6555 const int kWidth = 1920;
6556 const int kHeight = 1080;
6557 const int kNumFrames = 2 * kFramerateFps; // >1 seconds of frames.
6558 // Works on screenshare mode.
6559 ResetEncoder("VP8", 1, 1, 1, /*screenshare*/ true);
6560 // We rely on the automatic resolution adaptation, but we handle framerate
6561 // adaptation manually by mocking the stats proxy.
6562 video_source_.set_adaptation_enabled(true);
6563
6564 // BALANCED degradation preference is required for this feature.
Henrik Boström381d1092020-05-12 16:49:076565 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 17:46:076566 DataRate::BitsPerSec(kTargetBitrateBps),
6567 DataRate::BitsPerSec(kTargetBitrateBps),
6568 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Ilya Nikolaevskiy648b9d72019-12-03 15:54:176569 video_stream_encoder_->SetSource(&video_source_,
6570 webrtc::DegradationPreference::BALANCED);
Evan Shrubsole5cd7eb82020-05-25 12:08:396571 EXPECT_THAT(video_source_.sink_wants(), UnlimitedSinkWants());
Ilya Nikolaevskiy648b9d72019-12-03 15:54:176572
6573 VideoFrame frame = CreateFrame(1, kWidth, kHeight);
6574 frame.set_update_rect(VideoFrame::UpdateRect{0, 0, kWidth, kHeight});
6575
6576 // Pass enough frames with the full update to trigger animation detection.
6577 for (int i = 0; i < kNumFrames; ++i) {
Tomas Gunnarsson612445e2020-09-21 12:31:236578 int64_t timestamp_ms = CurrentTimeMs();
Ilya Nikolaevskiy648b9d72019-12-03 15:54:176579 frame.set_ntp_time_ms(timestamp_ms);
6580 frame.set_timestamp_us(timestamp_ms * 1000);
6581 video_source_.IncomingCapturedFrame(frame);
6582 WaitForEncodedFrame(timestamp_ms);
6583 }
6584
6585 // Resolution should be limited.
6586 rtc::VideoSinkWants expected;
6587 expected.max_framerate_fps = kFramerateFps;
6588 expected.max_pixel_count = 1280 * 720 + 1;
Evan Shrubsole5fd40602020-05-25 14:19:546589 EXPECT_THAT(video_source_.sink_wants(), FpsEqResolutionLt(expected));
Ilya Nikolaevskiy648b9d72019-12-03 15:54:176590
6591 // Pass one frame with no known update.
6592 // Resolution cap should be removed immediately.
Tomas Gunnarsson612445e2020-09-21 12:31:236593 int64_t timestamp_ms = CurrentTimeMs();
Ilya Nikolaevskiy648b9d72019-12-03 15:54:176594 frame.set_ntp_time_ms(timestamp_ms);
6595 frame.set_timestamp_us(timestamp_ms * 1000);
6596 frame.clear_update_rect();
6597
6598 video_source_.IncomingCapturedFrame(frame);
6599 WaitForEncodedFrame(timestamp_ms);
6600
6601 // Resolution should be unlimited now.
Evan Shrubsole5cd7eb82020-05-25 12:08:396602 EXPECT_THAT(video_source_.sink_wants(),
6603 FpsMatchesResolutionMax(Eq(kFramerateFps)));
Ilya Nikolaevskiy648b9d72019-12-03 15:54:176604
6605 video_stream_encoder_->Stop();
6606}
6607
Ilya Nikolaevskiy09eb6e22020-06-05 10:36:326608TEST_F(VideoStreamEncoderTest, ConfiguresVp9SvcAtOddResolutions) {
6609 const int kWidth = 720; // 540p adapted down.
6610 const int kHeight = 405;
6611 const int kNumFrames = 3;
6612 // Works on screenshare mode.
6613 ResetEncoder("VP9", /*num_streams=*/1, /*num_temporal_layers=*/1,
6614 /*num_spatial_layers=*/2, /*screenshare=*/true);
6615
6616 video_source_.set_adaptation_enabled(true);
6617
6618 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
6619 DataRate::BitsPerSec(kTargetBitrateBps),
6620 DataRate::BitsPerSec(kTargetBitrateBps),
6621 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
6622
6623 VideoFrame frame = CreateFrame(1, kWidth, kHeight);
6624
6625 // Pass enough frames with the full update to trigger animation detection.
6626 for (int i = 0; i < kNumFrames; ++i) {
Tomas Gunnarsson612445e2020-09-21 12:31:236627 int64_t timestamp_ms = CurrentTimeMs();
Ilya Nikolaevskiy09eb6e22020-06-05 10:36:326628 frame.set_ntp_time_ms(timestamp_ms);
6629 frame.set_timestamp_us(timestamp_ms * 1000);
6630 video_source_.IncomingCapturedFrame(frame);
6631 WaitForEncodedFrame(timestamp_ms);
6632 }
6633
6634 video_stream_encoder_->Stop();
6635}
6636
Yun Zhang1e4d4fd2020-09-30 07:22:466637TEST_F(VideoStreamEncoderTest, EncoderResetAccordingToParameterChange) {
6638 const float downscale_factors[] = {4.0, 2.0, 1.0};
6639 const int number_layers =
6640 sizeof(downscale_factors) / sizeof(downscale_factors[0]);
6641 VideoEncoderConfig config;
6642 test::FillEncoderConfiguration(kVideoCodecVP8, number_layers, &config);
6643 for (int i = 0; i < number_layers; ++i) {
6644 config.simulcast_layers[i].scale_resolution_down_by = downscale_factors[i];
6645 config.simulcast_layers[i].active = true;
6646 }
6647 config.video_stream_factory =
6648 new rtc::RefCountedObject<cricket::EncoderStreamFactory>(
6649 "VP8", /*max qp*/ 56, /*screencast*/ false,
6650 /*screenshare enabled*/ false);
6651 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
6652 DataRate::BitsPerSec(kSimulcastTargetBitrateBps),
6653 DataRate::BitsPerSec(kSimulcastTargetBitrateBps),
6654 DataRate::BitsPerSec(kSimulcastTargetBitrateBps), 0, 0, 0);
6655
6656 // First initialization.
6657 // Encoder should be initialized. Next frame should be key frame.
6658 video_stream_encoder_->ConfigureEncoder(config.Copy(), kMaxPayloadLength);
6659 sink_.SetNumExpectedLayers(number_layers);
6660 int64_t timestamp_ms = kFrameIntervalMs;
6661 video_source_.IncomingCapturedFrame(CreateFrame(timestamp_ms, 1280, 720));
6662 WaitForEncodedFrame(timestamp_ms);
6663 EXPECT_EQ(1, fake_encoder_.GetNumEncoderInitializations());
6664 EXPECT_THAT(fake_encoder_.LastFrameTypes(),
6665 ::testing::ElementsAreArray({VideoFrameType::kVideoFrameKey,
6666 VideoFrameType::kVideoFrameKey,
6667 VideoFrameType::kVideoFrameKey}));
6668
6669 // Disable top layer.
6670 // Encoder shouldn't be re-initialized. Next frame should be delta frame.
6671 config.simulcast_layers[number_layers - 1].active = false;
6672 video_stream_encoder_->ConfigureEncoder(config.Copy(), kMaxPayloadLength);
6673 sink_.SetNumExpectedLayers(number_layers - 1);
6674 timestamp_ms += kFrameIntervalMs;
6675 video_source_.IncomingCapturedFrame(CreateFrame(timestamp_ms, 1280, 720));
6676 WaitForEncodedFrame(timestamp_ms);
6677 EXPECT_EQ(1, fake_encoder_.GetNumEncoderInitializations());
6678 EXPECT_THAT(fake_encoder_.LastFrameTypes(),
6679 ::testing::ElementsAreArray({VideoFrameType::kVideoFrameDelta,
6680 VideoFrameType::kVideoFrameDelta,
6681 VideoFrameType::kVideoFrameDelta}));
6682
6683 // Re-enable top layer.
6684 // Encoder should be re-initialized. Next frame should be key frame.
6685 config.simulcast_layers[number_layers - 1].active = true;
6686 video_stream_encoder_->ConfigureEncoder(config.Copy(), kMaxPayloadLength);
6687 sink_.SetNumExpectedLayers(number_layers);
6688 timestamp_ms += kFrameIntervalMs;
6689 video_source_.IncomingCapturedFrame(CreateFrame(timestamp_ms, 1280, 720));
6690 WaitForEncodedFrame(timestamp_ms);
6691 EXPECT_EQ(2, fake_encoder_.GetNumEncoderInitializations());
6692 EXPECT_THAT(fake_encoder_.LastFrameTypes(),
6693 ::testing::ElementsAreArray({VideoFrameType::kVideoFrameKey,
6694 VideoFrameType::kVideoFrameKey,
6695 VideoFrameType::kVideoFrameKey}));
6696
6697 // Top layer max rate change.
6698 // Encoder shouldn't be re-initialized. Next frame should be delta frame.
6699 config.simulcast_layers[number_layers - 1].max_bitrate_bps -= 100;
6700 video_stream_encoder_->ConfigureEncoder(config.Copy(), kMaxPayloadLength);
6701 sink_.SetNumExpectedLayers(number_layers);
6702 timestamp_ms += kFrameIntervalMs;
6703 video_source_.IncomingCapturedFrame(CreateFrame(timestamp_ms, 1280, 720));
6704 WaitForEncodedFrame(timestamp_ms);
6705 EXPECT_EQ(2, fake_encoder_.GetNumEncoderInitializations());
6706 EXPECT_THAT(fake_encoder_.LastFrameTypes(),
6707 ::testing::ElementsAreArray({VideoFrameType::kVideoFrameDelta,
6708 VideoFrameType::kVideoFrameDelta,
6709 VideoFrameType::kVideoFrameDelta}));
6710
6711 // Top layer resolution change.
6712 // Encoder should be re-initialized. Next frame should be key frame.
6713 config.simulcast_layers[number_layers - 1].scale_resolution_down_by += 0.1;
6714 video_stream_encoder_->ConfigureEncoder(config.Copy(), kMaxPayloadLength);
6715 sink_.SetNumExpectedLayers(number_layers);
6716 timestamp_ms += kFrameIntervalMs;
6717 video_source_.IncomingCapturedFrame(CreateFrame(timestamp_ms, 1280, 720));
6718 WaitForEncodedFrame(timestamp_ms);
6719 EXPECT_EQ(3, fake_encoder_.GetNumEncoderInitializations());
6720 EXPECT_THAT(fake_encoder_.LastFrameTypes(),
6721 ::testing::ElementsAreArray({VideoFrameType::kVideoFrameKey,
6722 VideoFrameType::kVideoFrameKey,
6723 VideoFrameType::kVideoFrameKey}));
6724 video_stream_encoder_->Stop();
6725}
6726
perkj26091b12016-09-01 08:17:406727} // namespace webrtc