blob: 0d34c0108015048691740bd987e445bb1c14cb87 [file] [log] [blame]
perkj26091b12016-09-01 01:17:40 -07001/*
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 10:30:31 +020011#include "video/video_stream_encoder.h"
12
sprangfe627f32017-03-29 08:24:59 -070013#include <algorithm>
perkj803d97f2016-11-01 11:45:46 -070014#include <limits>
Danil Chapovalovd3ba2362019-04-10 17:01:23 +020015#include <memory>
Per512ecb32016-09-23 15:52:06 +020016#include <utility>
17
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +020018#include "absl/memory/memory.h"
Danil Chapovalovd3ba2362019-04-10 17:01:23 +020019#include "api/task_queue/default_task_queue_factory.h"
Elad Alon45befc52019-07-02 11:20:09 +020020#include "api/test/mock_fec_controller_override.h"
philipel9b058032020-02-10 11:30:00 +010021#include "api/test/mock_video_encoder.h"
Jiawei Ouc2ebe212018-11-08 10:02:56 -080022#include "api/video/builtin_video_bitrate_allocator_factory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020023#include "api/video/i420_buffer.h"
Evan Shrubsole895556e2020-10-05 09:15:13 +020024#include "api/video/nv12_buffer.h"
Evan Shrubsolece0a11d2020-04-16 11:36:55 +020025#include "api/video/video_adaptation_reason.h"
Erik Språngf93eda12019-01-16 17:10:57 +010026#include "api/video/video_bitrate_allocation.h"
Elad Alon370f93a2019-06-11 14:57:57 +020027#include "api/video_codecs/video_encoder.h"
Erik Språng4529fbc2018-10-12 10:30:31 +020028#include "api/video_codecs/vp8_temporal_layers.h"
Elad Aloncde8ab22019-03-20 11:56:20 +010029#include "api/video_codecs/vp8_temporal_layers_factory.h"
Henrik Boström0f0aa9c2020-06-02 13:02:36 +020030#include "call/adaptation/test/fake_adaptation_constraint.h"
Evan Shrubsoleaa6fbc12020-02-25 16:26:01 +010031#include "call/adaptation/test/fake_resource.h"
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +020032#include "common_video/h264/h264_common.h"
Noah Richards51db4212019-06-12 06:59:12 -070033#include "common_video/include/video_frame_buffer.h"
Steve Anton10542f22019-01-11 09:11:00 -080034#include "media/base/video_adapter.h"
Åsa Perssonc5a74ff2020-09-20 17:50:00 +020035#include "media/engine/webrtc_video_engine.h"
Sergey Silkin86684962018-03-28 19:32:37 +020036#include "modules/video_coding/codecs/vp9/include/vp9_globals.h"
Henrik Boström91aa7322020-04-28 12:24:33 +020037#include "modules/video_coding/utility/quality_scaler.h"
Åsa Perssonc29cb2c2019-03-25 12:06:59 +010038#include "modules/video_coding/utility/simulcast_rate_allocator.h"
Tomas Gunnarsson612445e2020-09-21 14:31:23 +020039#include "rtc_base/event.h"
Henrik Boström2671dac2020-05-19 16:29:09 +020040#include "rtc_base/gunit.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020041#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 09:11:00 -080042#include "rtc_base/ref_counted_object.h"
Markus Handella3765182020-07-08 13:13:32 +020043#include "rtc_base/synchronization/mutex.h"
Erik Språng7ca375c2019-02-06 16:20:17 +010044#include "system_wrappers/include/field_trial.h"
Mirko Bonadei17f48782018-09-28 08:51:10 +020045#include "system_wrappers/include/metrics.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020046#include "system_wrappers/include/sleep.h"
47#include "test/encoder_settings.h"
48#include "test/fake_encoder.h"
Kári Tristan Helgason639602a2018-08-02 10:51:40 +020049#include "test/field_trial.h"
Artem Titov33f9d2b2019-12-05 15:59:00 +010050#include "test/frame_forwarder.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020051#include "test/gmock.h"
52#include "test/gtest.h"
Tomas Gunnarsson612445e2020-09-21 14:31:23 +020053#include "test/time_controller/simulated_time_controller.h"
Niels Möllercbcbc222018-09-28 09:07:24 +020054#include "test/video_encoder_proxy_factory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020055#include "video/send_statistics_proxy.h"
perkj26091b12016-09-01 01:17:40 -070056
57namespace webrtc {
58
sprang57c2fff2017-01-16 06:24:02 -080059using ::testing::_;
philipeld9cc8c02019-09-16 14:53:40 +020060using ::testing::AllOf;
Per Kjellanderd0a8f512020-10-07 11:28:41 +020061using ::testing::AtLeast;
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +020062using ::testing::Eq;
philipeld9cc8c02019-09-16 14:53:40 +020063using ::testing::Field;
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +020064using ::testing::Ge;
65using ::testing::Gt;
66using ::testing::Le;
67using ::testing::Lt;
philipel9b058032020-02-10 11:30:00 +010068using ::testing::Matcher;
69using ::testing::NiceMock;
70using ::testing::Return;
philipeld9cc8c02019-09-16 14:53:40 +020071using ::testing::StrictMock;
kthelgason876222f2016-11-29 01:44:11 -080072
perkj803d97f2016-11-01 11:45:46 -070073namespace {
Åsa Persson8c1bf952018-09-13 10:42:19 +020074const int kMinPixelsPerFrame = 320 * 180;
Åsa Perssone644a032019-11-08 15:56:00 +010075const int kQpLow = 1;
76const int kQpHigh = 2;
Åsa Persson8c1bf952018-09-13 10:42:19 +020077const int kMinFramerateFps = 2;
78const int kMinBalancedFramerateFps = 7;
79const int64_t kFrameTimeoutMs = 100;
asapersson5f7226f2016-11-25 04:37:00 -080080const size_t kMaxPayloadLength = 1440;
Erik Språngd7329ca2019-02-21 21:19:53 +010081const uint32_t kTargetBitrateBps = 1000000;
Sergey Silkin5ee69672019-07-02 14:18:34 +020082const uint32_t kStartBitrateBps = 600000;
Erik Språngd7329ca2019-02-21 21:19:53 +010083const uint32_t kSimulcastTargetBitrateBps = 3150000;
84const uint32_t kLowTargetBitrateBps = kTargetBitrateBps / 10;
kthelgason2bc68642017-02-07 07:02:22 -080085const int kMaxInitialFramedrop = 4;
sprangfda496a2017-06-15 04:21:07 -070086const int kDefaultFramerate = 30;
Åsa Persson8c1bf952018-09-13 10:42:19 +020087const int64_t kFrameIntervalMs = rtc::kNumMillisecsPerSec / kDefaultFramerate;
Niels Möllerfe407b72019-09-10 10:48:48 +020088const int64_t kProcessIntervalMs = 1000;
Sergey Silkin41c650b2019-10-14 13:12:19 +020089const VideoEncoder::ResolutionBitrateLimits
90 kEncoderBitrateLimits540p(960 * 540, 100 * 1000, 100 * 1000, 2000 * 1000);
91const VideoEncoder::ResolutionBitrateLimits
92 kEncoderBitrateLimits720p(1280 * 720, 200 * 1000, 200 * 1000, 4000 * 1000);
asapersson5f7226f2016-11-25 04:37:00 -080093
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +020094uint8_t optimal_sps[] = {0, 0, 0, 1, H264::NaluType::kSps,
95 0x00, 0x00, 0x03, 0x03, 0xF4,
96 0x05, 0x03, 0xC7, 0xE0, 0x1B,
97 0x41, 0x10, 0x8D, 0x00};
98
perkj803d97f2016-11-01 11:45:46 -070099class TestBuffer : public webrtc::I420Buffer {
100 public:
101 TestBuffer(rtc::Event* event, int width, int height)
102 : I420Buffer(width, height), event_(event) {}
103
104 private:
105 friend class rtc::RefCountedObject<TestBuffer>;
106 ~TestBuffer() override {
107 if (event_)
108 event_->Set();
109 }
110 rtc::Event* const event_;
111};
112
Noah Richards51db4212019-06-12 06:59:12 -0700113// A fake native buffer that can't be converted to I420.
114class FakeNativeBuffer : public webrtc::VideoFrameBuffer {
115 public:
116 FakeNativeBuffer(rtc::Event* event, int width, int height)
117 : event_(event), width_(width), height_(height) {}
118 webrtc::VideoFrameBuffer::Type type() const override { return Type::kNative; }
119 int width() const override { return width_; }
120 int height() const override { return height_; }
121 rtc::scoped_refptr<webrtc::I420BufferInterface> ToI420() override {
122 return nullptr;
123 }
124
125 private:
126 friend class rtc::RefCountedObject<FakeNativeBuffer>;
127 ~FakeNativeBuffer() override {
128 if (event_)
129 event_->Set();
130 }
131 rtc::Event* const event_;
132 const int width_;
133 const int height_;
134};
135
Evan Shrubsole895556e2020-10-05 09:15:13 +0200136// A fake native buffer that is backed by an NV12 buffer.
137class FakeNV12NativeBuffer : public webrtc::VideoFrameBuffer {
138 public:
139 FakeNV12NativeBuffer(rtc::Event* event, int width, int height)
140 : nv12_buffer_(NV12Buffer::Create(width, height)), event_(event) {}
141
142 webrtc::VideoFrameBuffer::Type type() const override { return Type::kNative; }
143 int width() const override { return nv12_buffer_->width(); }
144 int height() const override { return nv12_buffer_->height(); }
145 rtc::scoped_refptr<webrtc::I420BufferInterface> ToI420() override {
146 return nv12_buffer_->ToI420();
147 }
Evan Shrubsoleb556b082020-10-08 14:56:45 +0200148 rtc::scoped_refptr<VideoFrameBuffer> GetMappedFrameBuffer(
149 rtc::ArrayView<VideoFrameBuffer::Type> types) override {
150 if (absl::c_find(types, Type::kNV12) != types.end()) {
151 return nv12_buffer_;
152 }
153 return nullptr;
154 }
Evan Shrubsole895556e2020-10-05 09:15:13 +0200155 const NV12BufferInterface* GetNV12() const { return nv12_buffer_; }
156
157 private:
158 friend class rtc::RefCountedObject<FakeNV12NativeBuffer>;
159 ~FakeNV12NativeBuffer() override {
160 if (event_)
161 event_->Set();
162 }
163 rtc::scoped_refptr<NV12Buffer> nv12_buffer_;
164 rtc::Event* const event_;
165};
166
Niels Möller7dc26b72017-12-06 10:27:48 +0100167class CpuOveruseDetectorProxy : public OveruseFrameDetector {
168 public:
Niels Möllerd1f7eb62018-03-28 16:40:58 +0200169 explicit CpuOveruseDetectorProxy(CpuOveruseMetricsObserver* metrics_observer)
170 : OveruseFrameDetector(metrics_observer),
Henrik Boström381d1092020-05-12 18:49:07 +0200171 last_target_framerate_fps_(-1),
172 framerate_updated_event_(true /* manual_reset */,
173 false /* initially_signaled */) {}
Niels Möller7dc26b72017-12-06 10:27:48 +0100174 virtual ~CpuOveruseDetectorProxy() {}
175
176 void OnTargetFramerateUpdated(int framerate_fps) override {
Markus Handella3765182020-07-08 13:13:32 +0200177 MutexLock lock(&lock_);
Niels Möller7dc26b72017-12-06 10:27:48 +0100178 last_target_framerate_fps_ = framerate_fps;
179 OveruseFrameDetector::OnTargetFramerateUpdated(framerate_fps);
Henrik Boström381d1092020-05-12 18:49:07 +0200180 framerate_updated_event_.Set();
Niels Möller7dc26b72017-12-06 10:27:48 +0100181 }
182
183 int GetLastTargetFramerate() {
Markus Handella3765182020-07-08 13:13:32 +0200184 MutexLock lock(&lock_);
Niels Möller7dc26b72017-12-06 10:27:48 +0100185 return last_target_framerate_fps_;
186 }
187
Niels Möller4db138e2018-04-19 09:04:13 +0200188 CpuOveruseOptions GetOptions() { return options_; }
189
Henrik Boström381d1092020-05-12 18:49:07 +0200190 rtc::Event* framerate_updated_event() { return &framerate_updated_event_; }
191
Niels Möller7dc26b72017-12-06 10:27:48 +0100192 private:
Markus Handella3765182020-07-08 13:13:32 +0200193 Mutex lock_;
Niels Möller7dc26b72017-12-06 10:27:48 +0100194 int last_target_framerate_fps_ RTC_GUARDED_BY(lock_);
Henrik Boström381d1092020-05-12 18:49:07 +0200195 rtc::Event framerate_updated_event_;
Niels Möller7dc26b72017-12-06 10:27:48 +0100196};
197
Henrik Boström0f0aa9c2020-06-02 13:02:36 +0200198class FakeVideoSourceRestrictionsListener
199 : public VideoSourceRestrictionsListener {
Henrik Boström381d1092020-05-12 18:49:07 +0200200 public:
Henrik Boström0f0aa9c2020-06-02 13:02:36 +0200201 FakeVideoSourceRestrictionsListener()
Henrik Boström381d1092020-05-12 18:49:07 +0200202 : was_restrictions_updated_(false), restrictions_updated_event_() {}
Henrik Boström0f0aa9c2020-06-02 13:02:36 +0200203 ~FakeVideoSourceRestrictionsListener() override {
Henrik Boström381d1092020-05-12 18:49:07 +0200204 RTC_DCHECK(was_restrictions_updated_);
205 }
206
207 rtc::Event* restrictions_updated_event() {
208 return &restrictions_updated_event_;
209 }
210
Henrik Boström0f0aa9c2020-06-02 13:02:36 +0200211 // VideoSourceRestrictionsListener implementation.
Henrik Boström381d1092020-05-12 18:49:07 +0200212 void OnVideoSourceRestrictionsUpdated(
213 VideoSourceRestrictions restrictions,
214 const VideoAdaptationCounters& adaptation_counters,
Evan Shrubsoleec0af262020-07-01 11:47:46 +0200215 rtc::scoped_refptr<Resource> reason,
216 const VideoSourceRestrictions& unfiltered_restrictions) override {
Henrik Boström381d1092020-05-12 18:49:07 +0200217 was_restrictions_updated_ = true;
218 restrictions_updated_event_.Set();
219 }
220
221 private:
222 bool was_restrictions_updated_;
223 rtc::Event restrictions_updated_event_;
224};
225
Evan Shrubsole5fd40602020-05-25 16:19:54 +0200226auto WantsFps(Matcher<int> fps_matcher) {
227 return Field("max_framerate_fps", &rtc::VideoSinkWants::max_framerate_fps,
228 fps_matcher);
229}
230
231auto WantsMaxPixels(Matcher<int> max_pixel_matcher) {
232 return Field("max_pixel_count", &rtc::VideoSinkWants::max_pixel_count,
233 AllOf(max_pixel_matcher, Gt(0)));
234}
235
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +0200236auto ResolutionMax() {
237 return AllOf(
Evan Shrubsole5fd40602020-05-25 16:19:54 +0200238 WantsMaxPixels(Eq(std::numeric_limits<int>::max())),
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +0200239 Field("target_pixel_count", &rtc::VideoSinkWants::target_pixel_count,
240 Eq(absl::nullopt)));
241}
242
243auto FpsMax() {
Evan Shrubsole5fd40602020-05-25 16:19:54 +0200244 return WantsFps(Eq(kDefaultFramerate));
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +0200245}
246
247auto FpsUnlimited() {
Evan Shrubsole5fd40602020-05-25 16:19:54 +0200248 return WantsFps(Eq(std::numeric_limits<int>::max()));
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +0200249}
250
251auto FpsMatchesResolutionMax(Matcher<int> fps_matcher) {
Evan Shrubsole5fd40602020-05-25 16:19:54 +0200252 return AllOf(WantsFps(fps_matcher), ResolutionMax());
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +0200253}
254
255auto FpsMaxResolutionMatches(Matcher<int> pixel_matcher) {
Evan Shrubsole5fd40602020-05-25 16:19:54 +0200256 return AllOf(FpsMax(), WantsMaxPixels(pixel_matcher));
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +0200257}
258
259auto FpsMaxResolutionMax() {
260 return AllOf(FpsMax(), ResolutionMax());
261}
262
263auto UnlimitedSinkWants() {
264 return AllOf(FpsUnlimited(), ResolutionMax());
265}
266
267auto FpsInRangeForPixelsInBalanced(int last_frame_pixels) {
268 Matcher<int> fps_range_matcher;
269
270 if (last_frame_pixels <= 320 * 240) {
271 fps_range_matcher = AllOf(Ge(7), Le(10));
Åsa Perssonc5a74ff2020-09-20 17:50:00 +0200272 } else if (last_frame_pixels <= 480 * 360) {
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +0200273 fps_range_matcher = AllOf(Ge(10), Le(15));
274 } else if (last_frame_pixels <= 640 * 480) {
275 fps_range_matcher = Ge(15);
276 } else {
277 fps_range_matcher = Eq(kDefaultFramerate);
278 }
279 return Field("max_framerate_fps", &rtc::VideoSinkWants::max_framerate_fps,
280 fps_range_matcher);
281}
282
Evan Shrubsole5fd40602020-05-25 16:19:54 +0200283auto FpsEqResolutionEqTo(const rtc::VideoSinkWants& other_wants) {
284 return AllOf(WantsFps(Eq(other_wants.max_framerate_fps)),
285 WantsMaxPixels(Eq(other_wants.max_pixel_count)));
286}
287
288auto FpsMaxResolutionLt(const rtc::VideoSinkWants& other_wants) {
289 return AllOf(FpsMax(), WantsMaxPixels(Lt(other_wants.max_pixel_count)));
290}
291
292auto FpsMaxResolutionGt(const rtc::VideoSinkWants& other_wants) {
293 return AllOf(FpsMax(), WantsMaxPixels(Gt(other_wants.max_pixel_count)));
294}
295
296auto FpsLtResolutionEq(const rtc::VideoSinkWants& other_wants) {
297 return AllOf(WantsFps(Lt(other_wants.max_framerate_fps)),
298 WantsMaxPixels(Eq(other_wants.max_pixel_count)));
299}
300
301auto FpsGtResolutionEq(const rtc::VideoSinkWants& other_wants) {
302 return AllOf(WantsFps(Gt(other_wants.max_framerate_fps)),
303 WantsMaxPixels(Eq(other_wants.max_pixel_count)));
304}
305
306auto FpsEqResolutionLt(const rtc::VideoSinkWants& other_wants) {
307 return AllOf(WantsFps(Eq(other_wants.max_framerate_fps)),
308 WantsMaxPixels(Lt(other_wants.max_pixel_count)));
309}
310
311auto FpsEqResolutionGt(const rtc::VideoSinkWants& other_wants) {
312 return AllOf(WantsFps(Eq(other_wants.max_framerate_fps)),
313 WantsMaxPixels(Gt(other_wants.max_pixel_count)));
314}
315
mflodmancc3d4422017-08-03 08:27:51 -0700316class VideoStreamEncoderUnderTest : public VideoStreamEncoder {
perkj803d97f2016-11-01 11:45:46 -0700317 public:
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200318 VideoStreamEncoderUnderTest(TimeController* time_controller,
319 TaskQueueFactory* task_queue_factory,
320 SendStatisticsProxy* stats_proxy,
321 const VideoStreamEncoderSettings& settings)
322 : VideoStreamEncoder(time_controller->GetClock(),
Sebastian Jansson572c60f2019-03-04 18:30:41 +0100323 1 /* number_of_cores */,
Yves Gerey665174f2018-06-19 15:03:05 +0200324 stats_proxy,
325 settings,
Yves Gerey665174f2018-06-19 15:03:05 +0200326 std::unique_ptr<OveruseFrameDetector>(
327 overuse_detector_proxy_ =
Sebastian Jansson74682c12019-03-01 11:50:20 +0100328 new CpuOveruseDetectorProxy(stats_proxy)),
Evan Shrubsoleaa6fbc12020-02-25 16:26:01 +0100329 task_queue_factory),
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200330 time_controller_(time_controller),
Henrik Boström5cc28b02020-06-01 17:59:05 +0200331 fake_cpu_resource_(FakeResource::Create("FakeResource[CPU]")),
Henrik Boström0f0aa9c2020-06-02 13:02:36 +0200332 fake_quality_resource_(FakeResource::Create("FakeResource[QP]")),
Evan Shrubsoledc4d4222020-07-09 11:47:10 +0200333 fake_adaptation_constraint_("FakeAdaptationConstraint") {
Henrik Boströmc55516d2020-05-11 16:29:22 +0200334 InjectAdaptationResource(fake_quality_resource_,
Evan Shrubsolece0a11d2020-04-16 11:36:55 +0200335 VideoAdaptationReason::kQuality);
Henrik Boströmc55516d2020-05-11 16:29:22 +0200336 InjectAdaptationResource(fake_cpu_resource_, VideoAdaptationReason::kCpu);
Henrik Boström0f0aa9c2020-06-02 13:02:36 +0200337 InjectAdaptationConstraint(&fake_adaptation_constraint_);
Evan Shrubsoleaa6fbc12020-02-25 16:26:01 +0100338 }
perkj803d97f2016-11-01 11:45:46 -0700339
Henrik Boström381d1092020-05-12 18:49:07 +0200340 void SetSourceAndWaitForRestrictionsUpdated(
341 rtc::VideoSourceInterface<VideoFrame>* source,
342 const DegradationPreference& degradation_preference) {
Henrik Boström0f0aa9c2020-06-02 13:02:36 +0200343 FakeVideoSourceRestrictionsListener listener;
344 AddRestrictionsListenerForTesting(&listener);
Henrik Boström381d1092020-05-12 18:49:07 +0200345 SetSource(source, degradation_preference);
346 listener.restrictions_updated_event()->Wait(5000);
Henrik Boström0f0aa9c2020-06-02 13:02:36 +0200347 RemoveRestrictionsListenerForTesting(&listener);
Henrik Boström381d1092020-05-12 18:49:07 +0200348 }
349
350 void SetSourceAndWaitForFramerateUpdated(
351 rtc::VideoSourceInterface<VideoFrame>* source,
352 const DegradationPreference& degradation_preference) {
353 overuse_detector_proxy_->framerate_updated_event()->Reset();
354 SetSource(source, degradation_preference);
355 overuse_detector_proxy_->framerate_updated_event()->Wait(5000);
356 }
357
358 void OnBitrateUpdatedAndWaitForManagedResources(
359 DataRate target_bitrate,
360 DataRate stable_target_bitrate,
361 DataRate link_allocation,
362 uint8_t fraction_lost,
363 int64_t round_trip_time_ms,
364 double cwnd_reduce_ratio) {
365 OnBitrateUpdated(target_bitrate, stable_target_bitrate, link_allocation,
366 fraction_lost, round_trip_time_ms, cwnd_reduce_ratio);
367 // Bitrate is updated on the encoder queue.
368 WaitUntilTaskQueueIsIdle();
Henrik Boström381d1092020-05-12 18:49:07 +0200369 }
370
kthelgason2fc52542017-03-03 00:24:41 -0800371 // This is used as a synchronisation mechanism, to make sure that the
372 // encoder queue is not blocked before we start sending it frames.
373 void WaitUntilTaskQueueIsIdle() {
Niels Möllerc572ff32018-11-07 08:43:50 +0100374 rtc::Event event;
Yves Gerey665174f2018-06-19 15:03:05 +0200375 encoder_queue()->PostTask([&event] { event.Set(); });
kthelgason2fc52542017-03-03 00:24:41 -0800376 ASSERT_TRUE(event.Wait(5000));
377 }
378
Henrik Boström91aa7322020-04-28 12:24:33 +0200379 // Triggers resource usage measurements on the fake CPU resource.
Åsa Perssonb67c44c2019-09-24 15:25:32 +0200380 void TriggerCpuOveruse() {
Henrik Boström91aa7322020-04-28 12:24:33 +0200381 rtc::Event event;
Evan Shrubsole85728412020-08-25 13:12:12 +0200382 encoder_queue()->PostTask([this, &event] {
Henrik Boström0f0aa9c2020-06-02 13:02:36 +0200383 fake_cpu_resource_->SetUsageState(ResourceUsageState::kOveruse);
Henrik Boström91aa7322020-04-28 12:24:33 +0200384 event.Set();
385 });
386 ASSERT_TRUE(event.Wait(5000));
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200387 time_controller_->AdvanceTime(TimeDelta::Millis(0));
Henrik Boström91aa7322020-04-28 12:24:33 +0200388 }
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200389
Henrik Boström91aa7322020-04-28 12:24:33 +0200390 void TriggerCpuUnderuse() {
391 rtc::Event event;
Evan Shrubsole85728412020-08-25 13:12:12 +0200392 encoder_queue()->PostTask([this, &event] {
Henrik Boström0f0aa9c2020-06-02 13:02:36 +0200393 fake_cpu_resource_->SetUsageState(ResourceUsageState::kUnderuse);
Henrik Boström91aa7322020-04-28 12:24:33 +0200394 event.Set();
395 });
396 ASSERT_TRUE(event.Wait(5000));
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200397 time_controller_->AdvanceTime(TimeDelta::Millis(0));
Åsa Perssonb67c44c2019-09-24 15:25:32 +0200398 }
kthelgason876222f2016-11-29 01:44:11 -0800399
Henrik Boström91aa7322020-04-28 12:24:33 +0200400 // Triggers resource usage measurements on the fake quality resource.
Åsa Perssonb67c44c2019-09-24 15:25:32 +0200401 void TriggerQualityLow() {
Henrik Boström91aa7322020-04-28 12:24:33 +0200402 rtc::Event event;
Evan Shrubsole85728412020-08-25 13:12:12 +0200403 encoder_queue()->PostTask([this, &event] {
Henrik Boström0f0aa9c2020-06-02 13:02:36 +0200404 fake_quality_resource_->SetUsageState(ResourceUsageState::kOveruse);
Henrik Boström91aa7322020-04-28 12:24:33 +0200405 event.Set();
406 });
407 ASSERT_TRUE(event.Wait(5000));
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200408 time_controller_->AdvanceTime(TimeDelta::Millis(0));
Åsa Perssonb67c44c2019-09-24 15:25:32 +0200409 }
Åsa Perssonb67c44c2019-09-24 15:25:32 +0200410 void TriggerQualityHigh() {
Henrik Boström91aa7322020-04-28 12:24:33 +0200411 rtc::Event event;
Evan Shrubsole85728412020-08-25 13:12:12 +0200412 encoder_queue()->PostTask([this, &event] {
Henrik Boström0f0aa9c2020-06-02 13:02:36 +0200413 fake_quality_resource_->SetUsageState(ResourceUsageState::kUnderuse);
Henrik Boström91aa7322020-04-28 12:24:33 +0200414 event.Set();
415 });
416 ASSERT_TRUE(event.Wait(5000));
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200417 time_controller_->AdvanceTime(TimeDelta::Millis(0));
Henrik Boström91aa7322020-04-28 12:24:33 +0200418 }
419
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200420 TimeController* const time_controller_;
Niels Möller7dc26b72017-12-06 10:27:48 +0100421 CpuOveruseDetectorProxy* overuse_detector_proxy_;
Henrik Boströmc55516d2020-05-11 16:29:22 +0200422 rtc::scoped_refptr<FakeResource> fake_cpu_resource_;
423 rtc::scoped_refptr<FakeResource> fake_quality_resource_;
Henrik Boström0f0aa9c2020-06-02 13:02:36 +0200424 FakeAdaptationConstraint fake_adaptation_constraint_;
perkj803d97f2016-11-01 11:45:46 -0700425};
426
Noah Richards51db4212019-06-12 06:59:12 -0700427// Simulates simulcast behavior and makes highest stream resolutions divisible
428// by 4.
429class CroppingVideoStreamFactory
430 : public VideoEncoderConfig::VideoStreamFactoryInterface {
431 public:
432 explicit CroppingVideoStreamFactory(size_t num_temporal_layers, int framerate)
433 : num_temporal_layers_(num_temporal_layers), framerate_(framerate) {
434 EXPECT_GT(num_temporal_layers, 0u);
435 EXPECT_GT(framerate, 0);
436 }
437
438 private:
439 std::vector<VideoStream> CreateEncoderStreams(
440 int width,
441 int height,
442 const VideoEncoderConfig& encoder_config) override {
443 std::vector<VideoStream> streams = test::CreateVideoStreams(
444 width - width % 4, height - height % 4, encoder_config);
445 for (VideoStream& stream : streams) {
446 stream.num_temporal_layers = num_temporal_layers_;
447 stream.max_framerate = framerate_;
448 }
449 return streams;
450 }
451
452 const size_t num_temporal_layers_;
453 const int framerate_;
454};
455
sprangb1ca0732017-02-01 08:38:12 -0800456class AdaptingFrameForwarder : public test::FrameForwarder {
457 public:
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200458 explicit AdaptingFrameForwarder(TimeController* time_controller)
459 : time_controller_(time_controller), adaptation_enabled_(false) {}
asaperssonfab67072017-04-04 05:51:49 -0700460 ~AdaptingFrameForwarder() override {}
sprangb1ca0732017-02-01 08:38:12 -0800461
462 void set_adaptation_enabled(bool enabled) {
Markus Handella3765182020-07-08 13:13:32 +0200463 MutexLock lock(&mutex_);
sprangb1ca0732017-02-01 08:38:12 -0800464 adaptation_enabled_ = enabled;
465 }
466
asaperssonfab67072017-04-04 05:51:49 -0700467 bool adaption_enabled() const {
Markus Handella3765182020-07-08 13:13:32 +0200468 MutexLock lock(&mutex_);
sprangb1ca0732017-02-01 08:38:12 -0800469 return adaptation_enabled_;
470 }
471
asapersson09f05612017-05-15 23:40:18 -0700472 rtc::VideoSinkWants last_wants() const {
Markus Handella3765182020-07-08 13:13:32 +0200473 MutexLock lock(&mutex_);
asapersson09f05612017-05-15 23:40:18 -0700474 return last_wants_;
475 }
476
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200477 absl::optional<int> last_sent_width() const { return last_width_; }
478 absl::optional<int> last_sent_height() const { return last_height_; }
Jonathan Yubc771b72017-12-08 17:04:29 -0800479
sprangb1ca0732017-02-01 08:38:12 -0800480 void IncomingCapturedFrame(const VideoFrame& video_frame) override {
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200481 RTC_DCHECK(time_controller_->GetMainThread()->IsCurrent());
482 time_controller_->AdvanceTime(TimeDelta::Millis(0));
483
sprangb1ca0732017-02-01 08:38:12 -0800484 int cropped_width = 0;
485 int cropped_height = 0;
486 int out_width = 0;
487 int out_height = 0;
sprangc5d62e22017-04-02 23:53:04 -0700488 if (adaption_enabled()) {
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200489 RTC_DLOG(INFO) << "IncomingCapturedFrame: AdaptFrameResolution()"
490 << "w=" << video_frame.width()
491 << "h=" << video_frame.height();
sprangc5d62e22017-04-02 23:53:04 -0700492 if (adapter_.AdaptFrameResolution(
493 video_frame.width(), video_frame.height(),
494 video_frame.timestamp_us() * 1000, &cropped_width,
495 &cropped_height, &out_width, &out_height)) {
Artem Titov1ebfb6a2019-01-03 23:49:37 +0100496 VideoFrame adapted_frame =
497 VideoFrame::Builder()
498 .set_video_frame_buffer(new rtc::RefCountedObject<TestBuffer>(
499 nullptr, out_width, out_height))
500 .set_timestamp_rtp(99)
501 .set_timestamp_ms(99)
502 .set_rotation(kVideoRotation_0)
503 .build();
sprangc5d62e22017-04-02 23:53:04 -0700504 adapted_frame.set_ntp_time_ms(video_frame.ntp_time_ms());
Ilya Nikolaevskiy648b9d72019-12-03 16:54:17 +0100505 if (video_frame.has_update_rect()) {
506 adapted_frame.set_update_rect(
507 video_frame.update_rect().ScaleWithFrame(
508 video_frame.width(), video_frame.height(), 0, 0,
509 video_frame.width(), video_frame.height(), out_width,
510 out_height));
511 }
sprangc5d62e22017-04-02 23:53:04 -0700512 test::FrameForwarder::IncomingCapturedFrame(adapted_frame);
Jonathan Yubc771b72017-12-08 17:04:29 -0800513 last_width_.emplace(adapted_frame.width());
514 last_height_.emplace(adapted_frame.height());
515 } else {
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200516 last_width_ = absl::nullopt;
517 last_height_ = absl::nullopt;
sprangc5d62e22017-04-02 23:53:04 -0700518 }
sprangb1ca0732017-02-01 08:38:12 -0800519 } else {
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200520 RTC_DLOG(INFO) << "IncomingCapturedFrame: adaptation not enabled";
sprangb1ca0732017-02-01 08:38:12 -0800521 test::FrameForwarder::IncomingCapturedFrame(video_frame);
Jonathan Yubc771b72017-12-08 17:04:29 -0800522 last_width_.emplace(video_frame.width());
523 last_height_.emplace(video_frame.height());
sprangb1ca0732017-02-01 08:38:12 -0800524 }
525 }
526
527 void AddOrUpdateSink(rtc::VideoSinkInterface<VideoFrame>* sink,
528 const rtc::VideoSinkWants& wants) override {
Markus Handella3765182020-07-08 13:13:32 +0200529 MutexLock lock(&mutex_);
Markus Handell16038ab2020-05-28 08:37:30 +0200530 last_wants_ = sink_wants_locked();
Rasmus Brandt287e4642019-11-15 16:56:01 +0100531 adapter_.OnSinkWants(wants);
Markus Handell16038ab2020-05-28 08:37:30 +0200532 test::FrameForwarder::AddOrUpdateSinkLocked(sink, wants);
sprangb1ca0732017-02-01 08:38:12 -0800533 }
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200534
535 TimeController* const time_controller_;
sprangb1ca0732017-02-01 08:38:12 -0800536 cricket::VideoAdapter adapter_;
Markus Handella3765182020-07-08 13:13:32 +0200537 bool adaptation_enabled_ RTC_GUARDED_BY(mutex_);
538 rtc::VideoSinkWants last_wants_ RTC_GUARDED_BY(mutex_);
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200539 absl::optional<int> last_width_;
540 absl::optional<int> last_height_;
sprangb1ca0732017-02-01 08:38:12 -0800541};
sprangc5d62e22017-04-02 23:53:04 -0700542
Niels Möller213618e2018-07-24 09:29:58 +0200543// TODO(nisse): Mock only VideoStreamEncoderObserver.
sprangc5d62e22017-04-02 23:53:04 -0700544class MockableSendStatisticsProxy : public SendStatisticsProxy {
545 public:
546 MockableSendStatisticsProxy(Clock* clock,
547 const VideoSendStream::Config& config,
548 VideoEncoderConfig::ContentType content_type)
549 : SendStatisticsProxy(clock, config, content_type) {}
550
551 VideoSendStream::Stats GetStats() override {
Markus Handella3765182020-07-08 13:13:32 +0200552 MutexLock lock(&lock_);
sprangc5d62e22017-04-02 23:53:04 -0700553 if (mock_stats_)
554 return *mock_stats_;
555 return SendStatisticsProxy::GetStats();
556 }
557
Niels Möller213618e2018-07-24 09:29:58 +0200558 int GetInputFrameRate() const override {
Markus Handella3765182020-07-08 13:13:32 +0200559 MutexLock lock(&lock_);
Niels Möller213618e2018-07-24 09:29:58 +0200560 if (mock_stats_)
561 return mock_stats_->input_frame_rate;
562 return SendStatisticsProxy::GetInputFrameRate();
563 }
sprangc5d62e22017-04-02 23:53:04 -0700564 void SetMockStats(const VideoSendStream::Stats& stats) {
Markus Handella3765182020-07-08 13:13:32 +0200565 MutexLock lock(&lock_);
sprangc5d62e22017-04-02 23:53:04 -0700566 mock_stats_.emplace(stats);
567 }
568
569 void ResetMockStats() {
Markus Handella3765182020-07-08 13:13:32 +0200570 MutexLock lock(&lock_);
sprangc5d62e22017-04-02 23:53:04 -0700571 mock_stats_.reset();
572 }
573
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200574 void SetDroppedFrameCallback(std::function<void(DropReason)> callback) {
575 on_frame_dropped_ = std::move(callback);
576 }
577
sprangc5d62e22017-04-02 23:53:04 -0700578 private:
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200579 void OnFrameDropped(DropReason reason) override {
580 SendStatisticsProxy::OnFrameDropped(reason);
581 if (on_frame_dropped_)
582 on_frame_dropped_(reason);
583 }
584
Markus Handella3765182020-07-08 13:13:32 +0200585 mutable Mutex lock_;
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200586 absl::optional<VideoSendStream::Stats> mock_stats_ RTC_GUARDED_BY(lock_);
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200587 std::function<void(DropReason)> on_frame_dropped_;
sprangc5d62e22017-04-02 23:53:04 -0700588};
589
philipel9b058032020-02-10 11:30:00 +0100590class MockEncoderSelector
591 : public VideoEncoderFactory::EncoderSelectorInterface {
592 public:
Danil Chapovalov91fdc602020-05-14 19:17:51 +0200593 MOCK_METHOD(void,
594 OnCurrentEncoder,
595 (const SdpVideoFormat& format),
596 (override));
597 MOCK_METHOD(absl::optional<SdpVideoFormat>,
598 OnAvailableBitrate,
599 (const DataRate& rate),
600 (override));
601 MOCK_METHOD(absl::optional<SdpVideoFormat>, OnEncoderBroken, (), (override));
philipel9b058032020-02-10 11:30:00 +0100602};
603
perkj803d97f2016-11-01 11:45:46 -0700604} // namespace
605
mflodmancc3d4422017-08-03 08:27:51 -0700606class VideoStreamEncoderTest : public ::testing::Test {
perkj26091b12016-09-01 01:17:40 -0700607 public:
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200608 static const int kDefaultTimeoutMs = 1000;
perkj26091b12016-09-01 01:17:40 -0700609
mflodmancc3d4422017-08-03 08:27:51 -0700610 VideoStreamEncoderTest()
perkj26091b12016-09-01 01:17:40 -0700611 : video_send_config_(VideoSendStream::Config(nullptr)),
perkjfa10b552016-10-02 23:45:26 -0700612 codec_width_(320),
613 codec_height_(240),
Åsa Persson8c1bf952018-09-13 10:42:19 +0200614 max_framerate_(kDefaultFramerate),
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200615 fake_encoder_(&time_controller_),
Niels Möller4db138e2018-04-19 09:04:13 +0200616 encoder_factory_(&fake_encoder_),
sprangc5d62e22017-04-02 23:53:04 -0700617 stats_proxy_(new MockableSendStatisticsProxy(
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200618 time_controller_.GetClock(),
perkj803d97f2016-11-01 11:45:46 -0700619 video_send_config_,
620 webrtc::VideoEncoderConfig::ContentType::kRealtimeVideo)),
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200621 sink_(&time_controller_, &fake_encoder_) {}
perkj26091b12016-09-01 01:17:40 -0700622
623 void SetUp() override {
perkj803d97f2016-11-01 11:45:46 -0700624 metrics::Reset();
perkj26091b12016-09-01 01:17:40 -0700625 video_send_config_ = VideoSendStream::Config(nullptr);
Niels Möller4db138e2018-04-19 09:04:13 +0200626 video_send_config_.encoder_settings.encoder_factory = &encoder_factory_;
Jiawei Ouc2ebe212018-11-08 10:02:56 -0800627 video_send_config_.encoder_settings.bitrate_allocator_factory =
Sergey Silkin5ee69672019-07-02 14:18:34 +0200628 &bitrate_allocator_factory_;
Niels Möller259a4972018-04-05 15:36:51 +0200629 video_send_config_.rtp.payload_name = "FAKE";
630 video_send_config_.rtp.payload_type = 125;
perkj26091b12016-09-01 01:17:40 -0700631
Per512ecb32016-09-23 15:52:06 +0200632 VideoEncoderConfig video_encoder_config;
Niels Möller259a4972018-04-05 15:36:51 +0200633 test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
Åsa Persson17107062020-10-08 08:57:51 +0200634 EXPECT_EQ(1u, video_encoder_config.simulcast_layers.size());
635 video_encoder_config.simulcast_layers[0].num_temporal_layers = 1;
636 video_encoder_config.simulcast_layers[0].max_framerate = max_framerate_;
Erik Språng08127a92016-11-16 16:41:30 +0100637 video_encoder_config_ = video_encoder_config.Copy();
sprang4847ae62017-06-27 07:06:52 -0700638
Niels Möllerf1338562018-04-26 09:51:47 +0200639 ConfigureEncoder(std::move(video_encoder_config));
asapersson5f7226f2016-11-25 04:37:00 -0800640 }
641
Niels Möllerf1338562018-04-26 09:51:47 +0200642 void ConfigureEncoder(VideoEncoderConfig video_encoder_config) {
mflodmancc3d4422017-08-03 08:27:51 -0700643 if (video_stream_encoder_)
644 video_stream_encoder_->Stop();
645 video_stream_encoder_.reset(new VideoStreamEncoderUnderTest(
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200646 &time_controller_, GetTaskQueueFactory(), stats_proxy_.get(),
647 video_send_config_.encoder_settings));
mflodmancc3d4422017-08-03 08:27:51 -0700648 video_stream_encoder_->SetSink(&sink_, false /* rotation_applied */);
649 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700650 &video_source_, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
mflodmancc3d4422017-08-03 08:27:51 -0700651 video_stream_encoder_->SetStartBitrate(kTargetBitrateBps);
652 video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config),
Niels Möllerf1338562018-04-26 09:51:47 +0200653 kMaxPayloadLength);
mflodmancc3d4422017-08-03 08:27:51 -0700654 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
asapersson5f7226f2016-11-25 04:37:00 -0800655 }
656
Per Kjellanderdcef6412020-10-07 15:09:05 +0200657 void ResetEncoder(
658 const std::string& payload_name,
659 size_t num_streams,
660 size_t num_temporal_layers,
661 unsigned char num_spatial_layers,
662 bool screenshare,
663 VideoStreamEncoderSettings::BitrateAllocationCallbackType
664 allocation_cb_type =
665 VideoStreamEncoderSettings::BitrateAllocationCallbackType::
666 kVideoBitrateAllocationWhenScreenSharing) {
Niels Möller259a4972018-04-05 15:36:51 +0200667 video_send_config_.rtp.payload_name = payload_name;
Per Kjellanderdcef6412020-10-07 15:09:05 +0200668 video_send_config_.encoder_settings.allocation_cb_type = allocation_cb_type;
asapersson5f7226f2016-11-25 04:37:00 -0800669
670 VideoEncoderConfig video_encoder_config;
Åsa Persson17107062020-10-08 08:57:51 +0200671 test::FillEncoderConfiguration(PayloadStringToCodecType(payload_name),
672 num_streams, &video_encoder_config);
673 for (auto& layer : video_encoder_config.simulcast_layers) {
674 layer.num_temporal_layers = num_temporal_layers;
675 layer.max_framerate = kDefaultFramerate;
676 }
Erik Språngd7329ca2019-02-21 21:19:53 +0100677 video_encoder_config.max_bitrate_bps =
678 num_streams == 1 ? kTargetBitrateBps : kSimulcastTargetBitrateBps;
sprang4847ae62017-06-27 07:06:52 -0700679 video_encoder_config.content_type =
680 screenshare ? VideoEncoderConfig::ContentType::kScreen
681 : VideoEncoderConfig::ContentType::kRealtimeVideo;
emircanbbcc3562017-08-18 00:28:40 -0700682 if (payload_name == "VP9") {
683 VideoCodecVP9 vp9_settings = VideoEncoder::GetDefaultVp9Settings();
684 vp9_settings.numberOfSpatialLayers = num_spatial_layers;
Mirta Dvornicic97910da2020-07-14 15:29:23 +0200685 vp9_settings.automaticResizeOn = num_spatial_layers <= 1;
emircanbbcc3562017-08-18 00:28:40 -0700686 video_encoder_config.encoder_specific_settings =
687 new rtc::RefCountedObject<
688 VideoEncoderConfig::Vp9EncoderSpecificSettings>(vp9_settings);
689 }
Niels Möllerf1338562018-04-26 09:51:47 +0200690 ConfigureEncoder(std::move(video_encoder_config));
perkj26091b12016-09-01 01:17:40 -0700691 }
692
sprang57c2fff2017-01-16 06:24:02 -0800693 VideoFrame CreateFrame(int64_t ntp_time_ms,
694 rtc::Event* destruction_event) const {
Artem Titov1ebfb6a2019-01-03 23:49:37 +0100695 VideoFrame frame =
696 VideoFrame::Builder()
697 .set_video_frame_buffer(new rtc::RefCountedObject<TestBuffer>(
698 destruction_event, codec_width_, codec_height_))
699 .set_timestamp_rtp(99)
700 .set_timestamp_ms(99)
701 .set_rotation(kVideoRotation_0)
702 .build();
sprang57c2fff2017-01-16 06:24:02 -0800703 frame.set_ntp_time_ms(ntp_time_ms);
perkj26091b12016-09-01 01:17:40 -0700704 return frame;
705 }
706
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +0100707 VideoFrame CreateFrameWithUpdatedPixel(int64_t ntp_time_ms,
708 rtc::Event* destruction_event,
709 int offset_x) const {
710 VideoFrame frame =
711 VideoFrame::Builder()
712 .set_video_frame_buffer(new rtc::RefCountedObject<TestBuffer>(
713 destruction_event, codec_width_, codec_height_))
714 .set_timestamp_rtp(99)
715 .set_timestamp_ms(99)
716 .set_rotation(kVideoRotation_0)
Artem Titov5256d8b2019-12-02 10:34:12 +0100717 .set_update_rect(VideoFrame::UpdateRect{offset_x, 0, 1, 1})
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +0100718 .build();
719 frame.set_ntp_time_ms(ntp_time_ms);
720 return frame;
721 }
722
sprang57c2fff2017-01-16 06:24:02 -0800723 VideoFrame CreateFrame(int64_t ntp_time_ms, int width, int height) const {
Artem Titov1ebfb6a2019-01-03 23:49:37 +0100724 VideoFrame frame =
725 VideoFrame::Builder()
726 .set_video_frame_buffer(
727 new rtc::RefCountedObject<TestBuffer>(nullptr, width, height))
728 .set_timestamp_rtp(99)
729 .set_timestamp_ms(99)
730 .set_rotation(kVideoRotation_0)
731 .build();
sprang57c2fff2017-01-16 06:24:02 -0800732 frame.set_ntp_time_ms(ntp_time_ms);
sprangc5d62e22017-04-02 23:53:04 -0700733 frame.set_timestamp_us(ntp_time_ms * 1000);
perkj803d97f2016-11-01 11:45:46 -0700734 return frame;
735 }
736
Evan Shrubsole895556e2020-10-05 09:15:13 +0200737 VideoFrame CreateNV12Frame(int64_t ntp_time_ms, int width, int height) const {
738 VideoFrame frame =
739 VideoFrame::Builder()
740 .set_video_frame_buffer(NV12Buffer::Create(width, height))
741 .set_timestamp_rtp(99)
742 .set_timestamp_ms(99)
743 .set_rotation(kVideoRotation_0)
744 .build();
745 frame.set_ntp_time_ms(ntp_time_ms);
746 frame.set_timestamp_us(ntp_time_ms * 1000);
747 return frame;
748 }
749
Noah Richards51db4212019-06-12 06:59:12 -0700750 VideoFrame CreateFakeNativeFrame(int64_t ntp_time_ms,
751 rtc::Event* destruction_event,
752 int width,
753 int height) const {
754 VideoFrame frame =
755 VideoFrame::Builder()
756 .set_video_frame_buffer(new rtc::RefCountedObject<FakeNativeBuffer>(
757 destruction_event, width, height))
758 .set_timestamp_rtp(99)
759 .set_timestamp_ms(99)
760 .set_rotation(kVideoRotation_0)
761 .build();
762 frame.set_ntp_time_ms(ntp_time_ms);
763 return frame;
764 }
765
Evan Shrubsole895556e2020-10-05 09:15:13 +0200766 VideoFrame CreateFakeNV12NativeFrame(int64_t ntp_time_ms,
767 rtc::Event* destruction_event,
768 int width,
769 int height) const {
770 VideoFrame frame = VideoFrame::Builder()
771 .set_video_frame_buffer(
772 new rtc::RefCountedObject<FakeNV12NativeBuffer>(
773 destruction_event, width, height))
774 .set_timestamp_rtp(99)
775 .set_timestamp_ms(99)
776 .set_rotation(kVideoRotation_0)
777 .build();
778 frame.set_ntp_time_ms(ntp_time_ms);
779 return frame;
780 }
781
Noah Richards51db4212019-06-12 06:59:12 -0700782 VideoFrame CreateFakeNativeFrame(int64_t ntp_time_ms,
783 rtc::Event* destruction_event) const {
784 return CreateFakeNativeFrame(ntp_time_ms, destruction_event, codec_width_,
785 codec_height_);
786 }
787
Åsa Perssonc29cb2c2019-03-25 12:06:59 +0100788 void VerifyAllocatedBitrate(const VideoBitrateAllocation& expected_bitrate) {
Henrik Boström381d1092020-05-12 18:49:07 +0200789 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100790 DataRate::BitsPerSec(kTargetBitrateBps),
791 DataRate::BitsPerSec(kTargetBitrateBps),
792 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Åsa Perssonc29cb2c2019-03-25 12:06:59 +0100793
794 video_source_.IncomingCapturedFrame(
795 CreateFrame(1, codec_width_, codec_height_));
796 WaitForEncodedFrame(1);
Per Kjellanderdcef6412020-10-07 15:09:05 +0200797 EXPECT_EQ(expected_bitrate, sink_.GetLastVideoBitrateAllocation());
Åsa Perssonc29cb2c2019-03-25 12:06:59 +0100798 }
799
sprang4847ae62017-06-27 07:06:52 -0700800 void WaitForEncodedFrame(int64_t expected_ntp_time) {
801 sink_.WaitForEncodedFrame(expected_ntp_time);
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200802 AdvanceTime(TimeDelta::Seconds(1) / max_framerate_);
sprang4847ae62017-06-27 07:06:52 -0700803 }
804
805 bool TimedWaitForEncodedFrame(int64_t expected_ntp_time, int64_t timeout_ms) {
806 bool ok = sink_.TimedWaitForEncodedFrame(expected_ntp_time, timeout_ms);
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200807 AdvanceTime(TimeDelta::Seconds(1) / max_framerate_);
sprang4847ae62017-06-27 07:06:52 -0700808 return ok;
809 }
810
811 void WaitForEncodedFrame(uint32_t expected_width, uint32_t expected_height) {
812 sink_.WaitForEncodedFrame(expected_width, expected_height);
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200813 AdvanceTime(TimeDelta::Seconds(1) / max_framerate_);
sprang4847ae62017-06-27 07:06:52 -0700814 }
815
816 void ExpectDroppedFrame() {
817 sink_.ExpectDroppedFrame();
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200818 AdvanceTime(TimeDelta::Seconds(1) / max_framerate_);
sprang4847ae62017-06-27 07:06:52 -0700819 }
820
821 bool WaitForFrame(int64_t timeout_ms) {
822 bool ok = sink_.WaitForFrame(timeout_ms);
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200823 AdvanceTime(TimeDelta::Seconds(1) / max_framerate_);
sprang4847ae62017-06-27 07:06:52 -0700824 return ok;
825 }
826
perkj26091b12016-09-01 01:17:40 -0700827 class TestEncoder : public test::FakeEncoder {
828 public:
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200829 explicit TestEncoder(TimeController* time_controller)
830 : FakeEncoder(time_controller->GetClock()),
831 time_controller_(time_controller) {
832 RTC_DCHECK(time_controller_);
833 }
perkj26091b12016-09-01 01:17:40 -0700834
asaperssonfab67072017-04-04 05:51:49 -0700835 VideoCodec codec_config() const {
Markus Handella3765182020-07-08 13:13:32 +0200836 MutexLock lock(&mutex_);
perkjfa10b552016-10-02 23:45:26 -0700837 return config_;
838 }
839
840 void BlockNextEncode() {
Markus Handella3765182020-07-08 13:13:32 +0200841 MutexLock lock(&local_mutex_);
perkjfa10b552016-10-02 23:45:26 -0700842 block_next_encode_ = true;
843 }
844
Erik Språngaed30702018-11-05 12:57:17 +0100845 VideoEncoder::EncoderInfo GetEncoderInfo() const override {
Markus Handella3765182020-07-08 13:13:32 +0200846 MutexLock lock(&local_mutex_);
Mirta Dvornicicccc1b572019-01-15 12:42:18 +0100847 EncoderInfo info;
Erik Språngb7cb7b52019-02-26 15:52:33 +0100848 if (initialized_ == EncoderState::kInitialized) {
Mirta Dvornicicccc1b572019-01-15 12:42:18 +0100849 if (quality_scaling_) {
Åsa Perssone644a032019-11-08 15:56:00 +0100850 info.scaling_settings = VideoEncoder::ScalingSettings(
851 kQpLow, kQpHigh, kMinPixelsPerFrame);
Mirta Dvornicicccc1b572019-01-15 12:42:18 +0100852 }
853 info.is_hardware_accelerated = is_hardware_accelerated_;
Åsa Perssonc29cb2c2019-03-25 12:06:59 +0100854 for (int i = 0; i < kMaxSpatialLayers; ++i) {
855 if (temporal_layers_supported_[i]) {
856 int num_layers = temporal_layers_supported_[i].value() ? 2 : 1;
857 info.fps_allocation[i].resize(num_layers);
858 }
859 }
Erik Språngaed30702018-11-05 12:57:17 +0100860 }
Sergey Silkin6456e352019-07-08 17:56:40 +0200861
862 info.resolution_bitrate_limits = resolution_bitrate_limits_;
Rasmus Brandt5cad55b2019-12-19 09:47:11 +0100863 info.requested_resolution_alignment = requested_resolution_alignment_;
Åsa Perssonc5a74ff2020-09-20 17:50:00 +0200864 info.apply_alignment_to_all_simulcast_layers =
865 apply_alignment_to_all_simulcast_layers_;
Evan Shrubsoleb556b082020-10-08 14:56:45 +0200866 info.preferred_pixel_formats = preferred_pixel_formats_;
Erik Språngaed30702018-11-05 12:57:17 +0100867 return info;
kthelgason876222f2016-11-29 01:44:11 -0800868 }
869
Erik Språngb7cb7b52019-02-26 15:52:33 +0100870 int32_t RegisterEncodeCompleteCallback(
871 EncodedImageCallback* callback) override {
Markus Handella3765182020-07-08 13:13:32 +0200872 MutexLock lock(&local_mutex_);
Erik Språngb7cb7b52019-02-26 15:52:33 +0100873 encoded_image_callback_ = callback;
874 return FakeEncoder::RegisterEncodeCompleteCallback(callback);
875 }
876
perkjfa10b552016-10-02 23:45:26 -0700877 void ContinueEncode() { continue_encode_event_.Set(); }
878
879 void CheckLastTimeStampsMatch(int64_t ntp_time_ms,
880 uint32_t timestamp) const {
Markus Handella3765182020-07-08 13:13:32 +0200881 MutexLock lock(&local_mutex_);
perkjfa10b552016-10-02 23:45:26 -0700882 EXPECT_EQ(timestamp_, timestamp);
883 EXPECT_EQ(ntp_time_ms_, ntp_time_ms);
884 }
885
kthelgason2fc52542017-03-03 00:24:41 -0800886 void SetQualityScaling(bool b) {
Markus Handella3765182020-07-08 13:13:32 +0200887 MutexLock lock(&local_mutex_);
kthelgason2fc52542017-03-03 00:24:41 -0800888 quality_scaling_ = b;
889 }
kthelgasonad9010c2017-02-14 00:46:51 -0800890
Rasmus Brandt5cad55b2019-12-19 09:47:11 +0100891 void SetRequestedResolutionAlignment(int requested_resolution_alignment) {
Markus Handella3765182020-07-08 13:13:32 +0200892 MutexLock lock(&local_mutex_);
Rasmus Brandt5cad55b2019-12-19 09:47:11 +0100893 requested_resolution_alignment_ = requested_resolution_alignment;
894 }
895
Åsa Perssonc5a74ff2020-09-20 17:50:00 +0200896 void SetApplyAlignmentToAllSimulcastLayers(bool b) {
897 MutexLock lock(&local_mutex_);
898 apply_alignment_to_all_simulcast_layers_ = b;
899 }
900
Mirta Dvornicicccc1b572019-01-15 12:42:18 +0100901 void SetIsHardwareAccelerated(bool is_hardware_accelerated) {
Markus Handella3765182020-07-08 13:13:32 +0200902 MutexLock lock(&local_mutex_);
Mirta Dvornicicccc1b572019-01-15 12:42:18 +0100903 is_hardware_accelerated_ = is_hardware_accelerated;
904 }
905
Åsa Perssonc29cb2c2019-03-25 12:06:59 +0100906 void SetTemporalLayersSupported(size_t spatial_idx, bool supported) {
907 RTC_DCHECK_LT(spatial_idx, kMaxSpatialLayers);
Markus Handella3765182020-07-08 13:13:32 +0200908 MutexLock lock(&local_mutex_);
Åsa Perssonc29cb2c2019-03-25 12:06:59 +0100909 temporal_layers_supported_[spatial_idx] = supported;
910 }
911
Sergey Silkin6456e352019-07-08 17:56:40 +0200912 void SetResolutionBitrateLimits(
913 std::vector<ResolutionBitrateLimits> thresholds) {
Markus Handella3765182020-07-08 13:13:32 +0200914 MutexLock lock(&local_mutex_);
Sergey Silkin6456e352019-07-08 17:56:40 +0200915 resolution_bitrate_limits_ = thresholds;
916 }
917
sprangfe627f32017-03-29 08:24:59 -0700918 void ForceInitEncodeFailure(bool force_failure) {
Markus Handella3765182020-07-08 13:13:32 +0200919 MutexLock lock(&local_mutex_);
sprangfe627f32017-03-29 08:24:59 -0700920 force_init_encode_failed_ = force_failure;
921 }
922
Niels Möller6bb5ab92019-01-11 11:11:10 +0100923 void SimulateOvershoot(double rate_factor) {
Markus Handella3765182020-07-08 13:13:32 +0200924 MutexLock lock(&local_mutex_);
Niels Möller6bb5ab92019-01-11 11:11:10 +0100925 rate_factor_ = rate_factor;
926 }
927
Erik Språngd7329ca2019-02-21 21:19:53 +0100928 uint32_t GetLastFramerate() const {
Markus Handella3765182020-07-08 13:13:32 +0200929 MutexLock lock(&local_mutex_);
Niels Möller6bb5ab92019-01-11 11:11:10 +0100930 return last_framerate_;
931 }
932
Erik Språngd7329ca2019-02-21 21:19:53 +0100933 VideoFrame::UpdateRect GetLastUpdateRect() const {
Markus Handella3765182020-07-08 13:13:32 +0200934 MutexLock lock(&local_mutex_);
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +0100935 return last_update_rect_;
936 }
937
Niels Möller87e2d782019-03-07 10:18:23 +0100938 const std::vector<VideoFrameType>& LastFrameTypes() const {
Markus Handella3765182020-07-08 13:13:32 +0200939 MutexLock lock(&local_mutex_);
Erik Språngd7329ca2019-02-21 21:19:53 +0100940 return last_frame_types_;
941 }
942
943 void InjectFrame(const VideoFrame& input_image, bool keyframe) {
Niels Möller87e2d782019-03-07 10:18:23 +0100944 const std::vector<VideoFrameType> frame_type = {
Niels Möller8f7ce222019-03-21 15:43:58 +0100945 keyframe ? VideoFrameType::kVideoFrameKey
946 : VideoFrameType::kVideoFrameDelta};
Erik Språngd7329ca2019-02-21 21:19:53 +0100947 {
Markus Handella3765182020-07-08 13:13:32 +0200948 MutexLock lock(&local_mutex_);
Erik Språngd7329ca2019-02-21 21:19:53 +0100949 last_frame_types_ = frame_type;
950 }
Niels Möllerb859b322019-03-07 12:40:01 +0100951 FakeEncoder::Encode(input_image, &frame_type);
Erik Språngd7329ca2019-02-21 21:19:53 +0100952 }
953
Erik Språngb7cb7b52019-02-26 15:52:33 +0100954 void InjectEncodedImage(const EncodedImage& image) {
Markus Handella3765182020-07-08 13:13:32 +0200955 MutexLock lock(&local_mutex_);
Danil Chapovalov2549f172020-08-12 17:30:36 +0200956 encoded_image_callback_->OnEncodedImage(image, nullptr);
Erik Språngb7cb7b52019-02-26 15:52:33 +0100957 }
958
Mirta Dvornicic97910da2020-07-14 15:29:23 +0200959 void SetEncodedImageData(
960 rtc::scoped_refptr<EncodedImageBufferInterface> encoded_image_data) {
Markus Handella3765182020-07-08 13:13:32 +0200961 MutexLock lock(&local_mutex_);
Mirta Dvornicic97910da2020-07-14 15:29:23 +0200962 encoded_image_data_ = encoded_image_data;
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +0200963 }
964
Erik Språngd7329ca2019-02-21 21:19:53 +0100965 void ExpectNullFrame() {
Markus Handella3765182020-07-08 13:13:32 +0200966 MutexLock lock(&local_mutex_);
Erik Språngd7329ca2019-02-21 21:19:53 +0100967 expect_null_frame_ = true;
968 }
969
Erik Språng5056af02019-09-02 15:53:11 +0200970 absl::optional<VideoEncoder::RateControlParameters>
971 GetAndResetLastRateControlSettings() {
972 auto settings = last_rate_control_settings_;
973 last_rate_control_settings_.reset();
974 return settings;
Erik Språngd7329ca2019-02-21 21:19:53 +0100975 }
976
Evan Shrubsole895556e2020-10-05 09:15:13 +0200977 absl::optional<VideoFrameBuffer::Type> GetLastInputPixelFormat() {
978 MutexLock lock(&local_mutex_);
979 return last_input_pixel_format_;
980 }
981
Sergey Silkin5ee69672019-07-02 14:18:34 +0200982 int GetNumEncoderInitializations() const {
Markus Handella3765182020-07-08 13:13:32 +0200983 MutexLock lock(&local_mutex_);
Sergey Silkin5ee69672019-07-02 14:18:34 +0200984 return num_encoder_initializations_;
985 }
986
Evan Shrubsole7c079f62019-09-26 09:55:03 +0200987 int GetNumSetRates() const {
Markus Handella3765182020-07-08 13:13:32 +0200988 MutexLock lock(&local_mutex_);
Evan Shrubsole7c079f62019-09-26 09:55:03 +0200989 return num_set_rates_;
990 }
991
Åsa Perssonc5a74ff2020-09-20 17:50:00 +0200992 VideoCodec video_codec() const {
993 MutexLock lock(&local_mutex_);
994 return video_codec_;
995 }
996
Evan Shrubsoleb556b082020-10-08 14:56:45 +0200997 void SetPreferredPixelFormats(
998 absl::InlinedVector<VideoFrameBuffer::Type, kMaxPreferredPixelFormats>
999 pixel_formats) {
1000 MutexLock lock(&local_mutex_);
1001 preferred_pixel_formats_ = std::move(pixel_formats);
1002 }
1003
perkjfa10b552016-10-02 23:45:26 -07001004 private:
perkj26091b12016-09-01 01:17:40 -07001005 int32_t Encode(const VideoFrame& input_image,
Niels Möller87e2d782019-03-07 10:18:23 +01001006 const std::vector<VideoFrameType>* frame_types) override {
perkj26091b12016-09-01 01:17:40 -07001007 bool block_encode;
1008 {
Markus Handella3765182020-07-08 13:13:32 +02001009 MutexLock lock(&local_mutex_);
Erik Språngd7329ca2019-02-21 21:19:53 +01001010 if (expect_null_frame_) {
1011 EXPECT_EQ(input_image.timestamp(), 0u);
1012 EXPECT_EQ(input_image.width(), 1);
1013 last_frame_types_ = *frame_types;
1014 expect_null_frame_ = false;
1015 } else {
1016 EXPECT_GT(input_image.timestamp(), timestamp_);
1017 EXPECT_GT(input_image.ntp_time_ms(), ntp_time_ms_);
1018 EXPECT_EQ(input_image.timestamp(), input_image.ntp_time_ms() * 90);
1019 }
perkj26091b12016-09-01 01:17:40 -07001020
1021 timestamp_ = input_image.timestamp();
1022 ntp_time_ms_ = input_image.ntp_time_ms();
perkj803d97f2016-11-01 11:45:46 -07001023 last_input_width_ = input_image.width();
1024 last_input_height_ = input_image.height();
perkj26091b12016-09-01 01:17:40 -07001025 block_encode = block_next_encode_;
1026 block_next_encode_ = false;
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001027 last_update_rect_ = input_image.update_rect();
Erik Språngd7329ca2019-02-21 21:19:53 +01001028 last_frame_types_ = *frame_types;
Evan Shrubsole895556e2020-10-05 09:15:13 +02001029 last_input_pixel_format_ = input_image.video_frame_buffer()->type();
perkj26091b12016-09-01 01:17:40 -07001030 }
Niels Möllerb859b322019-03-07 12:40:01 +01001031 int32_t result = FakeEncoder::Encode(input_image, frame_types);
perkj26091b12016-09-01 01:17:40 -07001032 if (block_encode)
perkja49cbd32016-09-16 07:53:41 -07001033 EXPECT_TRUE(continue_encode_event_.Wait(kDefaultTimeoutMs));
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02001034
perkj26091b12016-09-01 01:17:40 -07001035 return result;
1036 }
1037
Niels Möller08ae7ce2020-09-23 15:58:12 +02001038 CodecSpecificInfo EncodeHook(
1039 EncodedImage& encoded_image,
1040 rtc::scoped_refptr<EncodedImageBuffer> buffer) override {
Danil Chapovalov2549f172020-08-12 17:30:36 +02001041 CodecSpecificInfo codec_specific;
Mirta Dvornicic97910da2020-07-14 15:29:23 +02001042 {
1043 MutexLock lock(&mutex_);
Danil Chapovalov2549f172020-08-12 17:30:36 +02001044 codec_specific.codecType = config_.codecType;
Mirta Dvornicic97910da2020-07-14 15:29:23 +02001045 }
1046 MutexLock lock(&local_mutex_);
1047 if (encoded_image_data_) {
Danil Chapovalov2549f172020-08-12 17:30:36 +02001048 encoded_image.SetEncodedData(encoded_image_data_);
Mirta Dvornicic97910da2020-07-14 15:29:23 +02001049 }
Danil Chapovalov2549f172020-08-12 17:30:36 +02001050 return codec_specific;
Mirta Dvornicic97910da2020-07-14 15:29:23 +02001051 }
1052
sprangfe627f32017-03-29 08:24:59 -07001053 int32_t InitEncode(const VideoCodec* config,
Elad Alon370f93a2019-06-11 14:57:57 +02001054 const Settings& settings) override {
1055 int res = FakeEncoder::InitEncode(config, settings);
Sergey Silkin5ee69672019-07-02 14:18:34 +02001056
Markus Handella3765182020-07-08 13:13:32 +02001057 MutexLock lock(&local_mutex_);
Erik Språngb7cb7b52019-02-26 15:52:33 +01001058 EXPECT_EQ(initialized_, EncoderState::kUninitialized);
Sergey Silkin5ee69672019-07-02 14:18:34 +02001059
1060 ++num_encoder_initializations_;
Åsa Perssonc5a74ff2020-09-20 17:50:00 +02001061 video_codec_ = *config;
Sergey Silkin5ee69672019-07-02 14:18:34 +02001062
Erik Språng82fad3d2018-03-21 09:57:23 +01001063 if (config->codecType == kVideoCodecVP8) {
sprangfe627f32017-03-29 08:24:59 -07001064 // Simulate setting up temporal layers, in order to validate the life
1065 // cycle of these objects.
Elad Aloncde8ab22019-03-20 11:56:20 +01001066 Vp8TemporalLayersFactory factory;
Elad Alon45befc52019-07-02 11:20:09 +02001067 frame_buffer_controller_ =
1068 factory.Create(*config, settings, &fec_controller_override_);
sprangfe627f32017-03-29 08:24:59 -07001069 }
Erik Språngb7cb7b52019-02-26 15:52:33 +01001070 if (force_init_encode_failed_) {
1071 initialized_ = EncoderState::kInitializationFailed;
sprangfe627f32017-03-29 08:24:59 -07001072 return -1;
Erik Språngb7cb7b52019-02-26 15:52:33 +01001073 }
Mirta Dvornicicccc1b572019-01-15 12:42:18 +01001074
Erik Språngb7cb7b52019-02-26 15:52:33 +01001075 initialized_ = EncoderState::kInitialized;
sprangfe627f32017-03-29 08:24:59 -07001076 return res;
1077 }
1078
Erik Språngb7cb7b52019-02-26 15:52:33 +01001079 int32_t Release() override {
Markus Handella3765182020-07-08 13:13:32 +02001080 MutexLock lock(&local_mutex_);
Erik Språngb7cb7b52019-02-26 15:52:33 +01001081 EXPECT_NE(initialized_, EncoderState::kUninitialized);
1082 initialized_ = EncoderState::kUninitialized;
1083 return FakeEncoder::Release();
1084 }
1085
Erik Språng16cb8f52019-04-12 13:59:09 +02001086 void SetRates(const RateControlParameters& parameters) {
Markus Handella3765182020-07-08 13:13:32 +02001087 MutexLock lock(&local_mutex_);
Evan Shrubsole7c079f62019-09-26 09:55:03 +02001088 num_set_rates_++;
Niels Möller6bb5ab92019-01-11 11:11:10 +01001089 VideoBitrateAllocation adjusted_rate_allocation;
1090 for (size_t si = 0; si < kMaxSpatialLayers; ++si) {
1091 for (size_t ti = 0; ti < kMaxTemporalStreams; ++ti) {
Erik Språng16cb8f52019-04-12 13:59:09 +02001092 if (parameters.bitrate.HasBitrate(si, ti)) {
Niels Möller6bb5ab92019-01-11 11:11:10 +01001093 adjusted_rate_allocation.SetBitrate(
1094 si, ti,
Erik Språng16cb8f52019-04-12 13:59:09 +02001095 static_cast<uint32_t>(parameters.bitrate.GetBitrate(si, ti) *
Niels Möller6bb5ab92019-01-11 11:11:10 +01001096 rate_factor_));
1097 }
1098 }
1099 }
Erik Språng16cb8f52019-04-12 13:59:09 +02001100 last_framerate_ = static_cast<uint32_t>(parameters.framerate_fps + 0.5);
Erik Språng5056af02019-09-02 15:53:11 +02001101 last_rate_control_settings_ = parameters;
Erik Språng16cb8f52019-04-12 13:59:09 +02001102 RateControlParameters adjusted_paramters = parameters;
1103 adjusted_paramters.bitrate = adjusted_rate_allocation;
1104 FakeEncoder::SetRates(adjusted_paramters);
Niels Möller6bb5ab92019-01-11 11:11:10 +01001105 }
1106
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02001107 TimeController* const time_controller_;
Markus Handella3765182020-07-08 13:13:32 +02001108 mutable Mutex local_mutex_;
Erik Språngb7cb7b52019-02-26 15:52:33 +01001109 enum class EncoderState {
1110 kUninitialized,
1111 kInitializationFailed,
1112 kInitialized
Markus Handella3765182020-07-08 13:13:32 +02001113 } initialized_ RTC_GUARDED_BY(local_mutex_) = EncoderState::kUninitialized;
1114 bool block_next_encode_ RTC_GUARDED_BY(local_mutex_) = false;
perkj26091b12016-09-01 01:17:40 -07001115 rtc::Event continue_encode_event_;
Markus Handella3765182020-07-08 13:13:32 +02001116 uint32_t timestamp_ RTC_GUARDED_BY(local_mutex_) = 0;
1117 int64_t ntp_time_ms_ RTC_GUARDED_BY(local_mutex_) = 0;
1118 int last_input_width_ RTC_GUARDED_BY(local_mutex_) = 0;
1119 int last_input_height_ RTC_GUARDED_BY(local_mutex_) = 0;
1120 bool quality_scaling_ RTC_GUARDED_BY(local_mutex_) = true;
1121 int requested_resolution_alignment_ RTC_GUARDED_BY(local_mutex_) = 1;
Åsa Perssonc5a74ff2020-09-20 17:50:00 +02001122 bool apply_alignment_to_all_simulcast_layers_ RTC_GUARDED_BY(local_mutex_) =
1123 false;
Markus Handella3765182020-07-08 13:13:32 +02001124 bool is_hardware_accelerated_ RTC_GUARDED_BY(local_mutex_) = false;
Mirta Dvornicic97910da2020-07-14 15:29:23 +02001125 rtc::scoped_refptr<EncodedImageBufferInterface> encoded_image_data_
1126 RTC_GUARDED_BY(local_mutex_);
Elad Aloncde8ab22019-03-20 11:56:20 +01001127 std::unique_ptr<Vp8FrameBufferController> frame_buffer_controller_
Markus Handella3765182020-07-08 13:13:32 +02001128 RTC_GUARDED_BY(local_mutex_);
Åsa Perssonc29cb2c2019-03-25 12:06:59 +01001129 absl::optional<bool>
1130 temporal_layers_supported_[kMaxSpatialLayers] RTC_GUARDED_BY(
Markus Handella3765182020-07-08 13:13:32 +02001131 local_mutex_);
1132 bool force_init_encode_failed_ RTC_GUARDED_BY(local_mutex_) = false;
1133 double rate_factor_ RTC_GUARDED_BY(local_mutex_) = 1.0;
1134 uint32_t last_framerate_ RTC_GUARDED_BY(local_mutex_) = 0;
Erik Språng5056af02019-09-02 15:53:11 +02001135 absl::optional<VideoEncoder::RateControlParameters>
1136 last_rate_control_settings_;
Markus Handella3765182020-07-08 13:13:32 +02001137 VideoFrame::UpdateRect last_update_rect_ RTC_GUARDED_BY(local_mutex_) = {
1138 0, 0, 0, 0};
Niels Möller87e2d782019-03-07 10:18:23 +01001139 std::vector<VideoFrameType> last_frame_types_;
Erik Språngd7329ca2019-02-21 21:19:53 +01001140 bool expect_null_frame_ = false;
Markus Handella3765182020-07-08 13:13:32 +02001141 EncodedImageCallback* encoded_image_callback_ RTC_GUARDED_BY(local_mutex_) =
1142 nullptr;
Evan Shrubsolefb862742020-03-16 16:18:36 +01001143 NiceMock<MockFecControllerOverride> fec_controller_override_;
Markus Handella3765182020-07-08 13:13:32 +02001144 int num_encoder_initializations_ RTC_GUARDED_BY(local_mutex_) = 0;
Sergey Silkin6456e352019-07-08 17:56:40 +02001145 std::vector<ResolutionBitrateLimits> resolution_bitrate_limits_
Markus Handella3765182020-07-08 13:13:32 +02001146 RTC_GUARDED_BY(local_mutex_);
1147 int num_set_rates_ RTC_GUARDED_BY(local_mutex_) = 0;
Åsa Perssonc5a74ff2020-09-20 17:50:00 +02001148 VideoCodec video_codec_ RTC_GUARDED_BY(local_mutex_);
Evan Shrubsole895556e2020-10-05 09:15:13 +02001149 absl::optional<VideoFrameBuffer::Type> last_input_pixel_format_
1150 RTC_GUARDED_BY(local_mutex_);
Evan Shrubsoleb556b082020-10-08 14:56:45 +02001151 absl::InlinedVector<VideoFrameBuffer::Type, kMaxPreferredPixelFormats>
1152 preferred_pixel_formats_ RTC_GUARDED_BY(local_mutex_);
perkj26091b12016-09-01 01:17:40 -07001153 };
1154
mflodmancc3d4422017-08-03 08:27:51 -07001155 class TestSink : public VideoStreamEncoder::EncoderSink {
perkj26091b12016-09-01 01:17:40 -07001156 public:
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02001157 TestSink(TimeController* time_controller, TestEncoder* test_encoder)
1158 : time_controller_(time_controller), test_encoder_(test_encoder) {
1159 RTC_DCHECK(time_controller_);
1160 }
perkj26091b12016-09-01 01:17:40 -07001161
perkj26091b12016-09-01 01:17:40 -07001162 void WaitForEncodedFrame(int64_t expected_ntp_time) {
sprang4847ae62017-06-27 07:06:52 -07001163 EXPECT_TRUE(
1164 TimedWaitForEncodedFrame(expected_ntp_time, kDefaultTimeoutMs));
1165 }
1166
1167 bool TimedWaitForEncodedFrame(int64_t expected_ntp_time,
1168 int64_t timeout_ms) {
perkj26091b12016-09-01 01:17:40 -07001169 uint32_t timestamp = 0;
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02001170 if (!WaitForFrame(timeout_ms))
sprang4847ae62017-06-27 07:06:52 -07001171 return false;
perkj26091b12016-09-01 01:17:40 -07001172 {
Markus Handella3765182020-07-08 13:13:32 +02001173 MutexLock lock(&mutex_);
sprangb1ca0732017-02-01 08:38:12 -08001174 timestamp = last_timestamp_;
perkj26091b12016-09-01 01:17:40 -07001175 }
1176 test_encoder_->CheckLastTimeStampsMatch(expected_ntp_time, timestamp);
sprang4847ae62017-06-27 07:06:52 -07001177 return true;
perkj26091b12016-09-01 01:17:40 -07001178 }
1179
sprangb1ca0732017-02-01 08:38:12 -08001180 void WaitForEncodedFrame(uint32_t expected_width,
1181 uint32_t expected_height) {
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02001182 EXPECT_TRUE(WaitForFrame(kDefaultTimeoutMs));
Åsa Perssonc74d8da2017-12-04 14:13:56 +01001183 CheckLastFrameSizeMatches(expected_width, expected_height);
sprangc5d62e22017-04-02 23:53:04 -07001184 }
1185
Åsa Perssonc74d8da2017-12-04 14:13:56 +01001186 void CheckLastFrameSizeMatches(uint32_t expected_width,
sprangc5d62e22017-04-02 23:53:04 -07001187 uint32_t expected_height) {
sprangb1ca0732017-02-01 08:38:12 -08001188 uint32_t width = 0;
1189 uint32_t height = 0;
sprangb1ca0732017-02-01 08:38:12 -08001190 {
Markus Handella3765182020-07-08 13:13:32 +02001191 MutexLock lock(&mutex_);
sprangb1ca0732017-02-01 08:38:12 -08001192 width = last_width_;
1193 height = last_height_;
1194 }
1195 EXPECT_EQ(expected_height, height);
1196 EXPECT_EQ(expected_width, width);
1197 }
1198
Ilya Nikolaevskiyba96e2f2019-06-04 15:15:14 +02001199 void CheckLastFrameRotationMatches(VideoRotation expected_rotation) {
1200 VideoRotation rotation;
1201 {
Markus Handella3765182020-07-08 13:13:32 +02001202 MutexLock lock(&mutex_);
Ilya Nikolaevskiyba96e2f2019-06-04 15:15:14 +02001203 rotation = last_rotation_;
1204 }
1205 EXPECT_EQ(expected_rotation, rotation);
1206 }
1207
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02001208 void ExpectDroppedFrame() { EXPECT_FALSE(WaitForFrame(100)); }
kthelgason2bc68642017-02-07 07:02:22 -08001209
sprangc5d62e22017-04-02 23:53:04 -07001210 bool WaitForFrame(int64_t timeout_ms) {
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02001211 RTC_DCHECK(time_controller_->GetMainThread()->IsCurrent());
1212 bool ret = encoded_frame_event_.Wait(timeout_ms);
1213 time_controller_->AdvanceTime(TimeDelta::Millis(0));
1214 return ret;
sprangc5d62e22017-04-02 23:53:04 -07001215 }
1216
perkj26091b12016-09-01 01:17:40 -07001217 void SetExpectNoFrames() {
Markus Handella3765182020-07-08 13:13:32 +02001218 MutexLock lock(&mutex_);
perkj26091b12016-09-01 01:17:40 -07001219 expect_frames_ = false;
1220 }
1221
asaperssonfab67072017-04-04 05:51:49 -07001222 int number_of_reconfigurations() const {
Markus Handella3765182020-07-08 13:13:32 +02001223 MutexLock lock(&mutex_);
Per512ecb32016-09-23 15:52:06 +02001224 return number_of_reconfigurations_;
1225 }
1226
asaperssonfab67072017-04-04 05:51:49 -07001227 int last_min_transmit_bitrate() const {
Markus Handella3765182020-07-08 13:13:32 +02001228 MutexLock lock(&mutex_);
Per512ecb32016-09-23 15:52:06 +02001229 return min_transmit_bitrate_bps_;
1230 }
1231
Erik Språngd7329ca2019-02-21 21:19:53 +01001232 void SetNumExpectedLayers(size_t num_layers) {
Markus Handella3765182020-07-08 13:13:32 +02001233 MutexLock lock(&mutex_);
Erik Språngd7329ca2019-02-21 21:19:53 +01001234 num_expected_layers_ = num_layers;
1235 }
1236
Erik Språngb7cb7b52019-02-26 15:52:33 +01001237 int64_t GetLastCaptureTimeMs() const {
Markus Handella3765182020-07-08 13:13:32 +02001238 MutexLock lock(&mutex_);
Erik Språngb7cb7b52019-02-26 15:52:33 +01001239 return last_capture_time_ms_;
1240 }
1241
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +02001242 std::vector<uint8_t> GetLastEncodedImageData() {
Markus Handella3765182020-07-08 13:13:32 +02001243 MutexLock lock(&mutex_);
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +02001244 return std::move(last_encoded_image_data_);
1245 }
1246
Per Kjellanderdcef6412020-10-07 15:09:05 +02001247 VideoBitrateAllocation GetLastVideoBitrateAllocation() {
1248 MutexLock lock(&mutex_);
1249 return last_bitrate_allocation_;
1250 }
1251
1252 int number_of_bitrate_allocations() const {
1253 MutexLock lock(&mutex_);
1254 return number_of_bitrate_allocations_;
1255 }
1256
Per Kjellandera9434842020-10-15 17:53:22 +02001257 VideoLayersAllocation GetLastVideoLayersAllocation() {
1258 MutexLock lock(&mutex_);
1259 return last_layers_allocation_;
1260 }
1261
1262 int number_of_layers_allocations() const {
1263 MutexLock lock(&mutex_);
1264 return number_of_layers_allocations_;
1265 }
1266
perkj26091b12016-09-01 01:17:40 -07001267 private:
sergeyu2cb155a2016-11-04 11:39:29 -07001268 Result OnEncodedImage(
1269 const EncodedImage& encoded_image,
Danil Chapovalov2549f172020-08-12 17:30:36 +02001270 const CodecSpecificInfo* codec_specific_info) override {
Markus Handella3765182020-07-08 13:13:32 +02001271 MutexLock lock(&mutex_);
Per512ecb32016-09-23 15:52:06 +02001272 EXPECT_TRUE(expect_frames_);
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +02001273 last_encoded_image_data_ = std::vector<uint8_t>(
1274 encoded_image.data(), encoded_image.data() + encoded_image.size());
Erik Språngd7329ca2019-02-21 21:19:53 +01001275 uint32_t timestamp = encoded_image.Timestamp();
1276 if (last_timestamp_ != timestamp) {
1277 num_received_layers_ = 1;
1278 } else {
1279 ++num_received_layers_;
1280 }
1281 last_timestamp_ = timestamp;
Erik Språngb7cb7b52019-02-26 15:52:33 +01001282 last_capture_time_ms_ = encoded_image.capture_time_ms_;
sprangb1ca0732017-02-01 08:38:12 -08001283 last_width_ = encoded_image._encodedWidth;
1284 last_height_ = encoded_image._encodedHeight;
Ilya Nikolaevskiyba96e2f2019-06-04 15:15:14 +02001285 last_rotation_ = encoded_image.rotation_;
Erik Språngd7329ca2019-02-21 21:19:53 +01001286 if (num_received_layers_ == num_expected_layers_) {
1287 encoded_frame_event_.Set();
1288 }
sprangb1ca0732017-02-01 08:38:12 -08001289 return Result(Result::OK, last_timestamp_);
Per512ecb32016-09-23 15:52:06 +02001290 }
1291
Rasmus Brandtc402dbe2019-02-04 11:09:46 +01001292 void OnEncoderConfigurationChanged(
1293 std::vector<VideoStream> streams,
Ilya Nikolaevskiy93be66c2020-04-02 14:10:27 +02001294 bool is_svc,
Rasmus Brandtc402dbe2019-02-04 11:09:46 +01001295 VideoEncoderConfig::ContentType content_type,
1296 int min_transmit_bitrate_bps) override {
Markus Handella3765182020-07-08 13:13:32 +02001297 MutexLock lock(&mutex_);
Per512ecb32016-09-23 15:52:06 +02001298 ++number_of_reconfigurations_;
1299 min_transmit_bitrate_bps_ = min_transmit_bitrate_bps;
1300 }
1301
Per Kjellanderdcef6412020-10-07 15:09:05 +02001302 void OnBitrateAllocationUpdated(
1303 const VideoBitrateAllocation& allocation) override {
1304 MutexLock lock(&mutex_);
1305 ++number_of_bitrate_allocations_;
1306 last_bitrate_allocation_ = allocation;
1307 }
1308
Per Kjellandera9434842020-10-15 17:53:22 +02001309 void OnVideoLayersAllocationUpdated(
1310 VideoLayersAllocation allocation) override {
1311 MutexLock lock(&mutex_);
1312 ++number_of_layers_allocations_;
1313 last_layers_allocation_ = allocation;
1314 rtc::StringBuilder log;
1315 for (const auto& layer : allocation.active_spatial_layers) {
1316 log << layer.width << "x" << layer.height << "@" << layer.frame_rate_fps
1317 << "[";
1318 for (const auto target_bitrate :
1319 layer.target_bitrate_per_temporal_layer) {
1320 log << target_bitrate.kbps() << ",";
1321 }
1322 log << "]";
1323 }
1324 RTC_DLOG(INFO) << "OnVideoLayersAllocationUpdated " << log.str();
1325 }
1326
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02001327 TimeController* const time_controller_;
Markus Handella3765182020-07-08 13:13:32 +02001328 mutable Mutex mutex_;
perkj26091b12016-09-01 01:17:40 -07001329 TestEncoder* test_encoder_;
1330 rtc::Event encoded_frame_event_;
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +02001331 std::vector<uint8_t> last_encoded_image_data_;
sprangb1ca0732017-02-01 08:38:12 -08001332 uint32_t last_timestamp_ = 0;
Erik Språngb7cb7b52019-02-26 15:52:33 +01001333 int64_t last_capture_time_ms_ = 0;
sprangb1ca0732017-02-01 08:38:12 -08001334 uint32_t last_height_ = 0;
1335 uint32_t last_width_ = 0;
Ilya Nikolaevskiyba96e2f2019-06-04 15:15:14 +02001336 VideoRotation last_rotation_ = kVideoRotation_0;
Erik Språngd7329ca2019-02-21 21:19:53 +01001337 size_t num_expected_layers_ = 1;
1338 size_t num_received_layers_ = 0;
perkj26091b12016-09-01 01:17:40 -07001339 bool expect_frames_ = true;
Per512ecb32016-09-23 15:52:06 +02001340 int number_of_reconfigurations_ = 0;
1341 int min_transmit_bitrate_bps_ = 0;
Per Kjellanderdcef6412020-10-07 15:09:05 +02001342 VideoBitrateAllocation last_bitrate_allocation_ RTC_GUARDED_BY(&mutex_);
1343 int number_of_bitrate_allocations_ RTC_GUARDED_BY(&mutex_) = 0;
Per Kjellandera9434842020-10-15 17:53:22 +02001344 VideoLayersAllocation last_layers_allocation_ RTC_GUARDED_BY(&mutex_);
1345 int number_of_layers_allocations_ RTC_GUARDED_BY(&mutex_) = 0;
perkj26091b12016-09-01 01:17:40 -07001346 };
1347
Sergey Silkin5ee69672019-07-02 14:18:34 +02001348 class VideoBitrateAllocatorProxyFactory
1349 : public VideoBitrateAllocatorFactory {
1350 public:
1351 VideoBitrateAllocatorProxyFactory()
1352 : bitrate_allocator_factory_(
1353 CreateBuiltinVideoBitrateAllocatorFactory()) {}
1354
1355 std::unique_ptr<VideoBitrateAllocator> CreateVideoBitrateAllocator(
1356 const VideoCodec& codec) override {
Markus Handella3765182020-07-08 13:13:32 +02001357 MutexLock lock(&mutex_);
Sergey Silkin5ee69672019-07-02 14:18:34 +02001358 codec_config_ = codec;
1359 return bitrate_allocator_factory_->CreateVideoBitrateAllocator(codec);
1360 }
1361
1362 VideoCodec codec_config() const {
Markus Handella3765182020-07-08 13:13:32 +02001363 MutexLock lock(&mutex_);
Sergey Silkin5ee69672019-07-02 14:18:34 +02001364 return codec_config_;
1365 }
1366
1367 private:
1368 std::unique_ptr<VideoBitrateAllocatorFactory> bitrate_allocator_factory_;
1369
Markus Handella3765182020-07-08 13:13:32 +02001370 mutable Mutex mutex_;
1371 VideoCodec codec_config_ RTC_GUARDED_BY(mutex_);
Sergey Silkin5ee69672019-07-02 14:18:34 +02001372 };
1373
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02001374 Clock* clock() { return time_controller_.GetClock(); }
1375 void AdvanceTime(TimeDelta duration) {
1376 time_controller_.AdvanceTime(duration);
1377 }
1378
1379 int64_t CurrentTimeMs() { return clock()->CurrentTime().ms(); }
1380
1381 protected:
1382 virtual TaskQueueFactory* GetTaskQueueFactory() {
1383 return time_controller_.GetTaskQueueFactory();
1384 }
1385
1386 GlobalSimulatedTimeController time_controller_{Timestamp::Micros(1234)};
perkj26091b12016-09-01 01:17:40 -07001387 VideoSendStream::Config video_send_config_;
Erik Språng08127a92016-11-16 16:41:30 +01001388 VideoEncoderConfig video_encoder_config_;
Per512ecb32016-09-23 15:52:06 +02001389 int codec_width_;
1390 int codec_height_;
sprang4847ae62017-06-27 07:06:52 -07001391 int max_framerate_;
perkj26091b12016-09-01 01:17:40 -07001392 TestEncoder fake_encoder_;
Niels Möllercbcbc222018-09-28 09:07:24 +02001393 test::VideoEncoderProxyFactory encoder_factory_;
Sergey Silkin5ee69672019-07-02 14:18:34 +02001394 VideoBitrateAllocatorProxyFactory bitrate_allocator_factory_;
sprangc5d62e22017-04-02 23:53:04 -07001395 std::unique_ptr<MockableSendStatisticsProxy> stats_proxy_;
perkj26091b12016-09-01 01:17:40 -07001396 TestSink sink_;
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02001397 AdaptingFrameForwarder video_source_{&time_controller_};
mflodmancc3d4422017-08-03 08:27:51 -07001398 std::unique_ptr<VideoStreamEncoderUnderTest> video_stream_encoder_;
perkj26091b12016-09-01 01:17:40 -07001399};
1400
mflodmancc3d4422017-08-03 08:27:51 -07001401TEST_F(VideoStreamEncoderTest, EncodeOneFrame) {
Henrik Boström381d1092020-05-12 18:49:07 +02001402 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001403 DataRate::BitsPerSec(kTargetBitrateBps),
1404 DataRate::BitsPerSec(kTargetBitrateBps),
1405 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Niels Möllerc572ff32018-11-07 08:43:50 +01001406 rtc::Event frame_destroyed_event;
perkja49cbd32016-09-16 07:53:41 -07001407 video_source_.IncomingCapturedFrame(CreateFrame(1, &frame_destroyed_event));
sprang4847ae62017-06-27 07:06:52 -07001408 WaitForEncodedFrame(1);
perkja49cbd32016-09-16 07:53:41 -07001409 EXPECT_TRUE(frame_destroyed_event.Wait(kDefaultTimeoutMs));
mflodmancc3d4422017-08-03 08:27:51 -07001410 video_stream_encoder_->Stop();
perkj26091b12016-09-01 01:17:40 -07001411}
1412
mflodmancc3d4422017-08-03 08:27:51 -07001413TEST_F(VideoStreamEncoderTest, DropsFramesBeforeFirstOnBitrateUpdated) {
perkj26091b12016-09-01 01:17:40 -07001414 // Dropped since no target bitrate has been set.
Niels Möllerc572ff32018-11-07 08:43:50 +01001415 rtc::Event frame_destroyed_event;
Sebastian Janssona3177052018-04-10 13:05:49 +02001416 // The encoder will cache up to one frame for a short duration. Adding two
1417 // frames means that the first frame will be dropped and the second frame will
1418 // be sent when the encoder is enabled.
perkja49cbd32016-09-16 07:53:41 -07001419 video_source_.IncomingCapturedFrame(CreateFrame(1, &frame_destroyed_event));
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02001420 AdvanceTime(TimeDelta::Millis(10));
Sebastian Janssona3177052018-04-10 13:05:49 +02001421 video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
perkja49cbd32016-09-16 07:53:41 -07001422 EXPECT_TRUE(frame_destroyed_event.Wait(kDefaultTimeoutMs));
perkj26091b12016-09-01 01:17:40 -07001423
Henrik Boström381d1092020-05-12 18:49:07 +02001424 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001425 DataRate::BitsPerSec(kTargetBitrateBps),
1426 DataRate::BitsPerSec(kTargetBitrateBps),
1427 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
perkj26091b12016-09-01 01:17:40 -07001428
Sebastian Janssona3177052018-04-10 13:05:49 +02001429 // The pending frame should be received.
sprang4847ae62017-06-27 07:06:52 -07001430 WaitForEncodedFrame(2);
Sebastian Janssona3177052018-04-10 13:05:49 +02001431 video_source_.IncomingCapturedFrame(CreateFrame(3, nullptr));
1432
1433 WaitForEncodedFrame(3);
mflodmancc3d4422017-08-03 08:27:51 -07001434 video_stream_encoder_->Stop();
perkj26091b12016-09-01 01:17:40 -07001435}
1436
mflodmancc3d4422017-08-03 08:27:51 -07001437TEST_F(VideoStreamEncoderTest, DropsFramesWhenRateSetToZero) {
Henrik Boström381d1092020-05-12 18:49:07 +02001438 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001439 DataRate::BitsPerSec(kTargetBitrateBps),
1440 DataRate::BitsPerSec(kTargetBitrateBps),
1441 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
perkja49cbd32016-09-16 07:53:41 -07001442 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
sprang4847ae62017-06-27 07:06:52 -07001443 WaitForEncodedFrame(1);
perkj26091b12016-09-01 01:17:40 -07001444
Henrik Boström381d1092020-05-12 18:49:07 +02001445 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
1446 DataRate::BitsPerSec(0), DataRate::BitsPerSec(0), DataRate::BitsPerSec(0),
1447 0, 0, 0);
Sebastian Janssona3177052018-04-10 13:05:49 +02001448 // The encoder will cache up to one frame for a short duration. Adding two
1449 // frames means that the first frame will be dropped and the second frame will
1450 // be sent when the encoder is resumed.
perkja49cbd32016-09-16 07:53:41 -07001451 video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
Sebastian Janssona3177052018-04-10 13:05:49 +02001452 video_source_.IncomingCapturedFrame(CreateFrame(3, nullptr));
perkj26091b12016-09-01 01:17:40 -07001453
Henrik Boström381d1092020-05-12 18:49:07 +02001454 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001455 DataRate::BitsPerSec(kTargetBitrateBps),
1456 DataRate::BitsPerSec(kTargetBitrateBps),
1457 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
sprang4847ae62017-06-27 07:06:52 -07001458 WaitForEncodedFrame(3);
Sebastian Janssona3177052018-04-10 13:05:49 +02001459 video_source_.IncomingCapturedFrame(CreateFrame(4, nullptr));
1460 WaitForEncodedFrame(4);
mflodmancc3d4422017-08-03 08:27:51 -07001461 video_stream_encoder_->Stop();
perkj26091b12016-09-01 01:17:40 -07001462}
1463
mflodmancc3d4422017-08-03 08:27:51 -07001464TEST_F(VideoStreamEncoderTest, DropsFramesWithSameOrOldNtpTimestamp) {
Henrik Boström381d1092020-05-12 18:49:07 +02001465 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001466 DataRate::BitsPerSec(kTargetBitrateBps),
1467 DataRate::BitsPerSec(kTargetBitrateBps),
1468 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
perkja49cbd32016-09-16 07:53:41 -07001469 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
sprang4847ae62017-06-27 07:06:52 -07001470 WaitForEncodedFrame(1);
perkj26091b12016-09-01 01:17:40 -07001471
1472 // This frame will be dropped since it has the same ntp timestamp.
perkja49cbd32016-09-16 07:53:41 -07001473 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
perkj26091b12016-09-01 01:17:40 -07001474
perkja49cbd32016-09-16 07:53:41 -07001475 video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
sprang4847ae62017-06-27 07:06:52 -07001476 WaitForEncodedFrame(2);
mflodmancc3d4422017-08-03 08:27:51 -07001477 video_stream_encoder_->Stop();
perkj26091b12016-09-01 01:17:40 -07001478}
1479
mflodmancc3d4422017-08-03 08:27:51 -07001480TEST_F(VideoStreamEncoderTest, DropsFrameAfterStop) {
Henrik Boström381d1092020-05-12 18:49:07 +02001481 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001482 DataRate::BitsPerSec(kTargetBitrateBps),
1483 DataRate::BitsPerSec(kTargetBitrateBps),
1484 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
perkj26091b12016-09-01 01:17:40 -07001485
perkja49cbd32016-09-16 07:53:41 -07001486 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
sprang4847ae62017-06-27 07:06:52 -07001487 WaitForEncodedFrame(1);
perkj26091b12016-09-01 01:17:40 -07001488
mflodmancc3d4422017-08-03 08:27:51 -07001489 video_stream_encoder_->Stop();
perkj26091b12016-09-01 01:17:40 -07001490 sink_.SetExpectNoFrames();
Niels Möllerc572ff32018-11-07 08:43:50 +01001491 rtc::Event frame_destroyed_event;
perkja49cbd32016-09-16 07:53:41 -07001492 video_source_.IncomingCapturedFrame(CreateFrame(2, &frame_destroyed_event));
1493 EXPECT_TRUE(frame_destroyed_event.Wait(kDefaultTimeoutMs));
perkj26091b12016-09-01 01:17:40 -07001494}
1495
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02001496class VideoStreamEncoderBlockedTest : public VideoStreamEncoderTest {
1497 public:
1498 VideoStreamEncoderBlockedTest() {}
1499
1500 TaskQueueFactory* GetTaskQueueFactory() override {
1501 return task_queue_factory_.get();
1502 }
1503
1504 private:
1505 std::unique_ptr<TaskQueueFactory> task_queue_factory_ =
1506 CreateDefaultTaskQueueFactory();
1507};
1508
1509TEST_F(VideoStreamEncoderBlockedTest, DropsPendingFramesOnSlowEncode) {
Henrik Boström381d1092020-05-12 18:49:07 +02001510 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001511 DataRate::BitsPerSec(kTargetBitrateBps),
1512 DataRate::BitsPerSec(kTargetBitrateBps),
1513 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
perkj26091b12016-09-01 01:17:40 -07001514
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02001515 int dropped_count = 0;
1516 stats_proxy_->SetDroppedFrameCallback(
1517 [&dropped_count](VideoStreamEncoderObserver::DropReason) {
1518 ++dropped_count;
1519 });
1520
perkj26091b12016-09-01 01:17:40 -07001521 fake_encoder_.BlockNextEncode();
perkja49cbd32016-09-16 07:53:41 -07001522 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
sprang4847ae62017-06-27 07:06:52 -07001523 WaitForEncodedFrame(1);
perkj26091b12016-09-01 01:17:40 -07001524 // Here, the encoder thread will be blocked in the TestEncoder waiting for a
1525 // call to ContinueEncode.
perkja49cbd32016-09-16 07:53:41 -07001526 video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
1527 video_source_.IncomingCapturedFrame(CreateFrame(3, nullptr));
perkj26091b12016-09-01 01:17:40 -07001528 fake_encoder_.ContinueEncode();
sprang4847ae62017-06-27 07:06:52 -07001529 WaitForEncodedFrame(3);
perkj26091b12016-09-01 01:17:40 -07001530
mflodmancc3d4422017-08-03 08:27:51 -07001531 video_stream_encoder_->Stop();
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02001532
1533 EXPECT_EQ(1, dropped_count);
perkj26091b12016-09-01 01:17:40 -07001534}
1535
Noah Richards51db4212019-06-12 06:59:12 -07001536TEST_F(VideoStreamEncoderTest, DropFrameWithFailedI420Conversion) {
Henrik Boström381d1092020-05-12 18:49:07 +02001537 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001538 DataRate::BitsPerSec(kTargetBitrateBps),
1539 DataRate::BitsPerSec(kTargetBitrateBps),
1540 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Noah Richards51db4212019-06-12 06:59:12 -07001541
1542 rtc::Event frame_destroyed_event;
1543 video_source_.IncomingCapturedFrame(
1544 CreateFakeNativeFrame(1, &frame_destroyed_event));
1545 ExpectDroppedFrame();
1546 EXPECT_TRUE(frame_destroyed_event.Wait(kDefaultTimeoutMs));
1547 video_stream_encoder_->Stop();
1548}
1549
1550TEST_F(VideoStreamEncoderTest, DropFrameWithFailedI420ConversionWithCrop) {
1551 // Use the cropping factory.
1552 video_encoder_config_.video_stream_factory =
1553 new rtc::RefCountedObject<CroppingVideoStreamFactory>(1, 30);
1554 video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config_),
1555 kMaxPayloadLength);
1556 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
1557
1558 // Capture a frame at codec_width_/codec_height_.
Henrik Boström381d1092020-05-12 18:49:07 +02001559 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001560 DataRate::BitsPerSec(kTargetBitrateBps),
1561 DataRate::BitsPerSec(kTargetBitrateBps),
1562 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Noah Richards51db4212019-06-12 06:59:12 -07001563 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
1564 WaitForEncodedFrame(1);
1565 // The encoder will have been configured once.
1566 EXPECT_EQ(1, sink_.number_of_reconfigurations());
1567 EXPECT_EQ(codec_width_, fake_encoder_.codec_config().width);
1568 EXPECT_EQ(codec_height_, fake_encoder_.codec_config().height);
1569
1570 // Now send in a fake frame that needs to be cropped as the width/height
1571 // aren't divisible by 4 (see CreateEncoderStreams above).
1572 rtc::Event frame_destroyed_event;
1573 video_source_.IncomingCapturedFrame(CreateFakeNativeFrame(
1574 2, &frame_destroyed_event, codec_width_ + 1, codec_height_ + 1));
1575 ExpectDroppedFrame();
1576 EXPECT_TRUE(frame_destroyed_event.Wait(kDefaultTimeoutMs));
1577 video_stream_encoder_->Stop();
1578}
1579
Evan Shrubsole895556e2020-10-05 09:15:13 +02001580TEST_F(VideoStreamEncoderTest, NonI420FramesShouldNotBeConvertedToI420) {
1581 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
1582 DataRate::BitsPerSec(kTargetBitrateBps),
1583 DataRate::BitsPerSec(kTargetBitrateBps),
1584 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
1585
1586 video_source_.IncomingCapturedFrame(
1587 CreateNV12Frame(1, codec_width_, codec_height_));
1588 WaitForEncodedFrame(1);
1589 EXPECT_EQ(VideoFrameBuffer::Type::kNV12,
1590 fake_encoder_.GetLastInputPixelFormat());
1591 video_stream_encoder_->Stop();
1592}
1593
Evan Shrubsoleb556b082020-10-08 14:56:45 +02001594TEST_F(VideoStreamEncoderTest,
1595 NativeFrameIsConvertedToI420IfNoFrameTypePreference) {
1596 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
1597 DataRate::BitsPerSec(kTargetBitrateBps),
1598 DataRate::BitsPerSec(kTargetBitrateBps),
1599 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
1600
1601 fake_encoder_.SetPreferredPixelFormats({});
1602
1603 rtc::Event frame_destroyed_event;
1604 video_source_.IncomingCapturedFrame(CreateFakeNV12NativeFrame(
1605 1, &frame_destroyed_event, codec_width_, codec_height_));
1606 WaitForEncodedFrame(1);
1607 EXPECT_EQ(VideoFrameBuffer::Type::kI420,
1608 fake_encoder_.GetLastInputPixelFormat());
1609 video_stream_encoder_->Stop();
1610}
1611
1612TEST_F(VideoStreamEncoderTest, NativeFrameMappedToPreferredPixelFormat) {
1613 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
1614 DataRate::BitsPerSec(kTargetBitrateBps),
1615 DataRate::BitsPerSec(kTargetBitrateBps),
1616 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
1617
1618 fake_encoder_.SetPreferredPixelFormats({VideoFrameBuffer::Type::kNV12});
1619
1620 rtc::Event frame_destroyed_event;
1621 video_source_.IncomingCapturedFrame(CreateFakeNV12NativeFrame(
1622 1, &frame_destroyed_event, codec_width_, codec_height_));
1623 WaitForEncodedFrame(1);
1624 EXPECT_EQ(VideoFrameBuffer::Type::kNV12,
1625 fake_encoder_.GetLastInputPixelFormat());
1626 video_stream_encoder_->Stop();
1627}
1628
1629TEST_F(VideoStreamEncoderTest, NativeFrameConvertedToI420IfMappingNotFeasible) {
1630 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
1631 DataRate::BitsPerSec(kTargetBitrateBps),
1632 DataRate::BitsPerSec(kTargetBitrateBps),
1633 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
1634
1635 // Fake NV12 native frame does not allow mapping to I444.
1636 fake_encoder_.SetPreferredPixelFormats({VideoFrameBuffer::Type::kI444});
1637
1638 rtc::Event frame_destroyed_event;
1639 video_source_.IncomingCapturedFrame(CreateFakeNV12NativeFrame(
1640 1, &frame_destroyed_event, codec_width_, codec_height_));
1641 WaitForEncodedFrame(1);
1642 EXPECT_EQ(VideoFrameBuffer::Type::kI420,
1643 fake_encoder_.GetLastInputPixelFormat());
1644 video_stream_encoder_->Stop();
1645}
1646
Evan Shrubsole895556e2020-10-05 09:15:13 +02001647TEST_F(VideoStreamEncoderTest, NativeFrameBackedByNV12FrameIsEncodedFromI420) {
1648 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
1649 DataRate::BitsPerSec(kTargetBitrateBps),
1650 DataRate::BitsPerSec(kTargetBitrateBps),
1651 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
1652
1653 rtc::Event frame_destroyed_event;
1654 video_source_.IncomingCapturedFrame(CreateFakeNV12NativeFrame(
1655 1, &frame_destroyed_event, codec_width_, codec_height_));
1656 WaitForEncodedFrame(1);
1657 EXPECT_EQ(VideoFrameBuffer::Type::kI420,
1658 fake_encoder_.GetLastInputPixelFormat());
1659 video_stream_encoder_->Stop();
1660}
1661
Ying Wang9b881ab2020-02-07 14:29:32 +01001662TEST_F(VideoStreamEncoderTest, DropsFramesWhenCongestionWindowPushbackSet) {
Henrik Boström381d1092020-05-12 18:49:07 +02001663 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001664 DataRate::BitsPerSec(kTargetBitrateBps),
1665 DataRate::BitsPerSec(kTargetBitrateBps),
1666 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Ying Wang9b881ab2020-02-07 14:29:32 +01001667 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
1668 WaitForEncodedFrame(1);
1669
Henrik Boström381d1092020-05-12 18:49:07 +02001670 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001671 DataRate::BitsPerSec(kTargetBitrateBps),
1672 DataRate::BitsPerSec(kTargetBitrateBps),
1673 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0.5);
Ying Wang9b881ab2020-02-07 14:29:32 +01001674 // The congestion window pushback is set to 0.5, which will drop 1/2 of
1675 // frames. Adding two frames means that the first frame will be dropped and
1676 // the second frame will be sent to the encoder.
1677 video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
1678 video_source_.IncomingCapturedFrame(CreateFrame(3, nullptr));
1679 WaitForEncodedFrame(3);
1680 video_source_.IncomingCapturedFrame(CreateFrame(4, nullptr));
1681 video_source_.IncomingCapturedFrame(CreateFrame(5, nullptr));
1682 WaitForEncodedFrame(5);
1683 EXPECT_EQ(2u, stats_proxy_->GetStats().frames_dropped_by_congestion_window);
1684 video_stream_encoder_->Stop();
1685}
1686
mflodmancc3d4422017-08-03 08:27:51 -07001687TEST_F(VideoStreamEncoderTest,
1688 ConfigureEncoderTriggersOnEncoderConfigurationChanged) {
Henrik Boström381d1092020-05-12 18:49:07 +02001689 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001690 DataRate::BitsPerSec(kTargetBitrateBps),
1691 DataRate::BitsPerSec(kTargetBitrateBps),
1692 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Per21d45d22016-10-30 21:37:57 +01001693 EXPECT_EQ(0, sink_.number_of_reconfigurations());
Per512ecb32016-09-23 15:52:06 +02001694
1695 // Capture a frame and wait for it to synchronize with the encoder thread.
Perf8c5f2b2016-09-23 16:24:55 +02001696 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
sprang4847ae62017-06-27 07:06:52 -07001697 WaitForEncodedFrame(1);
Per21d45d22016-10-30 21:37:57 +01001698 // The encoder will have been configured once when the first frame is
1699 // received.
1700 EXPECT_EQ(1, sink_.number_of_reconfigurations());
Per512ecb32016-09-23 15:52:06 +02001701
1702 VideoEncoderConfig video_encoder_config;
Niels Möller259a4972018-04-05 15:36:51 +02001703 test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
Per512ecb32016-09-23 15:52:06 +02001704 video_encoder_config.min_transmit_bitrate_bps = 9999;
mflodmancc3d4422017-08-03 08:27:51 -07001705 video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config),
Niels Möllerf1338562018-04-26 09:51:47 +02001706 kMaxPayloadLength);
Per512ecb32016-09-23 15:52:06 +02001707
1708 // Capture a frame and wait for it to synchronize with the encoder thread.
Perf8c5f2b2016-09-23 16:24:55 +02001709 video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
sprang4847ae62017-06-27 07:06:52 -07001710 WaitForEncodedFrame(2);
Per21d45d22016-10-30 21:37:57 +01001711 EXPECT_EQ(2, sink_.number_of_reconfigurations());
perkj3b703ed2016-09-29 23:25:40 -07001712 EXPECT_EQ(9999, sink_.last_min_transmit_bitrate());
perkj26105b42016-09-29 22:39:10 -07001713
mflodmancc3d4422017-08-03 08:27:51 -07001714 video_stream_encoder_->Stop();
perkj26105b42016-09-29 22:39:10 -07001715}
1716
mflodmancc3d4422017-08-03 08:27:51 -07001717TEST_F(VideoStreamEncoderTest, FrameResolutionChangeReconfigureEncoder) {
Henrik Boström381d1092020-05-12 18:49:07 +02001718 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001719 DataRate::BitsPerSec(kTargetBitrateBps),
1720 DataRate::BitsPerSec(kTargetBitrateBps),
1721 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
perkjfa10b552016-10-02 23:45:26 -07001722
1723 // Capture a frame and wait for it to synchronize with the encoder thread.
1724 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
sprang4847ae62017-06-27 07:06:52 -07001725 WaitForEncodedFrame(1);
Per21d45d22016-10-30 21:37:57 +01001726 // The encoder will have been configured once.
1727 EXPECT_EQ(1, sink_.number_of_reconfigurations());
perkjfa10b552016-10-02 23:45:26 -07001728 EXPECT_EQ(codec_width_, fake_encoder_.codec_config().width);
1729 EXPECT_EQ(codec_height_, fake_encoder_.codec_config().height);
1730
1731 codec_width_ *= 2;
1732 codec_height_ *= 2;
1733 // Capture a frame with a higher resolution and wait for it to synchronize
1734 // with the encoder thread.
1735 video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
sprang4847ae62017-06-27 07:06:52 -07001736 WaitForEncodedFrame(2);
perkjfa10b552016-10-02 23:45:26 -07001737 EXPECT_EQ(codec_width_, fake_encoder_.codec_config().width);
1738 EXPECT_EQ(codec_height_, fake_encoder_.codec_config().height);
Per21d45d22016-10-30 21:37:57 +01001739 EXPECT_EQ(2, sink_.number_of_reconfigurations());
perkjfa10b552016-10-02 23:45:26 -07001740
mflodmancc3d4422017-08-03 08:27:51 -07001741 video_stream_encoder_->Stop();
perkjfa10b552016-10-02 23:45:26 -07001742}
1743
Sergey Silkin443b7ee2019-06-28 12:53:07 +02001744TEST_F(VideoStreamEncoderTest,
1745 EncoderInstanceDestroyedBeforeAnotherInstanceCreated) {
Henrik Boström381d1092020-05-12 18:49:07 +02001746 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001747 DataRate::BitsPerSec(kTargetBitrateBps),
1748 DataRate::BitsPerSec(kTargetBitrateBps),
1749 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Sergey Silkin443b7ee2019-06-28 12:53:07 +02001750
1751 // Capture a frame and wait for it to synchronize with the encoder thread.
1752 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
1753 WaitForEncodedFrame(1);
1754
1755 VideoEncoderConfig video_encoder_config;
1756 test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
1757 // Changing the max payload data length recreates encoder.
1758 video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config),
1759 kMaxPayloadLength / 2);
1760
1761 // Capture a frame and wait for it to synchronize with the encoder thread.
1762 video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
1763 WaitForEncodedFrame(2);
1764 EXPECT_EQ(1, encoder_factory_.GetMaxNumberOfSimultaneousEncoderInstances());
1765
1766 video_stream_encoder_->Stop();
1767}
1768
Sergey Silkin5ee69672019-07-02 14:18:34 +02001769TEST_F(VideoStreamEncoderTest, BitrateLimitsChangeReconfigureRateAllocator) {
Henrik Boström381d1092020-05-12 18:49:07 +02001770 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001771 DataRate::BitsPerSec(kTargetBitrateBps),
1772 DataRate::BitsPerSec(kTargetBitrateBps),
1773 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Sergey Silkin5ee69672019-07-02 14:18:34 +02001774
1775 VideoEncoderConfig video_encoder_config;
1776 test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
1777 video_encoder_config.max_bitrate_bps = kTargetBitrateBps;
1778 video_stream_encoder_->SetStartBitrate(kStartBitrateBps);
1779 video_stream_encoder_->ConfigureEncoder(video_encoder_config.Copy(),
1780 kMaxPayloadLength);
1781
1782 // Capture a frame and wait for it to synchronize with the encoder thread.
1783 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
1784 WaitForEncodedFrame(1);
1785 // The encoder will have been configured once when the first frame is
1786 // received.
1787 EXPECT_EQ(1, sink_.number_of_reconfigurations());
1788 EXPECT_EQ(kTargetBitrateBps,
1789 bitrate_allocator_factory_.codec_config().maxBitrate * 1000);
1790 EXPECT_EQ(kStartBitrateBps,
1791 bitrate_allocator_factory_.codec_config().startBitrate * 1000);
1792
Sergey Silkin6456e352019-07-08 17:56:40 +02001793 test::FillEncoderConfiguration(kVideoCodecVP8, 1,
1794 &video_encoder_config); //???
Sergey Silkin5ee69672019-07-02 14:18:34 +02001795 video_encoder_config.max_bitrate_bps = kTargetBitrateBps * 2;
1796 video_stream_encoder_->SetStartBitrate(kStartBitrateBps * 2);
1797 video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config),
1798 kMaxPayloadLength);
1799
1800 // Capture a frame and wait for it to synchronize with the encoder thread.
1801 video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
1802 WaitForEncodedFrame(2);
1803 EXPECT_EQ(2, sink_.number_of_reconfigurations());
1804 // Bitrate limits have changed - rate allocator should be reconfigured,
1805 // encoder should not be reconfigured.
1806 EXPECT_EQ(kTargetBitrateBps * 2,
1807 bitrate_allocator_factory_.codec_config().maxBitrate * 1000);
1808 EXPECT_EQ(kStartBitrateBps * 2,
1809 bitrate_allocator_factory_.codec_config().startBitrate * 1000);
1810 EXPECT_EQ(1, fake_encoder_.GetNumEncoderInitializations());
1811
1812 video_stream_encoder_->Stop();
1813}
1814
Sergey Silkin6456e352019-07-08 17:56:40 +02001815TEST_F(VideoStreamEncoderTest,
Sergey Silkincd02eba2020-01-20 14:48:40 +01001816 IntersectionOfEncoderAndAppBitrateLimitsUsedWhenBothProvided) {
Henrik Boström381d1092020-05-12 18:49:07 +02001817 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001818 DataRate::BitsPerSec(kTargetBitrateBps),
1819 DataRate::BitsPerSec(kTargetBitrateBps),
1820 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Sergey Silkin6456e352019-07-08 17:56:40 +02001821
Sergey Silkincd02eba2020-01-20 14:48:40 +01001822 const uint32_t kMinEncBitrateKbps = 100;
1823 const uint32_t kMaxEncBitrateKbps = 1000;
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001824 const VideoEncoder::ResolutionBitrateLimits encoder_bitrate_limits(
Sergey Silkincd02eba2020-01-20 14:48:40 +01001825 /*frame_size_pixels=*/codec_width_ * codec_height_,
1826 /*min_start_bitrate_bps=*/0,
1827 /*min_bitrate_bps=*/kMinEncBitrateKbps * 1000,
1828 /*max_bitrate_bps=*/kMaxEncBitrateKbps * 1000);
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001829 fake_encoder_.SetResolutionBitrateLimits({encoder_bitrate_limits});
1830
Sergey Silkincd02eba2020-01-20 14:48:40 +01001831 VideoEncoderConfig video_encoder_config;
1832 test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
1833 video_encoder_config.max_bitrate_bps = (kMaxEncBitrateKbps + 1) * 1000;
1834 video_encoder_config.simulcast_layers[0].min_bitrate_bps =
1835 (kMinEncBitrateKbps + 1) * 1000;
1836 video_stream_encoder_->ConfigureEncoder(video_encoder_config.Copy(),
1837 kMaxPayloadLength);
1838
1839 // When both encoder and app provide bitrate limits, the intersection of
1840 // provided sets should be used.
1841 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
1842 WaitForEncodedFrame(1);
1843 EXPECT_EQ(kMaxEncBitrateKbps,
1844 bitrate_allocator_factory_.codec_config().maxBitrate);
1845 EXPECT_EQ(kMinEncBitrateKbps + 1,
1846 bitrate_allocator_factory_.codec_config().minBitrate);
1847
1848 video_encoder_config.max_bitrate_bps = (kMaxEncBitrateKbps - 1) * 1000;
1849 video_encoder_config.simulcast_layers[0].min_bitrate_bps =
1850 (kMinEncBitrateKbps - 1) * 1000;
1851 video_stream_encoder_->ConfigureEncoder(video_encoder_config.Copy(),
1852 kMaxPayloadLength);
1853 video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001854 WaitForEncodedFrame(2);
Sergey Silkincd02eba2020-01-20 14:48:40 +01001855 EXPECT_EQ(kMaxEncBitrateKbps - 1,
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001856 bitrate_allocator_factory_.codec_config().maxBitrate);
Sergey Silkincd02eba2020-01-20 14:48:40 +01001857 EXPECT_EQ(kMinEncBitrateKbps,
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001858 bitrate_allocator_factory_.codec_config().minBitrate);
1859
Sergey Silkincd02eba2020-01-20 14:48:40 +01001860 video_stream_encoder_->Stop();
1861}
1862
1863TEST_F(VideoStreamEncoderTest,
1864 EncoderAndAppLimitsDontIntersectEncoderLimitsIgnored) {
Henrik Boström381d1092020-05-12 18:49:07 +02001865 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001866 DataRate::BitsPerSec(kTargetBitrateBps),
1867 DataRate::BitsPerSec(kTargetBitrateBps),
1868 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Sergey Silkincd02eba2020-01-20 14:48:40 +01001869
1870 const uint32_t kMinAppBitrateKbps = 100;
1871 const uint32_t kMaxAppBitrateKbps = 200;
1872 const uint32_t kMinEncBitrateKbps = kMaxAppBitrateKbps + 1;
1873 const uint32_t kMaxEncBitrateKbps = kMaxAppBitrateKbps * 2;
1874 const VideoEncoder::ResolutionBitrateLimits encoder_bitrate_limits(
1875 /*frame_size_pixels=*/codec_width_ * codec_height_,
1876 /*min_start_bitrate_bps=*/0,
1877 /*min_bitrate_bps=*/kMinEncBitrateKbps * 1000,
1878 /*max_bitrate_bps=*/kMaxEncBitrateKbps * 1000);
1879 fake_encoder_.SetResolutionBitrateLimits({encoder_bitrate_limits});
1880
1881 VideoEncoderConfig video_encoder_config;
1882 test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
1883 video_encoder_config.max_bitrate_bps = kMaxAppBitrateKbps * 1000;
1884 video_encoder_config.simulcast_layers[0].min_bitrate_bps =
1885 kMinAppBitrateKbps * 1000;
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001886 video_stream_encoder_->ConfigureEncoder(video_encoder_config.Copy(),
1887 kMaxPayloadLength);
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001888
Sergey Silkincd02eba2020-01-20 14:48:40 +01001889 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
1890 WaitForEncodedFrame(1);
1891 EXPECT_EQ(kMaxAppBitrateKbps,
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001892 bitrate_allocator_factory_.codec_config().maxBitrate);
Sergey Silkincd02eba2020-01-20 14:48:40 +01001893 EXPECT_EQ(kMinAppBitrateKbps,
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001894 bitrate_allocator_factory_.codec_config().minBitrate);
Sergey Silkin6456e352019-07-08 17:56:40 +02001895
1896 video_stream_encoder_->Stop();
1897}
1898
1899TEST_F(VideoStreamEncoderTest,
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001900 EncoderRecommendedMaxAndMinBitratesUsedForGivenResolution) {
Henrik Boström381d1092020-05-12 18:49:07 +02001901 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001902 DataRate::BitsPerSec(kTargetBitrateBps),
1903 DataRate::BitsPerSec(kTargetBitrateBps),
1904 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Sergey Silkin6456e352019-07-08 17:56:40 +02001905
1906 const VideoEncoder::ResolutionBitrateLimits encoder_bitrate_limits_270p(
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001907 480 * 270, 34 * 1000, 12 * 1000, 1234 * 1000);
Sergey Silkin6456e352019-07-08 17:56:40 +02001908 const VideoEncoder::ResolutionBitrateLimits encoder_bitrate_limits_360p(
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001909 640 * 360, 43 * 1000, 21 * 1000, 2345 * 1000);
Sergey Silkin6456e352019-07-08 17:56:40 +02001910 fake_encoder_.SetResolutionBitrateLimits(
1911 {encoder_bitrate_limits_270p, encoder_bitrate_limits_360p});
1912
1913 VideoEncoderConfig video_encoder_config;
1914 test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
1915 video_encoder_config.max_bitrate_bps = 0;
1916 video_stream_encoder_->ConfigureEncoder(video_encoder_config.Copy(),
1917 kMaxPayloadLength);
1918
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001919 // 270p. The bitrate limits recommended by encoder for 270p should be used.
Sergey Silkin6456e352019-07-08 17:56:40 +02001920 video_source_.IncomingCapturedFrame(CreateFrame(1, 480, 270));
1921 WaitForEncodedFrame(1);
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001922 EXPECT_EQ(static_cast<uint32_t>(encoder_bitrate_limits_270p.min_bitrate_bps),
1923 bitrate_allocator_factory_.codec_config().minBitrate * 1000);
Sergey Silkin6456e352019-07-08 17:56:40 +02001924 EXPECT_EQ(static_cast<uint32_t>(encoder_bitrate_limits_270p.max_bitrate_bps),
1925 bitrate_allocator_factory_.codec_config().maxBitrate * 1000);
1926
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001927 // 360p. The bitrate limits recommended by encoder for 360p should be used.
Sergey Silkin6456e352019-07-08 17:56:40 +02001928 video_source_.IncomingCapturedFrame(CreateFrame(2, 640, 360));
1929 WaitForEncodedFrame(2);
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001930 EXPECT_EQ(static_cast<uint32_t>(encoder_bitrate_limits_360p.min_bitrate_bps),
1931 bitrate_allocator_factory_.codec_config().minBitrate * 1000);
Sergey Silkin6456e352019-07-08 17:56:40 +02001932 EXPECT_EQ(static_cast<uint32_t>(encoder_bitrate_limits_360p.max_bitrate_bps),
1933 bitrate_allocator_factory_.codec_config().maxBitrate * 1000);
1934
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001935 // Resolution between 270p and 360p. The bitrate limits recommended by
Sergey Silkin6456e352019-07-08 17:56:40 +02001936 // encoder for 360p should be used.
1937 video_source_.IncomingCapturedFrame(
1938 CreateFrame(3, (640 + 480) / 2, (360 + 270) / 2));
1939 WaitForEncodedFrame(3);
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001940 EXPECT_EQ(static_cast<uint32_t>(encoder_bitrate_limits_360p.min_bitrate_bps),
1941 bitrate_allocator_factory_.codec_config().minBitrate * 1000);
Sergey Silkin6456e352019-07-08 17:56:40 +02001942 EXPECT_EQ(static_cast<uint32_t>(encoder_bitrate_limits_360p.max_bitrate_bps),
1943 bitrate_allocator_factory_.codec_config().maxBitrate * 1000);
1944
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001945 // Resolution higher than 360p. The caps recommended by encoder should be
Sergey Silkin6456e352019-07-08 17:56:40 +02001946 // ignored.
1947 video_source_.IncomingCapturedFrame(CreateFrame(4, 960, 540));
1948 WaitForEncodedFrame(4);
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001949 EXPECT_NE(static_cast<uint32_t>(encoder_bitrate_limits_270p.min_bitrate_bps),
1950 bitrate_allocator_factory_.codec_config().minBitrate * 1000);
Sergey Silkin6456e352019-07-08 17:56:40 +02001951 EXPECT_NE(static_cast<uint32_t>(encoder_bitrate_limits_270p.max_bitrate_bps),
1952 bitrate_allocator_factory_.codec_config().maxBitrate * 1000);
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001953 EXPECT_NE(static_cast<uint32_t>(encoder_bitrate_limits_360p.min_bitrate_bps),
1954 bitrate_allocator_factory_.codec_config().minBitrate * 1000);
Sergey Silkin6456e352019-07-08 17:56:40 +02001955 EXPECT_NE(static_cast<uint32_t>(encoder_bitrate_limits_360p.max_bitrate_bps),
1956 bitrate_allocator_factory_.codec_config().maxBitrate * 1000);
1957
1958 // Resolution lower than 270p. The max bitrate limit recommended by encoder
1959 // for 270p should be used.
1960 video_source_.IncomingCapturedFrame(CreateFrame(5, 320, 180));
1961 WaitForEncodedFrame(5);
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001962 EXPECT_EQ(static_cast<uint32_t>(encoder_bitrate_limits_270p.min_bitrate_bps),
1963 bitrate_allocator_factory_.codec_config().minBitrate * 1000);
Sergey Silkin6456e352019-07-08 17:56:40 +02001964 EXPECT_EQ(static_cast<uint32_t>(encoder_bitrate_limits_270p.max_bitrate_bps),
1965 bitrate_allocator_factory_.codec_config().maxBitrate * 1000);
1966
1967 video_stream_encoder_->Stop();
1968}
1969
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001970TEST_F(VideoStreamEncoderTest, EncoderRecommendedMaxBitrateCapsTargetBitrate) {
Henrik Boström381d1092020-05-12 18:49:07 +02001971 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001972 DataRate::BitsPerSec(kTargetBitrateBps),
1973 DataRate::BitsPerSec(kTargetBitrateBps),
1974 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001975
1976 VideoEncoderConfig video_encoder_config;
1977 test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
1978 video_encoder_config.max_bitrate_bps = 0;
1979 video_stream_encoder_->ConfigureEncoder(video_encoder_config.Copy(),
1980 kMaxPayloadLength);
1981
1982 // Encode 720p frame to get the default encoder target bitrate.
1983 video_source_.IncomingCapturedFrame(CreateFrame(1, 1280, 720));
1984 WaitForEncodedFrame(1);
1985 const uint32_t kDefaultTargetBitrateFor720pKbps =
1986 bitrate_allocator_factory_.codec_config()
1987 .simulcastStream[0]
1988 .targetBitrate;
1989
1990 // Set the max recommended encoder bitrate to something lower than the default
1991 // target bitrate.
1992 const VideoEncoder::ResolutionBitrateLimits encoder_bitrate_limits(
1993 1280 * 720, 10 * 1000, 10 * 1000,
1994 kDefaultTargetBitrateFor720pKbps / 2 * 1000);
1995 fake_encoder_.SetResolutionBitrateLimits({encoder_bitrate_limits});
1996
1997 // Change resolution to trigger encoder reinitialization.
1998 video_source_.IncomingCapturedFrame(CreateFrame(2, 640, 360));
1999 WaitForEncodedFrame(2);
2000 video_source_.IncomingCapturedFrame(CreateFrame(3, 1280, 720));
2001 WaitForEncodedFrame(3);
2002
2003 // Ensure the target bitrate is capped by the max bitrate.
2004 EXPECT_EQ(bitrate_allocator_factory_.codec_config().maxBitrate * 1000,
2005 static_cast<uint32_t>(encoder_bitrate_limits.max_bitrate_bps));
2006 EXPECT_EQ(bitrate_allocator_factory_.codec_config()
2007 .simulcastStream[0]
2008 .targetBitrate *
2009 1000,
2010 static_cast<uint32_t>(encoder_bitrate_limits.max_bitrate_bps));
2011
2012 video_stream_encoder_->Stop();
2013}
2014
mflodmancc3d4422017-08-03 08:27:51 -07002015TEST_F(VideoStreamEncoderTest, SwitchSourceDeregisterEncoderAsSink) {
perkj803d97f2016-11-01 11:45:46 -07002016 EXPECT_TRUE(video_source_.has_sinks());
2017 test::FrameForwarder new_video_source;
mflodmancc3d4422017-08-03 08:27:51 -07002018 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002019 &new_video_source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
perkj803d97f2016-11-01 11:45:46 -07002020 EXPECT_FALSE(video_source_.has_sinks());
2021 EXPECT_TRUE(new_video_source.has_sinks());
2022
mflodmancc3d4422017-08-03 08:27:51 -07002023 video_stream_encoder_->Stop();
perkj803d97f2016-11-01 11:45:46 -07002024}
2025
mflodmancc3d4422017-08-03 08:27:51 -07002026TEST_F(VideoStreamEncoderTest, SinkWantsRotationApplied) {
perkj803d97f2016-11-01 11:45:46 -07002027 EXPECT_FALSE(video_source_.sink_wants().rotation_applied);
mflodmancc3d4422017-08-03 08:27:51 -07002028 video_stream_encoder_->SetSink(&sink_, true /*rotation_applied*/);
perkj803d97f2016-11-01 11:45:46 -07002029 EXPECT_TRUE(video_source_.sink_wants().rotation_applied);
mflodmancc3d4422017-08-03 08:27:51 -07002030 video_stream_encoder_->Stop();
perkj803d97f2016-11-01 11:45:46 -07002031}
2032
Åsa Perssonc5a74ff2020-09-20 17:50:00 +02002033class ResolutionAlignmentTest
2034 : public VideoStreamEncoderTest,
2035 public ::testing::WithParamInterface<
2036 ::testing::tuple<int, std::vector<double>>> {
2037 public:
2038 ResolutionAlignmentTest()
2039 : requested_alignment_(::testing::get<0>(GetParam())),
2040 scale_factors_(::testing::get<1>(GetParam())) {}
2041
2042 protected:
2043 const int requested_alignment_;
2044 const std::vector<double> scale_factors_;
2045};
2046
2047INSTANTIATE_TEST_SUITE_P(
2048 AlignmentAndScaleFactors,
2049 ResolutionAlignmentTest,
2050 ::testing::Combine(
2051 ::testing::Values(1, 2, 3, 4, 5, 6, 16, 22), // requested_alignment_
2052 ::testing::Values(std::vector<double>{-1.0}, // scale_factors_
2053 std::vector<double>{-1.0, -1.0},
2054 std::vector<double>{-1.0, -1.0, -1.0},
2055 std::vector<double>{4.0, 2.0, 1.0},
2056 std::vector<double>{9999.0, -1.0, 1.0},
2057 std::vector<double>{3.99, 2.01, 1.0},
2058 std::vector<double>{4.9, 1.7, 1.25},
2059 std::vector<double>{10.0, 4.0, 3.0},
2060 std::vector<double>{1.75, 3.5},
2061 std::vector<double>{1.5, 2.5},
2062 std::vector<double>{1.3, 1.0})));
2063
2064TEST_P(ResolutionAlignmentTest, SinkWantsAlignmentApplied) {
2065 // Set requested resolution alignment.
Rasmus Brandt5cad55b2019-12-19 09:47:11 +01002066 video_source_.set_adaptation_enabled(true);
Åsa Perssonc5a74ff2020-09-20 17:50:00 +02002067 fake_encoder_.SetRequestedResolutionAlignment(requested_alignment_);
2068 fake_encoder_.SetApplyAlignmentToAllSimulcastLayers(true);
2069
2070 // Fill config with the scaling factor by which to reduce encoding size.
2071 const int num_streams = scale_factors_.size();
2072 VideoEncoderConfig config;
2073 test::FillEncoderConfiguration(kVideoCodecVP8, num_streams, &config);
2074 for (int i = 0; i < num_streams; ++i) {
2075 config.simulcast_layers[i].scale_resolution_down_by = scale_factors_[i];
2076 }
2077 config.video_stream_factory =
2078 new rtc::RefCountedObject<cricket::EncoderStreamFactory>(
2079 "VP8", /*max qp*/ 56, /*screencast*/ false,
2080 /*screenshare enabled*/ false);
2081 video_stream_encoder_->ConfigureEncoder(std::move(config), kMaxPayloadLength);
2082
Henrik Boström381d1092020-05-12 18:49:07 +02002083 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Åsa Perssonc5a74ff2020-09-20 17:50:00 +02002084 DataRate::BitsPerSec(kSimulcastTargetBitrateBps),
2085 DataRate::BitsPerSec(kSimulcastTargetBitrateBps),
2086 DataRate::BitsPerSec(kSimulcastTargetBitrateBps), 0, 0, 0);
2087 // Wait for all layers before triggering event.
2088 sink_.SetNumExpectedLayers(num_streams);
Rasmus Brandt5cad55b2019-12-19 09:47:11 +01002089
2090 // On the 1st frame, we should have initialized the encoder and
2091 // asked for its resolution requirements.
Åsa Perssonc5a74ff2020-09-20 17:50:00 +02002092 int64_t timestamp_ms = kFrameIntervalMs;
2093 video_source_.IncomingCapturedFrame(CreateFrame(timestamp_ms, 1280, 720));
2094 WaitForEncodedFrame(timestamp_ms);
2095 EXPECT_EQ(1, fake_encoder_.GetNumEncoderInitializations());
Rasmus Brandt5cad55b2019-12-19 09:47:11 +01002096
2097 // On the 2nd frame, we should be receiving a correctly aligned resolution.
2098 // (It's up the to the encoder to potentially drop the previous frame,
2099 // to avoid coding back-to-back keyframes.)
Åsa Perssonc5a74ff2020-09-20 17:50:00 +02002100 timestamp_ms += kFrameIntervalMs;
2101 video_source_.IncomingCapturedFrame(CreateFrame(timestamp_ms, 1280, 720));
2102 WaitForEncodedFrame(timestamp_ms);
2103 EXPECT_GE(fake_encoder_.GetNumEncoderInitializations(), 1);
2104
2105 VideoCodec codec = fake_encoder_.video_codec();
2106 EXPECT_EQ(codec.numberOfSimulcastStreams, num_streams);
2107 // Frame size should be a multiple of the requested alignment.
2108 for (int i = 0; i < codec.numberOfSimulcastStreams; ++i) {
2109 EXPECT_EQ(codec.simulcastStream[i].width % requested_alignment_, 0);
2110 EXPECT_EQ(codec.simulcastStream[i].height % requested_alignment_, 0);
2111 // Aspect ratio should match.
2112 EXPECT_EQ(codec.width * codec.simulcastStream[i].height,
2113 codec.height * codec.simulcastStream[i].width);
2114 }
Rasmus Brandt5cad55b2019-12-19 09:47:11 +01002115
2116 video_stream_encoder_->Stop();
2117}
2118
Jonathan Yubc771b72017-12-08 17:04:29 -08002119TEST_F(VideoStreamEncoderTest, TestCpuDowngrades_BalancedMode) {
2120 const int kFramerateFps = 30;
asaperssonf7e294d2017-06-13 23:25:22 -07002121 const int kWidth = 1280;
2122 const int kHeight = 720;
Jonathan Yubc771b72017-12-08 17:04:29 -08002123
2124 // We rely on the automatic resolution adaptation, but we handle framerate
2125 // adaptation manually by mocking the stats proxy.
2126 video_source_.set_adaptation_enabled(true);
asaperssonf7e294d2017-06-13 23:25:22 -07002127
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002128 // Enable BALANCED preference, no initial limitation.
Henrik Boström381d1092020-05-12 18:49:07 +02002129 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01002130 DataRate::BitsPerSec(kTargetBitrateBps),
2131 DataRate::BitsPerSec(kTargetBitrateBps),
2132 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002133 video_stream_encoder_->SetSource(&video_source_,
2134 webrtc::DegradationPreference::BALANCED);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02002135 EXPECT_THAT(video_source_.sink_wants(), UnlimitedSinkWants());
asaperssonf7e294d2017-06-13 23:25:22 -07002136 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
Jonathan Yubc771b72017-12-08 17:04:29 -08002137 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
asaperssonf7e294d2017-06-13 23:25:22 -07002138 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
2139
Jonathan Yubc771b72017-12-08 17:04:29 -08002140 // Adapt down as far as possible.
2141 rtc::VideoSinkWants last_wants;
2142 int64_t t = 1;
2143 int loop_count = 0;
2144 do {
2145 ++loop_count;
2146 last_wants = video_source_.sink_wants();
2147
2148 // Simulate the framerate we've been asked to adapt to.
2149 const int fps = std::min(kFramerateFps, last_wants.max_framerate_fps);
2150 const int frame_interval_ms = rtc::kNumMillisecsPerSec / fps;
2151 VideoSendStream::Stats mock_stats = stats_proxy_->GetStats();
2152 mock_stats.input_frame_rate = fps;
2153 stats_proxy_->SetMockStats(mock_stats);
2154
2155 video_source_.IncomingCapturedFrame(CreateFrame(t, kWidth, kHeight));
2156 sink_.WaitForEncodedFrame(t);
2157 t += frame_interval_ms;
2158
mflodmancc3d4422017-08-03 08:27:51 -07002159 video_stream_encoder_->TriggerCpuOveruse();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02002160 EXPECT_THAT(
Jonathan Yubc771b72017-12-08 17:04:29 -08002161 video_source_.sink_wants(),
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02002162 FpsInRangeForPixelsInBalanced(*video_source_.last_sent_width() *
2163 *video_source_.last_sent_height()));
Jonathan Yubc771b72017-12-08 17:04:29 -08002164 } while (video_source_.sink_wants().max_pixel_count <
2165 last_wants.max_pixel_count ||
2166 video_source_.sink_wants().max_framerate_fps <
2167 last_wants.max_framerate_fps);
asaperssonf7e294d2017-06-13 23:25:22 -07002168
Jonathan Yubc771b72017-12-08 17:04:29 -08002169 // Verify that we've adapted all the way down.
2170 stats_proxy_->ResetMockStats();
asaperssonf7e294d2017-06-13 23:25:22 -07002171 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
Jonathan Yubc771b72017-12-08 17:04:29 -08002172 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_framerate);
2173 EXPECT_EQ(loop_count - 1,
asaperssonf7e294d2017-06-13 23:25:22 -07002174 stats_proxy_->GetStats().number_of_cpu_adapt_changes);
Jonathan Yubc771b72017-12-08 17:04:29 -08002175 EXPECT_EQ(kMinPixelsPerFrame, *video_source_.last_sent_width() *
2176 *video_source_.last_sent_height());
2177 EXPECT_EQ(kMinBalancedFramerateFps,
2178 video_source_.sink_wants().max_framerate_fps);
asaperssonf7e294d2017-06-13 23:25:22 -07002179
Jonathan Yubc771b72017-12-08 17:04:29 -08002180 // Adapt back up the same number of times we adapted down.
2181 for (int i = 0; i < loop_count - 1; ++i) {
2182 last_wants = video_source_.sink_wants();
2183
2184 // Simulate the framerate we've been asked to adapt to.
2185 const int fps = std::min(kFramerateFps, last_wants.max_framerate_fps);
2186 const int frame_interval_ms = rtc::kNumMillisecsPerSec / fps;
2187 VideoSendStream::Stats mock_stats = stats_proxy_->GetStats();
2188 mock_stats.input_frame_rate = fps;
2189 stats_proxy_->SetMockStats(mock_stats);
2190
2191 video_source_.IncomingCapturedFrame(CreateFrame(t, kWidth, kHeight));
2192 sink_.WaitForEncodedFrame(t);
2193 t += frame_interval_ms;
2194
Henrik Boström91aa7322020-04-28 12:24:33 +02002195 video_stream_encoder_->TriggerCpuUnderuse();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02002196 EXPECT_THAT(
Jonathan Yubc771b72017-12-08 17:04:29 -08002197 video_source_.sink_wants(),
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02002198 FpsInRangeForPixelsInBalanced(*video_source_.last_sent_width() *
2199 *video_source_.last_sent_height()));
Jonathan Yubc771b72017-12-08 17:04:29 -08002200 EXPECT_TRUE(video_source_.sink_wants().max_pixel_count >
2201 last_wants.max_pixel_count ||
2202 video_source_.sink_wants().max_framerate_fps >
2203 last_wants.max_framerate_fps);
asaperssonf7e294d2017-06-13 23:25:22 -07002204 }
2205
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02002206 EXPECT_THAT(video_source_.sink_wants(), FpsMaxResolutionMax());
Jonathan Yubc771b72017-12-08 17:04:29 -08002207 stats_proxy_->ResetMockStats();
asaperssonf7e294d2017-06-13 23:25:22 -07002208 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
Jonathan Yubc771b72017-12-08 17:04:29 -08002209 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
2210 EXPECT_EQ((loop_count - 1) * 2,
2211 stats_proxy_->GetStats().number_of_cpu_adapt_changes);
asaperssonf7e294d2017-06-13 23:25:22 -07002212
mflodmancc3d4422017-08-03 08:27:51 -07002213 video_stream_encoder_->Stop();
asaperssonf7e294d2017-06-13 23:25:22 -07002214}
Rasmus Brandt5cad55b2019-12-19 09:47:11 +01002215
Evan Shrubsole2e2f6742020-05-14 10:41:15 +02002216TEST_F(VideoStreamEncoderTest,
2217 SinkWantsNotChangedByResourceLimitedBeforeDegradationPreferenceChange) {
2218 video_stream_encoder_->OnBitrateUpdated(
2219 DataRate::BitsPerSec(kTargetBitrateBps),
2220 DataRate::BitsPerSec(kTargetBitrateBps),
2221 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02002222 EXPECT_THAT(video_source_.sink_wants(), UnlimitedSinkWants());
Evan Shrubsole2e2f6742020-05-14 10:41:15 +02002223
2224 const int kFrameWidth = 1280;
2225 const int kFrameHeight = 720;
2226
2227 int64_t ntp_time = kFrameIntervalMs;
2228
2229 // Force an input frame rate to be available, or the adaptation call won't
2230 // know what framerate to adapt form.
2231 const int kInputFps = 30;
2232 VideoSendStream::Stats stats = stats_proxy_->GetStats();
2233 stats.input_frame_rate = kInputFps;
2234 stats_proxy_->SetMockStats(stats);
2235
2236 video_source_.set_adaptation_enabled(true);
2237 video_stream_encoder_->SetSource(
2238 &video_source_, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02002239 EXPECT_THAT(video_source_.sink_wants(), UnlimitedSinkWants());
Evan Shrubsole2e2f6742020-05-14 10:41:15 +02002240 video_source_.IncomingCapturedFrame(
2241 CreateFrame(ntp_time, kFrameWidth, kFrameHeight));
2242 sink_.WaitForEncodedFrame(ntp_time);
2243 ntp_time += kFrameIntervalMs;
2244
2245 // Trigger CPU overuse.
2246 video_stream_encoder_->TriggerCpuOveruse();
2247 video_source_.IncomingCapturedFrame(
2248 CreateFrame(ntp_time, kFrameWidth, kFrameHeight));
2249 sink_.WaitForEncodedFrame(ntp_time);
2250 ntp_time += kFrameIntervalMs;
2251
2252 EXPECT_FALSE(video_source_.sink_wants().target_pixel_count);
2253 EXPECT_EQ(std::numeric_limits<int>::max(),
2254 video_source_.sink_wants().max_pixel_count);
2255 // Some framerate constraint should be set.
2256 int restricted_fps = video_source_.sink_wants().max_framerate_fps;
2257 EXPECT_LT(restricted_fps, kInputFps);
2258 video_source_.IncomingCapturedFrame(
2259 CreateFrame(ntp_time, kFrameWidth, kFrameHeight));
2260 sink_.WaitForEncodedFrame(ntp_time);
2261 ntp_time += 100;
2262
Henrik Boström2671dac2020-05-19 16:29:09 +02002263 video_stream_encoder_->SetSourceAndWaitForRestrictionsUpdated(
Evan Shrubsole2e2f6742020-05-14 10:41:15 +02002264 &video_source_, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
2265 // Give the encoder queue time to process the change in degradation preference
2266 // by waiting for an encoded frame.
2267 video_source_.IncomingCapturedFrame(
2268 CreateFrame(ntp_time, kFrameWidth, kFrameHeight));
2269 sink_.WaitForEncodedFrame(ntp_time);
2270 ntp_time += kFrameIntervalMs;
2271
2272 video_stream_encoder_->TriggerQualityLow();
2273 video_source_.IncomingCapturedFrame(
2274 CreateFrame(ntp_time, kFrameWidth, kFrameHeight));
2275 sink_.WaitForEncodedFrame(ntp_time);
2276 ntp_time += kFrameIntervalMs;
2277
2278 // Some resolution constraint should be set.
2279 EXPECT_FALSE(video_source_.sink_wants().target_pixel_count);
2280 EXPECT_LT(video_source_.sink_wants().max_pixel_count,
2281 kFrameWidth * kFrameHeight);
2282 EXPECT_EQ(video_source_.sink_wants().max_framerate_fps, kInputFps);
2283
2284 int pixel_count = video_source_.sink_wants().max_pixel_count;
2285 // Triggering a CPU underuse should not change the sink wants since it has
2286 // not been overused for resolution since we changed degradation preference.
2287 video_stream_encoder_->TriggerCpuUnderuse();
2288 video_source_.IncomingCapturedFrame(
2289 CreateFrame(ntp_time, kFrameWidth, kFrameHeight));
2290 sink_.WaitForEncodedFrame(ntp_time);
2291 ntp_time += kFrameIntervalMs;
2292 EXPECT_EQ(video_source_.sink_wants().max_pixel_count, pixel_count);
2293 EXPECT_EQ(video_source_.sink_wants().max_framerate_fps, kInputFps);
2294
Evan Shrubsole64469032020-06-11 10:45:29 +02002295 // Change the degradation preference back. CPU underuse should not adapt since
2296 // QP is most limited.
Henrik Boström2671dac2020-05-19 16:29:09 +02002297 video_stream_encoder_->SetSourceAndWaitForRestrictionsUpdated(
Evan Shrubsole2e2f6742020-05-14 10:41:15 +02002298 &video_source_, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
2299 video_source_.IncomingCapturedFrame(
2300 CreateFrame(ntp_time, kFrameWidth, kFrameHeight));
2301 sink_.WaitForEncodedFrame(ntp_time);
2302 ntp_time += 100;
2303 // Resolution adaptations is gone after changing degradation preference.
2304 EXPECT_FALSE(video_source_.sink_wants().target_pixel_count);
2305 EXPECT_EQ(std::numeric_limits<int>::max(),
2306 video_source_.sink_wants().max_pixel_count);
2307 // The fps adaptation from above is now back.
2308 EXPECT_EQ(video_source_.sink_wants().max_framerate_fps, restricted_fps);
2309
2310 // Trigger CPU underuse.
2311 video_stream_encoder_->TriggerCpuUnderuse();
2312 video_source_.IncomingCapturedFrame(
2313 CreateFrame(ntp_time, kFrameWidth, kFrameHeight));
2314 sink_.WaitForEncodedFrame(ntp_time);
2315 ntp_time += kFrameIntervalMs;
Evan Shrubsole64469032020-06-11 10:45:29 +02002316 EXPECT_EQ(video_source_.sink_wants().max_framerate_fps, restricted_fps);
2317
2318 // Trigger QP underuse, fps should return to normal.
2319 video_stream_encoder_->TriggerQualityHigh();
2320 video_source_.IncomingCapturedFrame(
2321 CreateFrame(ntp_time, kFrameWidth, kFrameHeight));
2322 sink_.WaitForEncodedFrame(ntp_time);
2323 ntp_time += kFrameIntervalMs;
2324 EXPECT_THAT(video_source_.sink_wants(), FpsMax());
Evan Shrubsole2e2f6742020-05-14 10:41:15 +02002325
2326 video_stream_encoder_->Stop();
2327}
2328
mflodmancc3d4422017-08-03 08:27:51 -07002329TEST_F(VideoStreamEncoderTest, SinkWantsStoredByDegradationPreference) {
Henrik Boström381d1092020-05-12 18:49:07 +02002330 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01002331 DataRate::BitsPerSec(kTargetBitrateBps),
2332 DataRate::BitsPerSec(kTargetBitrateBps),
2333 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02002334 EXPECT_THAT(video_source_.sink_wants(), UnlimitedSinkWants());
perkj803d97f2016-11-01 11:45:46 -07002335
sprangc5d62e22017-04-02 23:53:04 -07002336 const int kFrameWidth = 1280;
2337 const int kFrameHeight = 720;
sprangc5d62e22017-04-02 23:53:04 -07002338
Åsa Persson8c1bf952018-09-13 10:42:19 +02002339 int64_t frame_timestamp = 1;
perkj803d97f2016-11-01 11:45:46 -07002340
kthelgason5e13d412016-12-01 03:59:51 -08002341 video_source_.IncomingCapturedFrame(
sprangc5d62e22017-04-02 23:53:04 -07002342 CreateFrame(frame_timestamp, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 07:06:52 -07002343 WaitForEncodedFrame(frame_timestamp);
sprangc5d62e22017-04-02 23:53:04 -07002344 frame_timestamp += kFrameIntervalMs;
2345
perkj803d97f2016-11-01 11:45:46 -07002346 // Trigger CPU overuse.
mflodmancc3d4422017-08-03 08:27:51 -07002347 video_stream_encoder_->TriggerCpuOveruse();
perkj803d97f2016-11-01 11:45:46 -07002348 video_source_.IncomingCapturedFrame(
sprangc5d62e22017-04-02 23:53:04 -07002349 CreateFrame(frame_timestamp, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 07:06:52 -07002350 WaitForEncodedFrame(frame_timestamp);
sprangc5d62e22017-04-02 23:53:04 -07002351 frame_timestamp += kFrameIntervalMs;
sprang3ea3c772017-03-30 07:23:48 -07002352
asapersson0944a802017-04-07 00:57:58 -07002353 // Default degradation preference is maintain-framerate, so will lower max
sprangc5d62e22017-04-02 23:53:04 -07002354 // wanted resolution.
2355 EXPECT_FALSE(video_source_.sink_wants().target_pixel_count);
2356 EXPECT_LT(video_source_.sink_wants().max_pixel_count,
2357 kFrameWidth * kFrameHeight);
Åsa Persson8c1bf952018-09-13 10:42:19 +02002358 EXPECT_EQ(kDefaultFramerate, video_source_.sink_wants().max_framerate_fps);
sprangc5d62e22017-04-02 23:53:04 -07002359
2360 // Set new source, switch to maintain-resolution.
perkj803d97f2016-11-01 11:45:46 -07002361 test::FrameForwarder new_video_source;
Henrik Boström381d1092020-05-12 18:49:07 +02002362 video_stream_encoder_->SetSourceAndWaitForRestrictionsUpdated(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002363 &new_video_source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
Henrik Boström07b17df2020-01-15 11:42:12 +01002364 // Give the encoder queue time to process the change in degradation preference
2365 // by waiting for an encoded frame.
2366 new_video_source.IncomingCapturedFrame(
2367 CreateFrame(frame_timestamp, kFrameWidth, kFrameWidth));
2368 sink_.WaitForEncodedFrame(frame_timestamp);
2369 frame_timestamp += kFrameIntervalMs;
sprangc5d62e22017-04-02 23:53:04 -07002370 // Initially no degradation registered.
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02002371 EXPECT_THAT(new_video_source.sink_wants(), FpsMaxResolutionMax());
perkj803d97f2016-11-01 11:45:46 -07002372
sprangc5d62e22017-04-02 23:53:04 -07002373 // Force an input frame rate to be available, or the adaptation call won't
2374 // know what framerate to adapt form.
asapersson02465b82017-04-10 01:12:52 -07002375 const int kInputFps = 30;
sprangc5d62e22017-04-02 23:53:04 -07002376 VideoSendStream::Stats stats = stats_proxy_->GetStats();
asapersson02465b82017-04-10 01:12:52 -07002377 stats.input_frame_rate = kInputFps;
sprangc5d62e22017-04-02 23:53:04 -07002378 stats_proxy_->SetMockStats(stats);
2379
mflodmancc3d4422017-08-03 08:27:51 -07002380 video_stream_encoder_->TriggerCpuOveruse();
perkj803d97f2016-11-01 11:45:46 -07002381 new_video_source.IncomingCapturedFrame(
sprangc5d62e22017-04-02 23:53:04 -07002382 CreateFrame(frame_timestamp, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 07:06:52 -07002383 WaitForEncodedFrame(frame_timestamp);
sprangc5d62e22017-04-02 23:53:04 -07002384 frame_timestamp += kFrameIntervalMs;
2385
2386 // Some framerate constraint should be set.
sprang84a37592017-02-10 07:04:27 -08002387 EXPECT_FALSE(new_video_source.sink_wants().target_pixel_count);
sprangc5d62e22017-04-02 23:53:04 -07002388 EXPECT_EQ(std::numeric_limits<int>::max(),
2389 new_video_source.sink_wants().max_pixel_count);
asapersson02465b82017-04-10 01:12:52 -07002390 EXPECT_LT(new_video_source.sink_wants().max_framerate_fps, kInputFps);
sprangc5d62e22017-04-02 23:53:04 -07002391
asapersson02465b82017-04-10 01:12:52 -07002392 // Turn off degradation completely.
Henrik Boström381d1092020-05-12 18:49:07 +02002393 video_stream_encoder_->SetSourceAndWaitForRestrictionsUpdated(
2394 &new_video_source, webrtc::DegradationPreference::DISABLED);
Henrik Boström07b17df2020-01-15 11:42:12 +01002395 // Give the encoder queue time to process the change in degradation preference
2396 // by waiting for an encoded frame.
2397 new_video_source.IncomingCapturedFrame(
2398 CreateFrame(frame_timestamp, kFrameWidth, kFrameWidth));
2399 sink_.WaitForEncodedFrame(frame_timestamp);
2400 frame_timestamp += kFrameIntervalMs;
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02002401 EXPECT_THAT(new_video_source.sink_wants(), FpsMaxResolutionMax());
sprangc5d62e22017-04-02 23:53:04 -07002402
mflodmancc3d4422017-08-03 08:27:51 -07002403 video_stream_encoder_->TriggerCpuOveruse();
sprangc5d62e22017-04-02 23:53:04 -07002404 new_video_source.IncomingCapturedFrame(
2405 CreateFrame(frame_timestamp, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 07:06:52 -07002406 WaitForEncodedFrame(frame_timestamp);
sprangc5d62e22017-04-02 23:53:04 -07002407 frame_timestamp += kFrameIntervalMs;
2408
2409 // Still no degradation.
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02002410 EXPECT_THAT(new_video_source.sink_wants(), FpsMaxResolutionMax());
perkj803d97f2016-11-01 11:45:46 -07002411
2412 // Calling SetSource with resolution scaling enabled apply the old SinkWants.
Henrik Boström381d1092020-05-12 18:49:07 +02002413 video_stream_encoder_->SetSourceAndWaitForRestrictionsUpdated(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002414 &new_video_source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
Henrik Boström07b17df2020-01-15 11:42:12 +01002415 // Give the encoder queue time to process the change in degradation preference
2416 // by waiting for an encoded frame.
2417 new_video_source.IncomingCapturedFrame(
2418 CreateFrame(frame_timestamp, kFrameWidth, kFrameWidth));
2419 sink_.WaitForEncodedFrame(frame_timestamp);
2420 frame_timestamp += kFrameIntervalMs;
sprangc5d62e22017-04-02 23:53:04 -07002421 EXPECT_LT(new_video_source.sink_wants().max_pixel_count,
2422 kFrameWidth * kFrameHeight);
sprang84a37592017-02-10 07:04:27 -08002423 EXPECT_FALSE(new_video_source.sink_wants().target_pixel_count);
Åsa Persson8c1bf952018-09-13 10:42:19 +02002424 EXPECT_EQ(kDefaultFramerate, new_video_source.sink_wants().max_framerate_fps);
sprangc5d62e22017-04-02 23:53:04 -07002425
2426 // Calling SetSource with framerate scaling enabled apply the old SinkWants.
Henrik Boström381d1092020-05-12 18:49:07 +02002427 video_stream_encoder_->SetSourceAndWaitForRestrictionsUpdated(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002428 &new_video_source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
Henrik Boström07b17df2020-01-15 11:42:12 +01002429 // Give the encoder queue time to process the change in degradation preference
2430 // by waiting for an encoded frame.
2431 new_video_source.IncomingCapturedFrame(
2432 CreateFrame(frame_timestamp, kFrameWidth, kFrameWidth));
2433 sink_.WaitForEncodedFrame(frame_timestamp);
2434 frame_timestamp += kFrameIntervalMs;
sprangc5d62e22017-04-02 23:53:04 -07002435 EXPECT_FALSE(new_video_source.sink_wants().target_pixel_count);
2436 EXPECT_EQ(std::numeric_limits<int>::max(),
2437 new_video_source.sink_wants().max_pixel_count);
asapersson02465b82017-04-10 01:12:52 -07002438 EXPECT_LT(new_video_source.sink_wants().max_framerate_fps, kInputFps);
perkj803d97f2016-11-01 11:45:46 -07002439
mflodmancc3d4422017-08-03 08:27:51 -07002440 video_stream_encoder_->Stop();
perkj803d97f2016-11-01 11:45:46 -07002441}
2442
mflodmancc3d4422017-08-03 08:27:51 -07002443TEST_F(VideoStreamEncoderTest, StatsTracksQualityAdaptationStats) {
Henrik Boström381d1092020-05-12 18:49:07 +02002444 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01002445 DataRate::BitsPerSec(kTargetBitrateBps),
2446 DataRate::BitsPerSec(kTargetBitrateBps),
2447 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
perkj803d97f2016-11-01 11:45:46 -07002448
asaperssonfab67072017-04-04 05:51:49 -07002449 const int kWidth = 1280;
2450 const int kHeight = 720;
asaperssonfab67072017-04-04 05:51:49 -07002451 video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002452 WaitForEncodedFrame(1);
asaperssonfab67072017-04-04 05:51:49 -07002453 VideoSendStream::Stats stats = stats_proxy_->GetStats();
2454 EXPECT_FALSE(stats.bw_limited_resolution);
2455 EXPECT_EQ(0, stats.number_of_quality_adapt_changes);
2456
2457 // Trigger adapt down.
mflodmancc3d4422017-08-03 08:27:51 -07002458 video_stream_encoder_->TriggerQualityLow();
asaperssonfab67072017-04-04 05:51:49 -07002459 video_source_.IncomingCapturedFrame(CreateFrame(2, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002460 WaitForEncodedFrame(2);
asaperssonfab67072017-04-04 05:51:49 -07002461
2462 stats = stats_proxy_->GetStats();
2463 EXPECT_TRUE(stats.bw_limited_resolution);
2464 EXPECT_EQ(1, stats.number_of_quality_adapt_changes);
2465
2466 // Trigger adapt up.
mflodmancc3d4422017-08-03 08:27:51 -07002467 video_stream_encoder_->TriggerQualityHigh();
asaperssonfab67072017-04-04 05:51:49 -07002468 video_source_.IncomingCapturedFrame(CreateFrame(3, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002469 WaitForEncodedFrame(3);
asaperssonfab67072017-04-04 05:51:49 -07002470
2471 stats = stats_proxy_->GetStats();
2472 EXPECT_FALSE(stats.bw_limited_resolution);
2473 EXPECT_EQ(2, stats.number_of_quality_adapt_changes);
2474 EXPECT_EQ(0, stats.number_of_cpu_adapt_changes);
2475
mflodmancc3d4422017-08-03 08:27:51 -07002476 video_stream_encoder_->Stop();
asaperssonfab67072017-04-04 05:51:49 -07002477}
2478
mflodmancc3d4422017-08-03 08:27:51 -07002479TEST_F(VideoStreamEncoderTest, StatsTracksCpuAdaptationStats) {
Henrik Boström381d1092020-05-12 18:49:07 +02002480 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01002481 DataRate::BitsPerSec(kTargetBitrateBps),
2482 DataRate::BitsPerSec(kTargetBitrateBps),
2483 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asaperssonfab67072017-04-04 05:51:49 -07002484
2485 const int kWidth = 1280;
2486 const int kHeight = 720;
asaperssonfab67072017-04-04 05:51:49 -07002487 video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002488 WaitForEncodedFrame(1);
perkj803d97f2016-11-01 11:45:46 -07002489 VideoSendStream::Stats stats = stats_proxy_->GetStats();
2490 EXPECT_FALSE(stats.cpu_limited_resolution);
2491 EXPECT_EQ(0, stats.number_of_cpu_adapt_changes);
2492
2493 // Trigger CPU overuse.
mflodmancc3d4422017-08-03 08:27:51 -07002494 video_stream_encoder_->TriggerCpuOveruse();
asaperssonfab67072017-04-04 05:51:49 -07002495 video_source_.IncomingCapturedFrame(CreateFrame(2, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002496 WaitForEncodedFrame(2);
perkj803d97f2016-11-01 11:45:46 -07002497
2498 stats = stats_proxy_->GetStats();
2499 EXPECT_TRUE(stats.cpu_limited_resolution);
2500 EXPECT_EQ(1, stats.number_of_cpu_adapt_changes);
2501
2502 // Trigger CPU normal use.
Henrik Boström91aa7322020-04-28 12:24:33 +02002503 video_stream_encoder_->TriggerCpuUnderuse();
asaperssonfab67072017-04-04 05:51:49 -07002504 video_source_.IncomingCapturedFrame(CreateFrame(3, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002505 WaitForEncodedFrame(3);
perkj803d97f2016-11-01 11:45:46 -07002506
2507 stats = stats_proxy_->GetStats();
2508 EXPECT_FALSE(stats.cpu_limited_resolution);
2509 EXPECT_EQ(2, stats.number_of_cpu_adapt_changes);
asaperssonfab67072017-04-04 05:51:49 -07002510 EXPECT_EQ(0, stats.number_of_quality_adapt_changes);
perkj803d97f2016-11-01 11:45:46 -07002511
mflodmancc3d4422017-08-03 08:27:51 -07002512 video_stream_encoder_->Stop();
perkj803d97f2016-11-01 11:45:46 -07002513}
2514
mflodmancc3d4422017-08-03 08:27:51 -07002515TEST_F(VideoStreamEncoderTest, SwitchingSourceKeepsCpuAdaptation) {
Henrik Boström381d1092020-05-12 18:49:07 +02002516 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01002517 DataRate::BitsPerSec(kTargetBitrateBps),
2518 DataRate::BitsPerSec(kTargetBitrateBps),
2519 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
kthelgason876222f2016-11-29 01:44:11 -08002520
asaperssonfab67072017-04-04 05:51:49 -07002521 const int kWidth = 1280;
2522 const int kHeight = 720;
2523 video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002524 WaitForEncodedFrame(1);
kthelgason876222f2016-11-29 01:44:11 -08002525 VideoSendStream::Stats stats = stats_proxy_->GetStats();
asapersson09f05612017-05-15 23:40:18 -07002526 EXPECT_FALSE(stats.bw_limited_resolution);
kthelgason876222f2016-11-29 01:44:11 -08002527 EXPECT_FALSE(stats.cpu_limited_resolution);
2528 EXPECT_EQ(0, stats.number_of_cpu_adapt_changes);
2529
asaperssonfab67072017-04-04 05:51:49 -07002530 // Trigger CPU overuse.
mflodmancc3d4422017-08-03 08:27:51 -07002531 video_stream_encoder_->TriggerCpuOveruse();
asaperssonfab67072017-04-04 05:51:49 -07002532 video_source_.IncomingCapturedFrame(CreateFrame(2, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002533 WaitForEncodedFrame(2);
kthelgason876222f2016-11-29 01:44:11 -08002534 stats = stats_proxy_->GetStats();
asapersson09f05612017-05-15 23:40:18 -07002535 EXPECT_FALSE(stats.bw_limited_resolution);
kthelgason876222f2016-11-29 01:44:11 -08002536 EXPECT_TRUE(stats.cpu_limited_resolution);
2537 EXPECT_EQ(1, stats.number_of_cpu_adapt_changes);
2538
2539 // Set new source with adaptation still enabled.
2540 test::FrameForwarder new_video_source;
mflodmancc3d4422017-08-03 08:27:51 -07002541 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002542 &new_video_source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
kthelgason876222f2016-11-29 01:44:11 -08002543
asaperssonfab67072017-04-04 05:51:49 -07002544 new_video_source.IncomingCapturedFrame(CreateFrame(3, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002545 WaitForEncodedFrame(3);
kthelgason876222f2016-11-29 01:44:11 -08002546 stats = stats_proxy_->GetStats();
asapersson09f05612017-05-15 23:40:18 -07002547 EXPECT_FALSE(stats.bw_limited_resolution);
kthelgason876222f2016-11-29 01:44:11 -08002548 EXPECT_TRUE(stats.cpu_limited_resolution);
2549 EXPECT_EQ(1, stats.number_of_cpu_adapt_changes);
2550
2551 // Set adaptation disabled.
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002552 video_stream_encoder_->SetSource(&new_video_source,
2553 webrtc::DegradationPreference::DISABLED);
kthelgason876222f2016-11-29 01:44:11 -08002554
asaperssonfab67072017-04-04 05:51:49 -07002555 new_video_source.IncomingCapturedFrame(CreateFrame(4, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002556 WaitForEncodedFrame(4);
kthelgason876222f2016-11-29 01:44:11 -08002557 stats = stats_proxy_->GetStats();
asapersson09f05612017-05-15 23:40:18 -07002558 EXPECT_FALSE(stats.bw_limited_resolution);
kthelgason876222f2016-11-29 01:44:11 -08002559 EXPECT_FALSE(stats.cpu_limited_resolution);
2560 EXPECT_EQ(1, stats.number_of_cpu_adapt_changes);
2561
2562 // Set adaptation back to enabled.
mflodmancc3d4422017-08-03 08:27:51 -07002563 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002564 &new_video_source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
kthelgason876222f2016-11-29 01:44:11 -08002565
asaperssonfab67072017-04-04 05:51:49 -07002566 new_video_source.IncomingCapturedFrame(CreateFrame(5, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002567 WaitForEncodedFrame(5);
kthelgason876222f2016-11-29 01:44:11 -08002568 stats = stats_proxy_->GetStats();
asapersson09f05612017-05-15 23:40:18 -07002569 EXPECT_FALSE(stats.bw_limited_resolution);
kthelgason876222f2016-11-29 01:44:11 -08002570 EXPECT_TRUE(stats.cpu_limited_resolution);
2571 EXPECT_EQ(1, stats.number_of_cpu_adapt_changes);
2572
asaperssonfab67072017-04-04 05:51:49 -07002573 // Trigger CPU normal use.
Henrik Boström91aa7322020-04-28 12:24:33 +02002574 video_stream_encoder_->TriggerCpuUnderuse();
asaperssonfab67072017-04-04 05:51:49 -07002575 new_video_source.IncomingCapturedFrame(CreateFrame(6, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002576 WaitForEncodedFrame(6);
kthelgason876222f2016-11-29 01:44:11 -08002577 stats = stats_proxy_->GetStats();
asapersson09f05612017-05-15 23:40:18 -07002578 EXPECT_FALSE(stats.bw_limited_resolution);
kthelgason876222f2016-11-29 01:44:11 -08002579 EXPECT_FALSE(stats.cpu_limited_resolution);
2580 EXPECT_EQ(2, stats.number_of_cpu_adapt_changes);
asapersson02465b82017-04-10 01:12:52 -07002581 EXPECT_EQ(0, stats.number_of_quality_adapt_changes);
kthelgason876222f2016-11-29 01:44:11 -08002582
mflodmancc3d4422017-08-03 08:27:51 -07002583 video_stream_encoder_->Stop();
kthelgason876222f2016-11-29 01:44:11 -08002584}
2585
mflodmancc3d4422017-08-03 08:27:51 -07002586TEST_F(VideoStreamEncoderTest, SwitchingSourceKeepsQualityAdaptation) {
Henrik Boström381d1092020-05-12 18:49:07 +02002587 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01002588 DataRate::BitsPerSec(kTargetBitrateBps),
2589 DataRate::BitsPerSec(kTargetBitrateBps),
2590 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
kthelgason876222f2016-11-29 01:44:11 -08002591
asaperssonfab67072017-04-04 05:51:49 -07002592 const int kWidth = 1280;
2593 const int kHeight = 720;
2594 video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002595 WaitForEncodedFrame(1);
kthelgason876222f2016-11-29 01:44:11 -08002596 VideoSendStream::Stats stats = stats_proxy_->GetStats();
kthelgason876222f2016-11-29 01:44:11 -08002597 EXPECT_FALSE(stats.bw_limited_resolution);
asapersson13874762017-06-07 00:01:02 -07002598 EXPECT_FALSE(stats.bw_limited_framerate);
asaperssonfab67072017-04-04 05:51:49 -07002599 EXPECT_EQ(0, stats.number_of_quality_adapt_changes);
kthelgason876222f2016-11-29 01:44:11 -08002600
2601 // Set new source with adaptation still enabled.
2602 test::FrameForwarder new_video_source;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002603 video_stream_encoder_->SetSource(&new_video_source,
2604 webrtc::DegradationPreference::BALANCED);
kthelgason876222f2016-11-29 01:44:11 -08002605
asaperssonfab67072017-04-04 05:51:49 -07002606 new_video_source.IncomingCapturedFrame(CreateFrame(2, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002607 WaitForEncodedFrame(2);
kthelgason876222f2016-11-29 01:44:11 -08002608 stats = stats_proxy_->GetStats();
kthelgason876222f2016-11-29 01:44:11 -08002609 EXPECT_FALSE(stats.bw_limited_resolution);
asapersson13874762017-06-07 00:01:02 -07002610 EXPECT_FALSE(stats.bw_limited_framerate);
asaperssonfab67072017-04-04 05:51:49 -07002611 EXPECT_EQ(0, stats.number_of_quality_adapt_changes);
kthelgason876222f2016-11-29 01:44:11 -08002612
asaperssonfab67072017-04-04 05:51:49 -07002613 // Trigger adapt down.
mflodmancc3d4422017-08-03 08:27:51 -07002614 video_stream_encoder_->TriggerQualityLow();
asaperssonfab67072017-04-04 05:51:49 -07002615 new_video_source.IncomingCapturedFrame(CreateFrame(3, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002616 WaitForEncodedFrame(3);
kthelgason876222f2016-11-29 01:44:11 -08002617 stats = stats_proxy_->GetStats();
kthelgason876222f2016-11-29 01:44:11 -08002618 EXPECT_TRUE(stats.bw_limited_resolution);
asapersson13874762017-06-07 00:01:02 -07002619 EXPECT_FALSE(stats.bw_limited_framerate);
asaperssonfab67072017-04-04 05:51:49 -07002620 EXPECT_EQ(1, stats.number_of_quality_adapt_changes);
kthelgason876222f2016-11-29 01:44:11 -08002621
asaperssonfab67072017-04-04 05:51:49 -07002622 // Set new source with adaptation still enabled.
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002623 video_stream_encoder_->SetSource(&new_video_source,
2624 webrtc::DegradationPreference::BALANCED);
kthelgason876222f2016-11-29 01:44:11 -08002625
asaperssonfab67072017-04-04 05:51:49 -07002626 new_video_source.IncomingCapturedFrame(CreateFrame(4, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002627 WaitForEncodedFrame(4);
kthelgason876222f2016-11-29 01:44:11 -08002628 stats = stats_proxy_->GetStats();
kthelgason876222f2016-11-29 01:44:11 -08002629 EXPECT_TRUE(stats.bw_limited_resolution);
asapersson13874762017-06-07 00:01:02 -07002630 EXPECT_FALSE(stats.bw_limited_framerate);
asaperssonfab67072017-04-04 05:51:49 -07002631 EXPECT_EQ(1, stats.number_of_quality_adapt_changes);
kthelgason876222f2016-11-29 01:44:11 -08002632
asapersson02465b82017-04-10 01:12:52 -07002633 // Disable resolution scaling.
mflodmancc3d4422017-08-03 08:27:51 -07002634 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002635 &new_video_source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
kthelgason876222f2016-11-29 01:44:11 -08002636
asaperssonfab67072017-04-04 05:51:49 -07002637 new_video_source.IncomingCapturedFrame(CreateFrame(5, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002638 WaitForEncodedFrame(5);
kthelgason876222f2016-11-29 01:44:11 -08002639 stats = stats_proxy_->GetStats();
kthelgason876222f2016-11-29 01:44:11 -08002640 EXPECT_FALSE(stats.bw_limited_resolution);
asapersson13874762017-06-07 00:01:02 -07002641 EXPECT_FALSE(stats.bw_limited_framerate);
asaperssonfab67072017-04-04 05:51:49 -07002642 EXPECT_EQ(1, stats.number_of_quality_adapt_changes);
2643 EXPECT_EQ(0, stats.number_of_cpu_adapt_changes);
kthelgason876222f2016-11-29 01:44:11 -08002644
mflodmancc3d4422017-08-03 08:27:51 -07002645 video_stream_encoder_->Stop();
kthelgason876222f2016-11-29 01:44:11 -08002646}
2647
mflodmancc3d4422017-08-03 08:27:51 -07002648TEST_F(VideoStreamEncoderTest,
2649 QualityAdaptationStatsAreResetWhenScalerIsDisabled) {
Henrik Boström381d1092020-05-12 18:49:07 +02002650 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01002651 DataRate::BitsPerSec(kTargetBitrateBps),
2652 DataRate::BitsPerSec(kTargetBitrateBps),
2653 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asapersson36e9eb42017-03-31 05:29:12 -07002654
2655 const int kWidth = 1280;
2656 const int kHeight = 720;
Åsa Persson8c1bf952018-09-13 10:42:19 +02002657 int64_t timestamp_ms = kFrameIntervalMs;
asapersson36e9eb42017-03-31 05:29:12 -07002658 video_source_.set_adaptation_enabled(true);
Åsa Persson8c1bf952018-09-13 10:42:19 +02002659 video_source_.IncomingCapturedFrame(
2660 CreateFrame(timestamp_ms, kWidth, kHeight));
2661 WaitForEncodedFrame(timestamp_ms);
asapersson36e9eb42017-03-31 05:29:12 -07002662 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
2663 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
2664 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
2665
2666 // Trigger adapt down.
mflodmancc3d4422017-08-03 08:27:51 -07002667 video_stream_encoder_->TriggerQualityLow();
Åsa Persson8c1bf952018-09-13 10:42:19 +02002668 timestamp_ms += kFrameIntervalMs;
2669 video_source_.IncomingCapturedFrame(
2670 CreateFrame(timestamp_ms, kWidth, kHeight));
2671 WaitForEncodedFrame(timestamp_ms);
asapersson36e9eb42017-03-31 05:29:12 -07002672 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
2673 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
2674 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
2675
2676 // Trigger overuse.
mflodmancc3d4422017-08-03 08:27:51 -07002677 video_stream_encoder_->TriggerCpuOveruse();
Åsa Persson8c1bf952018-09-13 10:42:19 +02002678 timestamp_ms += kFrameIntervalMs;
2679 video_source_.IncomingCapturedFrame(
2680 CreateFrame(timestamp_ms, kWidth, kHeight));
2681 WaitForEncodedFrame(timestamp_ms);
asapersson36e9eb42017-03-31 05:29:12 -07002682 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
2683 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
2684 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
2685
Niels Möller4db138e2018-04-19 09:04:13 +02002686 // Leave source unchanged, but disable quality scaler.
asapersson36e9eb42017-03-31 05:29:12 -07002687 fake_encoder_.SetQualityScaling(false);
Niels Möller4db138e2018-04-19 09:04:13 +02002688
2689 VideoEncoderConfig video_encoder_config;
2690 test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
2691 // Make format different, to force recreation of encoder.
2692 video_encoder_config.video_format.parameters["foo"] = "foo";
2693 video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config),
Niels Möllerf1338562018-04-26 09:51:47 +02002694 kMaxPayloadLength);
Åsa Persson8c1bf952018-09-13 10:42:19 +02002695 timestamp_ms += kFrameIntervalMs;
2696 video_source_.IncomingCapturedFrame(
2697 CreateFrame(timestamp_ms, kWidth, kHeight));
2698 WaitForEncodedFrame(timestamp_ms);
asapersson36e9eb42017-03-31 05:29:12 -07002699 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
2700 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
2701 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
2702
mflodmancc3d4422017-08-03 08:27:51 -07002703 video_stream_encoder_->Stop();
asapersson36e9eb42017-03-31 05:29:12 -07002704}
2705
mflodmancc3d4422017-08-03 08:27:51 -07002706TEST_F(VideoStreamEncoderTest,
Evan Shrubsole33be9df2020-03-05 18:39:32 +01002707 StatsTracksCpuAdaptationStatsWhenSwitchingSource_Balanced) {
Henrik Boström381d1092020-05-12 18:49:07 +02002708 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Evan Shrubsole33be9df2020-03-05 18:39:32 +01002709 DataRate::BitsPerSec(kTargetBitrateBps),
2710 DataRate::BitsPerSec(kTargetBitrateBps),
2711 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
2712
2713 const int kWidth = 1280;
2714 const int kHeight = 720;
2715 int sequence = 1;
2716
2717 // Enable BALANCED preference, no initial limitation.
2718 test::FrameForwarder source;
2719 video_stream_encoder_->SetSource(&source,
2720 webrtc::DegradationPreference::BALANCED);
2721 source.IncomingCapturedFrame(CreateFrame(sequence, kWidth, kHeight));
2722 WaitForEncodedFrame(sequence++);
2723 VideoSendStream::Stats stats = stats_proxy_->GetStats();
2724 EXPECT_FALSE(stats.cpu_limited_resolution);
2725 EXPECT_FALSE(stats.cpu_limited_framerate);
2726 EXPECT_EQ(0, stats.number_of_cpu_adapt_changes);
2727
2728 // Trigger CPU overuse, should now adapt down.
2729 video_stream_encoder_->TriggerCpuOveruse();
2730 source.IncomingCapturedFrame(CreateFrame(sequence, kWidth, kHeight));
2731 WaitForEncodedFrame(sequence++);
2732 stats = stats_proxy_->GetStats();
2733 EXPECT_EQ(1, stats.number_of_cpu_adapt_changes);
2734
2735 // Set new degradation preference should clear restrictions since we changed
2736 // from BALANCED.
Evan Shrubsolede2049e2020-05-25 16:54:21 +02002737 video_stream_encoder_->SetSourceAndWaitForRestrictionsUpdated(
Evan Shrubsole33be9df2020-03-05 18:39:32 +01002738 &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
2739 source.IncomingCapturedFrame(CreateFrame(sequence, kWidth, kHeight));
2740 WaitForEncodedFrame(sequence++);
2741 stats = stats_proxy_->GetStats();
2742 EXPECT_FALSE(stats.cpu_limited_resolution);
2743 EXPECT_FALSE(stats.cpu_limited_framerate);
2744 EXPECT_EQ(1, stats.number_of_cpu_adapt_changes);
2745
2746 // Force an input frame rate to be available, or the adaptation call won't
2747 // know what framerate to adapt from.
2748 VideoSendStream::Stats mock_stats = stats_proxy_->GetStats();
2749 mock_stats.input_frame_rate = 30;
2750 stats_proxy_->SetMockStats(mock_stats);
2751 video_stream_encoder_->TriggerCpuOveruse();
2752 stats_proxy_->ResetMockStats();
2753 source.IncomingCapturedFrame(CreateFrame(sequence, kWidth, kHeight));
2754 WaitForEncodedFrame(sequence++);
2755
2756 // We have now adapted once.
2757 stats = stats_proxy_->GetStats();
2758 EXPECT_EQ(2, stats.number_of_cpu_adapt_changes);
2759
2760 // Back to BALANCED, should clear the restrictions again.
Evan Shrubsolede2049e2020-05-25 16:54:21 +02002761 video_stream_encoder_->SetSourceAndWaitForRestrictionsUpdated(
2762 &source, webrtc::DegradationPreference::BALANCED);
Evan Shrubsole33be9df2020-03-05 18:39:32 +01002763 source.IncomingCapturedFrame(CreateFrame(sequence, kWidth, kHeight));
2764 WaitForEncodedFrame(sequence++);
2765 stats = stats_proxy_->GetStats();
2766 EXPECT_FALSE(stats.cpu_limited_resolution);
2767 EXPECT_FALSE(stats.cpu_limited_framerate);
2768 EXPECT_EQ(2, stats.number_of_cpu_adapt_changes);
2769
2770 video_stream_encoder_->Stop();
2771}
2772
2773TEST_F(VideoStreamEncoderTest,
mflodmancc3d4422017-08-03 08:27:51 -07002774 StatsTracksCpuAdaptationStatsWhenSwitchingSource) {
Henrik Boström381d1092020-05-12 18:49:07 +02002775 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01002776 DataRate::BitsPerSec(kTargetBitrateBps),
2777 DataRate::BitsPerSec(kTargetBitrateBps),
2778 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
perkj803d97f2016-11-01 11:45:46 -07002779
asapersson0944a802017-04-07 00:57:58 -07002780 const int kWidth = 1280;
2781 const int kHeight = 720;
sprang84a37592017-02-10 07:04:27 -08002782 int sequence = 1;
perkj803d97f2016-11-01 11:45:46 -07002783
asaperssonfab67072017-04-04 05:51:49 -07002784 video_source_.IncomingCapturedFrame(CreateFrame(sequence, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002785 WaitForEncodedFrame(sequence++);
perkj803d97f2016-11-01 11:45:46 -07002786 VideoSendStream::Stats stats = stats_proxy_->GetStats();
sprang84a37592017-02-10 07:04:27 -08002787 EXPECT_FALSE(stats.cpu_limited_resolution);
asapersson13874762017-06-07 00:01:02 -07002788 EXPECT_FALSE(stats.cpu_limited_framerate);
sprang84a37592017-02-10 07:04:27 -08002789 EXPECT_EQ(0, stats.number_of_cpu_adapt_changes);
2790
asapersson02465b82017-04-10 01:12:52 -07002791 // Trigger CPU overuse, should now adapt down.
mflodmancc3d4422017-08-03 08:27:51 -07002792 video_stream_encoder_->TriggerCpuOveruse();
asaperssonfab67072017-04-04 05:51:49 -07002793 video_source_.IncomingCapturedFrame(CreateFrame(sequence, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002794 WaitForEncodedFrame(sequence++);
sprang84a37592017-02-10 07:04:27 -08002795 stats = stats_proxy_->GetStats();
perkj803d97f2016-11-01 11:45:46 -07002796 EXPECT_TRUE(stats.cpu_limited_resolution);
asapersson13874762017-06-07 00:01:02 -07002797 EXPECT_FALSE(stats.cpu_limited_framerate);
perkj803d97f2016-11-01 11:45:46 -07002798 EXPECT_EQ(1, stats.number_of_cpu_adapt_changes);
2799
2800 // Set new source with adaptation still enabled.
2801 test::FrameForwarder new_video_source;
mflodmancc3d4422017-08-03 08:27:51 -07002802 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002803 &new_video_source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
perkj803d97f2016-11-01 11:45:46 -07002804
2805 new_video_source.IncomingCapturedFrame(
asaperssonfab67072017-04-04 05:51:49 -07002806 CreateFrame(sequence, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002807 WaitForEncodedFrame(sequence++);
perkj803d97f2016-11-01 11:45:46 -07002808 stats = stats_proxy_->GetStats();
2809 EXPECT_TRUE(stats.cpu_limited_resolution);
asapersson09f05612017-05-15 23:40:18 -07002810 EXPECT_FALSE(stats.cpu_limited_framerate);
perkj803d97f2016-11-01 11:45:46 -07002811 EXPECT_EQ(1, stats.number_of_cpu_adapt_changes);
2812
sprangc5d62e22017-04-02 23:53:04 -07002813 // Set cpu adaptation by frame dropping.
mflodmancc3d4422017-08-03 08:27:51 -07002814 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002815 &new_video_source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
perkj803d97f2016-11-01 11:45:46 -07002816 new_video_source.IncomingCapturedFrame(
asaperssonfab67072017-04-04 05:51:49 -07002817 CreateFrame(sequence, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002818 WaitForEncodedFrame(sequence++);
perkj803d97f2016-11-01 11:45:46 -07002819 stats = stats_proxy_->GetStats();
sprangc5d62e22017-04-02 23:53:04 -07002820 // Not adapted at first.
perkj803d97f2016-11-01 11:45:46 -07002821 EXPECT_FALSE(stats.cpu_limited_resolution);
asapersson09f05612017-05-15 23:40:18 -07002822 EXPECT_FALSE(stats.cpu_limited_framerate);
perkj803d97f2016-11-01 11:45:46 -07002823 EXPECT_EQ(1, stats.number_of_cpu_adapt_changes);
2824
sprangc5d62e22017-04-02 23:53:04 -07002825 // Force an input frame rate to be available, or the adaptation call won't
asapersson09f05612017-05-15 23:40:18 -07002826 // know what framerate to adapt from.
sprangc5d62e22017-04-02 23:53:04 -07002827 VideoSendStream::Stats mock_stats = stats_proxy_->GetStats();
2828 mock_stats.input_frame_rate = 30;
2829 stats_proxy_->SetMockStats(mock_stats);
mflodmancc3d4422017-08-03 08:27:51 -07002830 video_stream_encoder_->TriggerCpuOveruse();
sprangc5d62e22017-04-02 23:53:04 -07002831 stats_proxy_->ResetMockStats();
2832
2833 new_video_source.IncomingCapturedFrame(
asaperssonfab67072017-04-04 05:51:49 -07002834 CreateFrame(sequence, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002835 WaitForEncodedFrame(sequence++);
sprangc5d62e22017-04-02 23:53:04 -07002836
2837 // Framerate now adapted.
2838 stats = stats_proxy_->GetStats();
asapersson09f05612017-05-15 23:40:18 -07002839 EXPECT_FALSE(stats.cpu_limited_resolution);
2840 EXPECT_TRUE(stats.cpu_limited_framerate);
sprangc5d62e22017-04-02 23:53:04 -07002841 EXPECT_EQ(2, stats.number_of_cpu_adapt_changes);
2842
2843 // Disable CPU adaptation.
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002844 video_stream_encoder_->SetSource(&new_video_source,
2845 webrtc::DegradationPreference::DISABLED);
sprangc5d62e22017-04-02 23:53:04 -07002846 new_video_source.IncomingCapturedFrame(
asaperssonfab67072017-04-04 05:51:49 -07002847 CreateFrame(sequence, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002848 WaitForEncodedFrame(sequence++);
sprangc5d62e22017-04-02 23:53:04 -07002849
2850 stats = stats_proxy_->GetStats();
2851 EXPECT_FALSE(stats.cpu_limited_resolution);
asapersson13874762017-06-07 00:01:02 -07002852 EXPECT_FALSE(stats.cpu_limited_framerate);
sprangc5d62e22017-04-02 23:53:04 -07002853 EXPECT_EQ(2, stats.number_of_cpu_adapt_changes);
2854
2855 // Try to trigger overuse. Should not succeed.
2856 stats_proxy_->SetMockStats(mock_stats);
mflodmancc3d4422017-08-03 08:27:51 -07002857 video_stream_encoder_->TriggerCpuOveruse();
sprangc5d62e22017-04-02 23:53:04 -07002858 stats_proxy_->ResetMockStats();
2859
2860 stats = stats_proxy_->GetStats();
2861 EXPECT_FALSE(stats.cpu_limited_resolution);
asapersson13874762017-06-07 00:01:02 -07002862 EXPECT_FALSE(stats.cpu_limited_framerate);
sprangc5d62e22017-04-02 23:53:04 -07002863 EXPECT_EQ(2, stats.number_of_cpu_adapt_changes);
2864
2865 // Switch back the source with resolution adaptation enabled.
mflodmancc3d4422017-08-03 08:27:51 -07002866 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002867 &video_source_, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
asaperssonfab67072017-04-04 05:51:49 -07002868 video_source_.IncomingCapturedFrame(CreateFrame(sequence, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002869 WaitForEncodedFrame(sequence++);
perkj803d97f2016-11-01 11:45:46 -07002870 stats = stats_proxy_->GetStats();
2871 EXPECT_TRUE(stats.cpu_limited_resolution);
asapersson13874762017-06-07 00:01:02 -07002872 EXPECT_FALSE(stats.cpu_limited_framerate);
sprangc5d62e22017-04-02 23:53:04 -07002873 EXPECT_EQ(2, stats.number_of_cpu_adapt_changes);
perkj803d97f2016-11-01 11:45:46 -07002874
2875 // Trigger CPU normal usage.
Henrik Boström91aa7322020-04-28 12:24:33 +02002876 video_stream_encoder_->TriggerCpuUnderuse();
asaperssonfab67072017-04-04 05:51:49 -07002877 video_source_.IncomingCapturedFrame(CreateFrame(sequence, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002878 WaitForEncodedFrame(sequence++);
perkj803d97f2016-11-01 11:45:46 -07002879 stats = stats_proxy_->GetStats();
2880 EXPECT_FALSE(stats.cpu_limited_resolution);
asapersson13874762017-06-07 00:01:02 -07002881 EXPECT_FALSE(stats.cpu_limited_framerate);
sprangc5d62e22017-04-02 23:53:04 -07002882 EXPECT_EQ(3, stats.number_of_cpu_adapt_changes);
2883
2884 // Back to the source with adaptation off, set it back to maintain-resolution.
mflodmancc3d4422017-08-03 08:27:51 -07002885 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002886 &new_video_source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
sprangc5d62e22017-04-02 23:53:04 -07002887 new_video_source.IncomingCapturedFrame(
asaperssonfab67072017-04-04 05:51:49 -07002888 CreateFrame(sequence, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002889 WaitForEncodedFrame(sequence++);
sprangc5d62e22017-04-02 23:53:04 -07002890 stats = stats_proxy_->GetStats();
asapersson13874762017-06-07 00:01:02 -07002891 // Disabled, since we previously switched the source to disabled.
sprangc5d62e22017-04-02 23:53:04 -07002892 EXPECT_FALSE(stats.cpu_limited_resolution);
asapersson13874762017-06-07 00:01:02 -07002893 EXPECT_TRUE(stats.cpu_limited_framerate);
sprangc5d62e22017-04-02 23:53:04 -07002894 EXPECT_EQ(3, stats.number_of_cpu_adapt_changes);
2895
2896 // Trigger CPU normal usage.
Henrik Boström91aa7322020-04-28 12:24:33 +02002897 video_stream_encoder_->TriggerCpuUnderuse();
sprangc5d62e22017-04-02 23:53:04 -07002898 new_video_source.IncomingCapturedFrame(
asaperssonfab67072017-04-04 05:51:49 -07002899 CreateFrame(sequence, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002900 WaitForEncodedFrame(sequence++);
sprangc5d62e22017-04-02 23:53:04 -07002901 stats = stats_proxy_->GetStats();
2902 EXPECT_FALSE(stats.cpu_limited_resolution);
asapersson13874762017-06-07 00:01:02 -07002903 EXPECT_FALSE(stats.cpu_limited_framerate);
sprangc5d62e22017-04-02 23:53:04 -07002904 EXPECT_EQ(4, stats.number_of_cpu_adapt_changes);
asapersson02465b82017-04-10 01:12:52 -07002905 EXPECT_EQ(0, stats.number_of_quality_adapt_changes);
perkj803d97f2016-11-01 11:45:46 -07002906
mflodmancc3d4422017-08-03 08:27:51 -07002907 video_stream_encoder_->Stop();
perkj803d97f2016-11-01 11:45:46 -07002908}
2909
mflodmancc3d4422017-08-03 08:27:51 -07002910TEST_F(VideoStreamEncoderTest,
2911 ScalingUpAndDownDoesNothingWithMaintainResolution) {
asaperssonfab67072017-04-04 05:51:49 -07002912 const int kWidth = 1280;
2913 const int kHeight = 720;
Henrik Boström381d1092020-05-12 18:49:07 +02002914 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01002915 DataRate::BitsPerSec(kTargetBitrateBps),
2916 DataRate::BitsPerSec(kTargetBitrateBps),
2917 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
kthelgason876222f2016-11-29 01:44:11 -08002918
asaperssonfab67072017-04-04 05:51:49 -07002919 // Expect no scaling to begin with.
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02002920 EXPECT_THAT(video_source_.sink_wants(), UnlimitedSinkWants());
kthelgason876222f2016-11-29 01:44:11 -08002921
asaperssonfab67072017-04-04 05:51:49 -07002922 video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002923 WaitForEncodedFrame(1);
kthelgason876222f2016-11-29 01:44:11 -08002924
asaperssonfab67072017-04-04 05:51:49 -07002925 // Trigger scale down.
mflodmancc3d4422017-08-03 08:27:51 -07002926 video_stream_encoder_->TriggerQualityLow();
kthelgason5e13d412016-12-01 03:59:51 -08002927
asaperssonfab67072017-04-04 05:51:49 -07002928 video_source_.IncomingCapturedFrame(CreateFrame(2, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002929 WaitForEncodedFrame(2);
kthelgason5e13d412016-12-01 03:59:51 -08002930
kthelgason876222f2016-11-29 01:44:11 -08002931 // Expect a scale down.
2932 EXPECT_TRUE(video_source_.sink_wants().max_pixel_count);
asaperssonfab67072017-04-04 05:51:49 -07002933 EXPECT_LT(video_source_.sink_wants().max_pixel_count, kWidth * kHeight);
kthelgason876222f2016-11-29 01:44:11 -08002934
asapersson02465b82017-04-10 01:12:52 -07002935 // Set resolution scaling disabled.
kthelgason876222f2016-11-29 01:44:11 -08002936 test::FrameForwarder new_video_source;
mflodmancc3d4422017-08-03 08:27:51 -07002937 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002938 &new_video_source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
kthelgason876222f2016-11-29 01:44:11 -08002939
asaperssonfab67072017-04-04 05:51:49 -07002940 // Trigger scale down.
mflodmancc3d4422017-08-03 08:27:51 -07002941 video_stream_encoder_->TriggerQualityLow();
asaperssonfab67072017-04-04 05:51:49 -07002942 new_video_source.IncomingCapturedFrame(CreateFrame(3, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002943 WaitForEncodedFrame(3);
kthelgason876222f2016-11-29 01:44:11 -08002944
asaperssonfab67072017-04-04 05:51:49 -07002945 // Expect no scaling.
sprangc5d62e22017-04-02 23:53:04 -07002946 EXPECT_EQ(std::numeric_limits<int>::max(),
2947 new_video_source.sink_wants().max_pixel_count);
kthelgason876222f2016-11-29 01:44:11 -08002948
asaperssonfab67072017-04-04 05:51:49 -07002949 // Trigger scale up.
mflodmancc3d4422017-08-03 08:27:51 -07002950 video_stream_encoder_->TriggerQualityHigh();
asaperssonfab67072017-04-04 05:51:49 -07002951 new_video_source.IncomingCapturedFrame(CreateFrame(4, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002952 WaitForEncodedFrame(4);
kthelgason876222f2016-11-29 01:44:11 -08002953
asapersson02465b82017-04-10 01:12:52 -07002954 // Expect nothing to change, still no scaling.
sprangc5d62e22017-04-02 23:53:04 -07002955 EXPECT_EQ(std::numeric_limits<int>::max(),
2956 new_video_source.sink_wants().max_pixel_count);
kthelgason876222f2016-11-29 01:44:11 -08002957
mflodmancc3d4422017-08-03 08:27:51 -07002958 video_stream_encoder_->Stop();
kthelgason876222f2016-11-29 01:44:11 -08002959}
2960
mflodmancc3d4422017-08-03 08:27:51 -07002961TEST_F(VideoStreamEncoderTest,
2962 SkipsSameAdaptDownRequest_MaintainFramerateMode) {
asapersson02465b82017-04-10 01:12:52 -07002963 const int kWidth = 1280;
2964 const int kHeight = 720;
Henrik Boström381d1092020-05-12 18:49:07 +02002965 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01002966 DataRate::BitsPerSec(kTargetBitrateBps),
2967 DataRate::BitsPerSec(kTargetBitrateBps),
2968 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asapersson02465b82017-04-10 01:12:52 -07002969
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002970 // Enable MAINTAIN_FRAMERATE preference, no initial limitation.
asapersson02465b82017-04-10 01:12:52 -07002971 test::FrameForwarder source;
mflodmancc3d4422017-08-03 08:27:51 -07002972 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002973 &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
asapersson02465b82017-04-10 01:12:52 -07002974
2975 source.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002976 WaitForEncodedFrame(1);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02002977 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asapersson02465b82017-04-10 01:12:52 -07002978 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
2979 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
2980
2981 // Trigger adapt down, expect scaled down resolution.
mflodmancc3d4422017-08-03 08:27:51 -07002982 video_stream_encoder_->TriggerCpuOveruse();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02002983 EXPECT_THAT(source.sink_wants(),
2984 FpsMaxResolutionMatches(Lt(kWidth * kHeight)));
asapersson02465b82017-04-10 01:12:52 -07002985 const int kLastMaxPixelCount = source.sink_wants().max_pixel_count;
2986 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
2987 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
2988
2989 // Trigger adapt down for same input resolution, expect no change.
mflodmancc3d4422017-08-03 08:27:51 -07002990 video_stream_encoder_->TriggerCpuOveruse();
asapersson02465b82017-04-10 01:12:52 -07002991 EXPECT_EQ(kLastMaxPixelCount, source.sink_wants().max_pixel_count);
2992 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
2993 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
2994
mflodmancc3d4422017-08-03 08:27:51 -07002995 video_stream_encoder_->Stop();
asapersson02465b82017-04-10 01:12:52 -07002996}
2997
mflodmancc3d4422017-08-03 08:27:51 -07002998TEST_F(VideoStreamEncoderTest, SkipsSameOrLargerAdaptDownRequest_BalancedMode) {
asaperssonf7e294d2017-06-13 23:25:22 -07002999 const int kWidth = 1280;
3000 const int kHeight = 720;
Henrik Boström381d1092020-05-12 18:49:07 +02003001 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01003002 DataRate::BitsPerSec(kTargetBitrateBps),
3003 DataRate::BitsPerSec(kTargetBitrateBps),
3004 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asaperssonf7e294d2017-06-13 23:25:22 -07003005
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003006 // Enable BALANCED preference, no initial limitation.
asaperssonf7e294d2017-06-13 23:25:22 -07003007 test::FrameForwarder source;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003008 video_stream_encoder_->SetSource(&source,
3009 webrtc::DegradationPreference::BALANCED);
asaperssonf7e294d2017-06-13 23:25:22 -07003010 source.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
3011 sink_.WaitForEncodedFrame(1);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003012 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-13 23:25:22 -07003013
3014 // Trigger adapt down, expect scaled down resolution.
mflodmancc3d4422017-08-03 08:27:51 -07003015 video_stream_encoder_->TriggerQualityLow();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003016 EXPECT_THAT(source.sink_wants(),
3017 FpsMaxResolutionMatches(Lt(kWidth * kHeight)));
asaperssonf7e294d2017-06-13 23:25:22 -07003018 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
3019 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3020 const int kLastMaxPixelCount = source.sink_wants().max_pixel_count;
3021
3022 // Trigger adapt down for same input resolution, expect no change.
3023 source.IncomingCapturedFrame(CreateFrame(2, kWidth, kHeight));
3024 sink_.WaitForEncodedFrame(2);
mflodmancc3d4422017-08-03 08:27:51 -07003025 video_stream_encoder_->TriggerQualityLow();
asaperssonf7e294d2017-06-13 23:25:22 -07003026 EXPECT_EQ(kLastMaxPixelCount, source.sink_wants().max_pixel_count);
3027 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
3028 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3029
3030 // Trigger adapt down for larger input resolution, expect no change.
3031 source.IncomingCapturedFrame(CreateFrame(3, kWidth + 1, kHeight + 1));
3032 sink_.WaitForEncodedFrame(3);
mflodmancc3d4422017-08-03 08:27:51 -07003033 video_stream_encoder_->TriggerQualityLow();
asaperssonf7e294d2017-06-13 23:25:22 -07003034 EXPECT_EQ(kLastMaxPixelCount, source.sink_wants().max_pixel_count);
3035 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
3036 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3037
mflodmancc3d4422017-08-03 08:27:51 -07003038 video_stream_encoder_->Stop();
asaperssonf7e294d2017-06-13 23:25:22 -07003039}
3040
mflodmancc3d4422017-08-03 08:27:51 -07003041TEST_F(VideoStreamEncoderTest,
3042 NoChangeForInitialNormalUsage_MaintainFramerateMode) {
asapersson02465b82017-04-10 01:12:52 -07003043 const int kWidth = 1280;
3044 const int kHeight = 720;
Henrik Boström381d1092020-05-12 18:49:07 +02003045 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01003046 DataRate::BitsPerSec(kTargetBitrateBps),
3047 DataRate::BitsPerSec(kTargetBitrateBps),
3048 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asapersson02465b82017-04-10 01:12:52 -07003049
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003050 // Enable MAINTAIN_FRAMERATE preference, no initial limitation.
asapersson02465b82017-04-10 01:12:52 -07003051 test::FrameForwarder source;
mflodmancc3d4422017-08-03 08:27:51 -07003052 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003053 &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
asapersson02465b82017-04-10 01:12:52 -07003054
3055 source.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07003056 WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003057 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asapersson02465b82017-04-10 01:12:52 -07003058 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
3059 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3060
3061 // Trigger adapt up, expect no change.
Henrik Boström91aa7322020-04-28 12:24:33 +02003062 video_stream_encoder_->TriggerCpuUnderuse();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003063 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asapersson02465b82017-04-10 01:12:52 -07003064 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
3065 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3066
mflodmancc3d4422017-08-03 08:27:51 -07003067 video_stream_encoder_->Stop();
asapersson02465b82017-04-10 01:12:52 -07003068}
3069
mflodmancc3d4422017-08-03 08:27:51 -07003070TEST_F(VideoStreamEncoderTest,
3071 NoChangeForInitialNormalUsage_MaintainResolutionMode) {
asapersson02465b82017-04-10 01:12:52 -07003072 const int kWidth = 1280;
3073 const int kHeight = 720;
Henrik Boström381d1092020-05-12 18:49:07 +02003074 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01003075 DataRate::BitsPerSec(kTargetBitrateBps),
3076 DataRate::BitsPerSec(kTargetBitrateBps),
3077 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asapersson02465b82017-04-10 01:12:52 -07003078
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003079 // Enable MAINTAIN_RESOLUTION preference, no initial limitation.
asapersson02465b82017-04-10 01:12:52 -07003080 test::FrameForwarder source;
mflodmancc3d4422017-08-03 08:27:51 -07003081 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003082 &source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
asapersson02465b82017-04-10 01:12:52 -07003083
3084 source.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07003085 WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003086 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asapersson09f05612017-05-15 23:40:18 -07003087 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
asapersson02465b82017-04-10 01:12:52 -07003088 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3089
3090 // Trigger adapt up, expect no change.
Henrik Boström91aa7322020-04-28 12:24:33 +02003091 video_stream_encoder_->TriggerCpuUnderuse();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003092 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asapersson09f05612017-05-15 23:40:18 -07003093 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
asapersson02465b82017-04-10 01:12:52 -07003094 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3095
mflodmancc3d4422017-08-03 08:27:51 -07003096 video_stream_encoder_->Stop();
asapersson02465b82017-04-10 01:12:52 -07003097}
3098
mflodmancc3d4422017-08-03 08:27:51 -07003099TEST_F(VideoStreamEncoderTest, NoChangeForInitialNormalUsage_BalancedMode) {
asaperssonf7e294d2017-06-13 23:25:22 -07003100 const int kWidth = 1280;
3101 const int kHeight = 720;
Henrik Boström381d1092020-05-12 18:49:07 +02003102 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01003103 DataRate::BitsPerSec(kTargetBitrateBps),
3104 DataRate::BitsPerSec(kTargetBitrateBps),
3105 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asaperssonf7e294d2017-06-13 23:25:22 -07003106
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003107 // Enable BALANCED preference, no initial limitation.
asaperssonf7e294d2017-06-13 23:25:22 -07003108 test::FrameForwarder source;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003109 video_stream_encoder_->SetSource(&source,
3110 webrtc::DegradationPreference::BALANCED);
asaperssonf7e294d2017-06-13 23:25:22 -07003111
3112 source.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
3113 sink_.WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003114 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-13 23:25:22 -07003115 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
3116 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
3117 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3118
3119 // Trigger adapt up, expect no change.
mflodmancc3d4422017-08-03 08:27:51 -07003120 video_stream_encoder_->TriggerQualityHigh();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003121 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-13 23:25:22 -07003122 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
3123 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
3124 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3125
mflodmancc3d4422017-08-03 08:27:51 -07003126 video_stream_encoder_->Stop();
asaperssonf7e294d2017-06-13 23:25:22 -07003127}
3128
mflodmancc3d4422017-08-03 08:27:51 -07003129TEST_F(VideoStreamEncoderTest, NoChangeForInitialNormalUsage_DisabledMode) {
asapersson09f05612017-05-15 23:40:18 -07003130 const int kWidth = 1280;
3131 const int kHeight = 720;
Henrik Boström381d1092020-05-12 18:49:07 +02003132 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01003133 DataRate::BitsPerSec(kTargetBitrateBps),
3134 DataRate::BitsPerSec(kTargetBitrateBps),
3135 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asapersson09f05612017-05-15 23:40:18 -07003136
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003137 // Enable DISABLED preference, no initial limitation.
asapersson09f05612017-05-15 23:40:18 -07003138 test::FrameForwarder source;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003139 video_stream_encoder_->SetSource(&source,
3140 webrtc::DegradationPreference::DISABLED);
asapersson09f05612017-05-15 23:40:18 -07003141
3142 source.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
3143 sink_.WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003144 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asapersson09f05612017-05-15 23:40:18 -07003145 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
3146 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
3147 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3148
3149 // Trigger adapt up, expect no change.
mflodmancc3d4422017-08-03 08:27:51 -07003150 video_stream_encoder_->TriggerQualityHigh();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003151 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asapersson09f05612017-05-15 23:40:18 -07003152 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
3153 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
3154 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3155
mflodmancc3d4422017-08-03 08:27:51 -07003156 video_stream_encoder_->Stop();
asapersson09f05612017-05-15 23:40:18 -07003157}
3158
mflodmancc3d4422017-08-03 08:27:51 -07003159TEST_F(VideoStreamEncoderTest,
3160 AdaptsResolutionForLowQuality_MaintainFramerateMode) {
asapersson02465b82017-04-10 01:12:52 -07003161 const int kWidth = 1280;
3162 const int kHeight = 720;
Henrik Boström381d1092020-05-12 18:49:07 +02003163 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01003164 DataRate::BitsPerSec(kTargetBitrateBps),
3165 DataRate::BitsPerSec(kTargetBitrateBps),
3166 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asapersson02465b82017-04-10 01:12:52 -07003167
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003168 // Enable MAINTAIN_FRAMERATE preference, no initial limitation.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02003169 AdaptingFrameForwarder source(&time_controller_);
asapersson02465b82017-04-10 01:12:52 -07003170 source.set_adaptation_enabled(true);
mflodmancc3d4422017-08-03 08:27:51 -07003171 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003172 &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
asapersson02465b82017-04-10 01:12:52 -07003173
3174 source.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07003175 WaitForEncodedFrame(1);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003176 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asapersson02465b82017-04-10 01:12:52 -07003177 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
3178 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3179
3180 // Trigger adapt down, expect scaled down resolution.
mflodmancc3d4422017-08-03 08:27:51 -07003181 video_stream_encoder_->TriggerQualityLow();
asapersson02465b82017-04-10 01:12:52 -07003182 source.IncomingCapturedFrame(CreateFrame(2, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07003183 WaitForEncodedFrame(2);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003184 EXPECT_THAT(source.sink_wants(),
3185 FpsMaxResolutionMatches(Lt(kWidth * kHeight)));
asapersson02465b82017-04-10 01:12:52 -07003186 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
3187 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3188
3189 // Trigger adapt up, expect no restriction.
mflodmancc3d4422017-08-03 08:27:51 -07003190 video_stream_encoder_->TriggerQualityHigh();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003191 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asapersson02465b82017-04-10 01:12:52 -07003192 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
3193 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3194 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3195
mflodmancc3d4422017-08-03 08:27:51 -07003196 video_stream_encoder_->Stop();
asapersson02465b82017-04-10 01:12:52 -07003197}
3198
mflodmancc3d4422017-08-03 08:27:51 -07003199TEST_F(VideoStreamEncoderTest,
3200 AdaptsFramerateForLowQuality_MaintainResolutionMode) {
asapersson09f05612017-05-15 23:40:18 -07003201 const int kWidth = 1280;
3202 const int kHeight = 720;
3203 const int kInputFps = 30;
Henrik Boström381d1092020-05-12 18:49:07 +02003204 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01003205 DataRate::BitsPerSec(kTargetBitrateBps),
3206 DataRate::BitsPerSec(kTargetBitrateBps),
3207 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asapersson09f05612017-05-15 23:40:18 -07003208
3209 VideoSendStream::Stats stats = stats_proxy_->GetStats();
3210 stats.input_frame_rate = kInputFps;
3211 stats_proxy_->SetMockStats(stats);
3212
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003213 // Expect no scaling to begin with (preference: MAINTAIN_FRAMERATE).
asapersson09f05612017-05-15 23:40:18 -07003214 video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
3215 sink_.WaitForEncodedFrame(1);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003216 EXPECT_THAT(video_source_.sink_wants(), FpsMaxResolutionMax());
asapersson09f05612017-05-15 23:40:18 -07003217
3218 // Trigger adapt down, expect scaled down resolution.
mflodmancc3d4422017-08-03 08:27:51 -07003219 video_stream_encoder_->TriggerQualityLow();
asapersson09f05612017-05-15 23:40:18 -07003220 video_source_.IncomingCapturedFrame(CreateFrame(2, kWidth, kHeight));
3221 sink_.WaitForEncodedFrame(2);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003222 EXPECT_THAT(video_source_.sink_wants(),
3223 FpsMaxResolutionMatches(Lt(kWidth * kHeight)));
asapersson09f05612017-05-15 23:40:18 -07003224
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003225 // Enable MAINTAIN_RESOLUTION preference.
asapersson09f05612017-05-15 23:40:18 -07003226 test::FrameForwarder new_video_source;
Henrik Boström2671dac2020-05-19 16:29:09 +02003227 video_stream_encoder_->SetSourceAndWaitForRestrictionsUpdated(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003228 &new_video_source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
Henrik Boström07b17df2020-01-15 11:42:12 +01003229 // Give the encoder queue time to process the change in degradation preference
3230 // by waiting for an encoded frame.
3231 new_video_source.IncomingCapturedFrame(CreateFrame(3, kWidth, kHeight));
3232 sink_.WaitForEncodedFrame(3);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003233 EXPECT_THAT(new_video_source.sink_wants(), FpsMaxResolutionMax());
asapersson09f05612017-05-15 23:40:18 -07003234
3235 // Trigger adapt down, expect reduced framerate.
mflodmancc3d4422017-08-03 08:27:51 -07003236 video_stream_encoder_->TriggerQualityLow();
Henrik Boström07b17df2020-01-15 11:42:12 +01003237 new_video_source.IncomingCapturedFrame(CreateFrame(4, kWidth, kHeight));
3238 sink_.WaitForEncodedFrame(4);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003239 EXPECT_THAT(new_video_source.sink_wants(),
3240 FpsMatchesResolutionMax(Lt(kInputFps)));
asapersson09f05612017-05-15 23:40:18 -07003241
3242 // Trigger adapt up, expect no restriction.
mflodmancc3d4422017-08-03 08:27:51 -07003243 video_stream_encoder_->TriggerQualityHigh();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003244 EXPECT_THAT(new_video_source.sink_wants(), FpsMaxResolutionMax());
asapersson09f05612017-05-15 23:40:18 -07003245
mflodmancc3d4422017-08-03 08:27:51 -07003246 video_stream_encoder_->Stop();
asapersson09f05612017-05-15 23:40:18 -07003247}
3248
mflodmancc3d4422017-08-03 08:27:51 -07003249TEST_F(VideoStreamEncoderTest, DoesNotScaleBelowSetResolutionLimit) {
asaperssond0de2952017-04-21 01:47:31 -07003250 const int kWidth = 1280;
3251 const int kHeight = 720;
3252 const size_t kNumFrames = 10;
3253
Henrik Boström381d1092020-05-12 18:49:07 +02003254 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01003255 DataRate::BitsPerSec(kTargetBitrateBps),
3256 DataRate::BitsPerSec(kTargetBitrateBps),
3257 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
kthelgason5e13d412016-12-01 03:59:51 -08003258
asaperssond0de2952017-04-21 01:47:31 -07003259 // Enable adapter, expected input resolutions when downscaling:
asapersson142fcc92017-08-17 08:58:54 -07003260 // 1280x720 -> 960x540 -> 640x360 -> 480x270 -> 320x180 (kMinPixelsPerFrame)
asaperssond0de2952017-04-21 01:47:31 -07003261 video_source_.set_adaptation_enabled(true);
3262
3263 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
3264 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3265
3266 int downscales = 0;
3267 for (size_t i = 1; i <= kNumFrames; i++) {
Åsa Persson8c1bf952018-09-13 10:42:19 +02003268 video_source_.IncomingCapturedFrame(
3269 CreateFrame(i * kFrameIntervalMs, kWidth, kHeight));
3270 WaitForEncodedFrame(i * kFrameIntervalMs);
asaperssond0de2952017-04-21 01:47:31 -07003271
asaperssonfab67072017-04-04 05:51:49 -07003272 // Trigger scale down.
asaperssond0de2952017-04-21 01:47:31 -07003273 rtc::VideoSinkWants last_wants = video_source_.sink_wants();
mflodmancc3d4422017-08-03 08:27:51 -07003274 video_stream_encoder_->TriggerQualityLow();
sprangc5d62e22017-04-02 23:53:04 -07003275 EXPECT_GE(video_source_.sink_wants().max_pixel_count, kMinPixelsPerFrame);
asaperssond0de2952017-04-21 01:47:31 -07003276
3277 if (video_source_.sink_wants().max_pixel_count < last_wants.max_pixel_count)
3278 ++downscales;
3279
3280 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
3281 EXPECT_EQ(downscales,
3282 stats_proxy_->GetStats().number_of_quality_adapt_changes);
3283 EXPECT_GT(downscales, 0);
kthelgason5e13d412016-12-01 03:59:51 -08003284 }
mflodmancc3d4422017-08-03 08:27:51 -07003285 video_stream_encoder_->Stop();
asaperssond0de2952017-04-21 01:47:31 -07003286}
3287
mflodmancc3d4422017-08-03 08:27:51 -07003288TEST_F(VideoStreamEncoderTest,
asaperssond0de2952017-04-21 01:47:31 -07003289 AdaptsResolutionUpAndDownTwiceOnOveruse_MaintainFramerateMode) {
3290 const int kWidth = 1280;
3291 const int kHeight = 720;
Henrik Boström381d1092020-05-12 18:49:07 +02003292 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01003293 DataRate::BitsPerSec(kTargetBitrateBps),
3294 DataRate::BitsPerSec(kTargetBitrateBps),
3295 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asaperssond0de2952017-04-21 01:47:31 -07003296
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003297 // Enable MAINTAIN_FRAMERATE preference, no initial limitation.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02003298 AdaptingFrameForwarder source(&time_controller_);
asaperssond0de2952017-04-21 01:47:31 -07003299 source.set_adaptation_enabled(true);
mflodmancc3d4422017-08-03 08:27:51 -07003300 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003301 &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
asaperssond0de2952017-04-21 01:47:31 -07003302
Åsa Persson8c1bf952018-09-13 10:42:19 +02003303 int64_t timestamp_ms = kFrameIntervalMs;
3304 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07003305 WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003306 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssond0de2952017-04-21 01:47:31 -07003307 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
3308 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3309
3310 // Trigger adapt down, expect scaled down resolution.
mflodmancc3d4422017-08-03 08:27:51 -07003311 video_stream_encoder_->TriggerCpuOveruse();
Åsa Persson8c1bf952018-09-13 10:42:19 +02003312 timestamp_ms += kFrameIntervalMs;
3313 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
3314 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003315 EXPECT_THAT(source.sink_wants(),
3316 FpsMaxResolutionMatches(Lt(kWidth * kHeight)));
asaperssond0de2952017-04-21 01:47:31 -07003317 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
3318 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3319
3320 // Trigger adapt up, expect no restriction.
Henrik Boström91aa7322020-04-28 12:24:33 +02003321 video_stream_encoder_->TriggerCpuUnderuse();
Åsa Persson8c1bf952018-09-13 10:42:19 +02003322 timestamp_ms += kFrameIntervalMs;
3323 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07003324 WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003325 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssond0de2952017-04-21 01:47:31 -07003326 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
3327 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3328
3329 // Trigger adapt down, expect scaled down resolution.
mflodmancc3d4422017-08-03 08:27:51 -07003330 video_stream_encoder_->TriggerCpuOveruse();
Åsa Persson8c1bf952018-09-13 10:42:19 +02003331 timestamp_ms += kFrameIntervalMs;
3332 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
3333 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003334 EXPECT_THAT(source.sink_wants(),
3335 FpsMaxResolutionMatches(Lt(kWidth * kHeight)));
asaperssond0de2952017-04-21 01:47:31 -07003336 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
3337 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3338
3339 // Trigger adapt up, expect no restriction.
Henrik Boström91aa7322020-04-28 12:24:33 +02003340 video_stream_encoder_->TriggerCpuUnderuse();
Åsa Persson8c1bf952018-09-13 10:42:19 +02003341 timestamp_ms += kFrameIntervalMs;
3342 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
asapersson09f05612017-05-15 23:40:18 -07003343 sink_.WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003344 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssond0de2952017-04-21 01:47:31 -07003345 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
3346 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3347
mflodmancc3d4422017-08-03 08:27:51 -07003348 video_stream_encoder_->Stop();
asaperssond0de2952017-04-21 01:47:31 -07003349}
3350
mflodmancc3d4422017-08-03 08:27:51 -07003351TEST_F(VideoStreamEncoderTest,
asaperssonf7e294d2017-06-13 23:25:22 -07003352 AdaptsResolutionUpAndDownTwiceForLowQuality_BalancedMode_NoFpsLimit) {
3353 const int kWidth = 1280;
3354 const int kHeight = 720;
Henrik Boström381d1092020-05-12 18:49:07 +02003355 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01003356 DataRate::BitsPerSec(kTargetBitrateBps),
3357 DataRate::BitsPerSec(kTargetBitrateBps),
3358 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asaperssonf7e294d2017-06-13 23:25:22 -07003359
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003360 // Enable BALANCED preference, no initial limitation.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02003361 AdaptingFrameForwarder source(&time_controller_);
asaperssonf7e294d2017-06-13 23:25:22 -07003362 source.set_adaptation_enabled(true);
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003363 video_stream_encoder_->SetSource(&source,
3364 webrtc::DegradationPreference::BALANCED);
asaperssonf7e294d2017-06-13 23:25:22 -07003365
Åsa Persson8c1bf952018-09-13 10:42:19 +02003366 int64_t timestamp_ms = kFrameIntervalMs;
3367 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
asaperssonf7e294d2017-06-13 23:25:22 -07003368 sink_.WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003369 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-13 23:25:22 -07003370 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
3371 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3372
3373 // Trigger adapt down, expect scaled down resolution.
mflodmancc3d4422017-08-03 08:27:51 -07003374 video_stream_encoder_->TriggerQualityLow();
Åsa Persson8c1bf952018-09-13 10:42:19 +02003375 timestamp_ms += kFrameIntervalMs;
3376 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
3377 sink_.WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003378 EXPECT_THAT(source.sink_wants(),
3379 FpsMaxResolutionMatches(Lt(kWidth * kHeight)));
asaperssonf7e294d2017-06-13 23:25:22 -07003380 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
3381 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3382
3383 // Trigger adapt up, expect no restriction.
mflodmancc3d4422017-08-03 08:27:51 -07003384 video_stream_encoder_->TriggerQualityHigh();
Åsa Persson8c1bf952018-09-13 10:42:19 +02003385 timestamp_ms += kFrameIntervalMs;
3386 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
asaperssonf7e294d2017-06-13 23:25:22 -07003387 sink_.WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003388 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-13 23:25:22 -07003389 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
3390 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3391
3392 // Trigger adapt down, expect scaled down resolution.
mflodmancc3d4422017-08-03 08:27:51 -07003393 video_stream_encoder_->TriggerQualityLow();
Åsa Persson8c1bf952018-09-13 10:42:19 +02003394 timestamp_ms += kFrameIntervalMs;
3395 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
3396 sink_.WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003397 EXPECT_THAT(source.sink_wants(),
3398 FpsMaxResolutionMatches(Lt(kWidth * kHeight)));
asaperssonf7e294d2017-06-13 23:25:22 -07003399 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
3400 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3401
3402 // Trigger adapt up, expect no restriction.
mflodmancc3d4422017-08-03 08:27:51 -07003403 video_stream_encoder_->TriggerQualityHigh();
Åsa Persson8c1bf952018-09-13 10:42:19 +02003404 timestamp_ms += kFrameIntervalMs;
3405 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
asaperssonf7e294d2017-06-13 23:25:22 -07003406 sink_.WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003407 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-13 23:25:22 -07003408 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
3409 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3410
mflodmancc3d4422017-08-03 08:27:51 -07003411 video_stream_encoder_->Stop();
asaperssonf7e294d2017-06-13 23:25:22 -07003412}
3413
Sergey Silkin41c650b2019-10-14 13:12:19 +02003414TEST_F(VideoStreamEncoderTest, AdaptUpIfBwEstimateIsHigherThanMinBitrate) {
3415 fake_encoder_.SetResolutionBitrateLimits(
3416 {kEncoderBitrateLimits540p, kEncoderBitrateLimits720p});
3417
Henrik Boström381d1092020-05-12 18:49:07 +02003418 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01003419 DataRate::BitsPerSec(kEncoderBitrateLimits720p.min_start_bitrate_bps),
3420 DataRate::BitsPerSec(kEncoderBitrateLimits720p.min_start_bitrate_bps),
3421 DataRate::BitsPerSec(kEncoderBitrateLimits720p.min_start_bitrate_bps), 0,
3422 0, 0);
Sergey Silkin41c650b2019-10-14 13:12:19 +02003423
3424 // Enable MAINTAIN_FRAMERATE preference, no initial limitation.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02003425 AdaptingFrameForwarder source(&time_controller_);
Sergey Silkin41c650b2019-10-14 13:12:19 +02003426 source.set_adaptation_enabled(true);
3427 video_stream_encoder_->SetSource(
3428 &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
3429
3430 // Insert 720p frame.
3431 int64_t timestamp_ms = kFrameIntervalMs;
3432 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, 1280, 720));
3433 WaitForEncodedFrame(1280, 720);
3434
3435 // Reduce bitrate and trigger adapt down.
Henrik Boström381d1092020-05-12 18:49:07 +02003436 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01003437 DataRate::BitsPerSec(kEncoderBitrateLimits540p.min_start_bitrate_bps),
3438 DataRate::BitsPerSec(kEncoderBitrateLimits540p.min_start_bitrate_bps),
3439 DataRate::BitsPerSec(kEncoderBitrateLimits540p.min_start_bitrate_bps), 0,
3440 0, 0);
Sergey Silkin41c650b2019-10-14 13:12:19 +02003441 video_stream_encoder_->TriggerQualityLow();
3442
3443 // Insert 720p frame. It should be downscaled and encoded.
3444 timestamp_ms += kFrameIntervalMs;
3445 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, 1280, 720));
3446 WaitForEncodedFrame(960, 540);
3447
3448 // Trigger adapt up. Higher resolution should not be requested duo to lack
3449 // of bitrate.
3450 video_stream_encoder_->TriggerQualityHigh();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003451 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMatches(Lt(1280 * 720)));
Sergey Silkin41c650b2019-10-14 13:12:19 +02003452
3453 // Increase bitrate.
Henrik Boström381d1092020-05-12 18:49:07 +02003454 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01003455 DataRate::BitsPerSec(kEncoderBitrateLimits720p.min_start_bitrate_bps),
3456 DataRate::BitsPerSec(kEncoderBitrateLimits720p.min_start_bitrate_bps),
3457 DataRate::BitsPerSec(kEncoderBitrateLimits720p.min_start_bitrate_bps), 0,
3458 0, 0);
Sergey Silkin41c650b2019-10-14 13:12:19 +02003459
3460 // Trigger adapt up. Higher resolution should be requested.
3461 video_stream_encoder_->TriggerQualityHigh();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003462 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
Sergey Silkin41c650b2019-10-14 13:12:19 +02003463
3464 video_stream_encoder_->Stop();
3465}
3466
3467TEST_F(VideoStreamEncoderTest, DropFirstFramesIfBwEstimateIsTooLow) {
3468 fake_encoder_.SetResolutionBitrateLimits(
3469 {kEncoderBitrateLimits540p, kEncoderBitrateLimits720p});
3470
3471 // Set bitrate equal to min bitrate of 540p.
Henrik Boström381d1092020-05-12 18:49:07 +02003472 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01003473 DataRate::BitsPerSec(kEncoderBitrateLimits540p.min_start_bitrate_bps),
3474 DataRate::BitsPerSec(kEncoderBitrateLimits540p.min_start_bitrate_bps),
3475 DataRate::BitsPerSec(kEncoderBitrateLimits540p.min_start_bitrate_bps), 0,
3476 0, 0);
Sergey Silkin41c650b2019-10-14 13:12:19 +02003477
3478 // Enable MAINTAIN_FRAMERATE preference, no initial limitation.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02003479 AdaptingFrameForwarder source(&time_controller_);
Sergey Silkin41c650b2019-10-14 13:12:19 +02003480 source.set_adaptation_enabled(true);
3481 video_stream_encoder_->SetSource(
3482 &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
3483
3484 // Insert 720p frame. It should be dropped and lower resolution should be
3485 // requested.
3486 int64_t timestamp_ms = kFrameIntervalMs;
3487 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, 1280, 720));
3488 ExpectDroppedFrame();
Henrik Boström2671dac2020-05-19 16:29:09 +02003489 EXPECT_TRUE_WAIT(source.sink_wants().max_pixel_count < 1280 * 720, 5000);
Sergey Silkin41c650b2019-10-14 13:12:19 +02003490
3491 // Insert 720p frame. It should be downscaled and encoded.
3492 timestamp_ms += kFrameIntervalMs;
3493 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, 1280, 720));
3494 WaitForEncodedFrame(960, 540);
3495
3496 video_stream_encoder_->Stop();
3497}
3498
Åsa Perssonb67c44c2019-09-24 15:25:32 +02003499class BalancedDegradationTest : public VideoStreamEncoderTest {
3500 protected:
3501 void SetupTest() {
3502 // Reset encoder for field trials to take effect.
3503 ConfigureEncoder(video_encoder_config_.Copy());
Åsa Perssonccfb3402019-09-25 15:13:04 +02003504 OnBitrateUpdated(kTargetBitrateBps);
Åsa Perssonb67c44c2019-09-24 15:25:32 +02003505
3506 // Enable BALANCED preference.
3507 source_.set_adaptation_enabled(true);
Åsa Perssonccfb3402019-09-25 15:13:04 +02003508 video_stream_encoder_->SetSource(&source_, DegradationPreference::BALANCED);
3509 }
3510
3511 void OnBitrateUpdated(int bitrate_bps) {
Henrik Boström381d1092020-05-12 18:49:07 +02003512 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01003513 DataRate::BitsPerSec(bitrate_bps), DataRate::BitsPerSec(bitrate_bps),
3514 DataRate::BitsPerSec(bitrate_bps), 0, 0, 0);
Åsa Perssonb67c44c2019-09-24 15:25:32 +02003515 }
3516
Åsa Persson45b176f2019-09-30 11:19:05 +02003517 void InsertFrame() {
Åsa Perssonb67c44c2019-09-24 15:25:32 +02003518 timestamp_ms_ += kFrameIntervalMs;
3519 source_.IncomingCapturedFrame(CreateFrame(timestamp_ms_, kWidth, kHeight));
Åsa Persson45b176f2019-09-30 11:19:05 +02003520 }
3521
3522 void InsertFrameAndWaitForEncoded() {
3523 InsertFrame();
Åsa Perssonb67c44c2019-09-24 15:25:32 +02003524 sink_.WaitForEncodedFrame(timestamp_ms_);
3525 }
3526
3527 const int kWidth = 640; // pixels:640x360=230400
3528 const int kHeight = 360;
3529 const int64_t kFrameIntervalMs = 150; // Use low fps to not drop any frame.
3530 int64_t timestamp_ms_ = 0;
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02003531 AdaptingFrameForwarder source_{&time_controller_};
Åsa Perssonb67c44c2019-09-24 15:25:32 +02003532};
3533
Evan Shrubsolea1c77f62020-08-10 11:01:06 +02003534TEST_F(BalancedDegradationTest, AdaptDownTwiceIfMinFpsDiffLtThreshold) {
Åsa Perssonb67c44c2019-09-24 15:25:32 +02003535 test::ScopedFieldTrials field_trials(
3536 "WebRTC-Video-BalancedDegradationSettings/"
3537 "pixels:57600|129600|230400,fps:7|10|24,fps_diff:1|1|1/");
3538 SetupTest();
3539
3540 // Force input frame rate.
3541 const int kInputFps = 24;
3542 VideoSendStream::Stats stats = stats_proxy_->GetStats();
3543 stats.input_frame_rate = kInputFps;
3544 stats_proxy_->SetMockStats(stats);
3545
Åsa Persson45b176f2019-09-30 11:19:05 +02003546 InsertFrameAndWaitForEncoded();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003547 EXPECT_THAT(source_.sink_wants(), FpsMaxResolutionMax());
Åsa Perssonb67c44c2019-09-24 15:25:32 +02003548
Evan Shrubsolea1c77f62020-08-10 11:01:06 +02003549 // Trigger adapt down, expect scaled down framerate and resolution,
3550 // since Fps diff (input-requested:0) < threshold.
3551 video_stream_encoder_->TriggerQualityLow();
3552 EXPECT_THAT(source_.sink_wants(),
3553 AllOf(WantsFps(Eq(24)), WantsMaxPixels(Le(230400))));
Åsa Perssonb67c44c2019-09-24 15:25:32 +02003554
3555 video_stream_encoder_->Stop();
3556}
3557
Evan Shrubsolea1c77f62020-08-10 11:01:06 +02003558TEST_F(BalancedDegradationTest, AdaptDownOnceIfFpsDiffGeThreshold) {
Åsa Perssonb67c44c2019-09-24 15:25:32 +02003559 test::ScopedFieldTrials field_trials(
3560 "WebRTC-Video-BalancedDegradationSettings/"
3561 "pixels:57600|129600|230400,fps:7|10|24,fps_diff:1|1|1/");
3562 SetupTest();
3563
3564 // Force input frame rate.
3565 const int kInputFps = 25;
3566 VideoSendStream::Stats stats = stats_proxy_->GetStats();
3567 stats.input_frame_rate = kInputFps;
3568 stats_proxy_->SetMockStats(stats);
3569
Åsa Persson45b176f2019-09-30 11:19:05 +02003570 InsertFrameAndWaitForEncoded();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003571 EXPECT_THAT(source_.sink_wants(), FpsMaxResolutionMax());
Åsa Perssonb67c44c2019-09-24 15:25:32 +02003572
Evan Shrubsolea1c77f62020-08-10 11:01:06 +02003573 // Trigger adapt down, expect scaled down framerate only (640x360@24fps).
3574 // Fps diff (input-requested:1) == threshold.
3575 video_stream_encoder_->TriggerQualityLow();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003576 EXPECT_THAT(source_.sink_wants(), FpsMatchesResolutionMax(Eq(24)));
Åsa Perssonb67c44c2019-09-24 15:25:32 +02003577
3578 video_stream_encoder_->Stop();
3579}
3580
3581TEST_F(BalancedDegradationTest, AdaptDownUsesCodecSpecificFps) {
3582 test::ScopedFieldTrials field_trials(
3583 "WebRTC-Video-BalancedDegradationSettings/"
3584 "pixels:57600|129600|230400,fps:7|10|24,vp8_fps:8|11|22/");
3585 SetupTest();
3586
3587 EXPECT_EQ(kVideoCodecVP8, video_encoder_config_.codec_type);
3588
Åsa Persson45b176f2019-09-30 11:19:05 +02003589 InsertFrameAndWaitForEncoded();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003590 EXPECT_THAT(source_.sink_wants(), FpsMaxResolutionMax());
Åsa Perssonb67c44c2019-09-24 15:25:32 +02003591
3592 // Trigger adapt down, expect scaled down framerate (640x360@22fps).
3593 video_stream_encoder_->TriggerQualityLow();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003594 EXPECT_THAT(source_.sink_wants(), FpsMatchesResolutionMax(Eq(22)));
Åsa Perssonb67c44c2019-09-24 15:25:32 +02003595
3596 video_stream_encoder_->Stop();
3597}
3598
Åsa Perssonccfb3402019-09-25 15:13:04 +02003599TEST_F(BalancedDegradationTest, NoAdaptUpIfBwEstimateIsLessThanMinBitrate) {
Åsa Perssonb67c44c2019-09-24 15:25:32 +02003600 test::ScopedFieldTrials field_trials(
Åsa Persson1b247f12019-08-14 17:26:39 +02003601 "WebRTC-Video-BalancedDegradationSettings/"
3602 "pixels:57600|129600|230400,fps:7|10|14,kbps:0|0|425/");
Åsa Perssonccfb3402019-09-25 15:13:04 +02003603 SetupTest();
Åsa Persson1b247f12019-08-14 17:26:39 +02003604
Åsa Persson1b247f12019-08-14 17:26:39 +02003605 const int kMinBitrateBps = 425000;
3606 const int kTooLowMinBitrateBps = 424000;
Åsa Perssonccfb3402019-09-25 15:13:04 +02003607 OnBitrateUpdated(kTooLowMinBitrateBps);
Åsa Persson1b247f12019-08-14 17:26:39 +02003608
Åsa Persson45b176f2019-09-30 11:19:05 +02003609 InsertFrameAndWaitForEncoded();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003610 EXPECT_THAT(source_.sink_wants(), FpsMaxResolutionMax());
Åsa Persson1b247f12019-08-14 17:26:39 +02003611 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3612
3613 // Trigger adapt down, expect scaled down framerate (640x360@14fps).
3614 video_stream_encoder_->TriggerQualityLow();
Åsa Persson45b176f2019-09-30 11:19:05 +02003615 InsertFrameAndWaitForEncoded();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003616 EXPECT_THAT(source_.sink_wants(), FpsMatchesResolutionMax(Eq(14)));
Åsa Persson1b247f12019-08-14 17:26:39 +02003617 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3618
3619 // Trigger adapt down, expect scaled down resolution (480x270@14fps).
3620 video_stream_encoder_->TriggerQualityLow();
Åsa Persson45b176f2019-09-30 11:19:05 +02003621 InsertFrameAndWaitForEncoded();
Evan Shrubsole5fd40602020-05-25 16:19:54 +02003622 EXPECT_THAT(source_.sink_wants(), FpsEqResolutionLt(source_.last_wants()));
Åsa Persson1b247f12019-08-14 17:26:39 +02003623 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3624
Åsa Persson30ab0152019-08-27 12:22:33 +02003625 // Trigger adapt down, expect scaled down framerate (480x270@10fps).
3626 video_stream_encoder_->TriggerQualityLow();
Åsa Persson45b176f2019-09-30 11:19:05 +02003627 InsertFrameAndWaitForEncoded();
Evan Shrubsole5fd40602020-05-25 16:19:54 +02003628 EXPECT_THAT(source_.sink_wants(), FpsLtResolutionEq(source_.last_wants()));
Åsa Perssonccfb3402019-09-25 15:13:04 +02003629 EXPECT_EQ(source_.sink_wants().max_framerate_fps, 10);
Åsa Persson30ab0152019-08-27 12:22:33 +02003630 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3631
3632 // Trigger adapt up, expect no upscale in fps (target bitrate < min bitrate).
Åsa Persson1b247f12019-08-14 17:26:39 +02003633 video_stream_encoder_->TriggerQualityHigh();
Åsa Persson45b176f2019-09-30 11:19:05 +02003634 InsertFrameAndWaitForEncoded();
Åsa Persson30ab0152019-08-27 12:22:33 +02003635 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_quality_adapt_changes);
Åsa Persson1b247f12019-08-14 17:26:39 +02003636
Åsa Persson30ab0152019-08-27 12:22:33 +02003637 // Trigger adapt up, expect upscaled fps (target bitrate == min bitrate).
Åsa Perssonccfb3402019-09-25 15:13:04 +02003638 OnBitrateUpdated(kMinBitrateBps);
Åsa Persson1b247f12019-08-14 17:26:39 +02003639 video_stream_encoder_->TriggerQualityHigh();
Åsa Persson45b176f2019-09-30 11:19:05 +02003640 InsertFrameAndWaitForEncoded();
Åsa Perssonccfb3402019-09-25 15:13:04 +02003641 EXPECT_EQ(source_.sink_wants().max_framerate_fps, 14);
Åsa Persson30ab0152019-08-27 12:22:33 +02003642 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3643
3644 video_stream_encoder_->Stop();
3645}
3646
Åsa Perssonccfb3402019-09-25 15:13:04 +02003647TEST_F(BalancedDegradationTest,
Åsa Persson45b176f2019-09-30 11:19:05 +02003648 InitialFrameDropAdaptsFpsAndResolutionInOneStep) {
3649 test::ScopedFieldTrials field_trials(
3650 "WebRTC-Video-BalancedDegradationSettings/"
3651 "pixels:57600|129600|230400,fps:7|24|24/");
3652 SetupTest();
3653 OnBitrateUpdated(kLowTargetBitrateBps);
3654
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003655 EXPECT_THAT(source_.sink_wants(), UnlimitedSinkWants());
Åsa Persson45b176f2019-09-30 11:19:05 +02003656
3657 // Insert frame, expect scaled down:
3658 // framerate (640x360@24fps) -> resolution (480x270@24fps).
3659 InsertFrame();
3660 EXPECT_FALSE(WaitForFrame(1000));
3661 EXPECT_LT(source_.sink_wants().max_pixel_count, kWidth * kHeight);
3662 EXPECT_EQ(source_.sink_wants().max_framerate_fps, 24);
3663
3664 // Insert frame, expect scaled down:
3665 // resolution (320x180@24fps).
3666 InsertFrame();
3667 EXPECT_FALSE(WaitForFrame(1000));
3668 EXPECT_LT(source_.sink_wants().max_pixel_count,
3669 source_.last_wants().max_pixel_count);
3670 EXPECT_EQ(source_.sink_wants().max_framerate_fps, 24);
3671
3672 // Frame should not be dropped (min pixels per frame reached).
3673 InsertFrameAndWaitForEncoded();
3674
3675 video_stream_encoder_->Stop();
3676}
3677
3678TEST_F(BalancedDegradationTest,
Åsa Persson30ab0152019-08-27 12:22:33 +02003679 NoAdaptUpInResolutionIfBwEstimateIsLessThanMinBitrate) {
Åsa Perssonb67c44c2019-09-24 15:25:32 +02003680 test::ScopedFieldTrials field_trials(
Åsa Persson30ab0152019-08-27 12:22:33 +02003681 "WebRTC-Video-BalancedDegradationSettings/"
3682 "pixels:57600|129600|230400,fps:7|10|14,kbps_res:0|0|435/");
Åsa Perssonccfb3402019-09-25 15:13:04 +02003683 SetupTest();
Åsa Persson30ab0152019-08-27 12:22:33 +02003684
Åsa Persson30ab0152019-08-27 12:22:33 +02003685 const int kResolutionMinBitrateBps = 435000;
3686 const int kTooLowMinResolutionBitrateBps = 434000;
Åsa Perssonccfb3402019-09-25 15:13:04 +02003687 OnBitrateUpdated(kTooLowMinResolutionBitrateBps);
Åsa Persson30ab0152019-08-27 12:22:33 +02003688
Åsa Persson45b176f2019-09-30 11:19:05 +02003689 InsertFrameAndWaitForEncoded();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003690 EXPECT_THAT(source_.sink_wants(), FpsMaxResolutionMax());
Åsa Persson30ab0152019-08-27 12:22:33 +02003691 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3692
3693 // Trigger adapt down, expect scaled down framerate (640x360@14fps).
3694 video_stream_encoder_->TriggerQualityLow();
Åsa Persson45b176f2019-09-30 11:19:05 +02003695 InsertFrameAndWaitForEncoded();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003696 EXPECT_THAT(source_.sink_wants(), FpsMatchesResolutionMax(Eq(14)));
Åsa Persson30ab0152019-08-27 12:22:33 +02003697 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3698
3699 // Trigger adapt down, expect scaled down resolution (480x270@14fps).
3700 video_stream_encoder_->TriggerQualityLow();
Åsa Persson45b176f2019-09-30 11:19:05 +02003701 InsertFrameAndWaitForEncoded();
Evan Shrubsole5fd40602020-05-25 16:19:54 +02003702 EXPECT_THAT(source_.sink_wants(), FpsEqResolutionLt(source_.last_wants()));
Åsa Persson30ab0152019-08-27 12:22:33 +02003703 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3704
3705 // Trigger adapt down, expect scaled down framerate (480x270@10fps).
3706 video_stream_encoder_->TriggerQualityLow();
Åsa Persson45b176f2019-09-30 11:19:05 +02003707 InsertFrameAndWaitForEncoded();
Evan Shrubsole5fd40602020-05-25 16:19:54 +02003708 EXPECT_THAT(source_.sink_wants(), FpsLtResolutionEq(source_.last_wants()));
Åsa Persson1b247f12019-08-14 17:26:39 +02003709 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3710
Åsa Persson30ab0152019-08-27 12:22:33 +02003711 // Trigger adapt up, expect upscaled fps (no bitrate limit) (480x270@14fps).
3712 video_stream_encoder_->TriggerQualityHigh();
Åsa Persson45b176f2019-09-30 11:19:05 +02003713 InsertFrameAndWaitForEncoded();
Evan Shrubsole5fd40602020-05-25 16:19:54 +02003714 EXPECT_THAT(source_.sink_wants(), FpsGtResolutionEq(source_.last_wants()));
Åsa Persson30ab0152019-08-27 12:22:33 +02003715 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3716
3717 // Trigger adapt up, expect no upscale in res (target bitrate < min bitrate).
3718 video_stream_encoder_->TriggerQualityHigh();
Åsa Persson45b176f2019-09-30 11:19:05 +02003719 InsertFrameAndWaitForEncoded();
Åsa Persson30ab0152019-08-27 12:22:33 +02003720 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3721
3722 // Trigger adapt up, expect upscaled res (target bitrate == min bitrate).
Åsa Perssonccfb3402019-09-25 15:13:04 +02003723 OnBitrateUpdated(kResolutionMinBitrateBps);
Åsa Persson30ab0152019-08-27 12:22:33 +02003724 video_stream_encoder_->TriggerQualityHigh();
Åsa Persson45b176f2019-09-30 11:19:05 +02003725 InsertFrameAndWaitForEncoded();
Evan Shrubsole5fd40602020-05-25 16:19:54 +02003726 EXPECT_THAT(source_.sink_wants(), FpsEqResolutionGt(source_.last_wants()));
Åsa Persson30ab0152019-08-27 12:22:33 +02003727 EXPECT_EQ(5, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3728
3729 video_stream_encoder_->Stop();
3730}
3731
Åsa Perssonccfb3402019-09-25 15:13:04 +02003732TEST_F(BalancedDegradationTest,
Åsa Persson30ab0152019-08-27 12:22:33 +02003733 NoAdaptUpInFpsAndResolutionIfBwEstimateIsLessThanMinBitrate) {
Åsa Perssonb67c44c2019-09-24 15:25:32 +02003734 test::ScopedFieldTrials field_trials(
Åsa Persson30ab0152019-08-27 12:22:33 +02003735 "WebRTC-Video-BalancedDegradationSettings/"
3736 "pixels:57600|129600|230400,fps:7|10|14,kbps:0|0|425,kbps_res:0|0|435/");
Åsa Perssonccfb3402019-09-25 15:13:04 +02003737 SetupTest();
Åsa Persson30ab0152019-08-27 12:22:33 +02003738
Åsa Persson30ab0152019-08-27 12:22:33 +02003739 const int kMinBitrateBps = 425000;
3740 const int kTooLowMinBitrateBps = 424000;
3741 const int kResolutionMinBitrateBps = 435000;
3742 const int kTooLowMinResolutionBitrateBps = 434000;
Åsa Perssonccfb3402019-09-25 15:13:04 +02003743 OnBitrateUpdated(kTooLowMinBitrateBps);
Åsa Persson30ab0152019-08-27 12:22:33 +02003744
Åsa Persson45b176f2019-09-30 11:19:05 +02003745 InsertFrameAndWaitForEncoded();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003746 EXPECT_THAT(source_.sink_wants(), FpsMaxResolutionMax());
Åsa Persson30ab0152019-08-27 12:22:33 +02003747 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3748
3749 // Trigger adapt down, expect scaled down framerate (640x360@14fps).
3750 video_stream_encoder_->TriggerQualityLow();
Åsa Persson45b176f2019-09-30 11:19:05 +02003751 InsertFrameAndWaitForEncoded();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003752 EXPECT_THAT(source_.sink_wants(), FpsMatchesResolutionMax(Eq(14)));
Åsa Persson30ab0152019-08-27 12:22:33 +02003753 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3754
3755 // Trigger adapt down, expect scaled down resolution (480x270@14fps).
3756 video_stream_encoder_->TriggerQualityLow();
Åsa Persson45b176f2019-09-30 11:19:05 +02003757 InsertFrameAndWaitForEncoded();
Evan Shrubsole5fd40602020-05-25 16:19:54 +02003758 EXPECT_THAT(source_.sink_wants(), FpsEqResolutionLt(source_.last_wants()));
Åsa Persson30ab0152019-08-27 12:22:33 +02003759 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3760
3761 // Trigger adapt down, expect scaled down framerate (480x270@10fps).
3762 video_stream_encoder_->TriggerQualityLow();
Åsa Persson45b176f2019-09-30 11:19:05 +02003763 InsertFrameAndWaitForEncoded();
Evan Shrubsole5fd40602020-05-25 16:19:54 +02003764 EXPECT_THAT(source_.sink_wants(), FpsLtResolutionEq(source_.last_wants()));
Åsa Persson30ab0152019-08-27 12:22:33 +02003765 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3766
3767 // Trigger adapt up, expect no upscale (target bitrate < min bitrate).
3768 video_stream_encoder_->TriggerQualityHigh();
Åsa Persson45b176f2019-09-30 11:19:05 +02003769 InsertFrameAndWaitForEncoded();
Åsa Persson30ab0152019-08-27 12:22:33 +02003770 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3771
3772 // Trigger adapt up, expect upscaled fps (target bitrate == min bitrate).
Åsa Perssonccfb3402019-09-25 15:13:04 +02003773 OnBitrateUpdated(kMinBitrateBps);
Åsa Persson30ab0152019-08-27 12:22:33 +02003774 video_stream_encoder_->TriggerQualityHigh();
Åsa Persson45b176f2019-09-30 11:19:05 +02003775 InsertFrameAndWaitForEncoded();
Evan Shrubsole5fd40602020-05-25 16:19:54 +02003776 EXPECT_THAT(source_.sink_wants(), FpsGtResolutionEq(source_.last_wants()));
Åsa Persson30ab0152019-08-27 12:22:33 +02003777 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3778
3779 // Trigger adapt up, expect no upscale in res (target bitrate < min bitrate).
Åsa Perssonccfb3402019-09-25 15:13:04 +02003780 OnBitrateUpdated(kTooLowMinResolutionBitrateBps);
Åsa Persson30ab0152019-08-27 12:22:33 +02003781 video_stream_encoder_->TriggerQualityHigh();
Åsa Persson45b176f2019-09-30 11:19:05 +02003782 InsertFrameAndWaitForEncoded();
Åsa Persson30ab0152019-08-27 12:22:33 +02003783 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3784
3785 // Trigger adapt up, expect upscaled res (target bitrate == min bitrate).
Åsa Perssonccfb3402019-09-25 15:13:04 +02003786 OnBitrateUpdated(kResolutionMinBitrateBps);
Åsa Persson30ab0152019-08-27 12:22:33 +02003787 video_stream_encoder_->TriggerQualityHigh();
Åsa Persson45b176f2019-09-30 11:19:05 +02003788 InsertFrameAndWaitForEncoded();
Evan Shrubsole5fd40602020-05-25 16:19:54 +02003789 EXPECT_THAT(source_.sink_wants(), FpsEqResolutionGt(source_.last_wants()));
Åsa Persson30ab0152019-08-27 12:22:33 +02003790 EXPECT_EQ(5, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3791
Åsa Persson1b247f12019-08-14 17:26:39 +02003792 video_stream_encoder_->Stop();
3793}
3794
mflodmancc3d4422017-08-03 08:27:51 -07003795TEST_F(VideoStreamEncoderTest,
asaperssond0de2952017-04-21 01:47:31 -07003796 AdaptsResolutionOnOveruseAndLowQuality_MaintainFramerateMode) {
3797 const int kWidth = 1280;
3798 const int kHeight = 720;
Henrik Boström381d1092020-05-12 18:49:07 +02003799 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01003800 DataRate::BitsPerSec(kTargetBitrateBps),
3801 DataRate::BitsPerSec(kTargetBitrateBps),
3802 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asaperssond0de2952017-04-21 01:47:31 -07003803
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003804 // Enable MAINTAIN_FRAMERATE preference, no initial limitation.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02003805 AdaptingFrameForwarder source(&time_controller_);
asaperssond0de2952017-04-21 01:47:31 -07003806 source.set_adaptation_enabled(true);
mflodmancc3d4422017-08-03 08:27:51 -07003807 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003808 &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
asaperssond0de2952017-04-21 01:47:31 -07003809
Åsa Persson8c1bf952018-09-13 10:42:19 +02003810 int64_t timestamp_ms = kFrameIntervalMs;
3811 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07003812 WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003813 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssond0de2952017-04-21 01:47:31 -07003814 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
3815 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
3816 EXPECT_EQ(0, 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 (960x540).
mflodmancc3d4422017-08-03 08:27:51 -07003820 video_stream_encoder_->TriggerCpuOveruse();
Åsa Persson8c1bf952018-09-13 10:42:19 +02003821 timestamp_ms += kFrameIntervalMs;
3822 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
3823 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003824 EXPECT_THAT(source.sink_wants(),
3825 FpsMaxResolutionMatches(Lt(kWidth * kHeight)));
asaperssond0de2952017-04-21 01:47:31 -07003826 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
3827 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
3828 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3829 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3830
3831 // Trigger cpu adapt down, expect scaled down resolution (640x360).
mflodmancc3d4422017-08-03 08:27:51 -07003832 video_stream_encoder_->TriggerCpuOveruse();
Åsa Persson8c1bf952018-09-13 10:42:19 +02003833 timestamp_ms += kFrameIntervalMs;
3834 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
3835 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02003836 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionLt(source.last_wants()));
asaperssond0de2952017-04-21 01:47:31 -07003837 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
3838 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
3839 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3840 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3841
Jonathan Yubc771b72017-12-08 17:04:29 -08003842 // Trigger cpu adapt down, expect scaled down resolution (480x270).
mflodmancc3d4422017-08-03 08:27:51 -07003843 video_stream_encoder_->TriggerCpuOveruse();
Åsa Persson8c1bf952018-09-13 10:42:19 +02003844 timestamp_ms += kFrameIntervalMs;
3845 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
3846 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02003847 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionLt(source.last_wants()));
asaperssond0de2952017-04-21 01:47:31 -07003848 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
3849 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
Jonathan Yubc771b72017-12-08 17:04:29 -08003850 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
asaperssond0de2952017-04-21 01:47:31 -07003851 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3852
Jonathan Yubc771b72017-12-08 17:04:29 -08003853 // Trigger quality adapt down, expect scaled down resolution (320x180).
mflodmancc3d4422017-08-03 08:27:51 -07003854 video_stream_encoder_->TriggerQualityLow();
Åsa Persson8c1bf952018-09-13 10:42:19 +02003855 timestamp_ms += kFrameIntervalMs;
3856 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
3857 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02003858 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionLt(source.last_wants()));
Jonathan Yubc771b72017-12-08 17:04:29 -08003859 rtc::VideoSinkWants last_wants = source.sink_wants();
asaperssond0de2952017-04-21 01:47:31 -07003860 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
Jonathan Yubc771b72017-12-08 17:04:29 -08003865 // Trigger quality adapt down, expect no change (min resolution reached).
3866 video_stream_encoder_->TriggerQualityLow();
Åsa Persson8c1bf952018-09-13 10:42:19 +02003867 timestamp_ms += kFrameIntervalMs;
3868 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
3869 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02003870 EXPECT_THAT(source.sink_wants(), FpsMax());
3871 EXPECT_EQ(source.sink_wants().max_pixel_count, last_wants.max_pixel_count);
Jonathan Yubc771b72017-12-08 17:04:29 -08003872 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
3873 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
3874 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3875 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3876
Evan Shrubsole64469032020-06-11 10:45:29 +02003877 // Trigger quality adapt up, expect upscaled resolution (480x270).
3878 video_stream_encoder_->TriggerQualityHigh();
3879 timestamp_ms += kFrameIntervalMs;
3880 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
3881 WaitForEncodedFrame(timestamp_ms);
3882 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionGt(source.last_wants()));
3883 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
3884 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
3885 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3886 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3887
3888 // Trigger quality and cpu adapt up since both are most limited, expect
3889 // upscaled resolution (640x360).
Henrik Boström91aa7322020-04-28 12:24:33 +02003890 video_stream_encoder_->TriggerCpuUnderuse();
Evan Shrubsole64469032020-06-11 10:45:29 +02003891 video_stream_encoder_->TriggerQualityHigh();
Åsa Persson8c1bf952018-09-13 10:42:19 +02003892 timestamp_ms += kFrameIntervalMs;
3893 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
3894 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02003895 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionGt(source.last_wants()));
Jonathan Yubc771b72017-12-08 17:04:29 -08003896 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
3897 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
3898 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
Evan Shrubsole64469032020-06-11 10:45:29 +02003899 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_quality_adapt_changes);
Jonathan Yubc771b72017-12-08 17:04:29 -08003900
Evan Shrubsole64469032020-06-11 10:45:29 +02003901 // Trigger quality and cpu adapt up since both are most limited, expect
3902 // upscaled resolution (960x540).
Henrik Boström91aa7322020-04-28 12:24:33 +02003903 video_stream_encoder_->TriggerCpuUnderuse();
Evan Shrubsole64469032020-06-11 10:45:29 +02003904 video_stream_encoder_->TriggerQualityHigh();
Åsa Persson8c1bf952018-09-13 10:42:19 +02003905 timestamp_ms += kFrameIntervalMs;
3906 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
3907 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02003908 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionGt(source.last_wants()));
asaperssond0de2952017-04-21 01:47:31 -07003909 last_wants = source.sink_wants();
Evan Shrubsole64469032020-06-11 10:45:29 +02003910 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
asaperssond0de2952017-04-21 01:47:31 -07003911 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
Evan Shrubsole64469032020-06-11 10:45:29 +02003912 EXPECT_EQ(5, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3913 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_quality_adapt_changes);
asaperssond0de2952017-04-21 01:47:31 -07003914
Evan Shrubsole64469032020-06-11 10:45:29 +02003915 // Trigger cpu adapt up, expect no change since not most limited (960x540).
3916 // However the stats will change since the CPU resource is no longer limited.
Henrik Boström91aa7322020-04-28 12:24:33 +02003917 video_stream_encoder_->TriggerCpuUnderuse();
Åsa Persson8c1bf952018-09-13 10:42:19 +02003918 timestamp_ms += kFrameIntervalMs;
3919 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
3920 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02003921 EXPECT_THAT(source.sink_wants(), FpsEqResolutionEqTo(last_wants));
asaperssond0de2952017-04-21 01:47:31 -07003922 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
3923 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
Jonathan Yubc771b72017-12-08 17:04:29 -08003924 EXPECT_EQ(6, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
Evan Shrubsole64469032020-06-11 10:45:29 +02003925 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_quality_adapt_changes);
asaperssond0de2952017-04-21 01:47:31 -07003926
3927 // Trigger quality adapt up, expect no restriction (1280x720).
mflodmancc3d4422017-08-03 08:27:51 -07003928 video_stream_encoder_->TriggerQualityHigh();
Åsa Persson8c1bf952018-09-13 10:42:19 +02003929 timestamp_ms += kFrameIntervalMs;
3930 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07003931 WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02003932 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionGt(source.last_wants()));
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003933 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssond0de2952017-04-21 01:47:31 -07003934 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
3935 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
Jonathan Yubc771b72017-12-08 17:04:29 -08003936 EXPECT_EQ(6, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
Evan Shrubsole64469032020-06-11 10:45:29 +02003937 EXPECT_EQ(5, stats_proxy_->GetStats().number_of_quality_adapt_changes);
kthelgason5e13d412016-12-01 03:59:51 -08003938
mflodmancc3d4422017-08-03 08:27:51 -07003939 video_stream_encoder_->Stop();
kthelgason5e13d412016-12-01 03:59:51 -08003940}
3941
mflodmancc3d4422017-08-03 08:27:51 -07003942TEST_F(VideoStreamEncoderTest, CpuLimitedHistogramIsReported) {
asaperssonfab67072017-04-04 05:51:49 -07003943 const int kWidth = 640;
3944 const int kHeight = 360;
perkj803d97f2016-11-01 11:45:46 -07003945
Henrik Boström381d1092020-05-12 18:49:07 +02003946 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01003947 DataRate::BitsPerSec(kTargetBitrateBps),
3948 DataRate::BitsPerSec(kTargetBitrateBps),
3949 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
sprang4847ae62017-06-27 07:06:52 -07003950
perkj803d97f2016-11-01 11:45:46 -07003951 for (int i = 1; i <= SendStatisticsProxy::kMinRequiredMetricsSamples; ++i) {
asaperssonfab67072017-04-04 05:51:49 -07003952 video_source_.IncomingCapturedFrame(CreateFrame(i, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07003953 WaitForEncodedFrame(i);
perkj803d97f2016-11-01 11:45:46 -07003954 }
3955
mflodmancc3d4422017-08-03 08:27:51 -07003956 video_stream_encoder_->TriggerCpuOveruse();
perkj803d97f2016-11-01 11:45:46 -07003957 for (int i = 1; i <= SendStatisticsProxy::kMinRequiredMetricsSamples; ++i) {
asaperssonfab67072017-04-04 05:51:49 -07003958 video_source_.IncomingCapturedFrame(CreateFrame(
3959 SendStatisticsProxy::kMinRequiredMetricsSamples + i, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07003960 WaitForEncodedFrame(SendStatisticsProxy::kMinRequiredMetricsSamples + i);
perkj803d97f2016-11-01 11:45:46 -07003961 }
3962
mflodmancc3d4422017-08-03 08:27:51 -07003963 video_stream_encoder_->Stop();
3964 video_stream_encoder_.reset();
perkj803d97f2016-11-01 11:45:46 -07003965 stats_proxy_.reset();
sprangf8ee65e2017-02-28 08:49:33 -08003966
Ying Wangef3998f2019-12-09 13:06:53 +01003967 EXPECT_METRIC_EQ(
3968 1, metrics::NumSamples("WebRTC.Video.CpuLimitedResolutionInPercent"));
3969 EXPECT_METRIC_EQ(
perkj803d97f2016-11-01 11:45:46 -07003970 1, metrics::NumEvents("WebRTC.Video.CpuLimitedResolutionInPercent", 50));
3971}
3972
mflodmancc3d4422017-08-03 08:27:51 -07003973TEST_F(VideoStreamEncoderTest,
3974 CpuLimitedHistogramIsNotReportedForDisabledDegradation) {
Henrik Boström381d1092020-05-12 18:49:07 +02003975 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01003976 DataRate::BitsPerSec(kTargetBitrateBps),
3977 DataRate::BitsPerSec(kTargetBitrateBps),
3978 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asaperssonf4e44af2017-04-19 02:01:06 -07003979 const int kWidth = 640;
3980 const int kHeight = 360;
3981
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003982 video_stream_encoder_->SetSource(&video_source_,
3983 webrtc::DegradationPreference::DISABLED);
asaperssonf4e44af2017-04-19 02:01:06 -07003984
3985 for (int i = 1; i <= SendStatisticsProxy::kMinRequiredMetricsSamples; ++i) {
3986 video_source_.IncomingCapturedFrame(CreateFrame(i, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07003987 WaitForEncodedFrame(i);
asaperssonf4e44af2017-04-19 02:01:06 -07003988 }
3989
mflodmancc3d4422017-08-03 08:27:51 -07003990 video_stream_encoder_->Stop();
3991 video_stream_encoder_.reset();
asaperssonf4e44af2017-04-19 02:01:06 -07003992 stats_proxy_.reset();
3993
3994 EXPECT_EQ(0,
3995 metrics::NumSamples("WebRTC.Video.CpuLimitedResolutionInPercent"));
3996}
3997
Per Kjellanderdcef6412020-10-07 15:09:05 +02003998TEST_F(VideoStreamEncoderTest, ReportsVideoBitrateAllocation) {
3999 ResetEncoder("FAKE", 1, 1, 1, /*screenshare*/ false,
4000 VideoStreamEncoderSettings::BitrateAllocationCallbackType::
4001 kVideoBitrateAllocation);
sprang57c2fff2017-01-16 06:24:02 -08004002
4003 const int kDefaultFps = 30;
Erik Språng566124a2018-04-23 12:32:22 +02004004 const VideoBitrateAllocation expected_bitrate =
Mirta Dvornicic6799d732020-02-12 15:36:49 +01004005 SimulcastRateAllocator(fake_encoder_.codec_config())
Florent Castelli8bbdb5b2019-08-02 15:16:28 +02004006 .Allocate(VideoBitrateAllocationParameters(kLowTargetBitrateBps,
4007 kDefaultFps));
sprang57c2fff2017-01-16 06:24:02 -08004008
Henrik Boström381d1092020-05-12 18:49:07 +02004009 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01004010 DataRate::BitsPerSec(kLowTargetBitrateBps),
4011 DataRate::BitsPerSec(kLowTargetBitrateBps),
4012 DataRate::BitsPerSec(kLowTargetBitrateBps), 0, 0, 0);
sprang57c2fff2017-01-16 06:24:02 -08004013
sprang57c2fff2017-01-16 06:24:02 -08004014 video_source_.IncomingCapturedFrame(
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02004015 CreateFrame(CurrentTimeMs(), codec_width_, codec_height_));
4016 WaitForEncodedFrame(CurrentTimeMs());
Per Kjellanderdcef6412020-10-07 15:09:05 +02004017 EXPECT_EQ(sink_.GetLastVideoBitrateAllocation(), expected_bitrate);
4018 EXPECT_EQ(sink_.number_of_bitrate_allocations(), 1);
4019
Erik Språng5056af02019-09-02 15:53:11 +02004020 VideoBitrateAllocation bitrate_allocation =
4021 fake_encoder_.GetAndResetLastRateControlSettings()->bitrate;
Erik Språngd7329ca2019-02-21 21:19:53 +01004022 // Check that encoder has been updated too, not just allocation observer.
Erik Språng5056af02019-09-02 15:53:11 +02004023 EXPECT_EQ(bitrate_allocation.get_sum_bps(), kLowTargetBitrateBps);
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02004024 AdvanceTime(TimeDelta::Seconds(1) / kDefaultFps);
sprang57c2fff2017-01-16 06:24:02 -08004025
Per Kjellanderdcef6412020-10-07 15:09:05 +02004026 // VideoBitrateAllocation not updated on second frame.
sprang57c2fff2017-01-16 06:24:02 -08004027 video_source_.IncomingCapturedFrame(
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02004028 CreateFrame(CurrentTimeMs(), codec_width_, codec_height_));
4029 WaitForEncodedFrame(CurrentTimeMs());
Per Kjellanderdcef6412020-10-07 15:09:05 +02004030 EXPECT_EQ(sink_.number_of_bitrate_allocations(), 1);
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02004031 AdvanceTime(TimeDelta::Millis(1) / kDefaultFps);
sprang57c2fff2017-01-16 06:24:02 -08004032
Per Kjellanderdcef6412020-10-07 15:09:05 +02004033 // VideoBitrateAllocation updated after a process interval.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02004034 const int64_t start_time_ms = CurrentTimeMs();
Per Kjellanderd0a8f512020-10-07 11:28:41 +02004035 while (CurrentTimeMs() - start_time_ms < 5 * kProcessIntervalMs) {
Erik Språngd7329ca2019-02-21 21:19:53 +01004036 video_source_.IncomingCapturedFrame(
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02004037 CreateFrame(CurrentTimeMs(), codec_width_, codec_height_));
4038 WaitForEncodedFrame(CurrentTimeMs());
4039 AdvanceTime(TimeDelta::Millis(1) / kDefaultFps);
Erik Språngd7329ca2019-02-21 21:19:53 +01004040 }
Per Kjellanderdcef6412020-10-07 15:09:05 +02004041 EXPECT_GT(sink_.number_of_bitrate_allocations(), 3);
Erik Språngd7329ca2019-02-21 21:19:53 +01004042
mflodmancc3d4422017-08-03 08:27:51 -07004043 video_stream_encoder_->Stop();
sprang57c2fff2017-01-16 06:24:02 -08004044}
4045
Per Kjellandera9434842020-10-15 17:53:22 +02004046TEST_F(VideoStreamEncoderTest, ReportsVideoLayersAllocationForV8Simulcast) {
4047 ResetEncoder("VP8", /*num_streams*/ 2, 1, 1, /*screenshare*/ false,
4048 VideoStreamEncoderSettings::BitrateAllocationCallbackType::
4049 kVideoLayersAllocation);
4050
4051 const int kDefaultFps = 30;
4052
4053 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
4054 DataRate::BitsPerSec(kLowTargetBitrateBps),
4055 DataRate::BitsPerSec(kLowTargetBitrateBps),
4056 DataRate::BitsPerSec(kLowTargetBitrateBps), 0, 0, 0);
4057
4058 video_source_.IncomingCapturedFrame(
4059 CreateFrame(CurrentTimeMs(), codec_width_, codec_height_));
4060 WaitForEncodedFrame(CurrentTimeMs());
4061 EXPECT_EQ(sink_.number_of_layers_allocations(), 1);
4062 VideoLayersAllocation last_layer_allocation =
4063 sink_.GetLastVideoLayersAllocation();
4064 // kLowTargetBitrateBps is only enough for one spatial layer.
4065 ASSERT_EQ(last_layer_allocation.active_spatial_layers.size(), 1u);
4066
4067 VideoBitrateAllocation bitrate_allocation =
4068 fake_encoder_.GetAndResetLastRateControlSettings()->bitrate;
4069 // Check that encoder has been updated too, not just allocation observer.
4070 EXPECT_EQ(bitrate_allocation.get_sum_bps(), kLowTargetBitrateBps);
4071 AdvanceTime(TimeDelta::Seconds(1) / kDefaultFps);
4072
4073 // VideoLayersAllocation might be updated if frame rate change.
4074 int number_of_layers_allocation = 1;
4075 const int64_t start_time_ms = CurrentTimeMs();
4076 while (CurrentTimeMs() - start_time_ms < 10 * kProcessIntervalMs) {
4077 video_source_.IncomingCapturedFrame(
4078 CreateFrame(CurrentTimeMs(), codec_width_, codec_height_));
4079 WaitForEncodedFrame(CurrentTimeMs());
4080 AdvanceTime(TimeDelta::Millis(1) / kDefaultFps);
4081 if (number_of_layers_allocation != sink_.number_of_layers_allocations()) {
4082 number_of_layers_allocation = sink_.number_of_layers_allocations();
4083 VideoLayersAllocation new_allocation =
4084 sink_.GetLastVideoLayersAllocation();
4085 ASSERT_EQ(new_allocation.active_spatial_layers.size(), 1u);
4086 EXPECT_NE(new_allocation.active_spatial_layers[0].frame_rate_fps,
4087 last_layer_allocation.active_spatial_layers[0].frame_rate_fps);
4088 EXPECT_EQ(new_allocation.active_spatial_layers[0]
4089 .target_bitrate_per_temporal_layer,
4090 last_layer_allocation.active_spatial_layers[0]
4091 .target_bitrate_per_temporal_layer);
4092 last_layer_allocation = new_allocation;
4093 }
4094 }
4095 EXPECT_LE(sink_.number_of_layers_allocations(), 3);
4096 video_stream_encoder_->Stop();
4097}
4098
4099TEST_F(VideoStreamEncoderTest,
4100 ReportsUpdatedVideoLayersAllocationWhenBweChanges) {
4101 ResetEncoder("VP8", /*num_streams*/ 2, 1, 1, /*screenshare*/ false,
4102 VideoStreamEncoderSettings::BitrateAllocationCallbackType::
4103 kVideoLayersAllocation);
4104
4105 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
4106 DataRate::BitsPerSec(kLowTargetBitrateBps),
4107 DataRate::BitsPerSec(kLowTargetBitrateBps),
4108 DataRate::BitsPerSec(kLowTargetBitrateBps), 0, 0, 0);
4109
4110 video_source_.IncomingCapturedFrame(
4111 CreateFrame(CurrentTimeMs(), codec_width_, codec_height_));
4112 WaitForEncodedFrame(CurrentTimeMs());
4113 EXPECT_EQ(sink_.number_of_layers_allocations(), 1);
4114 VideoLayersAllocation last_layer_allocation =
4115 sink_.GetLastVideoLayersAllocation();
4116 // kLowTargetBitrateBps is only enough for one spatial layer.
4117 ASSERT_EQ(last_layer_allocation.active_spatial_layers.size(), 1u);
4118 EXPECT_EQ(last_layer_allocation.active_spatial_layers[0]
4119 .target_bitrate_per_temporal_layer[0],
4120 DataRate::BitsPerSec(kLowTargetBitrateBps));
4121
4122 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
4123 DataRate::BitsPerSec(kSimulcastTargetBitrateBps),
4124 DataRate::BitsPerSec(kSimulcastTargetBitrateBps),
4125 DataRate::BitsPerSec(kSimulcastTargetBitrateBps), 0, 0, 0);
4126 video_source_.IncomingCapturedFrame(
4127 CreateFrame(CurrentTimeMs(), codec_width_, codec_height_));
4128 WaitForEncodedFrame(CurrentTimeMs());
4129
4130 EXPECT_EQ(sink_.number_of_layers_allocations(), 2);
4131 last_layer_allocation = sink_.GetLastVideoLayersAllocation();
4132 ASSERT_EQ(last_layer_allocation.active_spatial_layers.size(), 2u);
4133 EXPECT_GT(last_layer_allocation.active_spatial_layers[1]
4134 .target_bitrate_per_temporal_layer[0],
4135 DataRate::Zero());
4136
4137 video_stream_encoder_->Stop();
4138}
4139
Åsa Perssonc29cb2c2019-03-25 12:06:59 +01004140TEST_F(VideoStreamEncoderTest, TemporalLayersNotDisabledIfSupported) {
4141 // 2 TLs configured, temporal layers supported by encoder.
4142 const int kNumTemporalLayers = 2;
Per Kjellanderdcef6412020-10-07 15:09:05 +02004143 ResetEncoder("VP8", 1, kNumTemporalLayers, 1, /*screenshare*/ false,
4144 VideoStreamEncoderSettings::BitrateAllocationCallbackType::
4145 kVideoBitrateAllocation);
Åsa Perssonc29cb2c2019-03-25 12:06:59 +01004146 fake_encoder_.SetTemporalLayersSupported(0, true);
4147
4148 // Bitrate allocated across temporal layers.
4149 const int kTl0Bps = kTargetBitrateBps *
4150 webrtc::SimulcastRateAllocator::GetTemporalRateAllocation(
Rasmus Brandt2b9317a2019-10-30 13:01:46 +01004151 kNumTemporalLayers, /*temporal_id*/ 0,
4152 /*base_heavy_tl3_alloc*/ false);
Åsa Perssonc29cb2c2019-03-25 12:06:59 +01004153 const int kTl1Bps = kTargetBitrateBps *
4154 webrtc::SimulcastRateAllocator::GetTemporalRateAllocation(
Rasmus Brandt2b9317a2019-10-30 13:01:46 +01004155 kNumTemporalLayers, /*temporal_id*/ 1,
4156 /*base_heavy_tl3_alloc*/ false);
Åsa Perssonc29cb2c2019-03-25 12:06:59 +01004157 VideoBitrateAllocation expected_bitrate;
4158 expected_bitrate.SetBitrate(/*si*/ 0, /*ti*/ 0, kTl0Bps);
4159 expected_bitrate.SetBitrate(/*si*/ 0, /*ti*/ 1, kTl1Bps - kTl0Bps);
4160
4161 VerifyAllocatedBitrate(expected_bitrate);
4162 video_stream_encoder_->Stop();
4163}
4164
4165TEST_F(VideoStreamEncoderTest, TemporalLayersDisabledIfNotSupported) {
4166 // 2 TLs configured, temporal layers not supported by encoder.
Per Kjellanderdcef6412020-10-07 15:09:05 +02004167 ResetEncoder("VP8", 1, /*num_temporal_layers*/ 2, 1, /*screenshare*/ false,
4168 VideoStreamEncoderSettings::BitrateAllocationCallbackType::
4169 kVideoBitrateAllocation);
Åsa Perssonc29cb2c2019-03-25 12:06:59 +01004170 fake_encoder_.SetTemporalLayersSupported(0, false);
4171
4172 // Temporal layers not supported by the encoder.
4173 // Total bitrate should be at ti:0.
4174 VideoBitrateAllocation expected_bitrate;
4175 expected_bitrate.SetBitrate(/*si*/ 0, /*ti*/ 0, kTargetBitrateBps);
4176
4177 VerifyAllocatedBitrate(expected_bitrate);
4178 video_stream_encoder_->Stop();
4179}
4180
4181TEST_F(VideoStreamEncoderTest, VerifyBitrateAllocationForTwoStreams) {
Per Kjellanderdcef6412020-10-07 15:09:05 +02004182 webrtc::test::ScopedFieldTrials field_trials(
4183 "WebRTC-Video-QualityScalerSettings/"
4184 "initial_bitrate_interval_ms:1000,initial_bitrate_factor:0.2/");
4185 // Reset encoder for field trials to take effect.
4186 ConfigureEncoder(video_encoder_config_.Copy());
4187
Åsa Perssonc29cb2c2019-03-25 12:06:59 +01004188 // 2 TLs configured, temporal layers only supported for first stream.
Per Kjellanderdcef6412020-10-07 15:09:05 +02004189 ResetEncoder("VP8", 2, /*num_temporal_layers*/ 2, 1, /*screenshare*/ false,
4190 VideoStreamEncoderSettings::BitrateAllocationCallbackType::
4191 kVideoBitrateAllocation);
Åsa Perssonc29cb2c2019-03-25 12:06:59 +01004192 fake_encoder_.SetTemporalLayersSupported(0, true);
4193 fake_encoder_.SetTemporalLayersSupported(1, false);
4194
4195 const int kS0Bps = 150000;
4196 const int kS0Tl0Bps =
Rasmus Brandt2b9317a2019-10-30 13:01:46 +01004197 kS0Bps *
4198 webrtc::SimulcastRateAllocator::GetTemporalRateAllocation(
4199 /*num_layers*/ 2, /*temporal_id*/ 0, /*base_heavy_tl3_alloc*/ false);
Åsa Perssonc29cb2c2019-03-25 12:06:59 +01004200 const int kS0Tl1Bps =
Rasmus Brandt2b9317a2019-10-30 13:01:46 +01004201 kS0Bps *
4202 webrtc::SimulcastRateAllocator::GetTemporalRateAllocation(
4203 /*num_layers*/ 2, /*temporal_id*/ 1, /*base_heavy_tl3_alloc*/ false);
Åsa Perssonc29cb2c2019-03-25 12:06:59 +01004204 const int kS1Bps = kTargetBitrateBps - kS0Tl1Bps;
4205 // Temporal layers not supported by si:1.
4206 VideoBitrateAllocation expected_bitrate;
4207 expected_bitrate.SetBitrate(/*si*/ 0, /*ti*/ 0, kS0Tl0Bps);
4208 expected_bitrate.SetBitrate(/*si*/ 0, /*ti*/ 1, kS0Tl1Bps - kS0Tl0Bps);
4209 expected_bitrate.SetBitrate(/*si*/ 1, /*ti*/ 0, kS1Bps);
4210
4211 VerifyAllocatedBitrate(expected_bitrate);
4212 video_stream_encoder_->Stop();
4213}
4214
Niels Möller7dc26b72017-12-06 10:27:48 +01004215TEST_F(VideoStreamEncoderTest, OveruseDetectorUpdatedOnReconfigureAndAdaption) {
4216 const int kFrameWidth = 1280;
4217 const int kFrameHeight = 720;
4218 const int kFramerate = 24;
4219
Henrik Boström381d1092020-05-12 18:49:07 +02004220 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01004221 DataRate::BitsPerSec(kTargetBitrateBps),
4222 DataRate::BitsPerSec(kTargetBitrateBps),
4223 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Niels Möller7dc26b72017-12-06 10:27:48 +01004224 test::FrameForwarder source;
4225 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07004226 &source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
Niels Möller7dc26b72017-12-06 10:27:48 +01004227
4228 // Insert a single frame, triggering initial configuration.
4229 source.IncomingCapturedFrame(CreateFrame(1, kFrameWidth, kFrameHeight));
4230 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
4231
4232 EXPECT_EQ(
4233 video_stream_encoder_->overuse_detector_proxy_->GetLastTargetFramerate(),
4234 kDefaultFramerate);
4235
4236 // Trigger reconfigure encoder (without resetting the entire instance).
4237 VideoEncoderConfig video_encoder_config;
Åsa Persson17107062020-10-08 08:57:51 +02004238 test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
4239 video_encoder_config.simulcast_layers[0].max_framerate = kFramerate;
Niels Möller7dc26b72017-12-06 10:27:48 +01004240 video_encoder_config.max_bitrate_bps = kTargetBitrateBps;
Niels Möller7dc26b72017-12-06 10:27:48 +01004241 video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config),
Niels Möllerf1338562018-04-26 09:51:47 +02004242 kMaxPayloadLength);
Niels Möller7dc26b72017-12-06 10:27:48 +01004243 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
4244
4245 // Detector should be updated with fps limit from codec config.
4246 EXPECT_EQ(
4247 video_stream_encoder_->overuse_detector_proxy_->GetLastTargetFramerate(),
4248 kFramerate);
4249
4250 // Trigger overuse, max framerate should be reduced.
4251 VideoSendStream::Stats stats = stats_proxy_->GetStats();
4252 stats.input_frame_rate = kFramerate;
4253 stats_proxy_->SetMockStats(stats);
4254 video_stream_encoder_->TriggerCpuOveruse();
4255 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
4256 int adapted_framerate =
4257 video_stream_encoder_->overuse_detector_proxy_->GetLastTargetFramerate();
4258 EXPECT_LT(adapted_framerate, kFramerate);
4259
4260 // Trigger underuse, max framerate should go back to codec configured fps.
4261 // Set extra low fps, to make sure it's actually reset, not just incremented.
4262 stats = stats_proxy_->GetStats();
4263 stats.input_frame_rate = adapted_framerate / 2;
4264 stats_proxy_->SetMockStats(stats);
Henrik Boström91aa7322020-04-28 12:24:33 +02004265 video_stream_encoder_->TriggerCpuUnderuse();
Niels Möller7dc26b72017-12-06 10:27:48 +01004266 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
4267 EXPECT_EQ(
4268 video_stream_encoder_->overuse_detector_proxy_->GetLastTargetFramerate(),
4269 kFramerate);
4270
4271 video_stream_encoder_->Stop();
4272}
4273
4274TEST_F(VideoStreamEncoderTest,
4275 OveruseDetectorUpdatedRespectsFramerateAfterUnderuse) {
4276 const int kFrameWidth = 1280;
4277 const int kFrameHeight = 720;
4278 const int kLowFramerate = 15;
4279 const int kHighFramerate = 25;
4280
Henrik Boström381d1092020-05-12 18:49:07 +02004281 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01004282 DataRate::BitsPerSec(kTargetBitrateBps),
4283 DataRate::BitsPerSec(kTargetBitrateBps),
4284 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Niels Möller7dc26b72017-12-06 10:27:48 +01004285 test::FrameForwarder source;
4286 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07004287 &source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
Niels Möller7dc26b72017-12-06 10:27:48 +01004288
4289 // Trigger initial configuration.
4290 VideoEncoderConfig video_encoder_config;
Åsa Persson17107062020-10-08 08:57:51 +02004291 test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
4292 video_encoder_config.simulcast_layers[0].max_framerate = kLowFramerate;
Niels Möller7dc26b72017-12-06 10:27:48 +01004293 video_encoder_config.max_bitrate_bps = kTargetBitrateBps;
Niels Möller7dc26b72017-12-06 10:27:48 +01004294 source.IncomingCapturedFrame(CreateFrame(1, kFrameWidth, kFrameHeight));
Åsa Persson17107062020-10-08 08:57:51 +02004295 video_stream_encoder_->ConfigureEncoder(video_encoder_config.Copy(),
Niels Möllerf1338562018-04-26 09:51:47 +02004296 kMaxPayloadLength);
Niels Möller7dc26b72017-12-06 10:27:48 +01004297 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
4298
4299 EXPECT_EQ(
4300 video_stream_encoder_->overuse_detector_proxy_->GetLastTargetFramerate(),
4301 kLowFramerate);
4302
4303 // Trigger overuse, max framerate should be reduced.
4304 VideoSendStream::Stats stats = stats_proxy_->GetStats();
4305 stats.input_frame_rate = kLowFramerate;
4306 stats_proxy_->SetMockStats(stats);
4307 video_stream_encoder_->TriggerCpuOveruse();
4308 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
4309 int adapted_framerate =
4310 video_stream_encoder_->overuse_detector_proxy_->GetLastTargetFramerate();
4311 EXPECT_LT(adapted_framerate, kLowFramerate);
4312
4313 // Reconfigure the encoder with a new (higher max framerate), max fps should
4314 // still respect the adaptation.
Åsa Persson17107062020-10-08 08:57:51 +02004315 video_encoder_config.simulcast_layers[0].max_framerate = kHighFramerate;
Niels Möller7dc26b72017-12-06 10:27:48 +01004316 source.IncomingCapturedFrame(CreateFrame(1, kFrameWidth, kFrameHeight));
4317 video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config),
Niels Möllerf1338562018-04-26 09:51:47 +02004318 kMaxPayloadLength);
Niels Möller7dc26b72017-12-06 10:27:48 +01004319 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
4320
4321 EXPECT_EQ(
4322 video_stream_encoder_->overuse_detector_proxy_->GetLastTargetFramerate(),
4323 adapted_framerate);
4324
4325 // Trigger underuse, max framerate should go back to codec configured fps.
4326 stats = stats_proxy_->GetStats();
4327 stats.input_frame_rate = adapted_framerate;
4328 stats_proxy_->SetMockStats(stats);
Henrik Boström91aa7322020-04-28 12:24:33 +02004329 video_stream_encoder_->TriggerCpuUnderuse();
Niels Möller7dc26b72017-12-06 10:27:48 +01004330 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
4331 EXPECT_EQ(
4332 video_stream_encoder_->overuse_detector_proxy_->GetLastTargetFramerate(),
4333 kHighFramerate);
4334
4335 video_stream_encoder_->Stop();
4336}
4337
mflodmancc3d4422017-08-03 08:27:51 -07004338TEST_F(VideoStreamEncoderTest,
4339 OveruseDetectorUpdatedOnDegradationPreferenceChange) {
sprangfda496a2017-06-15 04:21:07 -07004340 const int kFrameWidth = 1280;
4341 const int kFrameHeight = 720;
4342 const int kFramerate = 24;
4343
Henrik Boström381d1092020-05-12 18:49:07 +02004344 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01004345 DataRate::BitsPerSec(kTargetBitrateBps),
4346 DataRate::BitsPerSec(kTargetBitrateBps),
4347 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
sprangfda496a2017-06-15 04:21:07 -07004348 test::FrameForwarder source;
mflodmancc3d4422017-08-03 08:27:51 -07004349 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07004350 &source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
sprangfda496a2017-06-15 04:21:07 -07004351
4352 // Trigger initial configuration.
4353 VideoEncoderConfig video_encoder_config;
Åsa Persson17107062020-10-08 08:57:51 +02004354 test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
4355 video_encoder_config.simulcast_layers[0].max_framerate = kFramerate;
sprangfda496a2017-06-15 04:21:07 -07004356 video_encoder_config.max_bitrate_bps = kTargetBitrateBps;
sprangfda496a2017-06-15 04:21:07 -07004357 source.IncomingCapturedFrame(CreateFrame(1, kFrameWidth, kFrameHeight));
mflodmancc3d4422017-08-03 08:27:51 -07004358 video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config),
Niels Möllerf1338562018-04-26 09:51:47 +02004359 kMaxPayloadLength);
mflodmancc3d4422017-08-03 08:27:51 -07004360 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
sprangfda496a2017-06-15 04:21:07 -07004361
Niels Möller7dc26b72017-12-06 10:27:48 +01004362 EXPECT_EQ(
4363 video_stream_encoder_->overuse_detector_proxy_->GetLastTargetFramerate(),
4364 kFramerate);
sprangfda496a2017-06-15 04:21:07 -07004365
4366 // Trigger overuse, max framerate should be reduced.
4367 VideoSendStream::Stats stats = stats_proxy_->GetStats();
4368 stats.input_frame_rate = kFramerate;
4369 stats_proxy_->SetMockStats(stats);
mflodmancc3d4422017-08-03 08:27:51 -07004370 video_stream_encoder_->TriggerCpuOveruse();
4371 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
Niels Möller7dc26b72017-12-06 10:27:48 +01004372 int adapted_framerate =
4373 video_stream_encoder_->overuse_detector_proxy_->GetLastTargetFramerate();
sprangfda496a2017-06-15 04:21:07 -07004374 EXPECT_LT(adapted_framerate, kFramerate);
4375
4376 // Change degradation preference to not enable framerate scaling. Target
4377 // framerate should be changed to codec defined limit.
Henrik Boström381d1092020-05-12 18:49:07 +02004378 video_stream_encoder_->SetSourceAndWaitForFramerateUpdated(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07004379 &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
Niels Möller7dc26b72017-12-06 10:27:48 +01004380 EXPECT_EQ(
4381 video_stream_encoder_->overuse_detector_proxy_->GetLastTargetFramerate(),
4382 kFramerate);
sprangfda496a2017-06-15 04:21:07 -07004383
mflodmancc3d4422017-08-03 08:27:51 -07004384 video_stream_encoder_->Stop();
sprangfda496a2017-06-15 04:21:07 -07004385}
4386
mflodmancc3d4422017-08-03 08:27:51 -07004387TEST_F(VideoStreamEncoderTest, DropsFramesAndScalesWhenBitrateIsTooLow) {
asaperssonfab67072017-04-04 05:51:49 -07004388 const int kTooLowBitrateForFrameSizeBps = 10000;
Henrik Boström381d1092020-05-12 18:49:07 +02004389 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01004390 DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps),
4391 DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps),
4392 DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps), 0, 0, 0);
asaperssonfab67072017-04-04 05:51:49 -07004393 const int kWidth = 640;
4394 const int kHeight = 360;
kthelgason2bc68642017-02-07 07:02:22 -08004395
asaperssonfab67072017-04-04 05:51:49 -07004396 video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
kthelgason2bc68642017-02-07 07:02:22 -08004397
4398 // Expect to drop this frame, the wait should time out.
sprang4847ae62017-06-27 07:06:52 -07004399 ExpectDroppedFrame();
kthelgason2bc68642017-02-07 07:02:22 -08004400
4401 // Expect the sink_wants to specify a scaled frame.
Henrik Boström2671dac2020-05-19 16:29:09 +02004402 EXPECT_TRUE_WAIT(
4403 video_source_.sink_wants().max_pixel_count < kWidth * kHeight, 5000);
kthelgason2bc68642017-02-07 07:02:22 -08004404
sprangc5d62e22017-04-02 23:53:04 -07004405 int last_pixel_count = video_source_.sink_wants().max_pixel_count;
kthelgason2bc68642017-02-07 07:02:22 -08004406
asaperssonfab67072017-04-04 05:51:49 -07004407 // Next frame is scaled.
kthelgason2bc68642017-02-07 07:02:22 -08004408 video_source_.IncomingCapturedFrame(
asaperssonfab67072017-04-04 05:51:49 -07004409 CreateFrame(2, kWidth * 3 / 4, kHeight * 3 / 4));
kthelgason2bc68642017-02-07 07:02:22 -08004410
4411 // Expect to drop this frame, the wait should time out.
sprang4847ae62017-06-27 07:06:52 -07004412 ExpectDroppedFrame();
kthelgason2bc68642017-02-07 07:02:22 -08004413
Henrik Boström2671dac2020-05-19 16:29:09 +02004414 EXPECT_TRUE_WAIT(
4415 video_source_.sink_wants().max_pixel_count < last_pixel_count, 5000);
kthelgason2bc68642017-02-07 07:02:22 -08004416
mflodmancc3d4422017-08-03 08:27:51 -07004417 video_stream_encoder_->Stop();
kthelgason2bc68642017-02-07 07:02:22 -08004418}
4419
mflodmancc3d4422017-08-03 08:27:51 -07004420TEST_F(VideoStreamEncoderTest,
4421 NumberOfDroppedFramesLimitedWhenBitrateIsTooLow) {
asaperssonfab67072017-04-04 05:51:49 -07004422 const int kTooLowBitrateForFrameSizeBps = 10000;
Henrik Boström381d1092020-05-12 18:49:07 +02004423 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01004424 DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps),
4425 DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps),
4426 DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps), 0, 0, 0);
asaperssonfab67072017-04-04 05:51:49 -07004427 const int kWidth = 640;
4428 const int kHeight = 360;
kthelgason2bc68642017-02-07 07:02:22 -08004429
4430 // We expect the n initial frames to get dropped.
4431 int i;
4432 for (i = 1; i <= kMaxInitialFramedrop; ++i) {
asaperssonfab67072017-04-04 05:51:49 -07004433 video_source_.IncomingCapturedFrame(CreateFrame(i, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07004434 ExpectDroppedFrame();
kthelgason2bc68642017-02-07 07:02:22 -08004435 }
4436 // The n+1th frame should not be dropped, even though it's size is too large.
asaperssonfab67072017-04-04 05:51:49 -07004437 video_source_.IncomingCapturedFrame(CreateFrame(i, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07004438 WaitForEncodedFrame(i);
kthelgason2bc68642017-02-07 07:02:22 -08004439
4440 // Expect the sink_wants to specify a scaled frame.
asaperssonfab67072017-04-04 05:51:49 -07004441 EXPECT_LT(video_source_.sink_wants().max_pixel_count, kWidth * kHeight);
kthelgason2bc68642017-02-07 07:02:22 -08004442
mflodmancc3d4422017-08-03 08:27:51 -07004443 video_stream_encoder_->Stop();
kthelgason2bc68642017-02-07 07:02:22 -08004444}
4445
mflodmancc3d4422017-08-03 08:27:51 -07004446TEST_F(VideoStreamEncoderTest,
4447 InitialFrameDropOffWithMaintainResolutionPreference) {
asaperssonfab67072017-04-04 05:51:49 -07004448 const int kWidth = 640;
4449 const int kHeight = 360;
Henrik Boström381d1092020-05-12 18:49:07 +02004450 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01004451 DataRate::BitsPerSec(kLowTargetBitrateBps),
4452 DataRate::BitsPerSec(kLowTargetBitrateBps),
4453 DataRate::BitsPerSec(kLowTargetBitrateBps), 0, 0, 0);
kthelgason2bc68642017-02-07 07:02:22 -08004454
4455 // Set degradation preference.
mflodmancc3d4422017-08-03 08:27:51 -07004456 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07004457 &video_source_, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
kthelgason2bc68642017-02-07 07:02:22 -08004458
asaperssonfab67072017-04-04 05:51:49 -07004459 video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
kthelgason2bc68642017-02-07 07:02:22 -08004460 // Frame should not be dropped, even if it's too large.
sprang4847ae62017-06-27 07:06:52 -07004461 WaitForEncodedFrame(1);
kthelgason2bc68642017-02-07 07:02:22 -08004462
mflodmancc3d4422017-08-03 08:27:51 -07004463 video_stream_encoder_->Stop();
kthelgason2bc68642017-02-07 07:02:22 -08004464}
4465
mflodmancc3d4422017-08-03 08:27:51 -07004466TEST_F(VideoStreamEncoderTest, InitialFrameDropOffWhenEncoderDisabledScaling) {
asaperssonfab67072017-04-04 05:51:49 -07004467 const int kWidth = 640;
4468 const int kHeight = 360;
kthelgasonad9010c2017-02-14 00:46:51 -08004469 fake_encoder_.SetQualityScaling(false);
Niels Möller4db138e2018-04-19 09:04:13 +02004470
4471 VideoEncoderConfig video_encoder_config;
4472 test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
4473 // Make format different, to force recreation of encoder.
4474 video_encoder_config.video_format.parameters["foo"] = "foo";
4475 video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config),
Niels Möllerf1338562018-04-26 09:51:47 +02004476 kMaxPayloadLength);
Henrik Boström381d1092020-05-12 18:49:07 +02004477 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01004478 DataRate::BitsPerSec(kLowTargetBitrateBps),
4479 DataRate::BitsPerSec(kLowTargetBitrateBps),
4480 DataRate::BitsPerSec(kLowTargetBitrateBps), 0, 0, 0);
asapersson09f05612017-05-15 23:40:18 -07004481
kthelgasonb83797b2017-02-14 11:57:25 -08004482 // Force quality scaler reconfiguration by resetting the source.
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07004483 video_stream_encoder_->SetSource(&video_source_,
4484 webrtc::DegradationPreference::BALANCED);
kthelgasonad9010c2017-02-14 00:46:51 -08004485
asaperssonfab67072017-04-04 05:51:49 -07004486 video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
kthelgasonad9010c2017-02-14 00:46:51 -08004487 // Frame should not be dropped, even if it's too large.
sprang4847ae62017-06-27 07:06:52 -07004488 WaitForEncodedFrame(1);
kthelgasonad9010c2017-02-14 00:46:51 -08004489
mflodmancc3d4422017-08-03 08:27:51 -07004490 video_stream_encoder_->Stop();
kthelgasonad9010c2017-02-14 00:46:51 -08004491 fake_encoder_.SetQualityScaling(true);
4492}
4493
Åsa Persson139f4dc2019-08-02 09:29:58 +02004494TEST_F(VideoStreamEncoderTest, InitialFrameDropActivatesWhenBweDrops) {
4495 webrtc::test::ScopedFieldTrials field_trials(
4496 "WebRTC-Video-QualityScalerSettings/"
4497 "initial_bitrate_interval_ms:1000,initial_bitrate_factor:0.2/");
4498 // Reset encoder for field trials to take effect.
4499 ConfigureEncoder(video_encoder_config_.Copy());
4500 const int kNotTooLowBitrateForFrameSizeBps = kTargetBitrateBps * 0.2;
4501 const int kTooLowBitrateForFrameSizeBps = kTargetBitrateBps * 0.19;
4502 const int kWidth = 640;
4503 const int kHeight = 360;
4504
Henrik Boström381d1092020-05-12 18:49:07 +02004505 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01004506 DataRate::BitsPerSec(kTargetBitrateBps),
4507 DataRate::BitsPerSec(kTargetBitrateBps),
4508 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Åsa Persson139f4dc2019-08-02 09:29:58 +02004509 video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
4510 // Frame should not be dropped.
4511 WaitForEncodedFrame(1);
4512
Henrik Boström381d1092020-05-12 18:49:07 +02004513 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01004514 DataRate::BitsPerSec(kNotTooLowBitrateForFrameSizeBps),
4515 DataRate::BitsPerSec(kNotTooLowBitrateForFrameSizeBps),
4516 DataRate::BitsPerSec(kNotTooLowBitrateForFrameSizeBps), 0, 0, 0);
Åsa Persson139f4dc2019-08-02 09:29:58 +02004517 video_source_.IncomingCapturedFrame(CreateFrame(2, kWidth, kHeight));
4518 // Frame should not be dropped.
4519 WaitForEncodedFrame(2);
4520
Henrik Boström381d1092020-05-12 18:49:07 +02004521 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01004522 DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps),
4523 DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps),
4524 DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps), 0, 0, 0);
Åsa Persson139f4dc2019-08-02 09:29:58 +02004525 video_source_.IncomingCapturedFrame(CreateFrame(3, kWidth, kHeight));
4526 // Expect to drop this frame, the wait should time out.
4527 ExpectDroppedFrame();
4528
4529 // Expect the sink_wants to specify a scaled frame.
Henrik Boström2671dac2020-05-19 16:29:09 +02004530 EXPECT_TRUE_WAIT(
4531 video_source_.sink_wants().max_pixel_count < kWidth * kHeight, 5000);
Åsa Persson139f4dc2019-08-02 09:29:58 +02004532 video_stream_encoder_->Stop();
4533}
4534
Evan Shrubsolee3da1d32020-08-14 15:58:33 +02004535TEST_F(VideoStreamEncoderTest,
4536 InitialFrameDropNotReactivatedWhenBweDropsWhenScalingDisabled) {
4537 webrtc::test::ScopedFieldTrials field_trials(
4538 "WebRTC-Video-QualityScalerSettings/"
4539 "initial_bitrate_interval_ms:1000,initial_bitrate_factor:0.2/");
4540 fake_encoder_.SetQualityScaling(false);
4541 ConfigureEncoder(video_encoder_config_.Copy());
4542 const int kNotTooLowBitrateForFrameSizeBps = kTargetBitrateBps * 0.2;
4543 const int kTooLowBitrateForFrameSizeBps = kTargetBitrateBps * 0.19;
4544 const int kWidth = 640;
4545 const int kHeight = 360;
4546
4547 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
4548 DataRate::BitsPerSec(kTargetBitrateBps),
4549 DataRate::BitsPerSec(kTargetBitrateBps),
4550 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
4551 video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
4552 // Frame should not be dropped.
4553 WaitForEncodedFrame(1);
4554
4555 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
4556 DataRate::BitsPerSec(kNotTooLowBitrateForFrameSizeBps),
4557 DataRate::BitsPerSec(kNotTooLowBitrateForFrameSizeBps),
4558 DataRate::BitsPerSec(kNotTooLowBitrateForFrameSizeBps), 0, 0, 0);
4559 video_source_.IncomingCapturedFrame(CreateFrame(2, kWidth, kHeight));
4560 // Frame should not be dropped.
4561 WaitForEncodedFrame(2);
4562
4563 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
4564 DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps),
4565 DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps),
4566 DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps), 0, 0, 0);
4567 video_source_.IncomingCapturedFrame(CreateFrame(3, kWidth, kHeight));
4568 // Not dropped since quality scaling is disabled.
4569 WaitForEncodedFrame(3);
4570
4571 // Expect the sink_wants to specify a scaled frame.
Evan Shrubsole85728412020-08-25 13:12:12 +02004572 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
Evan Shrubsolee3da1d32020-08-14 15:58:33 +02004573 EXPECT_THAT(video_source_.sink_wants(), ResolutionMax());
4574
4575 video_stream_encoder_->Stop();
4576}
4577
Åsa Perssone644a032019-11-08 15:56:00 +01004578TEST_F(VideoStreamEncoderTest, RampsUpInQualityWhenBwIsHigh) {
4579 webrtc::test::ScopedFieldTrials field_trials(
4580 "WebRTC-Video-QualityRampupSettings/min_pixels:1,min_duration_ms:2000/");
4581
4582 // Reset encoder for field trials to take effect.
4583 VideoEncoderConfig config = video_encoder_config_.Copy();
4584 config.max_bitrate_bps = kTargetBitrateBps;
Evan Shrubsoledff79252020-04-16 11:34:32 +02004585 DataRate max_bitrate = DataRate::BitsPerSec(config.max_bitrate_bps);
Åsa Perssone644a032019-11-08 15:56:00 +01004586 ConfigureEncoder(std::move(config));
4587 fake_encoder_.SetQp(kQpLow);
4588
4589 // Enable MAINTAIN_FRAMERATE preference.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02004590 AdaptingFrameForwarder source(&time_controller_);
Åsa Perssone644a032019-11-08 15:56:00 +01004591 source.set_adaptation_enabled(true);
4592 video_stream_encoder_->SetSource(&source,
4593 DegradationPreference::MAINTAIN_FRAMERATE);
4594
4595 // Start at low bitrate.
4596 const int kLowBitrateBps = 200000;
Henrik Boström381d1092020-05-12 18:49:07 +02004597 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
4598 DataRate::BitsPerSec(kLowBitrateBps),
4599 DataRate::BitsPerSec(kLowBitrateBps),
4600 DataRate::BitsPerSec(kLowBitrateBps), 0, 0, 0);
Åsa Perssone644a032019-11-08 15:56:00 +01004601
4602 // Expect first frame to be dropped and resolution to be limited.
4603 const int kWidth = 1280;
4604 const int kHeight = 720;
4605 const int64_t kFrameIntervalMs = 100;
4606 int64_t timestamp_ms = kFrameIntervalMs;
4607 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
4608 ExpectDroppedFrame();
Henrik Boström2671dac2020-05-19 16:29:09 +02004609 EXPECT_TRUE_WAIT(source.sink_wants().max_pixel_count < kWidth * kHeight,
4610 5000);
Åsa Perssone644a032019-11-08 15:56:00 +01004611
4612 // Increase bitrate to encoder max.
Henrik Boström381d1092020-05-12 18:49:07 +02004613 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
4614 max_bitrate, max_bitrate, max_bitrate, 0, 0, 0);
Åsa Perssone644a032019-11-08 15:56:00 +01004615
4616 // Insert frames and advance |min_duration_ms|.
4617 for (size_t i = 1; i <= 10; i++) {
4618 timestamp_ms += kFrameIntervalMs;
4619 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
4620 WaitForEncodedFrame(timestamp_ms);
4621 }
4622 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
4623 EXPECT_LT(source.sink_wants().max_pixel_count, kWidth * kHeight);
4624
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02004625 AdvanceTime(TimeDelta::Millis(2000));
Åsa Perssone644a032019-11-08 15:56:00 +01004626
4627 // Insert frame should trigger high BW and release quality limitation.
4628 timestamp_ms += kFrameIntervalMs;
4629 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
4630 WaitForEncodedFrame(timestamp_ms);
Henrik Boström381d1092020-05-12 18:49:07 +02004631 // The ramp-up code involves the adaptation queue, give it time to execute.
4632 // TODO(hbos): Can we await an appropriate event instead?
Evan Shrubsole85728412020-08-25 13:12:12 +02004633 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02004634 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
Åsa Perssone644a032019-11-08 15:56:00 +01004635
4636 // Frame should not be adapted.
4637 timestamp_ms += kFrameIntervalMs;
4638 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
4639 WaitForEncodedFrame(kWidth, kHeight);
4640 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
4641
4642 video_stream_encoder_->Stop();
4643}
4644
mflodmancc3d4422017-08-03 08:27:51 -07004645TEST_F(VideoStreamEncoderTest,
Evan Shrubsole99b0f8d2020-08-25 13:12:28 +02004646 QualityScalerAdaptationsRemovedWhenQualityScalingDisabled) {
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02004647 AdaptingFrameForwarder source(&time_controller_);
Evan Shrubsole99b0f8d2020-08-25 13:12:28 +02004648 source.set_adaptation_enabled(true);
4649 video_stream_encoder_->SetSource(&source,
4650 DegradationPreference::MAINTAIN_FRAMERATE);
4651 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
4652 DataRate::BitsPerSec(kTargetBitrateBps),
4653 DataRate::BitsPerSec(kTargetBitrateBps),
4654 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
4655 fake_encoder_.SetQp(kQpHigh + 1);
4656 const int kWidth = 1280;
4657 const int kHeight = 720;
4658 const int64_t kFrameIntervalMs = 100;
4659 int64_t timestamp_ms = kFrameIntervalMs;
4660 for (size_t i = 1; i <= 100; i++) {
4661 timestamp_ms += kFrameIntervalMs;
4662 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
4663 WaitForEncodedFrame(timestamp_ms);
4664 }
4665 // Wait for QualityScaler, which will wait for 2000*2.5 ms until checking QP
4666 // for the first time.
4667 // TODO(eshr): We should avoid these waits by using threads with simulated
4668 // time.
4669 EXPECT_TRUE_WAIT(stats_proxy_->GetStats().bw_limited_resolution,
4670 2000 * 2.5 * 2);
4671 timestamp_ms += kFrameIntervalMs;
4672 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
4673 WaitForEncodedFrame(timestamp_ms);
4674 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
4675 EXPECT_THAT(source.sink_wants(), WantsMaxPixels(Lt(kWidth * kHeight)));
4676 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
4677
4678 // Disable Quality scaling by turning off scaler on the encoder and
4679 // reconfiguring.
4680 fake_encoder_.SetQualityScaling(false);
4681 video_stream_encoder_->ConfigureEncoder(video_encoder_config_.Copy(),
4682 kMaxPayloadLength);
4683 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02004684 AdvanceTime(TimeDelta::Millis(0));
Evan Shrubsole99b0f8d2020-08-25 13:12:28 +02004685 // Since we turned off the quality scaler, the adaptations made by it are
4686 // removed.
4687 EXPECT_THAT(source.sink_wants(), ResolutionMax());
4688 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
4689
4690 video_stream_encoder_->Stop();
4691}
4692
4693TEST_F(VideoStreamEncoderTest,
asaperssond0de2952017-04-21 01:47:31 -07004694 ResolutionNotAdaptedForTooSmallFrame_MaintainFramerateMode) {
4695 const int kTooSmallWidth = 10;
4696 const int kTooSmallHeight = 10;
Henrik Boström381d1092020-05-12 18:49:07 +02004697 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01004698 DataRate::BitsPerSec(kTargetBitrateBps),
4699 DataRate::BitsPerSec(kTargetBitrateBps),
4700 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asaperssond0de2952017-04-21 01:47:31 -07004701
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07004702 // Enable MAINTAIN_FRAMERATE preference, no initial limitation.
asaperssond0de2952017-04-21 01:47:31 -07004703 test::FrameForwarder source;
mflodmancc3d4422017-08-03 08:27:51 -07004704 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07004705 &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02004706 EXPECT_THAT(source.sink_wants(), UnlimitedSinkWants());
asaperssond0de2952017-04-21 01:47:31 -07004707 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
4708
4709 // Trigger adapt down, too small frame, expect no change.
4710 source.IncomingCapturedFrame(CreateFrame(1, kTooSmallWidth, kTooSmallHeight));
sprang4847ae62017-06-27 07:06:52 -07004711 WaitForEncodedFrame(1);
mflodmancc3d4422017-08-03 08:27:51 -07004712 video_stream_encoder_->TriggerCpuOveruse();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02004713 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssond0de2952017-04-21 01:47:31 -07004714 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
4715 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
4716
mflodmancc3d4422017-08-03 08:27:51 -07004717 video_stream_encoder_->Stop();
asaperssond0de2952017-04-21 01:47:31 -07004718}
4719
mflodmancc3d4422017-08-03 08:27:51 -07004720TEST_F(VideoStreamEncoderTest,
4721 ResolutionNotAdaptedForTooSmallFrame_BalancedMode) {
asaperssonf7e294d2017-06-13 23:25:22 -07004722 const int kTooSmallWidth = 10;
4723 const int kTooSmallHeight = 10;
4724 const int kFpsLimit = 7;
Henrik Boström381d1092020-05-12 18:49:07 +02004725 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01004726 DataRate::BitsPerSec(kTargetBitrateBps),
4727 DataRate::BitsPerSec(kTargetBitrateBps),
4728 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asaperssonf7e294d2017-06-13 23:25:22 -07004729
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07004730 // Enable BALANCED preference, no initial limitation.
asaperssonf7e294d2017-06-13 23:25:22 -07004731 test::FrameForwarder source;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07004732 video_stream_encoder_->SetSource(&source,
4733 webrtc::DegradationPreference::BALANCED);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02004734 EXPECT_THAT(source.sink_wants(), UnlimitedSinkWants());
asaperssonf7e294d2017-06-13 23:25:22 -07004735 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
4736 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
4737
4738 // Trigger adapt down, expect limited framerate.
4739 source.IncomingCapturedFrame(CreateFrame(1, kTooSmallWidth, kTooSmallHeight));
sprang4847ae62017-06-27 07:06:52 -07004740 WaitForEncodedFrame(1);
mflodmancc3d4422017-08-03 08:27:51 -07004741 video_stream_encoder_->TriggerQualityLow();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02004742 EXPECT_THAT(source.sink_wants(), FpsMatchesResolutionMax(Eq(kFpsLimit)));
asaperssonf7e294d2017-06-13 23:25:22 -07004743 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
4744 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
4745 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
4746
4747 // Trigger adapt down, too small frame, expect no change.
4748 source.IncomingCapturedFrame(CreateFrame(2, kTooSmallWidth, kTooSmallHeight));
sprang4847ae62017-06-27 07:06:52 -07004749 WaitForEncodedFrame(2);
mflodmancc3d4422017-08-03 08:27:51 -07004750 video_stream_encoder_->TriggerQualityLow();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02004751 EXPECT_THAT(source.sink_wants(), FpsMatchesResolutionMax(Eq(kFpsLimit)));
asaperssonf7e294d2017-06-13 23:25:22 -07004752 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
4753 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
4754 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
4755
mflodmancc3d4422017-08-03 08:27:51 -07004756 video_stream_encoder_->Stop();
asaperssonf7e294d2017-06-13 23:25:22 -07004757}
4758
mflodmancc3d4422017-08-03 08:27:51 -07004759TEST_F(VideoStreamEncoderTest, FailingInitEncodeDoesntCauseCrash) {
asapersson02465b82017-04-10 01:12:52 -07004760 fake_encoder_.ForceInitEncodeFailure(true);
Henrik Boström381d1092020-05-12 18:49:07 +02004761 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01004762 DataRate::BitsPerSec(kTargetBitrateBps),
4763 DataRate::BitsPerSec(kTargetBitrateBps),
4764 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Niels Möllerf1338562018-04-26 09:51:47 +02004765 ResetEncoder("VP8", 2, 1, 1, false);
asapersson02465b82017-04-10 01:12:52 -07004766 const int kFrameWidth = 1280;
4767 const int kFrameHeight = 720;
4768 video_source_.IncomingCapturedFrame(
4769 CreateFrame(1, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 07:06:52 -07004770 ExpectDroppedFrame();
mflodmancc3d4422017-08-03 08:27:51 -07004771 video_stream_encoder_->Stop();
asapersson02465b82017-04-10 01:12:52 -07004772}
4773
sprangb1ca0732017-02-01 08:38:12 -08004774// TODO(sprang): Extend this with fps throttling and any "balanced" extensions.
mflodmancc3d4422017-08-03 08:27:51 -07004775TEST_F(VideoStreamEncoderTest,
4776 AdaptsResolutionOnOveruse_MaintainFramerateMode) {
Henrik Boström381d1092020-05-12 18:49:07 +02004777 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01004778 DataRate::BitsPerSec(kTargetBitrateBps),
4779 DataRate::BitsPerSec(kTargetBitrateBps),
4780 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
sprangb1ca0732017-02-01 08:38:12 -08004781
4782 const int kFrameWidth = 1280;
4783 const int kFrameHeight = 720;
4784 // Enabled default VideoAdapter downscaling. First step is 3/4, not 3/5 as
mflodmancc3d4422017-08-03 08:27:51 -07004785 // requested by
4786 // VideoStreamEncoder::VideoSourceProxy::RequestResolutionLowerThan().
sprangb1ca0732017-02-01 08:38:12 -08004787 video_source_.set_adaptation_enabled(true);
4788
4789 video_source_.IncomingCapturedFrame(
Åsa Persson8c1bf952018-09-13 10:42:19 +02004790 CreateFrame(1 * kFrameIntervalMs, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 07:06:52 -07004791 WaitForEncodedFrame(kFrameWidth, kFrameHeight);
sprangb1ca0732017-02-01 08:38:12 -08004792
4793 // Trigger CPU overuse, downscale by 3/4.
mflodmancc3d4422017-08-03 08:27:51 -07004794 video_stream_encoder_->TriggerCpuOveruse();
sprangb1ca0732017-02-01 08:38:12 -08004795 video_source_.IncomingCapturedFrame(
Åsa Persson8c1bf952018-09-13 10:42:19 +02004796 CreateFrame(2 * kFrameIntervalMs, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 07:06:52 -07004797 WaitForEncodedFrame((kFrameWidth * 3) / 4, (kFrameHeight * 3) / 4);
sprangb1ca0732017-02-01 08:38:12 -08004798
asaperssonfab67072017-04-04 05:51:49 -07004799 // Trigger CPU normal use, return to original resolution.
Henrik Boström91aa7322020-04-28 12:24:33 +02004800 video_stream_encoder_->TriggerCpuUnderuse();
sprangb1ca0732017-02-01 08:38:12 -08004801 video_source_.IncomingCapturedFrame(
Åsa Persson8c1bf952018-09-13 10:42:19 +02004802 CreateFrame(3 * kFrameIntervalMs, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 07:06:52 -07004803 WaitForEncodedFrame(kFrameWidth, kFrameHeight);
sprangb1ca0732017-02-01 08:38:12 -08004804
mflodmancc3d4422017-08-03 08:27:51 -07004805 video_stream_encoder_->Stop();
sprangb1ca0732017-02-01 08:38:12 -08004806}
sprangfe627f32017-03-29 08:24:59 -07004807
mflodmancc3d4422017-08-03 08:27:51 -07004808TEST_F(VideoStreamEncoderTest,
4809 AdaptsFramerateOnOveruse_MaintainResolutionMode) {
sprangc5d62e22017-04-02 23:53:04 -07004810 const int kFrameWidth = 1280;
4811 const int kFrameHeight = 720;
sprangc5d62e22017-04-02 23:53:04 -07004812
Henrik Boström381d1092020-05-12 18:49:07 +02004813 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01004814 DataRate::BitsPerSec(kTargetBitrateBps),
4815 DataRate::BitsPerSec(kTargetBitrateBps),
4816 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
mflodmancc3d4422017-08-03 08:27:51 -07004817 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07004818 &video_source_, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
sprangc5d62e22017-04-02 23:53:04 -07004819 video_source_.set_adaptation_enabled(true);
4820
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02004821 int64_t timestamp_ms = CurrentTimeMs();
sprangc5d62e22017-04-02 23:53:04 -07004822
4823 video_source_.IncomingCapturedFrame(
4824 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 07:06:52 -07004825 WaitForEncodedFrame(timestamp_ms);
sprangc5d62e22017-04-02 23:53:04 -07004826
4827 // Try to trigger overuse. No fps estimate available => no effect.
mflodmancc3d4422017-08-03 08:27:51 -07004828 video_stream_encoder_->TriggerCpuOveruse();
sprangc5d62e22017-04-02 23:53:04 -07004829
4830 // Insert frames for one second to get a stable estimate.
sprang4847ae62017-06-27 07:06:52 -07004831 for (int i = 0; i < max_framerate_; ++i) {
sprangc5d62e22017-04-02 23:53:04 -07004832 timestamp_ms += kFrameIntervalMs;
sprangc5d62e22017-04-02 23:53:04 -07004833 video_source_.IncomingCapturedFrame(
4834 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 07:06:52 -07004835 WaitForEncodedFrame(timestamp_ms);
sprangc5d62e22017-04-02 23:53:04 -07004836 }
4837
4838 // Trigger CPU overuse, reduce framerate by 2/3.
mflodmancc3d4422017-08-03 08:27:51 -07004839 video_stream_encoder_->TriggerCpuOveruse();
sprangc5d62e22017-04-02 23:53:04 -07004840 int num_frames_dropped = 0;
sprang4847ae62017-06-27 07:06:52 -07004841 for (int i = 0; i < max_framerate_; ++i) {
sprangc5d62e22017-04-02 23:53:04 -07004842 timestamp_ms += kFrameIntervalMs;
sprangc5d62e22017-04-02 23:53:04 -07004843 video_source_.IncomingCapturedFrame(
4844 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 07:06:52 -07004845 if (!WaitForFrame(kFrameTimeoutMs)) {
sprangc5d62e22017-04-02 23:53:04 -07004846 ++num_frames_dropped;
4847 } else {
Åsa Perssonc74d8da2017-12-04 14:13:56 +01004848 sink_.CheckLastFrameSizeMatches(kFrameWidth, kFrameHeight);
sprangc5d62e22017-04-02 23:53:04 -07004849 }
4850 }
4851
sprang4847ae62017-06-27 07:06:52 -07004852 // Add some slack to account for frames dropped by the frame dropper.
4853 const int kErrorMargin = 1;
4854 EXPECT_NEAR(num_frames_dropped, max_framerate_ - (max_framerate_ * 2 / 3),
sprangc5d62e22017-04-02 23:53:04 -07004855 kErrorMargin);
4856
4857 // Trigger CPU overuse, reduce framerate by 2/3 again.
mflodmancc3d4422017-08-03 08:27:51 -07004858 video_stream_encoder_->TriggerCpuOveruse();
sprangc5d62e22017-04-02 23:53:04 -07004859 num_frames_dropped = 0;
Åsa Persson8c1bf952018-09-13 10:42:19 +02004860 for (int i = 0; i <= max_framerate_; ++i) {
sprangc5d62e22017-04-02 23:53:04 -07004861 timestamp_ms += kFrameIntervalMs;
sprangc5d62e22017-04-02 23:53:04 -07004862 video_source_.IncomingCapturedFrame(
4863 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 07:06:52 -07004864 if (!WaitForFrame(kFrameTimeoutMs)) {
sprangc5d62e22017-04-02 23:53:04 -07004865 ++num_frames_dropped;
4866 } else {
Åsa Perssonc74d8da2017-12-04 14:13:56 +01004867 sink_.CheckLastFrameSizeMatches(kFrameWidth, kFrameHeight);
sprangc5d62e22017-04-02 23:53:04 -07004868 }
4869 }
sprang4847ae62017-06-27 07:06:52 -07004870 EXPECT_NEAR(num_frames_dropped, max_framerate_ - (max_framerate_ * 4 / 9),
sprangc5d62e22017-04-02 23:53:04 -07004871 kErrorMargin);
4872
4873 // Go back up one step.
Henrik Boström91aa7322020-04-28 12:24:33 +02004874 video_stream_encoder_->TriggerCpuUnderuse();
sprangc5d62e22017-04-02 23:53:04 -07004875 num_frames_dropped = 0;
sprang4847ae62017-06-27 07:06:52 -07004876 for (int i = 0; i < max_framerate_; ++i) {
sprangc5d62e22017-04-02 23:53:04 -07004877 timestamp_ms += kFrameIntervalMs;
sprangc5d62e22017-04-02 23:53:04 -07004878 video_source_.IncomingCapturedFrame(
4879 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 07:06:52 -07004880 if (!WaitForFrame(kFrameTimeoutMs)) {
sprangc5d62e22017-04-02 23:53:04 -07004881 ++num_frames_dropped;
4882 } else {
Åsa Perssonc74d8da2017-12-04 14:13:56 +01004883 sink_.CheckLastFrameSizeMatches(kFrameWidth, kFrameHeight);
sprangc5d62e22017-04-02 23:53:04 -07004884 }
4885 }
sprang4847ae62017-06-27 07:06:52 -07004886 EXPECT_NEAR(num_frames_dropped, max_framerate_ - (max_framerate_ * 2 / 3),
sprangc5d62e22017-04-02 23:53:04 -07004887 kErrorMargin);
4888
4889 // Go back up to original mode.
Henrik Boström91aa7322020-04-28 12:24:33 +02004890 video_stream_encoder_->TriggerCpuUnderuse();
sprangc5d62e22017-04-02 23:53:04 -07004891 num_frames_dropped = 0;
sprang4847ae62017-06-27 07:06:52 -07004892 for (int i = 0; i < max_framerate_; ++i) {
sprangc5d62e22017-04-02 23:53:04 -07004893 timestamp_ms += kFrameIntervalMs;
sprangc5d62e22017-04-02 23:53:04 -07004894 video_source_.IncomingCapturedFrame(
4895 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 07:06:52 -07004896 if (!WaitForFrame(kFrameTimeoutMs)) {
sprangc5d62e22017-04-02 23:53:04 -07004897 ++num_frames_dropped;
4898 } else {
Åsa Perssonc74d8da2017-12-04 14:13:56 +01004899 sink_.CheckLastFrameSizeMatches(kFrameWidth, kFrameHeight);
sprangc5d62e22017-04-02 23:53:04 -07004900 }
4901 }
4902 EXPECT_NEAR(num_frames_dropped, 0, kErrorMargin);
4903
mflodmancc3d4422017-08-03 08:27:51 -07004904 video_stream_encoder_->Stop();
sprangc5d62e22017-04-02 23:53:04 -07004905}
4906
mflodmancc3d4422017-08-03 08:27:51 -07004907TEST_F(VideoStreamEncoderTest, DoesntAdaptDownPastMinFramerate) {
sprangc5d62e22017-04-02 23:53:04 -07004908 const int kFramerateFps = 5;
4909 const int kFrameIntervalMs = rtc::kNumMillisecsPerSec / kFramerateFps;
sprangc5d62e22017-04-02 23:53:04 -07004910 const int kFrameWidth = 1280;
4911 const int kFrameHeight = 720;
4912
sprang4847ae62017-06-27 07:06:52 -07004913 // Reconfigure encoder with two temporal layers and screensharing, which will
4914 // disable frame dropping and make testing easier.
Niels Möllerf1338562018-04-26 09:51:47 +02004915 ResetEncoder("VP8", 1, 2, 1, true);
sprang4847ae62017-06-27 07:06:52 -07004916
Henrik Boström381d1092020-05-12 18:49:07 +02004917 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01004918 DataRate::BitsPerSec(kTargetBitrateBps),
4919 DataRate::BitsPerSec(kTargetBitrateBps),
4920 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
mflodmancc3d4422017-08-03 08:27:51 -07004921 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07004922 &video_source_, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
sprangc5d62e22017-04-02 23:53:04 -07004923 video_source_.set_adaptation_enabled(true);
4924
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02004925 int64_t timestamp_ms = CurrentTimeMs();
sprangc5d62e22017-04-02 23:53:04 -07004926
4927 // Trigger overuse as much as we can.
Jonathan Yubc771b72017-12-08 17:04:29 -08004928 rtc::VideoSinkWants last_wants;
4929 do {
4930 last_wants = video_source_.sink_wants();
4931
sprangc5d62e22017-04-02 23:53:04 -07004932 // Insert frames to get a new fps estimate...
4933 for (int j = 0; j < kFramerateFps; ++j) {
4934 video_source_.IncomingCapturedFrame(
4935 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
Jonathan Yubc771b72017-12-08 17:04:29 -08004936 if (video_source_.last_sent_width()) {
4937 sink_.WaitForEncodedFrame(timestamp_ms);
4938 }
sprangc5d62e22017-04-02 23:53:04 -07004939 timestamp_ms += kFrameIntervalMs;
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02004940 AdvanceTime(TimeDelta::Millis(kFrameIntervalMs));
sprangc5d62e22017-04-02 23:53:04 -07004941 }
4942 // ...and then try to adapt again.
mflodmancc3d4422017-08-03 08:27:51 -07004943 video_stream_encoder_->TriggerCpuOveruse();
Jonathan Yubc771b72017-12-08 17:04:29 -08004944 } while (video_source_.sink_wants().max_framerate_fps <
4945 last_wants.max_framerate_fps);
sprangc5d62e22017-04-02 23:53:04 -07004946
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02004947 EXPECT_THAT(video_source_.sink_wants(),
4948 FpsMatchesResolutionMax(Eq(kMinFramerateFps)));
asaperssonf7e294d2017-06-13 23:25:22 -07004949
mflodmancc3d4422017-08-03 08:27:51 -07004950 video_stream_encoder_->Stop();
sprangc5d62e22017-04-02 23:53:04 -07004951}
asaperssonf7e294d2017-06-13 23:25:22 -07004952
mflodmancc3d4422017-08-03 08:27:51 -07004953TEST_F(VideoStreamEncoderTest,
4954 AdaptsResolutionAndFramerateForLowQuality_BalancedMode) {
asaperssonf7e294d2017-06-13 23:25:22 -07004955 const int kWidth = 1280;
4956 const int kHeight = 720;
4957 const int64_t kFrameIntervalMs = 150;
4958 int64_t timestamp_ms = kFrameIntervalMs;
Henrik Boström381d1092020-05-12 18:49:07 +02004959 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01004960 DataRate::BitsPerSec(kTargetBitrateBps),
4961 DataRate::BitsPerSec(kTargetBitrateBps),
4962 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asaperssonf7e294d2017-06-13 23:25:22 -07004963
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07004964 // Enable BALANCED preference, no initial limitation.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02004965 AdaptingFrameForwarder source(&time_controller_);
asaperssonf7e294d2017-06-13 23:25:22 -07004966 source.set_adaptation_enabled(true);
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07004967 video_stream_encoder_->SetSource(&source,
4968 webrtc::DegradationPreference::BALANCED);
asaperssonf7e294d2017-06-13 23:25:22 -07004969 timestamp_ms += kFrameIntervalMs;
4970 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07004971 WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02004972 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-13 23:25:22 -07004973 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
4974 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
4975 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
4976
4977 // Trigger adapt down, expect scaled down resolution (960x540@30fps).
mflodmancc3d4422017-08-03 08:27:51 -07004978 video_stream_encoder_->TriggerQualityLow();
asaperssonf7e294d2017-06-13 23:25:22 -07004979 timestamp_ms += kFrameIntervalMs;
4980 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07004981 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02004982 EXPECT_THAT(source.sink_wants(),
4983 FpsMaxResolutionMatches(Lt(kWidth * kHeight)));
asaperssonf7e294d2017-06-13 23:25:22 -07004984 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
4985 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
4986 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
4987
4988 // Trigger adapt down, expect scaled down resolution (640x360@30fps).
mflodmancc3d4422017-08-03 08:27:51 -07004989 video_stream_encoder_->TriggerQualityLow();
asaperssonf7e294d2017-06-13 23:25:22 -07004990 timestamp_ms += kFrameIntervalMs;
4991 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07004992 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02004993 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionLt(source.last_wants()));
asaperssonf7e294d2017-06-13 23:25:22 -07004994 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
4995 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
4996 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_quality_adapt_changes);
4997
4998 // Trigger adapt down, expect reduced fps (640x360@15fps).
mflodmancc3d4422017-08-03 08:27:51 -07004999 video_stream_encoder_->TriggerQualityLow();
asaperssonf7e294d2017-06-13 23:25:22 -07005000 timestamp_ms += kFrameIntervalMs;
5001 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005002 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02005003 EXPECT_THAT(source.sink_wants(), FpsLtResolutionEq(source.last_wants()));
asaperssonf7e294d2017-06-13 23:25:22 -07005004 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5005 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
5006 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5007
5008 // Trigger adapt down, expect scaled down resolution (480x270@15fps).
mflodmancc3d4422017-08-03 08:27:51 -07005009 video_stream_encoder_->TriggerQualityLow();
asaperssonf7e294d2017-06-13 23:25:22 -07005010 timestamp_ms += kFrameIntervalMs;
5011 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005012 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02005013 EXPECT_THAT(source.sink_wants(), FpsEqResolutionLt(source.last_wants()));
asaperssonf7e294d2017-06-13 23:25:22 -07005014 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5015 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
5016 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5017
5018 // Restrict bitrate, trigger adapt down, expect reduced fps (480x270@10fps).
mflodmancc3d4422017-08-03 08:27:51 -07005019 video_stream_encoder_->TriggerQualityLow();
asaperssonf7e294d2017-06-13 23:25:22 -07005020 timestamp_ms += kFrameIntervalMs;
5021 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005022 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02005023 EXPECT_THAT(source.sink_wants(), FpsLtResolutionEq(source.last_wants()));
asaperssonf7e294d2017-06-13 23:25:22 -07005024 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5025 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
5026 EXPECT_EQ(5, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5027
5028 // Trigger adapt down, expect scaled down resolution (320x180@10fps).
mflodmancc3d4422017-08-03 08:27:51 -07005029 video_stream_encoder_->TriggerQualityLow();
asaperssonf7e294d2017-06-13 23:25:22 -07005030 timestamp_ms += kFrameIntervalMs;
5031 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005032 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02005033 EXPECT_THAT(source.sink_wants(), FpsEqResolutionLt(source.last_wants()));
asaperssonf7e294d2017-06-13 23:25:22 -07005034 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5035 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
5036 EXPECT_EQ(6, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5037
5038 // Trigger adapt down, expect reduced fps (320x180@7fps).
mflodmancc3d4422017-08-03 08:27:51 -07005039 video_stream_encoder_->TriggerQualityLow();
asaperssonf7e294d2017-06-13 23:25:22 -07005040 timestamp_ms += kFrameIntervalMs;
5041 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005042 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02005043 EXPECT_THAT(source.sink_wants(), FpsLtResolutionEq(source.last_wants()));
asaperssonf7e294d2017-06-13 23:25:22 -07005044 rtc::VideoSinkWants last_wants = source.sink_wants();
5045 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5046 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
5047 EXPECT_EQ(7, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5048
5049 // Trigger adapt down, min resolution reached, expect no change.
mflodmancc3d4422017-08-03 08:27:51 -07005050 video_stream_encoder_->TriggerQualityLow();
asaperssonf7e294d2017-06-13 23:25:22 -07005051 timestamp_ms += kFrameIntervalMs;
5052 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005053 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02005054 EXPECT_THAT(source.sink_wants(), FpsEqResolutionEqTo(last_wants));
asaperssonf7e294d2017-06-13 23:25:22 -07005055 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5056 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
5057 EXPECT_EQ(7, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5058
Evan Shrubsole64469032020-06-11 10:45:29 +02005059 // Trigger adapt up, expect expect increased fps (320x180@10fps).
mflodmancc3d4422017-08-03 08:27:51 -07005060 video_stream_encoder_->TriggerQualityHigh();
asaperssonf7e294d2017-06-13 23:25:22 -07005061 timestamp_ms += kFrameIntervalMs;
5062 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005063 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02005064 EXPECT_THAT(source.sink_wants(), FpsGtResolutionEq(source.last_wants()));
asaperssonf7e294d2017-06-13 23:25:22 -07005065 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5066 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
5067 EXPECT_EQ(8, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5068
5069 // Trigger adapt up, expect upscaled resolution (480x270@10fps).
mflodmancc3d4422017-08-03 08:27:51 -07005070 video_stream_encoder_->TriggerQualityHigh();
asaperssonf7e294d2017-06-13 23:25:22 -07005071 timestamp_ms += kFrameIntervalMs;
5072 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005073 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02005074 EXPECT_THAT(source.sink_wants(), FpsEqResolutionGt(source.last_wants()));
asaperssonf7e294d2017-06-13 23:25:22 -07005075 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5076 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
5077 EXPECT_EQ(9, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5078
5079 // Increase bitrate, trigger adapt up, expect increased fps (480x270@15fps).
mflodmancc3d4422017-08-03 08:27:51 -07005080 video_stream_encoder_->TriggerQualityHigh();
asaperssonf7e294d2017-06-13 23:25:22 -07005081 timestamp_ms += kFrameIntervalMs;
5082 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005083 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02005084 EXPECT_THAT(source.sink_wants(), FpsGtResolutionEq(source.last_wants()));
asaperssonf7e294d2017-06-13 23:25:22 -07005085 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5086 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
5087 EXPECT_EQ(10, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5088
5089 // Trigger adapt up, expect upscaled resolution (640x360@15fps).
mflodmancc3d4422017-08-03 08:27:51 -07005090 video_stream_encoder_->TriggerQualityHigh();
asaperssonf7e294d2017-06-13 23:25:22 -07005091 timestamp_ms += kFrameIntervalMs;
5092 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005093 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02005094 EXPECT_THAT(source.sink_wants(), FpsEqResolutionGt(source.last_wants()));
asaperssonf7e294d2017-06-13 23:25:22 -07005095 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5096 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
5097 EXPECT_EQ(11, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5098
5099 // Trigger adapt up, expect increased fps (640x360@30fps).
mflodmancc3d4422017-08-03 08:27:51 -07005100 video_stream_encoder_->TriggerQualityHigh();
asaperssonf7e294d2017-06-13 23:25:22 -07005101 timestamp_ms += kFrameIntervalMs;
5102 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005103 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02005104 EXPECT_THAT(source.sink_wants(), FpsMax());
5105 EXPECT_EQ(source.sink_wants().max_pixel_count,
5106 source.last_wants().max_pixel_count);
asaperssonf7e294d2017-06-13 23:25:22 -07005107 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5108 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
5109 EXPECT_EQ(12, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5110
5111 // Trigger adapt up, expect upscaled resolution (960x540@30fps).
mflodmancc3d4422017-08-03 08:27:51 -07005112 video_stream_encoder_->TriggerQualityHigh();
asaperssonf7e294d2017-06-13 23:25:22 -07005113 timestamp_ms += kFrameIntervalMs;
5114 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005115 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02005116 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionGt(source.last_wants()));
asaperssonf7e294d2017-06-13 23:25:22 -07005117 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5118 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
5119 EXPECT_EQ(13, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5120
Åsa Persson30ab0152019-08-27 12:22:33 +02005121 // Trigger adapt up, expect no restriction (1280x720fps@30fps).
mflodmancc3d4422017-08-03 08:27:51 -07005122 video_stream_encoder_->TriggerQualityHigh();
asaperssonf7e294d2017-06-13 23:25:22 -07005123 timestamp_ms += kFrameIntervalMs;
5124 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005125 WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02005126 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionGt(source.last_wants()));
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02005127 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-13 23:25:22 -07005128 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
5129 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
5130 EXPECT_EQ(14, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5131
5132 // Trigger adapt up, expect no change.
mflodmancc3d4422017-08-03 08:27:51 -07005133 video_stream_encoder_->TriggerQualityHigh();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02005134 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-13 23:25:22 -07005135 EXPECT_EQ(14, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5136
mflodmancc3d4422017-08-03 08:27:51 -07005137 video_stream_encoder_->Stop();
asaperssonf7e294d2017-06-13 23:25:22 -07005138}
5139
mflodmancc3d4422017-08-03 08:27:51 -07005140TEST_F(VideoStreamEncoderTest, AdaptWithTwoReasonsAndDifferentOrder_Framerate) {
asaperssonf7e294d2017-06-13 23:25:22 -07005141 const int kWidth = 1280;
5142 const int kHeight = 720;
5143 const int64_t kFrameIntervalMs = 150;
5144 int64_t timestamp_ms = kFrameIntervalMs;
Henrik Boström381d1092020-05-12 18:49:07 +02005145 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005146 DataRate::BitsPerSec(kTargetBitrateBps),
5147 DataRate::BitsPerSec(kTargetBitrateBps),
5148 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asaperssonf7e294d2017-06-13 23:25:22 -07005149
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07005150 // Enable BALANCED preference, no initial limitation.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02005151 AdaptingFrameForwarder source(&time_controller_);
asaperssonf7e294d2017-06-13 23:25:22 -07005152 source.set_adaptation_enabled(true);
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07005153 video_stream_encoder_->SetSource(&source,
5154 webrtc::DegradationPreference::BALANCED);
asaperssonf7e294d2017-06-13 23:25:22 -07005155 timestamp_ms += kFrameIntervalMs;
5156 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005157 WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02005158 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-13 23:25:22 -07005159 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
5160 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
5161 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
5162 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
5163 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
5164 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5165
5166 // Trigger cpu adapt down, expect scaled down resolution (960x540@30fps).
mflodmancc3d4422017-08-03 08:27:51 -07005167 video_stream_encoder_->TriggerCpuOveruse();
asaperssonf7e294d2017-06-13 23:25:22 -07005168 timestamp_ms += kFrameIntervalMs;
5169 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005170 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02005171 EXPECT_THAT(source.sink_wants(),
5172 FpsMaxResolutionMatches(Lt(kWidth * kHeight)));
asaperssonf7e294d2017-06-13 23:25:22 -07005173 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
5174 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
5175 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
5176 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
5177 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
5178 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5179
5180 // Trigger cpu adapt down, expect scaled down resolution (640x360@30fps).
mflodmancc3d4422017-08-03 08:27:51 -07005181 video_stream_encoder_->TriggerCpuOveruse();
asaperssonf7e294d2017-06-13 23:25:22 -07005182 timestamp_ms += kFrameIntervalMs;
5183 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005184 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02005185 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionLt(source.last_wants()));
asaperssonf7e294d2017-06-13 23:25:22 -07005186 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
5187 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
5188 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
5189 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
5190 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
5191 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5192
5193 // Trigger quality adapt down, expect reduced fps (640x360@15fps).
mflodmancc3d4422017-08-03 08:27:51 -07005194 video_stream_encoder_->TriggerQualityLow();
asaperssonf7e294d2017-06-13 23:25:22 -07005195 timestamp_ms += kFrameIntervalMs;
5196 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005197 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02005198 EXPECT_THAT(source.sink_wants(), FpsLtResolutionEq(source.last_wants()));
Evan Shrubsole64469032020-06-11 10:45:29 +02005199 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
asaperssonf7e294d2017-06-13 23:25:22 -07005200 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
5201 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
5202 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
5203 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
5204 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5205
Evan Shrubsole64469032020-06-11 10:45:29 +02005206 // Trigger cpu adapt up, expect no change since QP is most limited.
5207 {
5208 // Store current sink wants since we expect no change and if there is no
5209 // change then last_wants() is not updated.
5210 auto previous_sink_wants = source.sink_wants();
5211 video_stream_encoder_->TriggerCpuUnderuse();
5212 timestamp_ms += kFrameIntervalMs;
5213 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
5214 WaitForEncodedFrame(timestamp_ms);
5215 EXPECT_THAT(source.sink_wants(), FpsEqResolutionEqTo(previous_sink_wants));
5216 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
5217 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5218 }
5219
5220 // Trigger quality adapt up, expect increased fps (640x360@30fps).
5221 video_stream_encoder_->TriggerQualityHigh();
5222 timestamp_ms += kFrameIntervalMs;
5223 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
5224 WaitForEncodedFrame(timestamp_ms);
5225 EXPECT_THAT(source.sink_wants(), FpsGtResolutionEq(source.last_wants()));
5226 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5227 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
5228 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
5229 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
5230 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
5231 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5232
5233 // Trigger quality adapt up and Cpu adapt up since both are most limited,
5234 // expect increased resolution (960x540@30fps).
5235 video_stream_encoder_->TriggerQualityHigh();
Henrik Boström91aa7322020-04-28 12:24:33 +02005236 video_stream_encoder_->TriggerCpuUnderuse();
asaperssonf7e294d2017-06-13 23:25:22 -07005237 timestamp_ms += kFrameIntervalMs;
5238 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005239 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole64469032020-06-11 10:45:29 +02005240 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionGt(source.last_wants()));
asaperssonf7e294d2017-06-13 23:25:22 -07005241 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5242 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
5243 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
5244 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
5245 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
Evan Shrubsole64469032020-06-11 10:45:29 +02005246 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_quality_adapt_changes);
asaperssonf7e294d2017-06-13 23:25:22 -07005247
Evan Shrubsole64469032020-06-11 10:45:29 +02005248 // Trigger quality adapt up and Cpu adapt up since both are most limited,
5249 // expect no restriction (1280x720fps@30fps).
mflodmancc3d4422017-08-03 08:27:51 -07005250 video_stream_encoder_->TriggerQualityHigh();
Henrik Boström91aa7322020-04-28 12:24:33 +02005251 video_stream_encoder_->TriggerCpuUnderuse();
asaperssonf7e294d2017-06-13 23:25:22 -07005252 timestamp_ms += kFrameIntervalMs;
5253 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005254 WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02005255 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionGt(source.last_wants()));
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02005256 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-13 23:25:22 -07005257 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
5258 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
5259 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
5260 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
5261 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
Evan Shrubsole64469032020-06-11 10:45:29 +02005262 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_quality_adapt_changes);
asaperssonf7e294d2017-06-13 23:25:22 -07005263
5264 // Trigger adapt up, expect no change.
mflodmancc3d4422017-08-03 08:27:51 -07005265 video_stream_encoder_->TriggerQualityHigh();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02005266 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-13 23:25:22 -07005267 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
Evan Shrubsole64469032020-06-11 10:45:29 +02005268 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_quality_adapt_changes);
asaperssonf7e294d2017-06-13 23:25:22 -07005269
mflodmancc3d4422017-08-03 08:27:51 -07005270 video_stream_encoder_->Stop();
asaperssonf7e294d2017-06-13 23:25:22 -07005271}
5272
mflodmancc3d4422017-08-03 08:27:51 -07005273TEST_F(VideoStreamEncoderTest,
5274 AdaptWithTwoReasonsAndDifferentOrder_Resolution) {
asaperssonf7e294d2017-06-13 23:25:22 -07005275 const int kWidth = 640;
5276 const int kHeight = 360;
5277 const int kFpsLimit = 15;
5278 const int64_t kFrameIntervalMs = 150;
5279 int64_t timestamp_ms = kFrameIntervalMs;
Henrik Boström381d1092020-05-12 18:49:07 +02005280 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005281 DataRate::BitsPerSec(kTargetBitrateBps),
5282 DataRate::BitsPerSec(kTargetBitrateBps),
5283 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asaperssonf7e294d2017-06-13 23:25:22 -07005284
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07005285 // Enable BALANCED preference, no initial limitation.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02005286 AdaptingFrameForwarder source(&time_controller_);
asaperssonf7e294d2017-06-13 23:25:22 -07005287 source.set_adaptation_enabled(true);
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07005288 video_stream_encoder_->SetSource(&source,
5289 webrtc::DegradationPreference::BALANCED);
asaperssonf7e294d2017-06-13 23:25:22 -07005290 timestamp_ms += kFrameIntervalMs;
5291 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005292 WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02005293 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-13 23:25:22 -07005294 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
5295 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
5296 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
5297 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
5298 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
5299 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5300
5301 // Trigger cpu adapt down, expect scaled down framerate (640x360@15fps).
mflodmancc3d4422017-08-03 08:27:51 -07005302 video_stream_encoder_->TriggerCpuOveruse();
asaperssonf7e294d2017-06-13 23:25:22 -07005303 timestamp_ms += kFrameIntervalMs;
5304 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005305 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02005306 EXPECT_THAT(source.sink_wants(), FpsMatchesResolutionMax(Eq(kFpsLimit)));
asaperssonf7e294d2017-06-13 23:25:22 -07005307 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
5308 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
5309 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
5310 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_framerate);
5311 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
5312 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5313
5314 // Trigger quality adapt down, expect scaled down resolution (480x270@15fps).
mflodmancc3d4422017-08-03 08:27:51 -07005315 video_stream_encoder_->TriggerQualityLow();
asaperssonf7e294d2017-06-13 23:25:22 -07005316 timestamp_ms += kFrameIntervalMs;
5317 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005318 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02005319 EXPECT_THAT(source.sink_wants(), FpsEqResolutionLt(source.last_wants()));
asaperssonf7e294d2017-06-13 23:25:22 -07005320 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
Evan Shrubsole64469032020-06-11 10:45:29 +02005321 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
asaperssonf7e294d2017-06-13 23:25:22 -07005322 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
5323 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_framerate);
5324 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
5325 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5326
Evan Shrubsole64469032020-06-11 10:45:29 +02005327 // Trigger cpu adapt up, expect no change because quality is most limited.
5328 {
5329 auto previous_sink_wants = source.sink_wants();
5330 // Store current sink wants since we expect no change ind if there is no
5331 // change then last__wants() is not updated.
5332 video_stream_encoder_->TriggerCpuUnderuse();
5333 timestamp_ms += kFrameIntervalMs;
5334 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
5335 WaitForEncodedFrame(timestamp_ms);
5336 EXPECT_THAT(source.sink_wants(), FpsEqResolutionEqTo(previous_sink_wants));
5337 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
5338 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5339 }
5340
5341 // Trigger quality adapt up, expect upscaled resolution (640x360@15fps).
5342 video_stream_encoder_->TriggerQualityHigh();
asaperssonf7e294d2017-06-13 23:25:22 -07005343 timestamp_ms += kFrameIntervalMs;
5344 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005345 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02005346 EXPECT_THAT(source.sink_wants(), FpsEqResolutionGt(source.last_wants()));
asaperssonf7e294d2017-06-13 23:25:22 -07005347 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
5348 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
5349 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
Evan Shrubsole64469032020-06-11 10:45:29 +02005350 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_framerate);
5351 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
5352 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_quality_adapt_changes);
asaperssonf7e294d2017-06-13 23:25:22 -07005353
Evan Shrubsole64469032020-06-11 10:45:29 +02005354 // Trigger quality and cpu adapt up, expect increased fps (640x360@30fps).
mflodmancc3d4422017-08-03 08:27:51 -07005355 video_stream_encoder_->TriggerQualityHigh();
Evan Shrubsole64469032020-06-11 10:45:29 +02005356 video_stream_encoder_->TriggerCpuUnderuse();
asaperssonf7e294d2017-06-13 23:25:22 -07005357 timestamp_ms += kFrameIntervalMs;
5358 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005359 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02005360 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-13 23:25:22 -07005361 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
5362 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
5363 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
5364 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
5365 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
Evan Shrubsole64469032020-06-11 10:45:29 +02005366 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_quality_adapt_changes);
asaperssonf7e294d2017-06-13 23:25:22 -07005367
5368 // Trigger adapt up, expect no change.
mflodmancc3d4422017-08-03 08:27:51 -07005369 video_stream_encoder_->TriggerQualityHigh();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02005370 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-13 23:25:22 -07005371 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
Evan Shrubsole64469032020-06-11 10:45:29 +02005372 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_quality_adapt_changes);
asaperssonf7e294d2017-06-13 23:25:22 -07005373
mflodmancc3d4422017-08-03 08:27:51 -07005374 video_stream_encoder_->Stop();
asaperssonf7e294d2017-06-13 23:25:22 -07005375}
5376
mflodmancc3d4422017-08-03 08:27:51 -07005377TEST_F(VideoStreamEncoderTest, AcceptsFullHdAdaptedDownSimulcastFrames) {
ilnik6b826ef2017-06-16 06:53:48 -07005378 const int kFrameWidth = 1920;
5379 const int kFrameHeight = 1080;
5380 // 3/4 of 1920.
5381 const int kAdaptedFrameWidth = 1440;
5382 // 3/4 of 1080 rounded down to multiple of 4.
5383 const int kAdaptedFrameHeight = 808;
5384 const int kFramerate = 24;
5385
Henrik Boström381d1092020-05-12 18:49:07 +02005386 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005387 DataRate::BitsPerSec(kTargetBitrateBps),
5388 DataRate::BitsPerSec(kTargetBitrateBps),
5389 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
ilnik6b826ef2017-06-16 06:53:48 -07005390 // Trigger reconfigure encoder (without resetting the entire instance).
5391 VideoEncoderConfig video_encoder_config;
Niels Möller259a4972018-04-05 15:36:51 +02005392 video_encoder_config.codec_type = kVideoCodecVP8;
ilnik6b826ef2017-06-16 06:53:48 -07005393 video_encoder_config.max_bitrate_bps = kTargetBitrateBps;
5394 video_encoder_config.number_of_streams = 1;
5395 video_encoder_config.video_stream_factory =
5396 new rtc::RefCountedObject<CroppingVideoStreamFactory>(1, kFramerate);
mflodmancc3d4422017-08-03 08:27:51 -07005397 video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config),
Niels Möllerf1338562018-04-26 09:51:47 +02005398 kMaxPayloadLength);
mflodmancc3d4422017-08-03 08:27:51 -07005399 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
ilnik6b826ef2017-06-16 06:53:48 -07005400
5401 video_source_.set_adaptation_enabled(true);
5402
5403 video_source_.IncomingCapturedFrame(
5404 CreateFrame(1, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 07:06:52 -07005405 WaitForEncodedFrame(kFrameWidth, kFrameHeight);
ilnik6b826ef2017-06-16 06:53:48 -07005406
5407 // Trigger CPU overuse, downscale by 3/4.
mflodmancc3d4422017-08-03 08:27:51 -07005408 video_stream_encoder_->TriggerCpuOveruse();
ilnik6b826ef2017-06-16 06:53:48 -07005409 video_source_.IncomingCapturedFrame(
5410 CreateFrame(2, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 07:06:52 -07005411 WaitForEncodedFrame(kAdaptedFrameWidth, kAdaptedFrameHeight);
ilnik6b826ef2017-06-16 06:53:48 -07005412
mflodmancc3d4422017-08-03 08:27:51 -07005413 video_stream_encoder_->Stop();
ilnik6b826ef2017-06-16 06:53:48 -07005414}
5415
mflodmancc3d4422017-08-03 08:27:51 -07005416TEST_F(VideoStreamEncoderTest, PeriodicallyUpdatesChannelParameters) {
sprang4847ae62017-06-27 07:06:52 -07005417 const int kFrameWidth = 1280;
5418 const int kFrameHeight = 720;
5419 const int kLowFps = 2;
5420 const int kHighFps = 30;
5421
Henrik Boström381d1092020-05-12 18:49:07 +02005422 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005423 DataRate::BitsPerSec(kTargetBitrateBps),
5424 DataRate::BitsPerSec(kTargetBitrateBps),
5425 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
sprang4847ae62017-06-27 07:06:52 -07005426
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02005427 int64_t timestamp_ms = CurrentTimeMs();
sprang4847ae62017-06-27 07:06:52 -07005428 max_framerate_ = kLowFps;
5429
5430 // Insert 2 seconds of 2fps video.
5431 for (int i = 0; i < kLowFps * 2; ++i) {
5432 video_source_.IncomingCapturedFrame(
5433 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
5434 WaitForEncodedFrame(timestamp_ms);
5435 timestamp_ms += 1000 / kLowFps;
5436 }
5437
5438 // Make sure encoder is updated with new target.
Henrik Boström381d1092020-05-12 18:49:07 +02005439 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005440 DataRate::BitsPerSec(kTargetBitrateBps),
5441 DataRate::BitsPerSec(kTargetBitrateBps),
5442 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
sprang4847ae62017-06-27 07:06:52 -07005443 video_source_.IncomingCapturedFrame(
5444 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
5445 WaitForEncodedFrame(timestamp_ms);
5446 timestamp_ms += 1000 / kLowFps;
5447
5448 EXPECT_EQ(kLowFps, fake_encoder_.GetConfiguredInputFramerate());
5449
5450 // Insert 30fps frames for just a little more than the forced update period.
Niels Möllerfe407b72019-09-10 10:48:48 +02005451 const int kVcmTimerIntervalFrames = (kProcessIntervalMs * kHighFps) / 1000;
sprang4847ae62017-06-27 07:06:52 -07005452 const int kFrameIntervalMs = 1000 / kHighFps;
5453 max_framerate_ = kHighFps;
5454 for (int i = 0; i < kVcmTimerIntervalFrames + 2; ++i) {
5455 video_source_.IncomingCapturedFrame(
5456 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
5457 // Wait for encoded frame, but skip ahead if it doesn't arrive as it might
5458 // be dropped if the encoder hans't been updated with the new higher target
5459 // framerate yet, causing it to overshoot the target bitrate and then
5460 // suffering the wrath of the media optimizer.
5461 TimedWaitForEncodedFrame(timestamp_ms, 2 * kFrameIntervalMs);
5462 timestamp_ms += kFrameIntervalMs;
5463 }
5464
5465 // Don expect correct measurement just yet, but it should be higher than
5466 // before.
5467 EXPECT_GT(fake_encoder_.GetConfiguredInputFramerate(), kLowFps);
5468
mflodmancc3d4422017-08-03 08:27:51 -07005469 video_stream_encoder_->Stop();
sprang4847ae62017-06-27 07:06:52 -07005470}
5471
mflodmancc3d4422017-08-03 08:27:51 -07005472TEST_F(VideoStreamEncoderTest, DoesNotUpdateBitrateAllocationWhenSuspended) {
sprang4847ae62017-06-27 07:06:52 -07005473 const int kFrameWidth = 1280;
5474 const int kFrameHeight = 720;
5475 const int kTargetBitrateBps = 1000000;
Per Kjellanderdcef6412020-10-07 15:09:05 +02005476 ResetEncoder("FAKE", 1, 1, 1, false,
5477 VideoStreamEncoderSettings::BitrateAllocationCallbackType::
5478 kVideoBitrateAllocation);
sprang4847ae62017-06-27 07:06:52 -07005479
Henrik Boström381d1092020-05-12 18:49:07 +02005480 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005481 DataRate::BitsPerSec(kTargetBitrateBps),
5482 DataRate::BitsPerSec(kTargetBitrateBps),
5483 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
mflodmancc3d4422017-08-03 08:27:51 -07005484 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
sprang4847ae62017-06-27 07:06:52 -07005485
5486 // Insert a first video frame, causes another bitrate update.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02005487 int64_t timestamp_ms = CurrentTimeMs();
sprang4847ae62017-06-27 07:06:52 -07005488 video_source_.IncomingCapturedFrame(
5489 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
5490 WaitForEncodedFrame(timestamp_ms);
Per Kjellanderdcef6412020-10-07 15:09:05 +02005491 EXPECT_EQ(sink_.number_of_bitrate_allocations(), 1);
sprang4847ae62017-06-27 07:06:52 -07005492
5493 // Next, simulate video suspension due to pacer queue overrun.
Henrik Boström381d1092020-05-12 18:49:07 +02005494 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
5495 DataRate::BitsPerSec(0), DataRate::BitsPerSec(0), DataRate::BitsPerSec(0),
5496 0, 1, 0);
sprang4847ae62017-06-27 07:06:52 -07005497
5498 // Skip ahead until a new periodic parameter update should have occured.
Niels Möllerfe407b72019-09-10 10:48:48 +02005499 timestamp_ms += kProcessIntervalMs;
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02005500 AdvanceTime(TimeDelta::Millis(kProcessIntervalMs));
sprang4847ae62017-06-27 07:06:52 -07005501
Per Kjellanderdcef6412020-10-07 15:09:05 +02005502 // No more allocations has been made.
sprang4847ae62017-06-27 07:06:52 -07005503 video_source_.IncomingCapturedFrame(
5504 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
5505 ExpectDroppedFrame();
Per Kjellanderdcef6412020-10-07 15:09:05 +02005506 EXPECT_EQ(sink_.number_of_bitrate_allocations(), 1);
sprang4847ae62017-06-27 07:06:52 -07005507
mflodmancc3d4422017-08-03 08:27:51 -07005508 video_stream_encoder_->Stop();
sprang4847ae62017-06-27 07:06:52 -07005509}
ilnik6b826ef2017-06-16 06:53:48 -07005510
Niels Möller4db138e2018-04-19 09:04:13 +02005511TEST_F(VideoStreamEncoderTest,
5512 DefaultCpuAdaptationThresholdsForSoftwareEncoder) {
5513 const int kFrameWidth = 1280;
5514 const int kFrameHeight = 720;
5515 const CpuOveruseOptions default_options;
Henrik Boström381d1092020-05-12 18:49:07 +02005516 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005517 DataRate::BitsPerSec(kTargetBitrateBps),
5518 DataRate::BitsPerSec(kTargetBitrateBps),
5519 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Niels Möller4db138e2018-04-19 09:04:13 +02005520 video_source_.IncomingCapturedFrame(
5521 CreateFrame(1, kFrameWidth, kFrameHeight));
5522 WaitForEncodedFrame(1);
5523 EXPECT_EQ(video_stream_encoder_->overuse_detector_proxy_->GetOptions()
5524 .low_encode_usage_threshold_percent,
5525 default_options.low_encode_usage_threshold_percent);
5526 EXPECT_EQ(video_stream_encoder_->overuse_detector_proxy_->GetOptions()
5527 .high_encode_usage_threshold_percent,
5528 default_options.high_encode_usage_threshold_percent);
5529 video_stream_encoder_->Stop();
5530}
5531
5532TEST_F(VideoStreamEncoderTest,
5533 HigherCpuAdaptationThresholdsForHardwareEncoder) {
5534 const int kFrameWidth = 1280;
5535 const int kFrameHeight = 720;
5536 CpuOveruseOptions hardware_options;
5537 hardware_options.low_encode_usage_threshold_percent = 150;
5538 hardware_options.high_encode_usage_threshold_percent = 200;
Mirta Dvornicicccc1b572019-01-15 12:42:18 +01005539 fake_encoder_.SetIsHardwareAccelerated(true);
Niels Möller4db138e2018-04-19 09:04:13 +02005540
Henrik Boström381d1092020-05-12 18:49:07 +02005541 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005542 DataRate::BitsPerSec(kTargetBitrateBps),
5543 DataRate::BitsPerSec(kTargetBitrateBps),
5544 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Niels Möller4db138e2018-04-19 09:04:13 +02005545 video_source_.IncomingCapturedFrame(
5546 CreateFrame(1, kFrameWidth, kFrameHeight));
5547 WaitForEncodedFrame(1);
5548 EXPECT_EQ(video_stream_encoder_->overuse_detector_proxy_->GetOptions()
5549 .low_encode_usage_threshold_percent,
5550 hardware_options.low_encode_usage_threshold_percent);
5551 EXPECT_EQ(video_stream_encoder_->overuse_detector_proxy_->GetOptions()
5552 .high_encode_usage_threshold_percent,
5553 hardware_options.high_encode_usage_threshold_percent);
5554 video_stream_encoder_->Stop();
5555}
5556
Niels Möller6bb5ab92019-01-11 11:11:10 +01005557TEST_F(VideoStreamEncoderTest, DropsFramesWhenEncoderOvershoots) {
5558 const int kFrameWidth = 320;
5559 const int kFrameHeight = 240;
5560 const int kFps = 30;
5561 const int kTargetBitrateBps = 120000;
5562 const int kNumFramesInRun = kFps * 5; // Runs of five seconds.
5563
Henrik Boström381d1092020-05-12 18:49:07 +02005564 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005565 DataRate::BitsPerSec(kTargetBitrateBps),
5566 DataRate::BitsPerSec(kTargetBitrateBps),
5567 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Niels Möller6bb5ab92019-01-11 11:11:10 +01005568
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02005569 int64_t timestamp_ms = CurrentTimeMs();
Niels Möller6bb5ab92019-01-11 11:11:10 +01005570 max_framerate_ = kFps;
5571
5572 // Insert 3 seconds of video, verify number of drops with normal bitrate.
5573 fake_encoder_.SimulateOvershoot(1.0);
5574 int num_dropped = 0;
5575 for (int i = 0; i < kNumFramesInRun; ++i) {
5576 video_source_.IncomingCapturedFrame(
5577 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
5578 // Wait up to two frame durations for a frame to arrive.
5579 if (!TimedWaitForEncodedFrame(timestamp_ms, 2 * 1000 / kFps)) {
5580 ++num_dropped;
5581 }
5582 timestamp_ms += 1000 / kFps;
5583 }
5584
Erik Språnga8d48ab2019-02-08 14:17:40 +01005585 // Framerate should be measured to be near the expected target rate.
5586 EXPECT_NEAR(fake_encoder_.GetLastFramerate(), kFps, 1);
5587
5588 // Frame drops should be within 5% of expected 0%.
5589 EXPECT_NEAR(num_dropped, 0, 5 * kNumFramesInRun / 100);
Niels Möller6bb5ab92019-01-11 11:11:10 +01005590
5591 // Make encoder produce frames at double the expected bitrate during 3 seconds
5592 // of video, verify number of drops. Rate needs to be slightly changed in
5593 // order to force the rate to be reconfigured.
Erik Språng7ca375c2019-02-06 16:20:17 +01005594 double overshoot_factor = 2.0;
5595 if (RateControlSettings::ParseFromFieldTrials().UseEncoderBitrateAdjuster()) {
5596 // With bitrate adjuster, when need to overshoot even more to trigger
5597 // frame dropping.
5598 overshoot_factor *= 2;
5599 }
5600 fake_encoder_.SimulateOvershoot(overshoot_factor);
Henrik Boström381d1092020-05-12 18:49:07 +02005601 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005602 DataRate::BitsPerSec(kTargetBitrateBps + 1000),
5603 DataRate::BitsPerSec(kTargetBitrateBps + 1000),
5604 DataRate::BitsPerSec(kTargetBitrateBps + 1000), 0, 0, 0);
Niels Möller6bb5ab92019-01-11 11:11:10 +01005605 num_dropped = 0;
5606 for (int i = 0; i < kNumFramesInRun; ++i) {
5607 video_source_.IncomingCapturedFrame(
5608 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
5609 // Wait up to two frame durations for a frame to arrive.
5610 if (!TimedWaitForEncodedFrame(timestamp_ms, 2 * 1000 / kFps)) {
5611 ++num_dropped;
5612 }
5613 timestamp_ms += 1000 / kFps;
5614 }
5615
Henrik Boström381d1092020-05-12 18:49:07 +02005616 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005617 DataRate::BitsPerSec(kTargetBitrateBps),
5618 DataRate::BitsPerSec(kTargetBitrateBps),
5619 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Erik Språnga8d48ab2019-02-08 14:17:40 +01005620
5621 // Target framerate should be still be near the expected target, despite
5622 // the frame drops.
5623 EXPECT_NEAR(fake_encoder_.GetLastFramerate(), kFps, 1);
5624
5625 // Frame drops should be within 5% of expected 50%.
5626 EXPECT_NEAR(num_dropped, kNumFramesInRun / 2, 5 * kNumFramesInRun / 100);
Niels Möller6bb5ab92019-01-11 11:11:10 +01005627
5628 video_stream_encoder_->Stop();
5629}
5630
5631TEST_F(VideoStreamEncoderTest, ConfiguresCorrectFrameRate) {
5632 const int kFrameWidth = 320;
5633 const int kFrameHeight = 240;
5634 const int kActualInputFps = 24;
5635 const int kTargetBitrateBps = 120000;
5636
5637 ASSERT_GT(max_framerate_, kActualInputFps);
5638
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02005639 int64_t timestamp_ms = CurrentTimeMs();
Niels Möller6bb5ab92019-01-11 11:11:10 +01005640 max_framerate_ = kActualInputFps;
Henrik Boström381d1092020-05-12 18:49:07 +02005641 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005642 DataRate::BitsPerSec(kTargetBitrateBps),
5643 DataRate::BitsPerSec(kTargetBitrateBps),
5644 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Niels Möller6bb5ab92019-01-11 11:11:10 +01005645
5646 // Insert 3 seconds of video, with an input fps lower than configured max.
5647 for (int i = 0; i < kActualInputFps * 3; ++i) {
5648 video_source_.IncomingCapturedFrame(
5649 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
5650 // Wait up to two frame durations for a frame to arrive.
5651 WaitForEncodedFrame(timestamp_ms);
5652 timestamp_ms += 1000 / kActualInputFps;
5653 }
5654
5655 EXPECT_NEAR(kActualInputFps, fake_encoder_.GetLastFramerate(), 1);
5656
5657 video_stream_encoder_->Stop();
5658}
5659
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02005660TEST_F(VideoStreamEncoderBlockedTest, AccumulatesUpdateRectOnDroppedFrames) {
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01005661 VideoFrame::UpdateRect rect;
Henrik Boström381d1092020-05-12 18:49:07 +02005662 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005663 DataRate::BitsPerSec(kTargetBitrateBps),
5664 DataRate::BitsPerSec(kTargetBitrateBps),
5665 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01005666
5667 fake_encoder_.BlockNextEncode();
5668 video_source_.IncomingCapturedFrame(
5669 CreateFrameWithUpdatedPixel(1, nullptr, 0));
5670 WaitForEncodedFrame(1);
5671 // On the very first frame full update should be forced.
5672 rect = fake_encoder_.GetLastUpdateRect();
5673 EXPECT_EQ(rect.offset_x, 0);
5674 EXPECT_EQ(rect.offset_y, 0);
5675 EXPECT_EQ(rect.height, codec_height_);
5676 EXPECT_EQ(rect.width, codec_width_);
5677 // Here, the encoder thread will be blocked in the TestEncoder waiting for a
5678 // call to ContinueEncode.
5679 video_source_.IncomingCapturedFrame(
5680 CreateFrameWithUpdatedPixel(2, nullptr, 1));
5681 ExpectDroppedFrame();
5682 video_source_.IncomingCapturedFrame(
5683 CreateFrameWithUpdatedPixel(3, nullptr, 10));
5684 ExpectDroppedFrame();
5685 fake_encoder_.ContinueEncode();
5686 WaitForEncodedFrame(3);
5687 // Updates to pixels 1 and 10 should be accumulated to one 10x1 rect.
5688 rect = fake_encoder_.GetLastUpdateRect();
5689 EXPECT_EQ(rect.offset_x, 1);
5690 EXPECT_EQ(rect.offset_y, 0);
5691 EXPECT_EQ(rect.width, 10);
5692 EXPECT_EQ(rect.height, 1);
5693
5694 video_source_.IncomingCapturedFrame(
5695 CreateFrameWithUpdatedPixel(4, nullptr, 0));
5696 WaitForEncodedFrame(4);
5697 // Previous frame was encoded, so no accumulation should happen.
5698 rect = fake_encoder_.GetLastUpdateRect();
5699 EXPECT_EQ(rect.offset_x, 0);
5700 EXPECT_EQ(rect.offset_y, 0);
5701 EXPECT_EQ(rect.width, 1);
5702 EXPECT_EQ(rect.height, 1);
5703
5704 video_stream_encoder_->Stop();
5705}
5706
Erik Språngd7329ca2019-02-21 21:19:53 +01005707TEST_F(VideoStreamEncoderTest, SetsFrameTypes) {
Henrik Boström381d1092020-05-12 18:49:07 +02005708 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005709 DataRate::BitsPerSec(kTargetBitrateBps),
5710 DataRate::BitsPerSec(kTargetBitrateBps),
5711 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Erik Språngd7329ca2019-02-21 21:19:53 +01005712
5713 // First frame is always keyframe.
5714 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
5715 WaitForEncodedFrame(1);
Niels Möller8f7ce222019-03-21 15:43:58 +01005716 EXPECT_THAT(
5717 fake_encoder_.LastFrameTypes(),
Mirko Bonadei6a489f22019-04-09 15:11:12 +02005718 ::testing::ElementsAre(VideoFrameType{VideoFrameType::kVideoFrameKey}));
Erik Språngd7329ca2019-02-21 21:19:53 +01005719
5720 // Insert delta frame.
5721 video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
5722 WaitForEncodedFrame(2);
Niels Möller8f7ce222019-03-21 15:43:58 +01005723 EXPECT_THAT(
5724 fake_encoder_.LastFrameTypes(),
Mirko Bonadei6a489f22019-04-09 15:11:12 +02005725 ::testing::ElementsAre(VideoFrameType{VideoFrameType::kVideoFrameDelta}));
Erik Språngd7329ca2019-02-21 21:19:53 +01005726
5727 // Request next frame be a key-frame.
5728 video_stream_encoder_->SendKeyFrame();
5729 video_source_.IncomingCapturedFrame(CreateFrame(3, nullptr));
5730 WaitForEncodedFrame(3);
Niels Möller8f7ce222019-03-21 15:43:58 +01005731 EXPECT_THAT(
5732 fake_encoder_.LastFrameTypes(),
Mirko Bonadei6a489f22019-04-09 15:11:12 +02005733 ::testing::ElementsAre(VideoFrameType{VideoFrameType::kVideoFrameKey}));
Erik Språngd7329ca2019-02-21 21:19:53 +01005734
5735 video_stream_encoder_->Stop();
5736}
5737
5738TEST_F(VideoStreamEncoderTest, SetsFrameTypesSimulcast) {
5739 // Setup simulcast with three streams.
5740 ResetEncoder("VP8", 3, 1, 1, false);
Henrik Boström381d1092020-05-12 18:49:07 +02005741 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005742 DataRate::BitsPerSec(kSimulcastTargetBitrateBps),
5743 DataRate::BitsPerSec(kSimulcastTargetBitrateBps),
5744 DataRate::BitsPerSec(kSimulcastTargetBitrateBps), 0, 0, 0);
Erik Språngd7329ca2019-02-21 21:19:53 +01005745 // Wait for all three layers before triggering event.
5746 sink_.SetNumExpectedLayers(3);
5747
5748 // First frame is always keyframe.
5749 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
5750 WaitForEncodedFrame(1);
5751 EXPECT_THAT(fake_encoder_.LastFrameTypes(),
Mirko Bonadei6a489f22019-04-09 15:11:12 +02005752 ::testing::ElementsAreArray({VideoFrameType::kVideoFrameKey,
5753 VideoFrameType::kVideoFrameKey,
5754 VideoFrameType::kVideoFrameKey}));
Erik Språngd7329ca2019-02-21 21:19:53 +01005755
5756 // Insert delta frame.
5757 video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
5758 WaitForEncodedFrame(2);
5759 EXPECT_THAT(fake_encoder_.LastFrameTypes(),
Mirko Bonadei6a489f22019-04-09 15:11:12 +02005760 ::testing::ElementsAreArray({VideoFrameType::kVideoFrameDelta,
5761 VideoFrameType::kVideoFrameDelta,
5762 VideoFrameType::kVideoFrameDelta}));
Erik Språngd7329ca2019-02-21 21:19:53 +01005763
5764 // Request next frame be a key-frame.
5765 // Only first stream is configured to produce key-frame.
5766 video_stream_encoder_->SendKeyFrame();
5767 video_source_.IncomingCapturedFrame(CreateFrame(3, nullptr));
5768 WaitForEncodedFrame(3);
Sergey Silkine62a08a2019-05-13 13:45:39 +02005769
5770 // TODO(webrtc:10615): Map keyframe request to spatial layer. Currently
5771 // keyframe request on any layer triggers keyframe on all layers.
Erik Språngd7329ca2019-02-21 21:19:53 +01005772 EXPECT_THAT(fake_encoder_.LastFrameTypes(),
Mirko Bonadei6a489f22019-04-09 15:11:12 +02005773 ::testing::ElementsAreArray({VideoFrameType::kVideoFrameKey,
Sergey Silkine62a08a2019-05-13 13:45:39 +02005774 VideoFrameType::kVideoFrameKey,
5775 VideoFrameType::kVideoFrameKey}));
Erik Språngd7329ca2019-02-21 21:19:53 +01005776
5777 video_stream_encoder_->Stop();
5778}
5779
5780TEST_F(VideoStreamEncoderTest, RequestKeyframeInternalSource) {
5781 // Configure internal source factory and setup test again.
5782 encoder_factory_.SetHasInternalSource(true);
5783 ResetEncoder("VP8", 1, 1, 1, false);
Henrik Boström381d1092020-05-12 18:49:07 +02005784 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005785 DataRate::BitsPerSec(kTargetBitrateBps),
5786 DataRate::BitsPerSec(kTargetBitrateBps),
5787 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Erik Språngd7329ca2019-02-21 21:19:53 +01005788
5789 // Call encoder directly, simulating internal source where encoded frame
5790 // callback in VideoStreamEncoder is called despite no OnFrame().
5791 fake_encoder_.InjectFrame(CreateFrame(1, nullptr), true);
5792 EXPECT_TRUE(WaitForFrame(kDefaultTimeoutMs));
Niels Möller8f7ce222019-03-21 15:43:58 +01005793 EXPECT_THAT(
5794 fake_encoder_.LastFrameTypes(),
Mirko Bonadei6a489f22019-04-09 15:11:12 +02005795 ::testing::ElementsAre(VideoFrameType{VideoFrameType::kVideoFrameKey}));
Erik Språngd7329ca2019-02-21 21:19:53 +01005796
Niels Möller8f7ce222019-03-21 15:43:58 +01005797 const std::vector<VideoFrameType> kDeltaFrame = {
5798 VideoFrameType::kVideoFrameDelta};
Erik Språngd7329ca2019-02-21 21:19:53 +01005799 // Need to set timestamp manually since manually for injected frame.
5800 VideoFrame frame = CreateFrame(101, nullptr);
5801 frame.set_timestamp(101);
5802 fake_encoder_.InjectFrame(frame, false);
5803 EXPECT_TRUE(WaitForFrame(kDefaultTimeoutMs));
Niels Möller8f7ce222019-03-21 15:43:58 +01005804 EXPECT_THAT(
5805 fake_encoder_.LastFrameTypes(),
Mirko Bonadei6a489f22019-04-09 15:11:12 +02005806 ::testing::ElementsAre(VideoFrameType{VideoFrameType::kVideoFrameDelta}));
Erik Språngd7329ca2019-02-21 21:19:53 +01005807
5808 // Request key-frame. The forces a dummy frame down into the encoder.
5809 fake_encoder_.ExpectNullFrame();
5810 video_stream_encoder_->SendKeyFrame();
5811 EXPECT_TRUE(WaitForFrame(kDefaultTimeoutMs));
Niels Möller8f7ce222019-03-21 15:43:58 +01005812 EXPECT_THAT(
5813 fake_encoder_.LastFrameTypes(),
Mirko Bonadei6a489f22019-04-09 15:11:12 +02005814 ::testing::ElementsAre(VideoFrameType{VideoFrameType::kVideoFrameKey}));
Erik Språngd7329ca2019-02-21 21:19:53 +01005815
5816 video_stream_encoder_->Stop();
5817}
Erik Språngb7cb7b52019-02-26 15:52:33 +01005818
5819TEST_F(VideoStreamEncoderTest, AdjustsTimestampInternalSource) {
5820 // Configure internal source factory and setup test again.
5821 encoder_factory_.SetHasInternalSource(true);
5822 ResetEncoder("VP8", 1, 1, 1, false);
Henrik Boström381d1092020-05-12 18:49:07 +02005823 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005824 DataRate::BitsPerSec(kTargetBitrateBps),
5825 DataRate::BitsPerSec(kTargetBitrateBps),
5826 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Erik Språngb7cb7b52019-02-26 15:52:33 +01005827
5828 int64_t timestamp = 1;
5829 EncodedImage image;
Niels Möller4d504c72019-06-18 15:56:56 +02005830 image.SetEncodedData(
5831 EncodedImageBuffer::Create(kTargetBitrateBps / kDefaultFramerate / 8));
Erik Språngb7cb7b52019-02-26 15:52:33 +01005832 image.capture_time_ms_ = ++timestamp;
5833 image.SetTimestamp(static_cast<uint32_t>(timestamp * 90));
5834 const int64_t kEncodeFinishDelayMs = 10;
5835 image.timing_.encode_start_ms = timestamp;
5836 image.timing_.encode_finish_ms = timestamp + kEncodeFinishDelayMs;
5837 fake_encoder_.InjectEncodedImage(image);
5838 // Wait for frame without incrementing clock.
5839 EXPECT_TRUE(sink_.WaitForFrame(kDefaultTimeoutMs));
5840 // Frame is captured kEncodeFinishDelayMs before it's encoded, so restored
5841 // capture timestamp should be kEncodeFinishDelayMs in the past.
5842 EXPECT_EQ(sink_.GetLastCaptureTimeMs(),
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02005843 CurrentTimeMs() - kEncodeFinishDelayMs);
Erik Språngb7cb7b52019-02-26 15:52:33 +01005844
5845 video_stream_encoder_->Stop();
5846}
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +02005847
5848TEST_F(VideoStreamEncoderTest, DoesNotRewriteH264BitstreamWithOptimalSps) {
Mirta Dvornicic97910da2020-07-14 15:29:23 +02005849 // SPS contains VUI with restrictions on the maximum number of reordered
5850 // pictures, there is no need to rewrite the bitstream to enable faster
5851 // decoding.
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +02005852 ResetEncoder("H264", 1, 1, 1, false);
5853
Mirta Dvornicic97910da2020-07-14 15:29:23 +02005854 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
5855 DataRate::BitsPerSec(kTargetBitrateBps),
5856 DataRate::BitsPerSec(kTargetBitrateBps),
5857 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
5858 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +02005859
Mirta Dvornicic97910da2020-07-14 15:29:23 +02005860 fake_encoder_.SetEncodedImageData(
5861 EncodedImageBuffer::Create(optimal_sps, sizeof(optimal_sps)));
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +02005862
Mirta Dvornicic97910da2020-07-14 15:29:23 +02005863 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
5864 WaitForEncodedFrame(1);
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +02005865
5866 EXPECT_THAT(sink_.GetLastEncodedImageData(),
5867 testing::ElementsAreArray(optimal_sps));
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +02005868
5869 video_stream_encoder_->Stop();
5870}
5871
5872TEST_F(VideoStreamEncoderTest, RewritesH264BitstreamWithNonOptimalSps) {
Mirta Dvornicic97910da2020-07-14 15:29:23 +02005873 // SPS does not contain VUI, the bitstream is will be rewritten with added
5874 // VUI with restrictions on the maximum number of reordered pictures to
5875 // enable faster decoding.
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +02005876 uint8_t original_sps[] = {0, 0, 0, 1, H264::NaluType::kSps,
5877 0x00, 0x00, 0x03, 0x03, 0xF4,
5878 0x05, 0x03, 0xC7, 0xC0};
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +02005879 ResetEncoder("H264", 1, 1, 1, false);
5880
Mirta Dvornicic97910da2020-07-14 15:29:23 +02005881 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
5882 DataRate::BitsPerSec(kTargetBitrateBps),
5883 DataRate::BitsPerSec(kTargetBitrateBps),
5884 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
5885 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +02005886
Mirta Dvornicic97910da2020-07-14 15:29:23 +02005887 fake_encoder_.SetEncodedImageData(
5888 EncodedImageBuffer::Create(original_sps, sizeof(original_sps)));
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +02005889
Mirta Dvornicic97910da2020-07-14 15:29:23 +02005890 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
5891 WaitForEncodedFrame(1);
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +02005892
5893 EXPECT_THAT(sink_.GetLastEncodedImageData(),
5894 testing::ElementsAreArray(optimal_sps));
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +02005895
5896 video_stream_encoder_->Stop();
5897}
5898
Ilya Nikolaevskiyba96e2f2019-06-04 15:15:14 +02005899TEST_F(VideoStreamEncoderTest, CopiesVideoFrameMetadataAfterDownscale) {
5900 const int kFrameWidth = 1280;
5901 const int kFrameHeight = 720;
5902 const int kTargetBitrateBps = 300000; // To low for HD resolution.
5903
Henrik Boström381d1092020-05-12 18:49:07 +02005904 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005905 DataRate::BitsPerSec(kTargetBitrateBps),
5906 DataRate::BitsPerSec(kTargetBitrateBps),
5907 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Ilya Nikolaevskiyba96e2f2019-06-04 15:15:14 +02005908 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
5909
5910 // Insert a first video frame. It should be dropped because of downscale in
5911 // resolution.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02005912 int64_t timestamp_ms = CurrentTimeMs();
Ilya Nikolaevskiyba96e2f2019-06-04 15:15:14 +02005913 VideoFrame frame = CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight);
5914 frame.set_rotation(kVideoRotation_270);
5915 video_source_.IncomingCapturedFrame(frame);
5916
5917 ExpectDroppedFrame();
5918
5919 // Second frame is downscaled.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02005920 timestamp_ms = CurrentTimeMs();
Ilya Nikolaevskiyba96e2f2019-06-04 15:15:14 +02005921 frame = CreateFrame(timestamp_ms, kFrameWidth / 2, kFrameHeight / 2);
5922 frame.set_rotation(kVideoRotation_90);
5923 video_source_.IncomingCapturedFrame(frame);
5924
5925 WaitForEncodedFrame(timestamp_ms);
5926 sink_.CheckLastFrameRotationMatches(kVideoRotation_90);
5927
5928 // Insert another frame, also downscaled.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02005929 timestamp_ms = CurrentTimeMs();
Ilya Nikolaevskiyba96e2f2019-06-04 15:15:14 +02005930 frame = CreateFrame(timestamp_ms, kFrameWidth / 2, kFrameHeight / 2);
5931 frame.set_rotation(kVideoRotation_180);
5932 video_source_.IncomingCapturedFrame(frame);
5933
5934 WaitForEncodedFrame(timestamp_ms);
5935 sink_.CheckLastFrameRotationMatches(kVideoRotation_180);
5936
5937 video_stream_encoder_->Stop();
5938}
5939
Erik Språng5056af02019-09-02 15:53:11 +02005940TEST_F(VideoStreamEncoderTest, BandwidthAllocationLowerBound) {
5941 const int kFrameWidth = 320;
5942 const int kFrameHeight = 180;
5943
5944 // Initial rate.
Henrik Boström381d1092020-05-12 18:49:07 +02005945 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005946 /*target_bitrate=*/DataRate::KilobitsPerSec(300),
5947 /*stable_target_bitrate=*/DataRate::KilobitsPerSec(300),
5948 /*link_allocation=*/DataRate::KilobitsPerSec(300),
Erik Språng5056af02019-09-02 15:53:11 +02005949 /*fraction_lost=*/0,
Ying Wang9b881ab2020-02-07 14:29:32 +01005950 /*rtt_ms=*/0,
5951 /*cwnd_reduce_ratio=*/0);
Erik Språng5056af02019-09-02 15:53:11 +02005952
5953 // Insert a first video frame so that encoder gets configured.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02005954 int64_t timestamp_ms = CurrentTimeMs();
Erik Språng5056af02019-09-02 15:53:11 +02005955 VideoFrame frame = CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight);
5956 frame.set_rotation(kVideoRotation_270);
5957 video_source_.IncomingCapturedFrame(frame);
5958 WaitForEncodedFrame(timestamp_ms);
5959
5960 // Set a target rate below the minimum allowed by the codec settings.
5961 VideoCodec codec_config = fake_encoder_.codec_config();
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005962 DataRate min_rate = DataRate::KilobitsPerSec(codec_config.minBitrate);
5963 DataRate target_rate = min_rate - DataRate::KilobitsPerSec(1);
Henrik Boström381d1092020-05-12 18:49:07 +02005964 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Erik Språng5056af02019-09-02 15:53:11 +02005965 /*target_bitrate=*/target_rate,
Florent Castellia8336d32019-09-09 13:36:55 +02005966 /*stable_target_bitrate=*/target_rate,
Erik Språng5056af02019-09-02 15:53:11 +02005967 /*link_allocation=*/target_rate,
5968 /*fraction_lost=*/0,
Ying Wang9b881ab2020-02-07 14:29:32 +01005969 /*rtt_ms=*/0,
5970 /*cwnd_reduce_ratio=*/0);
Erik Språng5056af02019-09-02 15:53:11 +02005971 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
5972
5973 // Target bitrate and bandwidth allocation should both be capped at min_rate.
5974 auto rate_settings = fake_encoder_.GetAndResetLastRateControlSettings();
5975 ASSERT_TRUE(rate_settings.has_value());
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005976 DataRate allocation_sum =
5977 DataRate::BitsPerSec(rate_settings->bitrate.get_sum_bps());
Erik Språng5056af02019-09-02 15:53:11 +02005978 EXPECT_EQ(min_rate, allocation_sum);
5979 EXPECT_EQ(rate_settings->bandwidth_allocation, min_rate);
5980
5981 video_stream_encoder_->Stop();
5982}
5983
Rasmus Brandt5cad55b2019-12-19 09:47:11 +01005984TEST_F(VideoStreamEncoderTest, EncoderRatesPropagatedOnReconfigure) {
Henrik Boström381d1092020-05-12 18:49:07 +02005985 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005986 DataRate::BitsPerSec(kTargetBitrateBps),
5987 DataRate::BitsPerSec(kTargetBitrateBps),
5988 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Evan Shrubsolee32ae4f2019-09-25 12:50:23 +02005989 // Capture a frame and wait for it to synchronize with the encoder thread.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02005990 int64_t timestamp_ms = CurrentTimeMs();
Evan Shrubsolee32ae4f2019-09-25 12:50:23 +02005991 video_source_.IncomingCapturedFrame(CreateFrame(timestamp_ms, nullptr));
5992 WaitForEncodedFrame(1);
5993
5994 auto prev_rate_settings = fake_encoder_.GetAndResetLastRateControlSettings();
5995 ASSERT_TRUE(prev_rate_settings.has_value());
5996 EXPECT_EQ(static_cast<int>(prev_rate_settings->framerate_fps),
5997 kDefaultFramerate);
5998
5999 // Send 1s of video to ensure the framerate is stable at kDefaultFramerate.
6000 for (int i = 0; i < 2 * kDefaultFramerate; i++) {
6001 timestamp_ms += 1000 / kDefaultFramerate;
6002 video_source_.IncomingCapturedFrame(CreateFrame(timestamp_ms, nullptr));
6003 WaitForEncodedFrame(timestamp_ms);
6004 }
6005 EXPECT_EQ(static_cast<int>(fake_encoder_.GetLastFramerate()),
6006 kDefaultFramerate);
6007 // Capture larger frame to trigger a reconfigure.
6008 codec_height_ *= 2;
6009 codec_width_ *= 2;
6010 timestamp_ms += 1000 / kDefaultFramerate;
6011 video_source_.IncomingCapturedFrame(CreateFrame(timestamp_ms, nullptr));
6012 WaitForEncodedFrame(timestamp_ms);
6013
6014 EXPECT_EQ(2, sink_.number_of_reconfigurations());
6015 auto current_rate_settings =
6016 fake_encoder_.GetAndResetLastRateControlSettings();
6017 // Ensure we have actually reconfigured twice
6018 // The rate settings should have been set again even though
6019 // they haven't changed.
6020 ASSERT_TRUE(current_rate_settings.has_value());
Evan Shrubsole7c079f62019-09-26 09:55:03 +02006021 EXPECT_EQ(prev_rate_settings, current_rate_settings);
Evan Shrubsolee32ae4f2019-09-25 12:50:23 +02006022
6023 video_stream_encoder_->Stop();
6024}
6025
philipeld9cc8c02019-09-16 14:53:40 +02006026struct MockEncoderSwitchRequestCallback : public EncoderSwitchRequestCallback {
Danil Chapovalov91fdc602020-05-14 19:17:51 +02006027 MOCK_METHOD(void, RequestEncoderFallback, (), (override));
6028 MOCK_METHOD(void, RequestEncoderSwitch, (const Config& conf), (override));
6029 MOCK_METHOD(void,
6030 RequestEncoderSwitch,
6031 (const webrtc::SdpVideoFormat& format),
6032 (override));
philipeld9cc8c02019-09-16 14:53:40 +02006033};
6034
6035TEST_F(VideoStreamEncoderTest, BitrateEncoderSwitch) {
6036 constexpr int kDontCare = 100;
6037
6038 StrictMock<MockEncoderSwitchRequestCallback> switch_callback;
6039 video_send_config_.encoder_settings.encoder_switch_request_callback =
6040 &switch_callback;
6041 VideoEncoderConfig encoder_config = video_encoder_config_.Copy();
6042 encoder_config.codec_type = kVideoCodecVP8;
6043 webrtc::test::ScopedFieldTrials field_trial(
6044 "WebRTC-NetworkCondition-EncoderSwitch/"
6045 "codec_thresholds:VP8;100;-1|H264;-1;30000,"
6046 "to_codec:AV1,to_param:ping,to_value:pong,window:2.0/");
6047
6048 // Reset encoder for new configuration to take effect.
6049 ConfigureEncoder(std::move(encoder_config));
6050
6051 // Send one frame to trigger ReconfigureEncoder.
6052 video_source_.IncomingCapturedFrame(
6053 CreateFrame(kDontCare, kDontCare, kDontCare));
6054
6055 using Config = EncoderSwitchRequestCallback::Config;
philipel9b058032020-02-10 11:30:00 +01006056 EXPECT_CALL(switch_callback, RequestEncoderSwitch(Matcher<const Config&>(
6057 AllOf(Field(&Config::codec_name, "AV1"),
philipeld9cc8c02019-09-16 14:53:40 +02006058 Field(&Config::param, "ping"),
philipel9b058032020-02-10 11:30:00 +01006059 Field(&Config::value, "pong")))));
philipeld9cc8c02019-09-16 14:53:40 +02006060
Henrik Boström381d1092020-05-12 18:49:07 +02006061 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01006062 /*target_bitrate=*/DataRate::KilobitsPerSec(50),
6063 /*stable_target_bitrate=*/DataRate::KilobitsPerSec(kDontCare),
6064 /*link_allocation=*/DataRate::KilobitsPerSec(kDontCare),
philipeld9cc8c02019-09-16 14:53:40 +02006065 /*fraction_lost=*/0,
Ying Wang9b881ab2020-02-07 14:29:32 +01006066 /*rtt_ms=*/0,
6067 /*cwnd_reduce_ratio=*/0);
Tomas Gunnarssond41c2a62020-09-21 15:56:42 +02006068 AdvanceTime(TimeDelta::Millis(0));
philipeld9cc8c02019-09-16 14:53:40 +02006069
6070 video_stream_encoder_->Stop();
6071}
6072
Mirta Dvornicic5ed40cf2020-02-21 16:35:51 +01006073TEST_F(VideoStreamEncoderTest, VideoSuspendedNoEncoderSwitch) {
6074 constexpr int kDontCare = 100;
6075
6076 StrictMock<MockEncoderSwitchRequestCallback> switch_callback;
6077 video_send_config_.encoder_settings.encoder_switch_request_callback =
6078 &switch_callback;
6079 VideoEncoderConfig encoder_config = video_encoder_config_.Copy();
6080 encoder_config.codec_type = kVideoCodecVP8;
6081 webrtc::test::ScopedFieldTrials field_trial(
6082 "WebRTC-NetworkCondition-EncoderSwitch/"
6083 "codec_thresholds:VP8;100;-1|H264;-1;30000,"
6084 "to_codec:AV1,to_param:ping,to_value:pong,window:2.0/");
6085
6086 // Reset encoder for new configuration to take effect.
6087 ConfigureEncoder(std::move(encoder_config));
6088
6089 // Send one frame to trigger ReconfigureEncoder.
6090 video_source_.IncomingCapturedFrame(
6091 CreateFrame(kDontCare, kDontCare, kDontCare));
6092
6093 using Config = EncoderSwitchRequestCallback::Config;
6094 EXPECT_CALL(switch_callback, RequestEncoderSwitch(Matcher<const Config&>(_)))
6095 .Times(0);
6096
Henrik Boström381d1092020-05-12 18:49:07 +02006097 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Mirta Dvornicic5ed40cf2020-02-21 16:35:51 +01006098 /*target_bitrate=*/DataRate::KilobitsPerSec(0),
6099 /*stable_target_bitrate=*/DataRate::KilobitsPerSec(0),
6100 /*link_allocation=*/DataRate::KilobitsPerSec(kDontCare),
6101 /*fraction_lost=*/0,
6102 /*rtt_ms=*/0,
6103 /*cwnd_reduce_ratio=*/0);
6104
6105 video_stream_encoder_->Stop();
6106}
6107
philipeld9cc8c02019-09-16 14:53:40 +02006108TEST_F(VideoStreamEncoderTest, ResolutionEncoderSwitch) {
6109 constexpr int kSufficientBitrateToNotDrop = 1000;
6110 constexpr int kHighRes = 500;
6111 constexpr int kLowRes = 100;
6112
6113 StrictMock<MockEncoderSwitchRequestCallback> switch_callback;
6114 video_send_config_.encoder_settings.encoder_switch_request_callback =
6115 &switch_callback;
6116 webrtc::test::ScopedFieldTrials field_trial(
6117 "WebRTC-NetworkCondition-EncoderSwitch/"
6118 "codec_thresholds:VP8;120;-1|H264;-1;30000,"
6119 "to_codec:AV1,to_param:ping,to_value:pong,window:2.0/");
6120 VideoEncoderConfig encoder_config = video_encoder_config_.Copy();
6121 encoder_config.codec_type = kVideoCodecH264;
6122
6123 // Reset encoder for new configuration to take effect.
6124 ConfigureEncoder(std::move(encoder_config));
6125
6126 // The VideoStreamEncoder needs some bitrate before it can start encoding,
6127 // setting some bitrate so that subsequent calls to WaitForEncodedFrame does
6128 // not fail.
Henrik Boström381d1092020-05-12 18:49:07 +02006129 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01006130 /*target_bitrate=*/DataRate::KilobitsPerSec(kSufficientBitrateToNotDrop),
6131 /*stable_target_bitrate=*/
6132 DataRate::KilobitsPerSec(kSufficientBitrateToNotDrop),
6133 /*link_allocation=*/DataRate::KilobitsPerSec(kSufficientBitrateToNotDrop),
philipeld9cc8c02019-09-16 14:53:40 +02006134 /*fraction_lost=*/0,
Ying Wang9b881ab2020-02-07 14:29:32 +01006135 /*rtt_ms=*/0,
6136 /*cwnd_reduce_ratio=*/0);
philipeld9cc8c02019-09-16 14:53:40 +02006137
6138 // Send one frame to trigger ReconfigureEncoder.
6139 video_source_.IncomingCapturedFrame(CreateFrame(1, kHighRes, kHighRes));
6140 WaitForEncodedFrame(1);
6141
6142 using Config = EncoderSwitchRequestCallback::Config;
philipel9b058032020-02-10 11:30:00 +01006143 EXPECT_CALL(switch_callback, RequestEncoderSwitch(Matcher<const Config&>(
6144 AllOf(Field(&Config::codec_name, "AV1"),
philipeld9cc8c02019-09-16 14:53:40 +02006145 Field(&Config::param, "ping"),
philipel9b058032020-02-10 11:30:00 +01006146 Field(&Config::value, "pong")))));
philipeld9cc8c02019-09-16 14:53:40 +02006147
6148 video_source_.IncomingCapturedFrame(CreateFrame(2, kLowRes, kLowRes));
6149 WaitForEncodedFrame(2);
6150
6151 video_stream_encoder_->Stop();
6152}
6153
philipel9b058032020-02-10 11:30:00 +01006154TEST_F(VideoStreamEncoderTest, EncoderSelectorCurrentEncoderIsSignaled) {
6155 constexpr int kDontCare = 100;
6156 StrictMock<MockEncoderSelector> encoder_selector;
6157 auto encoder_factory = std::make_unique<test::VideoEncoderProxyFactory>(
6158 &fake_encoder_, &encoder_selector);
6159 video_send_config_.encoder_settings.encoder_factory = encoder_factory.get();
6160
6161 // Reset encoder for new configuration to take effect.
6162 ConfigureEncoder(video_encoder_config_.Copy());
6163
6164 EXPECT_CALL(encoder_selector, OnCurrentEncoder(_));
6165
6166 video_source_.IncomingCapturedFrame(
6167 CreateFrame(kDontCare, kDontCare, kDontCare));
6168 video_stream_encoder_->Stop();
6169
6170 // The encoders produces by the VideoEncoderProxyFactory have a pointer back
6171 // to it's factory, so in order for the encoder instance in the
6172 // |video_stream_encoder_| to be destroyed before the |encoder_factory| we
6173 // reset the |video_stream_encoder_| here.
6174 video_stream_encoder_.reset();
6175}
6176
6177TEST_F(VideoStreamEncoderTest, EncoderSelectorBitrateSwitch) {
6178 constexpr int kDontCare = 100;
6179
6180 NiceMock<MockEncoderSelector> encoder_selector;
6181 StrictMock<MockEncoderSwitchRequestCallback> switch_callback;
6182 video_send_config_.encoder_settings.encoder_switch_request_callback =
6183 &switch_callback;
6184 auto encoder_factory = std::make_unique<test::VideoEncoderProxyFactory>(
6185 &fake_encoder_, &encoder_selector);
6186 video_send_config_.encoder_settings.encoder_factory = encoder_factory.get();
6187
6188 // Reset encoder for new configuration to take effect.
6189 ConfigureEncoder(video_encoder_config_.Copy());
6190
Mirta Dvornicic4f34d782020-02-26 13:01:19 +01006191 ON_CALL(encoder_selector, OnAvailableBitrate(_))
philipel9b058032020-02-10 11:30:00 +01006192 .WillByDefault(Return(SdpVideoFormat("AV1")));
6193 EXPECT_CALL(switch_callback,
6194 RequestEncoderSwitch(Matcher<const SdpVideoFormat&>(
6195 Field(&SdpVideoFormat::name, "AV1"))));
6196
Henrik Boström381d1092020-05-12 18:49:07 +02006197 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01006198 /*target_bitrate=*/DataRate::KilobitsPerSec(50),
6199 /*stable_target_bitrate=*/DataRate::KilobitsPerSec(kDontCare),
6200 /*link_allocation=*/DataRate::KilobitsPerSec(kDontCare),
philipel9b058032020-02-10 11:30:00 +01006201 /*fraction_lost=*/0,
6202 /*rtt_ms=*/0,
6203 /*cwnd_reduce_ratio=*/0);
Tomas Gunnarssond41c2a62020-09-21 15:56:42 +02006204 AdvanceTime(TimeDelta::Millis(0));
philipel9b058032020-02-10 11:30:00 +01006205
6206 video_stream_encoder_->Stop();
6207}
6208
6209TEST_F(VideoStreamEncoderTest, EncoderSelectorBrokenEncoderSwitch) {
6210 constexpr int kSufficientBitrateToNotDrop = 1000;
6211 constexpr int kDontCare = 100;
6212
6213 NiceMock<MockVideoEncoder> video_encoder;
6214 NiceMock<MockEncoderSelector> encoder_selector;
6215 StrictMock<MockEncoderSwitchRequestCallback> switch_callback;
6216 video_send_config_.encoder_settings.encoder_switch_request_callback =
6217 &switch_callback;
6218 auto encoder_factory = std::make_unique<test::VideoEncoderProxyFactory>(
6219 &video_encoder, &encoder_selector);
6220 video_send_config_.encoder_settings.encoder_factory = encoder_factory.get();
6221
6222 // Reset encoder for new configuration to take effect.
6223 ConfigureEncoder(video_encoder_config_.Copy());
6224
6225 // The VideoStreamEncoder needs some bitrate before it can start encoding,
6226 // setting some bitrate so that subsequent calls to WaitForEncodedFrame does
6227 // not fail.
Henrik Boström381d1092020-05-12 18:49:07 +02006228 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01006229 /*target_bitrate=*/DataRate::KilobitsPerSec(kSufficientBitrateToNotDrop),
6230 /*stable_target_bitrate=*/
6231 DataRate::KilobitsPerSec(kSufficientBitrateToNotDrop),
6232 /*link_allocation=*/DataRate::KilobitsPerSec(kSufficientBitrateToNotDrop),
philipel9b058032020-02-10 11:30:00 +01006233 /*fraction_lost=*/0,
6234 /*rtt_ms=*/0,
6235 /*cwnd_reduce_ratio=*/0);
6236
6237 ON_CALL(video_encoder, Encode(_, _))
6238 .WillByDefault(Return(WEBRTC_VIDEO_CODEC_ENCODER_FAILURE));
6239 ON_CALL(encoder_selector, OnEncoderBroken())
6240 .WillByDefault(Return(SdpVideoFormat("AV2")));
6241
6242 rtc::Event encode_attempted;
6243 EXPECT_CALL(switch_callback,
6244 RequestEncoderSwitch(Matcher<const SdpVideoFormat&>(_)))
6245 .WillOnce([&encode_attempted](const SdpVideoFormat& format) {
6246 EXPECT_EQ(format.name, "AV2");
6247 encode_attempted.Set();
6248 });
6249
6250 video_source_.IncomingCapturedFrame(CreateFrame(1, kDontCare, kDontCare));
6251 encode_attempted.Wait(3000);
6252
Tomas Gunnarssond41c2a62020-09-21 15:56:42 +02006253 AdvanceTime(TimeDelta::Millis(0));
6254
philipel9b058032020-02-10 11:30:00 +01006255 video_stream_encoder_->Stop();
6256
6257 // The encoders produces by the VideoEncoderProxyFactory have a pointer back
6258 // to it's factory, so in order for the encoder instance in the
6259 // |video_stream_encoder_| to be destroyed before the |encoder_factory| we
6260 // reset the |video_stream_encoder_| here.
6261 video_stream_encoder_.reset();
6262}
6263
Evan Shrubsole7c079f62019-09-26 09:55:03 +02006264TEST_F(VideoStreamEncoderTest,
Rasmus Brandt5cad55b2019-12-19 09:47:11 +01006265 AllocationPropagatedToEncoderWhenTargetRateChanged) {
Evan Shrubsole7c079f62019-09-26 09:55:03 +02006266 const int kFrameWidth = 320;
6267 const int kFrameHeight = 180;
6268
6269 // Set initial rate.
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01006270 auto rate = DataRate::KilobitsPerSec(100);
Henrik Boström381d1092020-05-12 18:49:07 +02006271 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Evan Shrubsole7c079f62019-09-26 09:55:03 +02006272 /*target_bitrate=*/rate,
6273 /*stable_target_bitrate=*/rate,
6274 /*link_allocation=*/rate,
6275 /*fraction_lost=*/0,
Ying Wang9b881ab2020-02-07 14:29:32 +01006276 /*rtt_ms=*/0,
6277 /*cwnd_reduce_ratio=*/0);
Evan Shrubsole7c079f62019-09-26 09:55:03 +02006278
6279 // Insert a first video frame so that encoder gets configured.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02006280 int64_t timestamp_ms = CurrentTimeMs();
Evan Shrubsole7c079f62019-09-26 09:55:03 +02006281 VideoFrame frame = CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight);
6282 frame.set_rotation(kVideoRotation_270);
6283 video_source_.IncomingCapturedFrame(frame);
6284 WaitForEncodedFrame(timestamp_ms);
6285 EXPECT_EQ(1, fake_encoder_.GetNumSetRates());
6286
6287 // Change of target bitrate propagates to the encoder.
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01006288 auto new_stable_rate = rate - DataRate::KilobitsPerSec(5);
Henrik Boström381d1092020-05-12 18:49:07 +02006289 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Evan Shrubsole7c079f62019-09-26 09:55:03 +02006290 /*target_bitrate=*/new_stable_rate,
6291 /*stable_target_bitrate=*/new_stable_rate,
6292 /*link_allocation=*/rate,
6293 /*fraction_lost=*/0,
Ying Wang9b881ab2020-02-07 14:29:32 +01006294 /*rtt_ms=*/0,
6295 /*cwnd_reduce_ratio=*/0);
Evan Shrubsole7c079f62019-09-26 09:55:03 +02006296 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
6297 EXPECT_EQ(2, fake_encoder_.GetNumSetRates());
6298 video_stream_encoder_->Stop();
6299}
6300
6301TEST_F(VideoStreamEncoderTest,
Rasmus Brandt5cad55b2019-12-19 09:47:11 +01006302 AllocationNotPropagatedToEncoderWhenTargetRateUnchanged) {
Evan Shrubsole7c079f62019-09-26 09:55:03 +02006303 const int kFrameWidth = 320;
6304 const int kFrameHeight = 180;
6305
6306 // Set initial rate.
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01006307 auto rate = DataRate::KilobitsPerSec(100);
Henrik Boström381d1092020-05-12 18:49:07 +02006308 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Evan Shrubsole7c079f62019-09-26 09:55:03 +02006309 /*target_bitrate=*/rate,
6310 /*stable_target_bitrate=*/rate,
6311 /*link_allocation=*/rate,
6312 /*fraction_lost=*/0,
Ying Wang9b881ab2020-02-07 14:29:32 +01006313 /*rtt_ms=*/0,
6314 /*cwnd_reduce_ratio=*/0);
Evan Shrubsole7c079f62019-09-26 09:55:03 +02006315
6316 // Insert a first video frame so that encoder gets configured.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02006317 int64_t timestamp_ms = CurrentTimeMs();
Evan Shrubsole7c079f62019-09-26 09:55:03 +02006318 VideoFrame frame = CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight);
6319 frame.set_rotation(kVideoRotation_270);
6320 video_source_.IncomingCapturedFrame(frame);
6321 WaitForEncodedFrame(timestamp_ms);
6322 EXPECT_EQ(1, fake_encoder_.GetNumSetRates());
6323
6324 // Set a higher target rate without changing the link_allocation. Should not
6325 // reset encoder's rate.
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01006326 auto new_stable_rate = rate - DataRate::KilobitsPerSec(5);
Henrik Boström381d1092020-05-12 18:49:07 +02006327 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Evan Shrubsole7c079f62019-09-26 09:55:03 +02006328 /*target_bitrate=*/rate,
6329 /*stable_target_bitrate=*/new_stable_rate,
6330 /*link_allocation=*/rate,
6331 /*fraction_lost=*/0,
Ying Wang9b881ab2020-02-07 14:29:32 +01006332 /*rtt_ms=*/0,
6333 /*cwnd_reduce_ratio=*/0);
Evan Shrubsole7c079f62019-09-26 09:55:03 +02006334 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
6335 EXPECT_EQ(1, fake_encoder_.GetNumSetRates());
6336 video_stream_encoder_->Stop();
6337}
6338
Ilya Nikolaevskiy648b9d72019-12-03 16:54:17 +01006339TEST_F(VideoStreamEncoderTest, AutomaticAnimationDetection) {
6340 test::ScopedFieldTrials field_trials(
6341 "WebRTC-AutomaticAnimationDetectionScreenshare/"
6342 "enabled:true,min_fps:20,min_duration_ms:1000,min_area_ratio:0.8/");
6343 const int kFramerateFps = 30;
6344 const int kWidth = 1920;
6345 const int kHeight = 1080;
6346 const int kNumFrames = 2 * kFramerateFps; // >1 seconds of frames.
6347 // Works on screenshare mode.
6348 ResetEncoder("VP8", 1, 1, 1, /*screenshare*/ true);
6349 // We rely on the automatic resolution adaptation, but we handle framerate
6350 // adaptation manually by mocking the stats proxy.
6351 video_source_.set_adaptation_enabled(true);
6352
6353 // BALANCED degradation preference is required for this feature.
Henrik Boström381d1092020-05-12 18:49:07 +02006354 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01006355 DataRate::BitsPerSec(kTargetBitrateBps),
6356 DataRate::BitsPerSec(kTargetBitrateBps),
6357 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Ilya Nikolaevskiy648b9d72019-12-03 16:54:17 +01006358 video_stream_encoder_->SetSource(&video_source_,
6359 webrtc::DegradationPreference::BALANCED);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02006360 EXPECT_THAT(video_source_.sink_wants(), UnlimitedSinkWants());
Ilya Nikolaevskiy648b9d72019-12-03 16:54:17 +01006361
6362 VideoFrame frame = CreateFrame(1, kWidth, kHeight);
6363 frame.set_update_rect(VideoFrame::UpdateRect{0, 0, kWidth, kHeight});
6364
6365 // Pass enough frames with the full update to trigger animation detection.
6366 for (int i = 0; i < kNumFrames; ++i) {
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02006367 int64_t timestamp_ms = CurrentTimeMs();
Ilya Nikolaevskiy648b9d72019-12-03 16:54:17 +01006368 frame.set_ntp_time_ms(timestamp_ms);
6369 frame.set_timestamp_us(timestamp_ms * 1000);
6370 video_source_.IncomingCapturedFrame(frame);
6371 WaitForEncodedFrame(timestamp_ms);
6372 }
6373
6374 // Resolution should be limited.
6375 rtc::VideoSinkWants expected;
6376 expected.max_framerate_fps = kFramerateFps;
6377 expected.max_pixel_count = 1280 * 720 + 1;
Evan Shrubsole5fd40602020-05-25 16:19:54 +02006378 EXPECT_THAT(video_source_.sink_wants(), FpsEqResolutionLt(expected));
Ilya Nikolaevskiy648b9d72019-12-03 16:54:17 +01006379
6380 // Pass one frame with no known update.
6381 // Resolution cap should be removed immediately.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02006382 int64_t timestamp_ms = CurrentTimeMs();
Ilya Nikolaevskiy648b9d72019-12-03 16:54:17 +01006383 frame.set_ntp_time_ms(timestamp_ms);
6384 frame.set_timestamp_us(timestamp_ms * 1000);
6385 frame.clear_update_rect();
6386
6387 video_source_.IncomingCapturedFrame(frame);
6388 WaitForEncodedFrame(timestamp_ms);
6389
6390 // Resolution should be unlimited now.
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02006391 EXPECT_THAT(video_source_.sink_wants(),
6392 FpsMatchesResolutionMax(Eq(kFramerateFps)));
Ilya Nikolaevskiy648b9d72019-12-03 16:54:17 +01006393
6394 video_stream_encoder_->Stop();
6395}
6396
Ilya Nikolaevskiy09eb6e22020-06-05 12:36:32 +02006397TEST_F(VideoStreamEncoderTest, ConfiguresVp9SvcAtOddResolutions) {
6398 const int kWidth = 720; // 540p adapted down.
6399 const int kHeight = 405;
6400 const int kNumFrames = 3;
6401 // Works on screenshare mode.
6402 ResetEncoder("VP9", /*num_streams=*/1, /*num_temporal_layers=*/1,
6403 /*num_spatial_layers=*/2, /*screenshare=*/true);
6404
6405 video_source_.set_adaptation_enabled(true);
6406
6407 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
6408 DataRate::BitsPerSec(kTargetBitrateBps),
6409 DataRate::BitsPerSec(kTargetBitrateBps),
6410 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
6411
6412 VideoFrame frame = CreateFrame(1, kWidth, kHeight);
6413
6414 // Pass enough frames with the full update to trigger animation detection.
6415 for (int i = 0; i < kNumFrames; ++i) {
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02006416 int64_t timestamp_ms = CurrentTimeMs();
Ilya Nikolaevskiy09eb6e22020-06-05 12:36:32 +02006417 frame.set_ntp_time_ms(timestamp_ms);
6418 frame.set_timestamp_us(timestamp_ms * 1000);
6419 video_source_.IncomingCapturedFrame(frame);
6420 WaitForEncodedFrame(timestamp_ms);
6421 }
6422
6423 video_stream_encoder_->Stop();
6424}
6425
Yun Zhang1e4d4fd2020-09-30 00:22:46 -07006426TEST_F(VideoStreamEncoderTest, EncoderResetAccordingToParameterChange) {
6427 const float downscale_factors[] = {4.0, 2.0, 1.0};
6428 const int number_layers =
6429 sizeof(downscale_factors) / sizeof(downscale_factors[0]);
6430 VideoEncoderConfig config;
6431 test::FillEncoderConfiguration(kVideoCodecVP8, number_layers, &config);
6432 for (int i = 0; i < number_layers; ++i) {
6433 config.simulcast_layers[i].scale_resolution_down_by = downscale_factors[i];
6434 config.simulcast_layers[i].active = true;
6435 }
6436 config.video_stream_factory =
6437 new rtc::RefCountedObject<cricket::EncoderStreamFactory>(
6438 "VP8", /*max qp*/ 56, /*screencast*/ false,
6439 /*screenshare enabled*/ false);
6440 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
6441 DataRate::BitsPerSec(kSimulcastTargetBitrateBps),
6442 DataRate::BitsPerSec(kSimulcastTargetBitrateBps),
6443 DataRate::BitsPerSec(kSimulcastTargetBitrateBps), 0, 0, 0);
6444
6445 // First initialization.
6446 // Encoder should be initialized. Next frame should be key frame.
6447 video_stream_encoder_->ConfigureEncoder(config.Copy(), kMaxPayloadLength);
6448 sink_.SetNumExpectedLayers(number_layers);
6449 int64_t timestamp_ms = kFrameIntervalMs;
6450 video_source_.IncomingCapturedFrame(CreateFrame(timestamp_ms, 1280, 720));
6451 WaitForEncodedFrame(timestamp_ms);
6452 EXPECT_EQ(1, fake_encoder_.GetNumEncoderInitializations());
6453 EXPECT_THAT(fake_encoder_.LastFrameTypes(),
6454 ::testing::ElementsAreArray({VideoFrameType::kVideoFrameKey,
6455 VideoFrameType::kVideoFrameKey,
6456 VideoFrameType::kVideoFrameKey}));
6457
6458 // Disable top layer.
6459 // Encoder shouldn't be re-initialized. Next frame should be delta frame.
6460 config.simulcast_layers[number_layers - 1].active = false;
6461 video_stream_encoder_->ConfigureEncoder(config.Copy(), kMaxPayloadLength);
6462 sink_.SetNumExpectedLayers(number_layers - 1);
6463 timestamp_ms += kFrameIntervalMs;
6464 video_source_.IncomingCapturedFrame(CreateFrame(timestamp_ms, 1280, 720));
6465 WaitForEncodedFrame(timestamp_ms);
6466 EXPECT_EQ(1, fake_encoder_.GetNumEncoderInitializations());
6467 EXPECT_THAT(fake_encoder_.LastFrameTypes(),
6468 ::testing::ElementsAreArray({VideoFrameType::kVideoFrameDelta,
6469 VideoFrameType::kVideoFrameDelta,
6470 VideoFrameType::kVideoFrameDelta}));
6471
6472 // Re-enable top layer.
6473 // Encoder should be re-initialized. Next frame should be key frame.
6474 config.simulcast_layers[number_layers - 1].active = true;
6475 video_stream_encoder_->ConfigureEncoder(config.Copy(), kMaxPayloadLength);
6476 sink_.SetNumExpectedLayers(number_layers);
6477 timestamp_ms += kFrameIntervalMs;
6478 video_source_.IncomingCapturedFrame(CreateFrame(timestamp_ms, 1280, 720));
6479 WaitForEncodedFrame(timestamp_ms);
6480 EXPECT_EQ(2, fake_encoder_.GetNumEncoderInitializations());
6481 EXPECT_THAT(fake_encoder_.LastFrameTypes(),
6482 ::testing::ElementsAreArray({VideoFrameType::kVideoFrameKey,
6483 VideoFrameType::kVideoFrameKey,
6484 VideoFrameType::kVideoFrameKey}));
6485
6486 // Top layer max rate change.
6487 // Encoder shouldn't be re-initialized. Next frame should be delta frame.
6488 config.simulcast_layers[number_layers - 1].max_bitrate_bps -= 100;
6489 video_stream_encoder_->ConfigureEncoder(config.Copy(), kMaxPayloadLength);
6490 sink_.SetNumExpectedLayers(number_layers);
6491 timestamp_ms += kFrameIntervalMs;
6492 video_source_.IncomingCapturedFrame(CreateFrame(timestamp_ms, 1280, 720));
6493 WaitForEncodedFrame(timestamp_ms);
6494 EXPECT_EQ(2, fake_encoder_.GetNumEncoderInitializations());
6495 EXPECT_THAT(fake_encoder_.LastFrameTypes(),
6496 ::testing::ElementsAreArray({VideoFrameType::kVideoFrameDelta,
6497 VideoFrameType::kVideoFrameDelta,
6498 VideoFrameType::kVideoFrameDelta}));
6499
6500 // Top layer resolution change.
6501 // Encoder should be re-initialized. Next frame should be key frame.
6502 config.simulcast_layers[number_layers - 1].scale_resolution_down_by += 0.1;
6503 video_stream_encoder_->ConfigureEncoder(config.Copy(), kMaxPayloadLength);
6504 sink_.SetNumExpectedLayers(number_layers);
6505 timestamp_ms += kFrameIntervalMs;
6506 video_source_.IncomingCapturedFrame(CreateFrame(timestamp_ms, 1280, 720));
6507 WaitForEncodedFrame(timestamp_ms);
6508 EXPECT_EQ(3, fake_encoder_.GetNumEncoderInitializations());
6509 EXPECT_THAT(fake_encoder_.LastFrameTypes(),
6510 ::testing::ElementsAreArray({VideoFrameType::kVideoFrameKey,
6511 VideoFrameType::kVideoFrameKey,
6512 VideoFrameType::kVideoFrameKey}));
6513 video_stream_encoder_->Stop();
6514}
6515
perkj26091b12016-09-01 01:17:40 -07006516} // namespace webrtc