blob: 2161b4fd37ee524e50f4f83faa971ff69f03f69e [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 "test/encoder_settings.h"
47#include "test/fake_encoder.h"
Kári Tristan Helgason639602a2018-08-02 10:51:40 +020048#include "test/field_trial.h"
Artem Titov33f9d2b2019-12-05 15:59:00 +010049#include "test/frame_forwarder.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020050#include "test/gmock.h"
51#include "test/gtest.h"
Tomas Gunnarsson612445e2020-09-21 14:31:23 +020052#include "test/time_controller/simulated_time_controller.h"
Niels Möllercbcbc222018-09-28 09:07:24 +020053#include "test/video_encoder_proxy_factory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020054#include "video/send_statistics_proxy.h"
perkj26091b12016-09-01 01:17:40 -070055
56namespace webrtc {
57
sprang57c2fff2017-01-16 06:24:02 -080058using ::testing::_;
philipeld9cc8c02019-09-16 14:53:40 +020059using ::testing::AllOf;
Per Kjellanderd0a8f512020-10-07 11:28:41 +020060using ::testing::AtLeast;
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +020061using ::testing::Eq;
philipeld9cc8c02019-09-16 14:53:40 +020062using ::testing::Field;
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +020063using ::testing::Ge;
64using ::testing::Gt;
65using ::testing::Le;
66using ::testing::Lt;
philipel9b058032020-02-10 11:30:00 +010067using ::testing::Matcher;
68using ::testing::NiceMock;
69using ::testing::Return;
philipeld9cc8c02019-09-16 14:53:40 +020070using ::testing::StrictMock;
kthelgason876222f2016-11-29 01:44:11 -080071
perkj803d97f2016-11-01 11:45:46 -070072namespace {
Åsa Persson8c1bf952018-09-13 10:42:19 +020073const int kMinPixelsPerFrame = 320 * 180;
Åsa Perssone644a032019-11-08 15:56:00 +010074const int kQpLow = 1;
75const int kQpHigh = 2;
Åsa Persson8c1bf952018-09-13 10:42:19 +020076const int kMinFramerateFps = 2;
77const int kMinBalancedFramerateFps = 7;
78const int64_t kFrameTimeoutMs = 100;
asapersson5f7226f2016-11-25 04:37:00 -080079const size_t kMaxPayloadLength = 1440;
Erik Språngd7329ca2019-02-21 21:19:53 +010080const uint32_t kTargetBitrateBps = 1000000;
Sergey Silkin5ee69672019-07-02 14:18:34 +020081const uint32_t kStartBitrateBps = 600000;
Erik Språngd7329ca2019-02-21 21:19:53 +010082const uint32_t kSimulcastTargetBitrateBps = 3150000;
83const uint32_t kLowTargetBitrateBps = kTargetBitrateBps / 10;
kthelgason2bc68642017-02-07 07:02:22 -080084const int kMaxInitialFramedrop = 4;
sprangfda496a2017-06-15 04:21:07 -070085const int kDefaultFramerate = 30;
Åsa Persson8c1bf952018-09-13 10:42:19 +020086const int64_t kFrameIntervalMs = rtc::kNumMillisecsPerSec / kDefaultFramerate;
Niels Möllerfe407b72019-09-10 10:48:48 +020087const int64_t kProcessIntervalMs = 1000;
Sergey Silkin41c650b2019-10-14 13:12:19 +020088const VideoEncoder::ResolutionBitrateLimits
89 kEncoderBitrateLimits540p(960 * 540, 100 * 1000, 100 * 1000, 2000 * 1000);
90const VideoEncoder::ResolutionBitrateLimits
91 kEncoderBitrateLimits720p(1280 * 720, 200 * 1000, 200 * 1000, 4000 * 1000);
asapersson5f7226f2016-11-25 04:37:00 -080092
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +020093uint8_t optimal_sps[] = {0, 0, 0, 1, H264::NaluType::kSps,
94 0x00, 0x00, 0x03, 0x03, 0xF4,
95 0x05, 0x03, 0xC7, 0xE0, 0x1B,
96 0x41, 0x10, 0x8D, 0x00};
97
perkj803d97f2016-11-01 11:45:46 -070098class TestBuffer : public webrtc::I420Buffer {
99 public:
100 TestBuffer(rtc::Event* event, int width, int height)
101 : I420Buffer(width, height), event_(event) {}
102
103 private:
104 friend class rtc::RefCountedObject<TestBuffer>;
105 ~TestBuffer() override {
106 if (event_)
107 event_->Set();
108 }
109 rtc::Event* const event_;
110};
111
Noah Richards51db4212019-06-12 06:59:12 -0700112// A fake native buffer that can't be converted to I420.
113class FakeNativeBuffer : public webrtc::VideoFrameBuffer {
114 public:
115 FakeNativeBuffer(rtc::Event* event, int width, int height)
116 : event_(event), width_(width), height_(height) {}
117 webrtc::VideoFrameBuffer::Type type() const override { return Type::kNative; }
118 int width() const override { return width_; }
119 int height() const override { return height_; }
120 rtc::scoped_refptr<webrtc::I420BufferInterface> ToI420() override {
121 return nullptr;
122 }
123
124 private:
125 friend class rtc::RefCountedObject<FakeNativeBuffer>;
126 ~FakeNativeBuffer() override {
127 if (event_)
128 event_->Set();
129 }
130 rtc::Event* const event_;
131 const int width_;
132 const int height_;
133};
134
Evan Shrubsole895556e2020-10-05 09:15:13 +0200135// A fake native buffer that is backed by an NV12 buffer.
136class FakeNV12NativeBuffer : public webrtc::VideoFrameBuffer {
137 public:
138 FakeNV12NativeBuffer(rtc::Event* event, int width, int height)
139 : nv12_buffer_(NV12Buffer::Create(width, height)), event_(event) {}
140
141 webrtc::VideoFrameBuffer::Type type() const override { return Type::kNative; }
142 int width() const override { return nv12_buffer_->width(); }
143 int height() const override { return nv12_buffer_->height(); }
144 rtc::scoped_refptr<webrtc::I420BufferInterface> ToI420() override {
145 return nv12_buffer_->ToI420();
146 }
Evan Shrubsoleb556b082020-10-08 14:56:45 +0200147 rtc::scoped_refptr<VideoFrameBuffer> GetMappedFrameBuffer(
148 rtc::ArrayView<VideoFrameBuffer::Type> types) override {
149 if (absl::c_find(types, Type::kNV12) != types.end()) {
150 return nv12_buffer_;
151 }
152 return nullptr;
153 }
Evan Shrubsole895556e2020-10-05 09:15:13 +0200154 const NV12BufferInterface* GetNV12() const { return nv12_buffer_; }
155
156 private:
157 friend class rtc::RefCountedObject<FakeNV12NativeBuffer>;
158 ~FakeNV12NativeBuffer() override {
159 if (event_)
160 event_->Set();
161 }
162 rtc::scoped_refptr<NV12Buffer> nv12_buffer_;
163 rtc::Event* const event_;
164};
165
Niels Möller7dc26b72017-12-06 10:27:48 +0100166class CpuOveruseDetectorProxy : public OveruseFrameDetector {
167 public:
Niels Möllerd1f7eb62018-03-28 16:40:58 +0200168 explicit CpuOveruseDetectorProxy(CpuOveruseMetricsObserver* metrics_observer)
169 : OveruseFrameDetector(metrics_observer),
Henrik Boström381d1092020-05-12 18:49:07 +0200170 last_target_framerate_fps_(-1),
171 framerate_updated_event_(true /* manual_reset */,
172 false /* initially_signaled */) {}
Niels Möller7dc26b72017-12-06 10:27:48 +0100173 virtual ~CpuOveruseDetectorProxy() {}
174
175 void OnTargetFramerateUpdated(int framerate_fps) override {
Markus Handella3765182020-07-08 13:13:32 +0200176 MutexLock lock(&lock_);
Niels Möller7dc26b72017-12-06 10:27:48 +0100177 last_target_framerate_fps_ = framerate_fps;
178 OveruseFrameDetector::OnTargetFramerateUpdated(framerate_fps);
Henrik Boström381d1092020-05-12 18:49:07 +0200179 framerate_updated_event_.Set();
Niels Möller7dc26b72017-12-06 10:27:48 +0100180 }
181
182 int GetLastTargetFramerate() {
Markus Handella3765182020-07-08 13:13:32 +0200183 MutexLock lock(&lock_);
Niels Möller7dc26b72017-12-06 10:27:48 +0100184 return last_target_framerate_fps_;
185 }
186
Niels Möller4db138e2018-04-19 09:04:13 +0200187 CpuOveruseOptions GetOptions() { return options_; }
188
Henrik Boström381d1092020-05-12 18:49:07 +0200189 rtc::Event* framerate_updated_event() { return &framerate_updated_event_; }
190
Niels Möller7dc26b72017-12-06 10:27:48 +0100191 private:
Markus Handella3765182020-07-08 13:13:32 +0200192 Mutex lock_;
Niels Möller7dc26b72017-12-06 10:27:48 +0100193 int last_target_framerate_fps_ RTC_GUARDED_BY(lock_);
Henrik Boström381d1092020-05-12 18:49:07 +0200194 rtc::Event framerate_updated_event_;
Niels Möller7dc26b72017-12-06 10:27:48 +0100195};
196
Henrik Boström0f0aa9c2020-06-02 13:02:36 +0200197class FakeVideoSourceRestrictionsListener
198 : public VideoSourceRestrictionsListener {
Henrik Boström381d1092020-05-12 18:49:07 +0200199 public:
Henrik Boström0f0aa9c2020-06-02 13:02:36 +0200200 FakeVideoSourceRestrictionsListener()
Henrik Boström381d1092020-05-12 18:49:07 +0200201 : was_restrictions_updated_(false), restrictions_updated_event_() {}
Henrik Boström0f0aa9c2020-06-02 13:02:36 +0200202 ~FakeVideoSourceRestrictionsListener() override {
Henrik Boström381d1092020-05-12 18:49:07 +0200203 RTC_DCHECK(was_restrictions_updated_);
204 }
205
206 rtc::Event* restrictions_updated_event() {
207 return &restrictions_updated_event_;
208 }
209
Henrik Boström0f0aa9c2020-06-02 13:02:36 +0200210 // VideoSourceRestrictionsListener implementation.
Henrik Boström381d1092020-05-12 18:49:07 +0200211 void OnVideoSourceRestrictionsUpdated(
212 VideoSourceRestrictions restrictions,
213 const VideoAdaptationCounters& adaptation_counters,
Evan Shrubsoleec0af262020-07-01 11:47:46 +0200214 rtc::scoped_refptr<Resource> reason,
215 const VideoSourceRestrictions& unfiltered_restrictions) override {
Henrik Boström381d1092020-05-12 18:49:07 +0200216 was_restrictions_updated_ = true;
217 restrictions_updated_event_.Set();
218 }
219
220 private:
221 bool was_restrictions_updated_;
222 rtc::Event restrictions_updated_event_;
223};
224
Evan Shrubsole5fd40602020-05-25 16:19:54 +0200225auto WantsFps(Matcher<int> fps_matcher) {
226 return Field("max_framerate_fps", &rtc::VideoSinkWants::max_framerate_fps,
227 fps_matcher);
228}
229
230auto WantsMaxPixels(Matcher<int> max_pixel_matcher) {
231 return Field("max_pixel_count", &rtc::VideoSinkWants::max_pixel_count,
232 AllOf(max_pixel_matcher, Gt(0)));
233}
234
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +0200235auto ResolutionMax() {
236 return AllOf(
Evan Shrubsole5fd40602020-05-25 16:19:54 +0200237 WantsMaxPixels(Eq(std::numeric_limits<int>::max())),
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +0200238 Field("target_pixel_count", &rtc::VideoSinkWants::target_pixel_count,
239 Eq(absl::nullopt)));
240}
241
242auto FpsMax() {
Evan Shrubsole5fd40602020-05-25 16:19:54 +0200243 return WantsFps(Eq(kDefaultFramerate));
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +0200244}
245
246auto FpsUnlimited() {
Evan Shrubsole5fd40602020-05-25 16:19:54 +0200247 return WantsFps(Eq(std::numeric_limits<int>::max()));
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +0200248}
249
250auto FpsMatchesResolutionMax(Matcher<int> fps_matcher) {
Evan Shrubsole5fd40602020-05-25 16:19:54 +0200251 return AllOf(WantsFps(fps_matcher), ResolutionMax());
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +0200252}
253
254auto FpsMaxResolutionMatches(Matcher<int> pixel_matcher) {
Evan Shrubsole5fd40602020-05-25 16:19:54 +0200255 return AllOf(FpsMax(), WantsMaxPixels(pixel_matcher));
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +0200256}
257
258auto FpsMaxResolutionMax() {
259 return AllOf(FpsMax(), ResolutionMax());
260}
261
262auto UnlimitedSinkWants() {
263 return AllOf(FpsUnlimited(), ResolutionMax());
264}
265
266auto FpsInRangeForPixelsInBalanced(int last_frame_pixels) {
267 Matcher<int> fps_range_matcher;
268
269 if (last_frame_pixels <= 320 * 240) {
270 fps_range_matcher = AllOf(Ge(7), Le(10));
Åsa Perssonc5a74ff2020-09-20 17:50:00 +0200271 } else if (last_frame_pixels <= 480 * 360) {
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +0200272 fps_range_matcher = AllOf(Ge(10), Le(15));
273 } else if (last_frame_pixels <= 640 * 480) {
274 fps_range_matcher = Ge(15);
275 } else {
276 fps_range_matcher = Eq(kDefaultFramerate);
277 }
278 return Field("max_framerate_fps", &rtc::VideoSinkWants::max_framerate_fps,
279 fps_range_matcher);
280}
281
Evan Shrubsole5fd40602020-05-25 16:19:54 +0200282auto FpsEqResolutionEqTo(const rtc::VideoSinkWants& other_wants) {
283 return AllOf(WantsFps(Eq(other_wants.max_framerate_fps)),
284 WantsMaxPixels(Eq(other_wants.max_pixel_count)));
285}
286
287auto FpsMaxResolutionLt(const rtc::VideoSinkWants& other_wants) {
288 return AllOf(FpsMax(), WantsMaxPixels(Lt(other_wants.max_pixel_count)));
289}
290
291auto FpsMaxResolutionGt(const rtc::VideoSinkWants& other_wants) {
292 return AllOf(FpsMax(), WantsMaxPixels(Gt(other_wants.max_pixel_count)));
293}
294
295auto FpsLtResolutionEq(const rtc::VideoSinkWants& other_wants) {
296 return AllOf(WantsFps(Lt(other_wants.max_framerate_fps)),
297 WantsMaxPixels(Eq(other_wants.max_pixel_count)));
298}
299
300auto FpsGtResolutionEq(const rtc::VideoSinkWants& other_wants) {
301 return AllOf(WantsFps(Gt(other_wants.max_framerate_fps)),
302 WantsMaxPixels(Eq(other_wants.max_pixel_count)));
303}
304
305auto FpsEqResolutionLt(const rtc::VideoSinkWants& other_wants) {
306 return AllOf(WantsFps(Eq(other_wants.max_framerate_fps)),
307 WantsMaxPixels(Lt(other_wants.max_pixel_count)));
308}
309
310auto FpsEqResolutionGt(const rtc::VideoSinkWants& other_wants) {
311 return AllOf(WantsFps(Eq(other_wants.max_framerate_fps)),
312 WantsMaxPixels(Gt(other_wants.max_pixel_count)));
313}
314
mflodmancc3d4422017-08-03 08:27:51 -0700315class VideoStreamEncoderUnderTest : public VideoStreamEncoder {
perkj803d97f2016-11-01 11:45:46 -0700316 public:
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200317 VideoStreamEncoderUnderTest(TimeController* time_controller,
318 TaskQueueFactory* task_queue_factory,
319 SendStatisticsProxy* stats_proxy,
320 const VideoStreamEncoderSettings& settings)
321 : VideoStreamEncoder(time_controller->GetClock(),
Sebastian Jansson572c60f2019-03-04 18:30:41 +0100322 1 /* number_of_cores */,
Yves Gerey665174f2018-06-19 15:03:05 +0200323 stats_proxy,
324 settings,
Yves Gerey665174f2018-06-19 15:03:05 +0200325 std::unique_ptr<OveruseFrameDetector>(
326 overuse_detector_proxy_ =
Sebastian Jansson74682c12019-03-01 11:50:20 +0100327 new CpuOveruseDetectorProxy(stats_proxy)),
Evan Shrubsoleaa6fbc12020-02-25 16:26:01 +0100328 task_queue_factory),
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200329 time_controller_(time_controller),
Henrik Boström5cc28b02020-06-01 17:59:05 +0200330 fake_cpu_resource_(FakeResource::Create("FakeResource[CPU]")),
Henrik Boström0f0aa9c2020-06-02 13:02:36 +0200331 fake_quality_resource_(FakeResource::Create("FakeResource[QP]")),
Evan Shrubsoledc4d4222020-07-09 11:47:10 +0200332 fake_adaptation_constraint_("FakeAdaptationConstraint") {
Henrik Boströmc55516d2020-05-11 16:29:22 +0200333 InjectAdaptationResource(fake_quality_resource_,
Evan Shrubsolece0a11d2020-04-16 11:36:55 +0200334 VideoAdaptationReason::kQuality);
Henrik Boströmc55516d2020-05-11 16:29:22 +0200335 InjectAdaptationResource(fake_cpu_resource_, VideoAdaptationReason::kCpu);
Henrik Boström0f0aa9c2020-06-02 13:02:36 +0200336 InjectAdaptationConstraint(&fake_adaptation_constraint_);
Evan Shrubsoleaa6fbc12020-02-25 16:26:01 +0100337 }
perkj803d97f2016-11-01 11:45:46 -0700338
Henrik Boström381d1092020-05-12 18:49:07 +0200339 void SetSourceAndWaitForRestrictionsUpdated(
340 rtc::VideoSourceInterface<VideoFrame>* source,
341 const DegradationPreference& degradation_preference) {
Henrik Boström0f0aa9c2020-06-02 13:02:36 +0200342 FakeVideoSourceRestrictionsListener listener;
343 AddRestrictionsListenerForTesting(&listener);
Henrik Boström381d1092020-05-12 18:49:07 +0200344 SetSource(source, degradation_preference);
345 listener.restrictions_updated_event()->Wait(5000);
Henrik Boström0f0aa9c2020-06-02 13:02:36 +0200346 RemoveRestrictionsListenerForTesting(&listener);
Henrik Boström381d1092020-05-12 18:49:07 +0200347 }
348
349 void SetSourceAndWaitForFramerateUpdated(
350 rtc::VideoSourceInterface<VideoFrame>* source,
351 const DegradationPreference& degradation_preference) {
352 overuse_detector_proxy_->framerate_updated_event()->Reset();
353 SetSource(source, degradation_preference);
354 overuse_detector_proxy_->framerate_updated_event()->Wait(5000);
355 }
356
357 void OnBitrateUpdatedAndWaitForManagedResources(
358 DataRate target_bitrate,
359 DataRate stable_target_bitrate,
360 DataRate link_allocation,
361 uint8_t fraction_lost,
362 int64_t round_trip_time_ms,
363 double cwnd_reduce_ratio) {
364 OnBitrateUpdated(target_bitrate, stable_target_bitrate, link_allocation,
365 fraction_lost, round_trip_time_ms, cwnd_reduce_ratio);
366 // Bitrate is updated on the encoder queue.
367 WaitUntilTaskQueueIsIdle();
Henrik Boström381d1092020-05-12 18:49:07 +0200368 }
369
kthelgason2fc52542017-03-03 00:24:41 -0800370 // This is used as a synchronisation mechanism, to make sure that the
371 // encoder queue is not blocked before we start sending it frames.
372 void WaitUntilTaskQueueIsIdle() {
Niels Möllerc572ff32018-11-07 08:43:50 +0100373 rtc::Event event;
Yves Gerey665174f2018-06-19 15:03:05 +0200374 encoder_queue()->PostTask([&event] { event.Set(); });
kthelgason2fc52542017-03-03 00:24:41 -0800375 ASSERT_TRUE(event.Wait(5000));
376 }
377
Henrik Boström91aa7322020-04-28 12:24:33 +0200378 // Triggers resource usage measurements on the fake CPU resource.
Åsa Perssonb67c44c2019-09-24 15:25:32 +0200379 void TriggerCpuOveruse() {
Henrik Boström91aa7322020-04-28 12:24:33 +0200380 rtc::Event event;
Evan Shrubsole85728412020-08-25 13:12:12 +0200381 encoder_queue()->PostTask([this, &event] {
Henrik Boström0f0aa9c2020-06-02 13:02:36 +0200382 fake_cpu_resource_->SetUsageState(ResourceUsageState::kOveruse);
Henrik Boström91aa7322020-04-28 12:24:33 +0200383 event.Set();
384 });
385 ASSERT_TRUE(event.Wait(5000));
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200386 time_controller_->AdvanceTime(TimeDelta::Millis(0));
Henrik Boström91aa7322020-04-28 12:24:33 +0200387 }
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200388
Henrik Boström91aa7322020-04-28 12:24:33 +0200389 void TriggerCpuUnderuse() {
390 rtc::Event event;
Evan Shrubsole85728412020-08-25 13:12:12 +0200391 encoder_queue()->PostTask([this, &event] {
Henrik Boström0f0aa9c2020-06-02 13:02:36 +0200392 fake_cpu_resource_->SetUsageState(ResourceUsageState::kUnderuse);
Henrik Boström91aa7322020-04-28 12:24:33 +0200393 event.Set();
394 });
395 ASSERT_TRUE(event.Wait(5000));
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200396 time_controller_->AdvanceTime(TimeDelta::Millis(0));
Åsa Perssonb67c44c2019-09-24 15:25:32 +0200397 }
kthelgason876222f2016-11-29 01:44:11 -0800398
Henrik Boström91aa7322020-04-28 12:24:33 +0200399 // Triggers resource usage measurements on the fake quality resource.
Åsa Perssonb67c44c2019-09-24 15:25:32 +0200400 void TriggerQualityLow() {
Henrik Boström91aa7322020-04-28 12:24:33 +0200401 rtc::Event event;
Evan Shrubsole85728412020-08-25 13:12:12 +0200402 encoder_queue()->PostTask([this, &event] {
Henrik Boström0f0aa9c2020-06-02 13:02:36 +0200403 fake_quality_resource_->SetUsageState(ResourceUsageState::kOveruse);
Henrik Boström91aa7322020-04-28 12:24:33 +0200404 event.Set();
405 });
406 ASSERT_TRUE(event.Wait(5000));
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200407 time_controller_->AdvanceTime(TimeDelta::Millis(0));
Åsa Perssonb67c44c2019-09-24 15:25:32 +0200408 }
Åsa Perssonb67c44c2019-09-24 15:25:32 +0200409 void TriggerQualityHigh() {
Henrik Boström91aa7322020-04-28 12:24:33 +0200410 rtc::Event event;
Evan Shrubsole85728412020-08-25 13:12:12 +0200411 encoder_queue()->PostTask([this, &event] {
Henrik Boström0f0aa9c2020-06-02 13:02:36 +0200412 fake_quality_resource_->SetUsageState(ResourceUsageState::kUnderuse);
Henrik Boström91aa7322020-04-28 12:24:33 +0200413 event.Set();
414 });
415 ASSERT_TRUE(event.Wait(5000));
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200416 time_controller_->AdvanceTime(TimeDelta::Millis(0));
Henrik Boström91aa7322020-04-28 12:24:33 +0200417 }
418
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200419 TimeController* const time_controller_;
Niels Möller7dc26b72017-12-06 10:27:48 +0100420 CpuOveruseDetectorProxy* overuse_detector_proxy_;
Henrik Boströmc55516d2020-05-11 16:29:22 +0200421 rtc::scoped_refptr<FakeResource> fake_cpu_resource_;
422 rtc::scoped_refptr<FakeResource> fake_quality_resource_;
Henrik Boström0f0aa9c2020-06-02 13:02:36 +0200423 FakeAdaptationConstraint fake_adaptation_constraint_;
perkj803d97f2016-11-01 11:45:46 -0700424};
425
Noah Richards51db4212019-06-12 06:59:12 -0700426// Simulates simulcast behavior and makes highest stream resolutions divisible
427// by 4.
428class CroppingVideoStreamFactory
429 : public VideoEncoderConfig::VideoStreamFactoryInterface {
430 public:
431 explicit CroppingVideoStreamFactory(size_t num_temporal_layers, int framerate)
432 : num_temporal_layers_(num_temporal_layers), framerate_(framerate) {
433 EXPECT_GT(num_temporal_layers, 0u);
434 EXPECT_GT(framerate, 0);
435 }
436
437 private:
438 std::vector<VideoStream> CreateEncoderStreams(
439 int width,
440 int height,
441 const VideoEncoderConfig& encoder_config) override {
442 std::vector<VideoStream> streams = test::CreateVideoStreams(
443 width - width % 4, height - height % 4, encoder_config);
444 for (VideoStream& stream : streams) {
445 stream.num_temporal_layers = num_temporal_layers_;
446 stream.max_framerate = framerate_;
447 }
448 return streams;
449 }
450
451 const size_t num_temporal_layers_;
452 const int framerate_;
453};
454
sprangb1ca0732017-02-01 08:38:12 -0800455class AdaptingFrameForwarder : public test::FrameForwarder {
456 public:
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200457 explicit AdaptingFrameForwarder(TimeController* time_controller)
458 : time_controller_(time_controller), adaptation_enabled_(false) {}
asaperssonfab67072017-04-04 05:51:49 -0700459 ~AdaptingFrameForwarder() override {}
sprangb1ca0732017-02-01 08:38:12 -0800460
461 void set_adaptation_enabled(bool enabled) {
Markus Handella3765182020-07-08 13:13:32 +0200462 MutexLock lock(&mutex_);
sprangb1ca0732017-02-01 08:38:12 -0800463 adaptation_enabled_ = enabled;
464 }
465
asaperssonfab67072017-04-04 05:51:49 -0700466 bool adaption_enabled() const {
Markus Handella3765182020-07-08 13:13:32 +0200467 MutexLock lock(&mutex_);
sprangb1ca0732017-02-01 08:38:12 -0800468 return adaptation_enabled_;
469 }
470
asapersson09f05612017-05-15 23:40:18 -0700471 rtc::VideoSinkWants last_wants() const {
Markus Handella3765182020-07-08 13:13:32 +0200472 MutexLock lock(&mutex_);
asapersson09f05612017-05-15 23:40:18 -0700473 return last_wants_;
474 }
475
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200476 absl::optional<int> last_sent_width() const { return last_width_; }
477 absl::optional<int> last_sent_height() const { return last_height_; }
Jonathan Yubc771b72017-12-08 17:04:29 -0800478
sprangb1ca0732017-02-01 08:38:12 -0800479 void IncomingCapturedFrame(const VideoFrame& video_frame) override {
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200480 RTC_DCHECK(time_controller_->GetMainThread()->IsCurrent());
481 time_controller_->AdvanceTime(TimeDelta::Millis(0));
482
sprangb1ca0732017-02-01 08:38:12 -0800483 int cropped_width = 0;
484 int cropped_height = 0;
485 int out_width = 0;
486 int out_height = 0;
sprangc5d62e22017-04-02 23:53:04 -0700487 if (adaption_enabled()) {
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200488 RTC_DLOG(INFO) << "IncomingCapturedFrame: AdaptFrameResolution()"
489 << "w=" << video_frame.width()
490 << "h=" << video_frame.height();
sprangc5d62e22017-04-02 23:53:04 -0700491 if (adapter_.AdaptFrameResolution(
492 video_frame.width(), video_frame.height(),
493 video_frame.timestamp_us() * 1000, &cropped_width,
494 &cropped_height, &out_width, &out_height)) {
Artem Titov1ebfb6a2019-01-03 23:49:37 +0100495 VideoFrame adapted_frame =
496 VideoFrame::Builder()
497 .set_video_frame_buffer(new rtc::RefCountedObject<TestBuffer>(
498 nullptr, out_width, out_height))
499 .set_timestamp_rtp(99)
500 .set_timestamp_ms(99)
501 .set_rotation(kVideoRotation_0)
502 .build();
sprangc5d62e22017-04-02 23:53:04 -0700503 adapted_frame.set_ntp_time_ms(video_frame.ntp_time_ms());
Ilya Nikolaevskiy648b9d72019-12-03 16:54:17 +0100504 if (video_frame.has_update_rect()) {
505 adapted_frame.set_update_rect(
506 video_frame.update_rect().ScaleWithFrame(
507 video_frame.width(), video_frame.height(), 0, 0,
508 video_frame.width(), video_frame.height(), out_width,
509 out_height));
510 }
sprangc5d62e22017-04-02 23:53:04 -0700511 test::FrameForwarder::IncomingCapturedFrame(adapted_frame);
Jonathan Yubc771b72017-12-08 17:04:29 -0800512 last_width_.emplace(adapted_frame.width());
513 last_height_.emplace(adapted_frame.height());
514 } else {
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200515 last_width_ = absl::nullopt;
516 last_height_ = absl::nullopt;
sprangc5d62e22017-04-02 23:53:04 -0700517 }
sprangb1ca0732017-02-01 08:38:12 -0800518 } else {
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200519 RTC_DLOG(INFO) << "IncomingCapturedFrame: adaptation not enabled";
sprangb1ca0732017-02-01 08:38:12 -0800520 test::FrameForwarder::IncomingCapturedFrame(video_frame);
Jonathan Yubc771b72017-12-08 17:04:29 -0800521 last_width_.emplace(video_frame.width());
522 last_height_.emplace(video_frame.height());
sprangb1ca0732017-02-01 08:38:12 -0800523 }
524 }
525
526 void AddOrUpdateSink(rtc::VideoSinkInterface<VideoFrame>* sink,
527 const rtc::VideoSinkWants& wants) override {
Markus Handella3765182020-07-08 13:13:32 +0200528 MutexLock lock(&mutex_);
Markus Handell16038ab2020-05-28 08:37:30 +0200529 last_wants_ = sink_wants_locked();
Rasmus Brandt287e4642019-11-15 16:56:01 +0100530 adapter_.OnSinkWants(wants);
Markus Handell16038ab2020-05-28 08:37:30 +0200531 test::FrameForwarder::AddOrUpdateSinkLocked(sink, wants);
sprangb1ca0732017-02-01 08:38:12 -0800532 }
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200533
534 TimeController* const time_controller_;
sprangb1ca0732017-02-01 08:38:12 -0800535 cricket::VideoAdapter adapter_;
Markus Handella3765182020-07-08 13:13:32 +0200536 bool adaptation_enabled_ RTC_GUARDED_BY(mutex_);
537 rtc::VideoSinkWants last_wants_ RTC_GUARDED_BY(mutex_);
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200538 absl::optional<int> last_width_;
539 absl::optional<int> last_height_;
sprangb1ca0732017-02-01 08:38:12 -0800540};
sprangc5d62e22017-04-02 23:53:04 -0700541
Niels Möller213618e2018-07-24 09:29:58 +0200542// TODO(nisse): Mock only VideoStreamEncoderObserver.
sprangc5d62e22017-04-02 23:53:04 -0700543class MockableSendStatisticsProxy : public SendStatisticsProxy {
544 public:
545 MockableSendStatisticsProxy(Clock* clock,
546 const VideoSendStream::Config& config,
547 VideoEncoderConfig::ContentType content_type)
548 : SendStatisticsProxy(clock, config, content_type) {}
549
550 VideoSendStream::Stats GetStats() override {
Markus Handella3765182020-07-08 13:13:32 +0200551 MutexLock lock(&lock_);
sprangc5d62e22017-04-02 23:53:04 -0700552 if (mock_stats_)
553 return *mock_stats_;
554 return SendStatisticsProxy::GetStats();
555 }
556
Niels Möller213618e2018-07-24 09:29:58 +0200557 int GetInputFrameRate() const override {
Markus Handella3765182020-07-08 13:13:32 +0200558 MutexLock lock(&lock_);
Niels Möller213618e2018-07-24 09:29:58 +0200559 if (mock_stats_)
560 return mock_stats_->input_frame_rate;
561 return SendStatisticsProxy::GetInputFrameRate();
562 }
sprangc5d62e22017-04-02 23:53:04 -0700563 void SetMockStats(const VideoSendStream::Stats& stats) {
Markus Handella3765182020-07-08 13:13:32 +0200564 MutexLock lock(&lock_);
sprangc5d62e22017-04-02 23:53:04 -0700565 mock_stats_.emplace(stats);
566 }
567
568 void ResetMockStats() {
Markus Handella3765182020-07-08 13:13:32 +0200569 MutexLock lock(&lock_);
sprangc5d62e22017-04-02 23:53:04 -0700570 mock_stats_.reset();
571 }
572
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200573 void SetDroppedFrameCallback(std::function<void(DropReason)> callback) {
574 on_frame_dropped_ = std::move(callback);
575 }
576
sprangc5d62e22017-04-02 23:53:04 -0700577 private:
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200578 void OnFrameDropped(DropReason reason) override {
579 SendStatisticsProxy::OnFrameDropped(reason);
580 if (on_frame_dropped_)
581 on_frame_dropped_(reason);
582 }
583
Markus Handella3765182020-07-08 13:13:32 +0200584 mutable Mutex lock_;
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200585 absl::optional<VideoSendStream::Stats> mock_stats_ RTC_GUARDED_BY(lock_);
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200586 std::function<void(DropReason)> on_frame_dropped_;
sprangc5d62e22017-04-02 23:53:04 -0700587};
588
philipel9b058032020-02-10 11:30:00 +0100589class MockEncoderSelector
590 : public VideoEncoderFactory::EncoderSelectorInterface {
591 public:
Danil Chapovalov91fdc602020-05-14 19:17:51 +0200592 MOCK_METHOD(void,
593 OnCurrentEncoder,
594 (const SdpVideoFormat& format),
595 (override));
596 MOCK_METHOD(absl::optional<SdpVideoFormat>,
597 OnAvailableBitrate,
598 (const DataRate& rate),
599 (override));
600 MOCK_METHOD(absl::optional<SdpVideoFormat>, OnEncoderBroken, (), (override));
philipel9b058032020-02-10 11:30:00 +0100601};
602
perkj803d97f2016-11-01 11:45:46 -0700603} // namespace
604
mflodmancc3d4422017-08-03 08:27:51 -0700605class VideoStreamEncoderTest : public ::testing::Test {
perkj26091b12016-09-01 01:17:40 -0700606 public:
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200607 static const int kDefaultTimeoutMs = 1000;
perkj26091b12016-09-01 01:17:40 -0700608
mflodmancc3d4422017-08-03 08:27:51 -0700609 VideoStreamEncoderTest()
perkj26091b12016-09-01 01:17:40 -0700610 : video_send_config_(VideoSendStream::Config(nullptr)),
perkjfa10b552016-10-02 23:45:26 -0700611 codec_width_(320),
612 codec_height_(240),
Åsa Persson8c1bf952018-09-13 10:42:19 +0200613 max_framerate_(kDefaultFramerate),
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200614 fake_encoder_(&time_controller_),
Niels Möller4db138e2018-04-19 09:04:13 +0200615 encoder_factory_(&fake_encoder_),
sprangc5d62e22017-04-02 23:53:04 -0700616 stats_proxy_(new MockableSendStatisticsProxy(
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200617 time_controller_.GetClock(),
perkj803d97f2016-11-01 11:45:46 -0700618 video_send_config_,
619 webrtc::VideoEncoderConfig::ContentType::kRealtimeVideo)),
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200620 sink_(&time_controller_, &fake_encoder_) {}
perkj26091b12016-09-01 01:17:40 -0700621
622 void SetUp() override {
perkj803d97f2016-11-01 11:45:46 -0700623 metrics::Reset();
perkj26091b12016-09-01 01:17:40 -0700624 video_send_config_ = VideoSendStream::Config(nullptr);
Niels Möller4db138e2018-04-19 09:04:13 +0200625 video_send_config_.encoder_settings.encoder_factory = &encoder_factory_;
Jiawei Ouc2ebe212018-11-08 10:02:56 -0800626 video_send_config_.encoder_settings.bitrate_allocator_factory =
Sergey Silkin5ee69672019-07-02 14:18:34 +0200627 &bitrate_allocator_factory_;
Niels Möller259a4972018-04-05 15:36:51 +0200628 video_send_config_.rtp.payload_name = "FAKE";
629 video_send_config_.rtp.payload_type = 125;
perkj26091b12016-09-01 01:17:40 -0700630
Per512ecb32016-09-23 15:52:06 +0200631 VideoEncoderConfig video_encoder_config;
Niels Möller259a4972018-04-05 15:36:51 +0200632 test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
Åsa Persson17107062020-10-08 08:57:51 +0200633 EXPECT_EQ(1u, video_encoder_config.simulcast_layers.size());
634 video_encoder_config.simulcast_layers[0].num_temporal_layers = 1;
635 video_encoder_config.simulcast_layers[0].max_framerate = max_framerate_;
Erik Språng08127a92016-11-16 16:41:30 +0100636 video_encoder_config_ = video_encoder_config.Copy();
sprang4847ae62017-06-27 07:06:52 -0700637
Niels Möllerf1338562018-04-26 09:51:47 +0200638 ConfigureEncoder(std::move(video_encoder_config));
asapersson5f7226f2016-11-25 04:37:00 -0800639 }
640
Niels Möllerf1338562018-04-26 09:51:47 +0200641 void ConfigureEncoder(VideoEncoderConfig video_encoder_config) {
mflodmancc3d4422017-08-03 08:27:51 -0700642 if (video_stream_encoder_)
643 video_stream_encoder_->Stop();
644 video_stream_encoder_.reset(new VideoStreamEncoderUnderTest(
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200645 &time_controller_, GetTaskQueueFactory(), stats_proxy_.get(),
646 video_send_config_.encoder_settings));
mflodmancc3d4422017-08-03 08:27:51 -0700647 video_stream_encoder_->SetSink(&sink_, false /* rotation_applied */);
648 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700649 &video_source_, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
mflodmancc3d4422017-08-03 08:27:51 -0700650 video_stream_encoder_->SetStartBitrate(kTargetBitrateBps);
651 video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config),
Niels Möllerf1338562018-04-26 09:51:47 +0200652 kMaxPayloadLength);
mflodmancc3d4422017-08-03 08:27:51 -0700653 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
asapersson5f7226f2016-11-25 04:37:00 -0800654 }
655
Per Kjellanderdcef6412020-10-07 15:09:05 +0200656 void ResetEncoder(
657 const std::string& payload_name,
658 size_t num_streams,
659 size_t num_temporal_layers,
660 unsigned char num_spatial_layers,
661 bool screenshare,
662 VideoStreamEncoderSettings::BitrateAllocationCallbackType
663 allocation_cb_type =
664 VideoStreamEncoderSettings::BitrateAllocationCallbackType::
665 kVideoBitrateAllocationWhenScreenSharing) {
Niels Möller259a4972018-04-05 15:36:51 +0200666 video_send_config_.rtp.payload_name = payload_name;
Per Kjellanderdcef6412020-10-07 15:09:05 +0200667 video_send_config_.encoder_settings.allocation_cb_type = allocation_cb_type;
asapersson5f7226f2016-11-25 04:37:00 -0800668
669 VideoEncoderConfig video_encoder_config;
Åsa Persson17107062020-10-08 08:57:51 +0200670 test::FillEncoderConfiguration(PayloadStringToCodecType(payload_name),
671 num_streams, &video_encoder_config);
672 for (auto& layer : video_encoder_config.simulcast_layers) {
673 layer.num_temporal_layers = num_temporal_layers;
674 layer.max_framerate = kDefaultFramerate;
675 }
Erik Språngd7329ca2019-02-21 21:19:53 +0100676 video_encoder_config.max_bitrate_bps =
677 num_streams == 1 ? kTargetBitrateBps : kSimulcastTargetBitrateBps;
sprang4847ae62017-06-27 07:06:52 -0700678 video_encoder_config.content_type =
679 screenshare ? VideoEncoderConfig::ContentType::kScreen
680 : VideoEncoderConfig::ContentType::kRealtimeVideo;
emircanbbcc3562017-08-18 00:28:40 -0700681 if (payload_name == "VP9") {
682 VideoCodecVP9 vp9_settings = VideoEncoder::GetDefaultVp9Settings();
683 vp9_settings.numberOfSpatialLayers = num_spatial_layers;
Mirta Dvornicic97910da2020-07-14 15:29:23 +0200684 vp9_settings.automaticResizeOn = num_spatial_layers <= 1;
emircanbbcc3562017-08-18 00:28:40 -0700685 video_encoder_config.encoder_specific_settings =
686 new rtc::RefCountedObject<
687 VideoEncoderConfig::Vp9EncoderSpecificSettings>(vp9_settings);
688 }
Niels Möllerf1338562018-04-26 09:51:47 +0200689 ConfigureEncoder(std::move(video_encoder_config));
perkj26091b12016-09-01 01:17:40 -0700690 }
691
sprang57c2fff2017-01-16 06:24:02 -0800692 VideoFrame CreateFrame(int64_t ntp_time_ms,
693 rtc::Event* destruction_event) const {
Artem Titov1ebfb6a2019-01-03 23:49:37 +0100694 VideoFrame frame =
695 VideoFrame::Builder()
696 .set_video_frame_buffer(new rtc::RefCountedObject<TestBuffer>(
697 destruction_event, codec_width_, codec_height_))
698 .set_timestamp_rtp(99)
699 .set_timestamp_ms(99)
700 .set_rotation(kVideoRotation_0)
701 .build();
sprang57c2fff2017-01-16 06:24:02 -0800702 frame.set_ntp_time_ms(ntp_time_ms);
perkj26091b12016-09-01 01:17:40 -0700703 return frame;
704 }
705
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +0100706 VideoFrame CreateFrameWithUpdatedPixel(int64_t ntp_time_ms,
707 rtc::Event* destruction_event,
708 int offset_x) const {
709 VideoFrame frame =
710 VideoFrame::Builder()
711 .set_video_frame_buffer(new rtc::RefCountedObject<TestBuffer>(
712 destruction_event, codec_width_, codec_height_))
713 .set_timestamp_rtp(99)
714 .set_timestamp_ms(99)
715 .set_rotation(kVideoRotation_0)
Artem Titov5256d8b2019-12-02 10:34:12 +0100716 .set_update_rect(VideoFrame::UpdateRect{offset_x, 0, 1, 1})
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +0100717 .build();
718 frame.set_ntp_time_ms(ntp_time_ms);
719 return frame;
720 }
721
sprang57c2fff2017-01-16 06:24:02 -0800722 VideoFrame CreateFrame(int64_t ntp_time_ms, int width, int height) const {
Artem Titov1ebfb6a2019-01-03 23:49:37 +0100723 VideoFrame frame =
724 VideoFrame::Builder()
725 .set_video_frame_buffer(
726 new rtc::RefCountedObject<TestBuffer>(nullptr, width, height))
727 .set_timestamp_rtp(99)
728 .set_timestamp_ms(99)
729 .set_rotation(kVideoRotation_0)
730 .build();
sprang57c2fff2017-01-16 06:24:02 -0800731 frame.set_ntp_time_ms(ntp_time_ms);
sprangc5d62e22017-04-02 23:53:04 -0700732 frame.set_timestamp_us(ntp_time_ms * 1000);
perkj803d97f2016-11-01 11:45:46 -0700733 return frame;
734 }
735
Evan Shrubsole895556e2020-10-05 09:15:13 +0200736 VideoFrame CreateNV12Frame(int64_t ntp_time_ms, int width, int height) const {
737 VideoFrame frame =
738 VideoFrame::Builder()
739 .set_video_frame_buffer(NV12Buffer::Create(width, height))
740 .set_timestamp_rtp(99)
741 .set_timestamp_ms(99)
742 .set_rotation(kVideoRotation_0)
743 .build();
744 frame.set_ntp_time_ms(ntp_time_ms);
745 frame.set_timestamp_us(ntp_time_ms * 1000);
746 return frame;
747 }
748
Noah Richards51db4212019-06-12 06:59:12 -0700749 VideoFrame CreateFakeNativeFrame(int64_t ntp_time_ms,
750 rtc::Event* destruction_event,
751 int width,
752 int height) const {
753 VideoFrame frame =
754 VideoFrame::Builder()
755 .set_video_frame_buffer(new rtc::RefCountedObject<FakeNativeBuffer>(
756 destruction_event, width, height))
757 .set_timestamp_rtp(99)
758 .set_timestamp_ms(99)
759 .set_rotation(kVideoRotation_0)
760 .build();
761 frame.set_ntp_time_ms(ntp_time_ms);
762 return frame;
763 }
764
Evan Shrubsole895556e2020-10-05 09:15:13 +0200765 VideoFrame CreateFakeNV12NativeFrame(int64_t ntp_time_ms,
766 rtc::Event* destruction_event,
767 int width,
768 int height) const {
769 VideoFrame frame = VideoFrame::Builder()
770 .set_video_frame_buffer(
771 new rtc::RefCountedObject<FakeNV12NativeBuffer>(
772 destruction_event, width, height))
773 .set_timestamp_rtp(99)
774 .set_timestamp_ms(99)
775 .set_rotation(kVideoRotation_0)
776 .build();
777 frame.set_ntp_time_ms(ntp_time_ms);
778 return frame;
779 }
780
Noah Richards51db4212019-06-12 06:59:12 -0700781 VideoFrame CreateFakeNativeFrame(int64_t ntp_time_ms,
782 rtc::Event* destruction_event) const {
783 return CreateFakeNativeFrame(ntp_time_ms, destruction_event, codec_width_,
784 codec_height_);
785 }
786
Åsa Perssonc29cb2c2019-03-25 12:06:59 +0100787 void VerifyAllocatedBitrate(const VideoBitrateAllocation& expected_bitrate) {
Henrik Boström381d1092020-05-12 18:49:07 +0200788 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100789 DataRate::BitsPerSec(kTargetBitrateBps),
790 DataRate::BitsPerSec(kTargetBitrateBps),
791 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Åsa Perssonc29cb2c2019-03-25 12:06:59 +0100792
793 video_source_.IncomingCapturedFrame(
794 CreateFrame(1, codec_width_, codec_height_));
795 WaitForEncodedFrame(1);
Per Kjellanderdcef6412020-10-07 15:09:05 +0200796 EXPECT_EQ(expected_bitrate, sink_.GetLastVideoBitrateAllocation());
Åsa Perssonc29cb2c2019-03-25 12:06:59 +0100797 }
798
sprang4847ae62017-06-27 07:06:52 -0700799 void WaitForEncodedFrame(int64_t expected_ntp_time) {
800 sink_.WaitForEncodedFrame(expected_ntp_time);
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200801 AdvanceTime(TimeDelta::Seconds(1) / max_framerate_);
sprang4847ae62017-06-27 07:06:52 -0700802 }
803
804 bool TimedWaitForEncodedFrame(int64_t expected_ntp_time, int64_t timeout_ms) {
805 bool ok = sink_.TimedWaitForEncodedFrame(expected_ntp_time, timeout_ms);
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200806 AdvanceTime(TimeDelta::Seconds(1) / max_framerate_);
sprang4847ae62017-06-27 07:06:52 -0700807 return ok;
808 }
809
810 void WaitForEncodedFrame(uint32_t expected_width, uint32_t expected_height) {
811 sink_.WaitForEncodedFrame(expected_width, expected_height);
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200812 AdvanceTime(TimeDelta::Seconds(1) / max_framerate_);
sprang4847ae62017-06-27 07:06:52 -0700813 }
814
815 void ExpectDroppedFrame() {
816 sink_.ExpectDroppedFrame();
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200817 AdvanceTime(TimeDelta::Seconds(1) / max_framerate_);
sprang4847ae62017-06-27 07:06:52 -0700818 }
819
820 bool WaitForFrame(int64_t timeout_ms) {
821 bool ok = sink_.WaitForFrame(timeout_ms);
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200822 AdvanceTime(TimeDelta::Seconds(1) / max_framerate_);
sprang4847ae62017-06-27 07:06:52 -0700823 return ok;
824 }
825
perkj26091b12016-09-01 01:17:40 -0700826 class TestEncoder : public test::FakeEncoder {
827 public:
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200828 explicit TestEncoder(TimeController* time_controller)
829 : FakeEncoder(time_controller->GetClock()),
830 time_controller_(time_controller) {
831 RTC_DCHECK(time_controller_);
832 }
perkj26091b12016-09-01 01:17:40 -0700833
asaperssonfab67072017-04-04 05:51:49 -0700834 VideoCodec codec_config() const {
Markus Handella3765182020-07-08 13:13:32 +0200835 MutexLock lock(&mutex_);
perkjfa10b552016-10-02 23:45:26 -0700836 return config_;
837 }
838
839 void BlockNextEncode() {
Markus Handella3765182020-07-08 13:13:32 +0200840 MutexLock lock(&local_mutex_);
perkjfa10b552016-10-02 23:45:26 -0700841 block_next_encode_ = true;
842 }
843
Erik Språngaed30702018-11-05 12:57:17 +0100844 VideoEncoder::EncoderInfo GetEncoderInfo() const override {
Markus Handella3765182020-07-08 13:13:32 +0200845 MutexLock lock(&local_mutex_);
Erik Språng9d69cbe2020-10-22 17:44:42 +0200846 EncoderInfo info = FakeEncoder::GetEncoderInfo();
Erik Språngb7cb7b52019-02-26 15:52:33 +0100847 if (initialized_ == EncoderState::kInitialized) {
Mirta Dvornicicccc1b572019-01-15 12:42:18 +0100848 if (quality_scaling_) {
Åsa Perssone644a032019-11-08 15:56:00 +0100849 info.scaling_settings = VideoEncoder::ScalingSettings(
850 kQpLow, kQpHigh, kMinPixelsPerFrame);
Mirta Dvornicicccc1b572019-01-15 12:42:18 +0100851 }
852 info.is_hardware_accelerated = is_hardware_accelerated_;
Åsa Perssonc29cb2c2019-03-25 12:06:59 +0100853 for (int i = 0; i < kMaxSpatialLayers; ++i) {
854 if (temporal_layers_supported_[i]) {
855 int num_layers = temporal_layers_supported_[i].value() ? 2 : 1;
856 info.fps_allocation[i].resize(num_layers);
857 }
858 }
Erik Språngaed30702018-11-05 12:57:17 +0100859 }
Sergey Silkin6456e352019-07-08 17:56:40 +0200860
861 info.resolution_bitrate_limits = resolution_bitrate_limits_;
Rasmus Brandt5cad55b2019-12-19 09:47:11 +0100862 info.requested_resolution_alignment = requested_resolution_alignment_;
Åsa Perssonc5a74ff2020-09-20 17:50:00 +0200863 info.apply_alignment_to_all_simulcast_layers =
864 apply_alignment_to_all_simulcast_layers_;
Evan Shrubsoleb556b082020-10-08 14:56:45 +0200865 info.preferred_pixel_formats = preferred_pixel_formats_;
Erik Språngaed30702018-11-05 12:57:17 +0100866 return info;
kthelgason876222f2016-11-29 01:44:11 -0800867 }
868
Erik Språngb7cb7b52019-02-26 15:52:33 +0100869 int32_t RegisterEncodeCompleteCallback(
870 EncodedImageCallback* callback) override {
Markus Handella3765182020-07-08 13:13:32 +0200871 MutexLock lock(&local_mutex_);
Erik Språngb7cb7b52019-02-26 15:52:33 +0100872 encoded_image_callback_ = callback;
873 return FakeEncoder::RegisterEncodeCompleteCallback(callback);
874 }
875
perkjfa10b552016-10-02 23:45:26 -0700876 void ContinueEncode() { continue_encode_event_.Set(); }
877
878 void CheckLastTimeStampsMatch(int64_t ntp_time_ms,
879 uint32_t timestamp) const {
Markus Handella3765182020-07-08 13:13:32 +0200880 MutexLock lock(&local_mutex_);
perkjfa10b552016-10-02 23:45:26 -0700881 EXPECT_EQ(timestamp_, timestamp);
882 EXPECT_EQ(ntp_time_ms_, ntp_time_ms);
883 }
884
kthelgason2fc52542017-03-03 00:24:41 -0800885 void SetQualityScaling(bool b) {
Markus Handella3765182020-07-08 13:13:32 +0200886 MutexLock lock(&local_mutex_);
kthelgason2fc52542017-03-03 00:24:41 -0800887 quality_scaling_ = b;
888 }
kthelgasonad9010c2017-02-14 00:46:51 -0800889
Rasmus Brandt5cad55b2019-12-19 09:47:11 +0100890 void SetRequestedResolutionAlignment(int requested_resolution_alignment) {
Markus Handella3765182020-07-08 13:13:32 +0200891 MutexLock lock(&local_mutex_);
Rasmus Brandt5cad55b2019-12-19 09:47:11 +0100892 requested_resolution_alignment_ = requested_resolution_alignment;
893 }
894
Åsa Perssonc5a74ff2020-09-20 17:50:00 +0200895 void SetApplyAlignmentToAllSimulcastLayers(bool b) {
896 MutexLock lock(&local_mutex_);
897 apply_alignment_to_all_simulcast_layers_ = b;
898 }
899
Mirta Dvornicicccc1b572019-01-15 12:42:18 +0100900 void SetIsHardwareAccelerated(bool is_hardware_accelerated) {
Markus Handella3765182020-07-08 13:13:32 +0200901 MutexLock lock(&local_mutex_);
Mirta Dvornicicccc1b572019-01-15 12:42:18 +0100902 is_hardware_accelerated_ = is_hardware_accelerated;
903 }
904
Åsa Perssonc29cb2c2019-03-25 12:06:59 +0100905 void SetTemporalLayersSupported(size_t spatial_idx, bool supported) {
906 RTC_DCHECK_LT(spatial_idx, kMaxSpatialLayers);
Markus Handella3765182020-07-08 13:13:32 +0200907 MutexLock lock(&local_mutex_);
Åsa Perssonc29cb2c2019-03-25 12:06:59 +0100908 temporal_layers_supported_[spatial_idx] = supported;
909 }
910
Sergey Silkin6456e352019-07-08 17:56:40 +0200911 void SetResolutionBitrateLimits(
912 std::vector<ResolutionBitrateLimits> thresholds) {
Markus Handella3765182020-07-08 13:13:32 +0200913 MutexLock lock(&local_mutex_);
Sergey Silkin6456e352019-07-08 17:56:40 +0200914 resolution_bitrate_limits_ = thresholds;
915 }
916
sprangfe627f32017-03-29 08:24:59 -0700917 void ForceInitEncodeFailure(bool force_failure) {
Markus Handella3765182020-07-08 13:13:32 +0200918 MutexLock lock(&local_mutex_);
sprangfe627f32017-03-29 08:24:59 -0700919 force_init_encode_failed_ = force_failure;
920 }
921
Niels Möller6bb5ab92019-01-11 11:11:10 +0100922 void SimulateOvershoot(double rate_factor) {
Markus Handella3765182020-07-08 13:13:32 +0200923 MutexLock lock(&local_mutex_);
Niels Möller6bb5ab92019-01-11 11:11:10 +0100924 rate_factor_ = rate_factor;
925 }
926
Erik Språngd7329ca2019-02-21 21:19:53 +0100927 uint32_t GetLastFramerate() const {
Markus Handella3765182020-07-08 13:13:32 +0200928 MutexLock lock(&local_mutex_);
Niels Möller6bb5ab92019-01-11 11:11:10 +0100929 return last_framerate_;
930 }
931
Erik Språngd7329ca2019-02-21 21:19:53 +0100932 VideoFrame::UpdateRect GetLastUpdateRect() const {
Markus Handella3765182020-07-08 13:13:32 +0200933 MutexLock lock(&local_mutex_);
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +0100934 return last_update_rect_;
935 }
936
Niels Möller87e2d782019-03-07 10:18:23 +0100937 const std::vector<VideoFrameType>& LastFrameTypes() const {
Markus Handella3765182020-07-08 13:13:32 +0200938 MutexLock lock(&local_mutex_);
Erik Språngd7329ca2019-02-21 21:19:53 +0100939 return last_frame_types_;
940 }
941
942 void InjectFrame(const VideoFrame& input_image, bool keyframe) {
Niels Möller87e2d782019-03-07 10:18:23 +0100943 const std::vector<VideoFrameType> frame_type = {
Niels Möller8f7ce222019-03-21 15:43:58 +0100944 keyframe ? VideoFrameType::kVideoFrameKey
945 : VideoFrameType::kVideoFrameDelta};
Erik Språngd7329ca2019-02-21 21:19:53 +0100946 {
Markus Handella3765182020-07-08 13:13:32 +0200947 MutexLock lock(&local_mutex_);
Erik Språngd7329ca2019-02-21 21:19:53 +0100948 last_frame_types_ = frame_type;
949 }
Niels Möllerb859b322019-03-07 12:40:01 +0100950 FakeEncoder::Encode(input_image, &frame_type);
Erik Språngd7329ca2019-02-21 21:19:53 +0100951 }
952
Erik Språngb7cb7b52019-02-26 15:52:33 +0100953 void InjectEncodedImage(const EncodedImage& image) {
Markus Handella3765182020-07-08 13:13:32 +0200954 MutexLock lock(&local_mutex_);
Danil Chapovalov2549f172020-08-12 17:30:36 +0200955 encoded_image_callback_->OnEncodedImage(image, nullptr);
Erik Språngb7cb7b52019-02-26 15:52:33 +0100956 }
957
Mirta Dvornicic97910da2020-07-14 15:29:23 +0200958 void SetEncodedImageData(
959 rtc::scoped_refptr<EncodedImageBufferInterface> encoded_image_data) {
Markus Handella3765182020-07-08 13:13:32 +0200960 MutexLock lock(&local_mutex_);
Mirta Dvornicic97910da2020-07-14 15:29:23 +0200961 encoded_image_data_ = encoded_image_data;
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +0200962 }
963
Erik Språngd7329ca2019-02-21 21:19:53 +0100964 void ExpectNullFrame() {
Markus Handella3765182020-07-08 13:13:32 +0200965 MutexLock lock(&local_mutex_);
Erik Språngd7329ca2019-02-21 21:19:53 +0100966 expect_null_frame_ = true;
967 }
968
Erik Språng5056af02019-09-02 15:53:11 +0200969 absl::optional<VideoEncoder::RateControlParameters>
970 GetAndResetLastRateControlSettings() {
971 auto settings = last_rate_control_settings_;
972 last_rate_control_settings_.reset();
973 return settings;
Erik Språngd7329ca2019-02-21 21:19:53 +0100974 }
975
Evan Shrubsole895556e2020-10-05 09:15:13 +0200976 absl::optional<VideoFrameBuffer::Type> GetLastInputPixelFormat() {
977 MutexLock lock(&local_mutex_);
978 return last_input_pixel_format_;
979 }
980
Sergey Silkin5ee69672019-07-02 14:18:34 +0200981 int GetNumEncoderInitializations() const {
Markus Handella3765182020-07-08 13:13:32 +0200982 MutexLock lock(&local_mutex_);
Sergey Silkin5ee69672019-07-02 14:18:34 +0200983 return num_encoder_initializations_;
984 }
985
Evan Shrubsole7c079f62019-09-26 09:55:03 +0200986 int GetNumSetRates() const {
Markus Handella3765182020-07-08 13:13:32 +0200987 MutexLock lock(&local_mutex_);
Evan Shrubsole7c079f62019-09-26 09:55:03 +0200988 return num_set_rates_;
989 }
990
Åsa Perssonc5a74ff2020-09-20 17:50:00 +0200991 VideoCodec video_codec() const {
992 MutexLock lock(&local_mutex_);
993 return video_codec_;
994 }
995
Evan Shrubsoleb556b082020-10-08 14:56:45 +0200996 void SetPreferredPixelFormats(
997 absl::InlinedVector<VideoFrameBuffer::Type, kMaxPreferredPixelFormats>
998 pixel_formats) {
999 MutexLock lock(&local_mutex_);
1000 preferred_pixel_formats_ = std::move(pixel_formats);
1001 }
1002
perkjfa10b552016-10-02 23:45:26 -07001003 private:
perkj26091b12016-09-01 01:17:40 -07001004 int32_t Encode(const VideoFrame& input_image,
Niels Möller87e2d782019-03-07 10:18:23 +01001005 const std::vector<VideoFrameType>* frame_types) override {
perkj26091b12016-09-01 01:17:40 -07001006 bool block_encode;
1007 {
Markus Handella3765182020-07-08 13:13:32 +02001008 MutexLock lock(&local_mutex_);
Erik Språngd7329ca2019-02-21 21:19:53 +01001009 if (expect_null_frame_) {
1010 EXPECT_EQ(input_image.timestamp(), 0u);
1011 EXPECT_EQ(input_image.width(), 1);
1012 last_frame_types_ = *frame_types;
1013 expect_null_frame_ = false;
1014 } else {
1015 EXPECT_GT(input_image.timestamp(), timestamp_);
1016 EXPECT_GT(input_image.ntp_time_ms(), ntp_time_ms_);
1017 EXPECT_EQ(input_image.timestamp(), input_image.ntp_time_ms() * 90);
1018 }
perkj26091b12016-09-01 01:17:40 -07001019
1020 timestamp_ = input_image.timestamp();
1021 ntp_time_ms_ = input_image.ntp_time_ms();
perkj803d97f2016-11-01 11:45:46 -07001022 last_input_width_ = input_image.width();
1023 last_input_height_ = input_image.height();
perkj26091b12016-09-01 01:17:40 -07001024 block_encode = block_next_encode_;
1025 block_next_encode_ = false;
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001026 last_update_rect_ = input_image.update_rect();
Erik Språngd7329ca2019-02-21 21:19:53 +01001027 last_frame_types_ = *frame_types;
Evan Shrubsole895556e2020-10-05 09:15:13 +02001028 last_input_pixel_format_ = input_image.video_frame_buffer()->type();
perkj26091b12016-09-01 01:17:40 -07001029 }
Niels Möllerb859b322019-03-07 12:40:01 +01001030 int32_t result = FakeEncoder::Encode(input_image, frame_types);
perkj26091b12016-09-01 01:17:40 -07001031 if (block_encode)
perkja49cbd32016-09-16 07:53:41 -07001032 EXPECT_TRUE(continue_encode_event_.Wait(kDefaultTimeoutMs));
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02001033
perkj26091b12016-09-01 01:17:40 -07001034 return result;
1035 }
1036
Niels Möller08ae7ce2020-09-23 15:58:12 +02001037 CodecSpecificInfo EncodeHook(
1038 EncodedImage& encoded_image,
1039 rtc::scoped_refptr<EncodedImageBuffer> buffer) override {
Danil Chapovalov2549f172020-08-12 17:30:36 +02001040 CodecSpecificInfo codec_specific;
Mirta Dvornicic97910da2020-07-14 15:29:23 +02001041 {
1042 MutexLock lock(&mutex_);
Danil Chapovalov2549f172020-08-12 17:30:36 +02001043 codec_specific.codecType = config_.codecType;
Mirta Dvornicic97910da2020-07-14 15:29:23 +02001044 }
1045 MutexLock lock(&local_mutex_);
1046 if (encoded_image_data_) {
Danil Chapovalov2549f172020-08-12 17:30:36 +02001047 encoded_image.SetEncodedData(encoded_image_data_);
Mirta Dvornicic97910da2020-07-14 15:29:23 +02001048 }
Danil Chapovalov2549f172020-08-12 17:30:36 +02001049 return codec_specific;
Mirta Dvornicic97910da2020-07-14 15:29:23 +02001050 }
1051
sprangfe627f32017-03-29 08:24:59 -07001052 int32_t InitEncode(const VideoCodec* config,
Elad Alon370f93a2019-06-11 14:57:57 +02001053 const Settings& settings) override {
1054 int res = FakeEncoder::InitEncode(config, settings);
Sergey Silkin5ee69672019-07-02 14:18:34 +02001055
Markus Handella3765182020-07-08 13:13:32 +02001056 MutexLock lock(&local_mutex_);
Erik Språngb7cb7b52019-02-26 15:52:33 +01001057 EXPECT_EQ(initialized_, EncoderState::kUninitialized);
Sergey Silkin5ee69672019-07-02 14:18:34 +02001058
1059 ++num_encoder_initializations_;
Åsa Perssonc5a74ff2020-09-20 17:50:00 +02001060 video_codec_ = *config;
Sergey Silkin5ee69672019-07-02 14:18:34 +02001061
Erik Språng82fad3d2018-03-21 09:57:23 +01001062 if (config->codecType == kVideoCodecVP8) {
sprangfe627f32017-03-29 08:24:59 -07001063 // Simulate setting up temporal layers, in order to validate the life
1064 // cycle of these objects.
Elad Aloncde8ab22019-03-20 11:56:20 +01001065 Vp8TemporalLayersFactory factory;
Elad Alon45befc52019-07-02 11:20:09 +02001066 frame_buffer_controller_ =
1067 factory.Create(*config, settings, &fec_controller_override_);
sprangfe627f32017-03-29 08:24:59 -07001068 }
Erik Språngb7cb7b52019-02-26 15:52:33 +01001069 if (force_init_encode_failed_) {
1070 initialized_ = EncoderState::kInitializationFailed;
sprangfe627f32017-03-29 08:24:59 -07001071 return -1;
Erik Språngb7cb7b52019-02-26 15:52:33 +01001072 }
Mirta Dvornicicccc1b572019-01-15 12:42:18 +01001073
Erik Språngb7cb7b52019-02-26 15:52:33 +01001074 initialized_ = EncoderState::kInitialized;
sprangfe627f32017-03-29 08:24:59 -07001075 return res;
1076 }
1077
Erik Språngb7cb7b52019-02-26 15:52:33 +01001078 int32_t Release() override {
Markus Handella3765182020-07-08 13:13:32 +02001079 MutexLock lock(&local_mutex_);
Erik Språngb7cb7b52019-02-26 15:52:33 +01001080 EXPECT_NE(initialized_, EncoderState::kUninitialized);
1081 initialized_ = EncoderState::kUninitialized;
1082 return FakeEncoder::Release();
1083 }
1084
Erik Språng16cb8f52019-04-12 13:59:09 +02001085 void SetRates(const RateControlParameters& parameters) {
Markus Handella3765182020-07-08 13:13:32 +02001086 MutexLock lock(&local_mutex_);
Evan Shrubsole7c079f62019-09-26 09:55:03 +02001087 num_set_rates_++;
Niels Möller6bb5ab92019-01-11 11:11:10 +01001088 VideoBitrateAllocation adjusted_rate_allocation;
1089 for (size_t si = 0; si < kMaxSpatialLayers; ++si) {
1090 for (size_t ti = 0; ti < kMaxTemporalStreams; ++ti) {
Erik Språng16cb8f52019-04-12 13:59:09 +02001091 if (parameters.bitrate.HasBitrate(si, ti)) {
Niels Möller6bb5ab92019-01-11 11:11:10 +01001092 adjusted_rate_allocation.SetBitrate(
1093 si, ti,
Erik Språng16cb8f52019-04-12 13:59:09 +02001094 static_cast<uint32_t>(parameters.bitrate.GetBitrate(si, ti) *
Niels Möller6bb5ab92019-01-11 11:11:10 +01001095 rate_factor_));
1096 }
1097 }
1098 }
Erik Språng16cb8f52019-04-12 13:59:09 +02001099 last_framerate_ = static_cast<uint32_t>(parameters.framerate_fps + 0.5);
Erik Språng5056af02019-09-02 15:53:11 +02001100 last_rate_control_settings_ = parameters;
Erik Språng16cb8f52019-04-12 13:59:09 +02001101 RateControlParameters adjusted_paramters = parameters;
1102 adjusted_paramters.bitrate = adjusted_rate_allocation;
1103 FakeEncoder::SetRates(adjusted_paramters);
Niels Möller6bb5ab92019-01-11 11:11:10 +01001104 }
1105
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02001106 TimeController* const time_controller_;
Markus Handella3765182020-07-08 13:13:32 +02001107 mutable Mutex local_mutex_;
Erik Språngb7cb7b52019-02-26 15:52:33 +01001108 enum class EncoderState {
1109 kUninitialized,
1110 kInitializationFailed,
1111 kInitialized
Markus Handella3765182020-07-08 13:13:32 +02001112 } initialized_ RTC_GUARDED_BY(local_mutex_) = EncoderState::kUninitialized;
1113 bool block_next_encode_ RTC_GUARDED_BY(local_mutex_) = false;
perkj26091b12016-09-01 01:17:40 -07001114 rtc::Event continue_encode_event_;
Markus Handella3765182020-07-08 13:13:32 +02001115 uint32_t timestamp_ RTC_GUARDED_BY(local_mutex_) = 0;
1116 int64_t ntp_time_ms_ RTC_GUARDED_BY(local_mutex_) = 0;
1117 int last_input_width_ RTC_GUARDED_BY(local_mutex_) = 0;
1118 int last_input_height_ RTC_GUARDED_BY(local_mutex_) = 0;
1119 bool quality_scaling_ RTC_GUARDED_BY(local_mutex_) = true;
1120 int requested_resolution_alignment_ RTC_GUARDED_BY(local_mutex_) = 1;
Åsa Perssonc5a74ff2020-09-20 17:50:00 +02001121 bool apply_alignment_to_all_simulcast_layers_ RTC_GUARDED_BY(local_mutex_) =
1122 false;
Markus Handella3765182020-07-08 13:13:32 +02001123 bool is_hardware_accelerated_ RTC_GUARDED_BY(local_mutex_) = false;
Mirta Dvornicic97910da2020-07-14 15:29:23 +02001124 rtc::scoped_refptr<EncodedImageBufferInterface> encoded_image_data_
1125 RTC_GUARDED_BY(local_mutex_);
Elad Aloncde8ab22019-03-20 11:56:20 +01001126 std::unique_ptr<Vp8FrameBufferController> frame_buffer_controller_
Markus Handella3765182020-07-08 13:13:32 +02001127 RTC_GUARDED_BY(local_mutex_);
Åsa Perssonc29cb2c2019-03-25 12:06:59 +01001128 absl::optional<bool>
1129 temporal_layers_supported_[kMaxSpatialLayers] RTC_GUARDED_BY(
Markus Handella3765182020-07-08 13:13:32 +02001130 local_mutex_);
1131 bool force_init_encode_failed_ RTC_GUARDED_BY(local_mutex_) = false;
1132 double rate_factor_ RTC_GUARDED_BY(local_mutex_) = 1.0;
1133 uint32_t last_framerate_ RTC_GUARDED_BY(local_mutex_) = 0;
Erik Språng5056af02019-09-02 15:53:11 +02001134 absl::optional<VideoEncoder::RateControlParameters>
1135 last_rate_control_settings_;
Markus Handella3765182020-07-08 13:13:32 +02001136 VideoFrame::UpdateRect last_update_rect_ RTC_GUARDED_BY(local_mutex_) = {
1137 0, 0, 0, 0};
Niels Möller87e2d782019-03-07 10:18:23 +01001138 std::vector<VideoFrameType> last_frame_types_;
Erik Språngd7329ca2019-02-21 21:19:53 +01001139 bool expect_null_frame_ = false;
Markus Handella3765182020-07-08 13:13:32 +02001140 EncodedImageCallback* encoded_image_callback_ RTC_GUARDED_BY(local_mutex_) =
1141 nullptr;
Evan Shrubsolefb862742020-03-16 16:18:36 +01001142 NiceMock<MockFecControllerOverride> fec_controller_override_;
Markus Handella3765182020-07-08 13:13:32 +02001143 int num_encoder_initializations_ RTC_GUARDED_BY(local_mutex_) = 0;
Sergey Silkin6456e352019-07-08 17:56:40 +02001144 std::vector<ResolutionBitrateLimits> resolution_bitrate_limits_
Markus Handella3765182020-07-08 13:13:32 +02001145 RTC_GUARDED_BY(local_mutex_);
1146 int num_set_rates_ RTC_GUARDED_BY(local_mutex_) = 0;
Åsa Perssonc5a74ff2020-09-20 17:50:00 +02001147 VideoCodec video_codec_ RTC_GUARDED_BY(local_mutex_);
Evan Shrubsole895556e2020-10-05 09:15:13 +02001148 absl::optional<VideoFrameBuffer::Type> last_input_pixel_format_
1149 RTC_GUARDED_BY(local_mutex_);
Evan Shrubsoleb556b082020-10-08 14:56:45 +02001150 absl::InlinedVector<VideoFrameBuffer::Type, kMaxPreferredPixelFormats>
1151 preferred_pixel_formats_ RTC_GUARDED_BY(local_mutex_);
perkj26091b12016-09-01 01:17:40 -07001152 };
1153
mflodmancc3d4422017-08-03 08:27:51 -07001154 class TestSink : public VideoStreamEncoder::EncoderSink {
perkj26091b12016-09-01 01:17:40 -07001155 public:
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02001156 TestSink(TimeController* time_controller, TestEncoder* test_encoder)
1157 : time_controller_(time_controller), test_encoder_(test_encoder) {
1158 RTC_DCHECK(time_controller_);
1159 }
perkj26091b12016-09-01 01:17:40 -07001160
perkj26091b12016-09-01 01:17:40 -07001161 void WaitForEncodedFrame(int64_t expected_ntp_time) {
sprang4847ae62017-06-27 07:06:52 -07001162 EXPECT_TRUE(
1163 TimedWaitForEncodedFrame(expected_ntp_time, kDefaultTimeoutMs));
1164 }
1165
1166 bool TimedWaitForEncodedFrame(int64_t expected_ntp_time,
1167 int64_t timeout_ms) {
perkj26091b12016-09-01 01:17:40 -07001168 uint32_t timestamp = 0;
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02001169 if (!WaitForFrame(timeout_ms))
sprang4847ae62017-06-27 07:06:52 -07001170 return false;
perkj26091b12016-09-01 01:17:40 -07001171 {
Markus Handella3765182020-07-08 13:13:32 +02001172 MutexLock lock(&mutex_);
sprangb1ca0732017-02-01 08:38:12 -08001173 timestamp = last_timestamp_;
perkj26091b12016-09-01 01:17:40 -07001174 }
1175 test_encoder_->CheckLastTimeStampsMatch(expected_ntp_time, timestamp);
sprang4847ae62017-06-27 07:06:52 -07001176 return true;
perkj26091b12016-09-01 01:17:40 -07001177 }
1178
sprangb1ca0732017-02-01 08:38:12 -08001179 void WaitForEncodedFrame(uint32_t expected_width,
1180 uint32_t expected_height) {
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02001181 EXPECT_TRUE(WaitForFrame(kDefaultTimeoutMs));
Åsa Perssonc74d8da2017-12-04 14:13:56 +01001182 CheckLastFrameSizeMatches(expected_width, expected_height);
sprangc5d62e22017-04-02 23:53:04 -07001183 }
1184
Åsa Perssonc74d8da2017-12-04 14:13:56 +01001185 void CheckLastFrameSizeMatches(uint32_t expected_width,
sprangc5d62e22017-04-02 23:53:04 -07001186 uint32_t expected_height) {
sprangb1ca0732017-02-01 08:38:12 -08001187 uint32_t width = 0;
1188 uint32_t height = 0;
sprangb1ca0732017-02-01 08:38:12 -08001189 {
Markus Handella3765182020-07-08 13:13:32 +02001190 MutexLock lock(&mutex_);
sprangb1ca0732017-02-01 08:38:12 -08001191 width = last_width_;
1192 height = last_height_;
1193 }
1194 EXPECT_EQ(expected_height, height);
1195 EXPECT_EQ(expected_width, width);
1196 }
1197
Ilya Nikolaevskiyba96e2f2019-06-04 15:15:14 +02001198 void CheckLastFrameRotationMatches(VideoRotation expected_rotation) {
1199 VideoRotation rotation;
1200 {
Markus Handella3765182020-07-08 13:13:32 +02001201 MutexLock lock(&mutex_);
Ilya Nikolaevskiyba96e2f2019-06-04 15:15:14 +02001202 rotation = last_rotation_;
1203 }
1204 EXPECT_EQ(expected_rotation, rotation);
1205 }
1206
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02001207 void ExpectDroppedFrame() { EXPECT_FALSE(WaitForFrame(100)); }
kthelgason2bc68642017-02-07 07:02:22 -08001208
sprangc5d62e22017-04-02 23:53:04 -07001209 bool WaitForFrame(int64_t timeout_ms) {
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02001210 RTC_DCHECK(time_controller_->GetMainThread()->IsCurrent());
1211 bool ret = encoded_frame_event_.Wait(timeout_ms);
1212 time_controller_->AdvanceTime(TimeDelta::Millis(0));
1213 return ret;
sprangc5d62e22017-04-02 23:53:04 -07001214 }
1215
perkj26091b12016-09-01 01:17:40 -07001216 void SetExpectNoFrames() {
Markus Handella3765182020-07-08 13:13:32 +02001217 MutexLock lock(&mutex_);
perkj26091b12016-09-01 01:17:40 -07001218 expect_frames_ = false;
1219 }
1220
asaperssonfab67072017-04-04 05:51:49 -07001221 int number_of_reconfigurations() const {
Markus Handella3765182020-07-08 13:13:32 +02001222 MutexLock lock(&mutex_);
Per512ecb32016-09-23 15:52:06 +02001223 return number_of_reconfigurations_;
1224 }
1225
asaperssonfab67072017-04-04 05:51:49 -07001226 int last_min_transmit_bitrate() const {
Markus Handella3765182020-07-08 13:13:32 +02001227 MutexLock lock(&mutex_);
Per512ecb32016-09-23 15:52:06 +02001228 return min_transmit_bitrate_bps_;
1229 }
1230
Erik Språngd7329ca2019-02-21 21:19:53 +01001231 void SetNumExpectedLayers(size_t num_layers) {
Markus Handella3765182020-07-08 13:13:32 +02001232 MutexLock lock(&mutex_);
Erik Språngd7329ca2019-02-21 21:19:53 +01001233 num_expected_layers_ = num_layers;
1234 }
1235
Erik Språngb7cb7b52019-02-26 15:52:33 +01001236 int64_t GetLastCaptureTimeMs() const {
Markus Handella3765182020-07-08 13:13:32 +02001237 MutexLock lock(&mutex_);
Erik Språngb7cb7b52019-02-26 15:52:33 +01001238 return last_capture_time_ms_;
1239 }
1240
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +02001241 std::vector<uint8_t> GetLastEncodedImageData() {
Markus Handella3765182020-07-08 13:13:32 +02001242 MutexLock lock(&mutex_);
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +02001243 return std::move(last_encoded_image_data_);
1244 }
1245
Per Kjellanderdcef6412020-10-07 15:09:05 +02001246 VideoBitrateAllocation GetLastVideoBitrateAllocation() {
1247 MutexLock lock(&mutex_);
1248 return last_bitrate_allocation_;
1249 }
1250
1251 int number_of_bitrate_allocations() const {
1252 MutexLock lock(&mutex_);
1253 return number_of_bitrate_allocations_;
1254 }
1255
Per Kjellandera9434842020-10-15 17:53:22 +02001256 VideoLayersAllocation GetLastVideoLayersAllocation() {
1257 MutexLock lock(&mutex_);
1258 return last_layers_allocation_;
1259 }
1260
1261 int number_of_layers_allocations() const {
1262 MutexLock lock(&mutex_);
1263 return number_of_layers_allocations_;
1264 }
1265
perkj26091b12016-09-01 01:17:40 -07001266 private:
sergeyu2cb155a2016-11-04 11:39:29 -07001267 Result OnEncodedImage(
1268 const EncodedImage& encoded_image,
Danil Chapovalov2549f172020-08-12 17:30:36 +02001269 const CodecSpecificInfo* codec_specific_info) override {
Markus Handella3765182020-07-08 13:13:32 +02001270 MutexLock lock(&mutex_);
Per512ecb32016-09-23 15:52:06 +02001271 EXPECT_TRUE(expect_frames_);
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +02001272 last_encoded_image_data_ = std::vector<uint8_t>(
1273 encoded_image.data(), encoded_image.data() + encoded_image.size());
Erik Språngd7329ca2019-02-21 21:19:53 +01001274 uint32_t timestamp = encoded_image.Timestamp();
1275 if (last_timestamp_ != timestamp) {
1276 num_received_layers_ = 1;
1277 } else {
1278 ++num_received_layers_;
1279 }
1280 last_timestamp_ = timestamp;
Erik Språngb7cb7b52019-02-26 15:52:33 +01001281 last_capture_time_ms_ = encoded_image.capture_time_ms_;
sprangb1ca0732017-02-01 08:38:12 -08001282 last_width_ = encoded_image._encodedWidth;
1283 last_height_ = encoded_image._encodedHeight;
Ilya Nikolaevskiyba96e2f2019-06-04 15:15:14 +02001284 last_rotation_ = encoded_image.rotation_;
Erik Språngd7329ca2019-02-21 21:19:53 +01001285 if (num_received_layers_ == num_expected_layers_) {
1286 encoded_frame_event_.Set();
1287 }
sprangb1ca0732017-02-01 08:38:12 -08001288 return Result(Result::OK, last_timestamp_);
Per512ecb32016-09-23 15:52:06 +02001289 }
1290
Rasmus Brandtc402dbe2019-02-04 11:09:46 +01001291 void OnEncoderConfigurationChanged(
1292 std::vector<VideoStream> streams,
Ilya Nikolaevskiy93be66c2020-04-02 14:10:27 +02001293 bool is_svc,
Rasmus Brandtc402dbe2019-02-04 11:09:46 +01001294 VideoEncoderConfig::ContentType content_type,
1295 int min_transmit_bitrate_bps) override {
Markus Handella3765182020-07-08 13:13:32 +02001296 MutexLock lock(&mutex_);
Per512ecb32016-09-23 15:52:06 +02001297 ++number_of_reconfigurations_;
1298 min_transmit_bitrate_bps_ = min_transmit_bitrate_bps;
1299 }
1300
Per Kjellanderdcef6412020-10-07 15:09:05 +02001301 void OnBitrateAllocationUpdated(
1302 const VideoBitrateAllocation& allocation) override {
1303 MutexLock lock(&mutex_);
1304 ++number_of_bitrate_allocations_;
1305 last_bitrate_allocation_ = allocation;
1306 }
1307
Per Kjellandera9434842020-10-15 17:53:22 +02001308 void OnVideoLayersAllocationUpdated(
1309 VideoLayersAllocation allocation) override {
1310 MutexLock lock(&mutex_);
1311 ++number_of_layers_allocations_;
1312 last_layers_allocation_ = allocation;
1313 rtc::StringBuilder log;
1314 for (const auto& layer : allocation.active_spatial_layers) {
1315 log << layer.width << "x" << layer.height << "@" << layer.frame_rate_fps
1316 << "[";
1317 for (const auto target_bitrate :
1318 layer.target_bitrate_per_temporal_layer) {
1319 log << target_bitrate.kbps() << ",";
1320 }
1321 log << "]";
1322 }
1323 RTC_DLOG(INFO) << "OnVideoLayersAllocationUpdated " << log.str();
1324 }
1325
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02001326 TimeController* const time_controller_;
Markus Handella3765182020-07-08 13:13:32 +02001327 mutable Mutex mutex_;
perkj26091b12016-09-01 01:17:40 -07001328 TestEncoder* test_encoder_;
1329 rtc::Event encoded_frame_event_;
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +02001330 std::vector<uint8_t> last_encoded_image_data_;
sprangb1ca0732017-02-01 08:38:12 -08001331 uint32_t last_timestamp_ = 0;
Erik Språngb7cb7b52019-02-26 15:52:33 +01001332 int64_t last_capture_time_ms_ = 0;
sprangb1ca0732017-02-01 08:38:12 -08001333 uint32_t last_height_ = 0;
1334 uint32_t last_width_ = 0;
Ilya Nikolaevskiyba96e2f2019-06-04 15:15:14 +02001335 VideoRotation last_rotation_ = kVideoRotation_0;
Erik Språngd7329ca2019-02-21 21:19:53 +01001336 size_t num_expected_layers_ = 1;
1337 size_t num_received_layers_ = 0;
perkj26091b12016-09-01 01:17:40 -07001338 bool expect_frames_ = true;
Per512ecb32016-09-23 15:52:06 +02001339 int number_of_reconfigurations_ = 0;
1340 int min_transmit_bitrate_bps_ = 0;
Per Kjellanderdcef6412020-10-07 15:09:05 +02001341 VideoBitrateAllocation last_bitrate_allocation_ RTC_GUARDED_BY(&mutex_);
1342 int number_of_bitrate_allocations_ RTC_GUARDED_BY(&mutex_) = 0;
Per Kjellandera9434842020-10-15 17:53:22 +02001343 VideoLayersAllocation last_layers_allocation_ RTC_GUARDED_BY(&mutex_);
1344 int number_of_layers_allocations_ RTC_GUARDED_BY(&mutex_) = 0;
perkj26091b12016-09-01 01:17:40 -07001345 };
1346
Sergey Silkin5ee69672019-07-02 14:18:34 +02001347 class VideoBitrateAllocatorProxyFactory
1348 : public VideoBitrateAllocatorFactory {
1349 public:
1350 VideoBitrateAllocatorProxyFactory()
1351 : bitrate_allocator_factory_(
1352 CreateBuiltinVideoBitrateAllocatorFactory()) {}
1353
1354 std::unique_ptr<VideoBitrateAllocator> CreateVideoBitrateAllocator(
1355 const VideoCodec& codec) override {
Markus Handella3765182020-07-08 13:13:32 +02001356 MutexLock lock(&mutex_);
Sergey Silkin5ee69672019-07-02 14:18:34 +02001357 codec_config_ = codec;
1358 return bitrate_allocator_factory_->CreateVideoBitrateAllocator(codec);
1359 }
1360
1361 VideoCodec codec_config() const {
Markus Handella3765182020-07-08 13:13:32 +02001362 MutexLock lock(&mutex_);
Sergey Silkin5ee69672019-07-02 14:18:34 +02001363 return codec_config_;
1364 }
1365
1366 private:
1367 std::unique_ptr<VideoBitrateAllocatorFactory> bitrate_allocator_factory_;
1368
Markus Handella3765182020-07-08 13:13:32 +02001369 mutable Mutex mutex_;
1370 VideoCodec codec_config_ RTC_GUARDED_BY(mutex_);
Sergey Silkin5ee69672019-07-02 14:18:34 +02001371 };
1372
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02001373 Clock* clock() { return time_controller_.GetClock(); }
1374 void AdvanceTime(TimeDelta duration) {
1375 time_controller_.AdvanceTime(duration);
1376 }
1377
1378 int64_t CurrentTimeMs() { return clock()->CurrentTime().ms(); }
1379
1380 protected:
1381 virtual TaskQueueFactory* GetTaskQueueFactory() {
1382 return time_controller_.GetTaskQueueFactory();
1383 }
1384
1385 GlobalSimulatedTimeController time_controller_{Timestamp::Micros(1234)};
perkj26091b12016-09-01 01:17:40 -07001386 VideoSendStream::Config video_send_config_;
Erik Språng08127a92016-11-16 16:41:30 +01001387 VideoEncoderConfig video_encoder_config_;
Per512ecb32016-09-23 15:52:06 +02001388 int codec_width_;
1389 int codec_height_;
sprang4847ae62017-06-27 07:06:52 -07001390 int max_framerate_;
perkj26091b12016-09-01 01:17:40 -07001391 TestEncoder fake_encoder_;
Niels Möllercbcbc222018-09-28 09:07:24 +02001392 test::VideoEncoderProxyFactory encoder_factory_;
Sergey Silkin5ee69672019-07-02 14:18:34 +02001393 VideoBitrateAllocatorProxyFactory bitrate_allocator_factory_;
sprangc5d62e22017-04-02 23:53:04 -07001394 std::unique_ptr<MockableSendStatisticsProxy> stats_proxy_;
perkj26091b12016-09-01 01:17:40 -07001395 TestSink sink_;
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02001396 AdaptingFrameForwarder video_source_{&time_controller_};
mflodmancc3d4422017-08-03 08:27:51 -07001397 std::unique_ptr<VideoStreamEncoderUnderTest> video_stream_encoder_;
perkj26091b12016-09-01 01:17:40 -07001398};
1399
mflodmancc3d4422017-08-03 08:27:51 -07001400TEST_F(VideoStreamEncoderTest, EncodeOneFrame) {
Henrik Boström381d1092020-05-12 18:49:07 +02001401 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001402 DataRate::BitsPerSec(kTargetBitrateBps),
1403 DataRate::BitsPerSec(kTargetBitrateBps),
1404 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Niels Möllerc572ff32018-11-07 08:43:50 +01001405 rtc::Event frame_destroyed_event;
perkja49cbd32016-09-16 07:53:41 -07001406 video_source_.IncomingCapturedFrame(CreateFrame(1, &frame_destroyed_event));
sprang4847ae62017-06-27 07:06:52 -07001407 WaitForEncodedFrame(1);
perkja49cbd32016-09-16 07:53:41 -07001408 EXPECT_TRUE(frame_destroyed_event.Wait(kDefaultTimeoutMs));
mflodmancc3d4422017-08-03 08:27:51 -07001409 video_stream_encoder_->Stop();
perkj26091b12016-09-01 01:17:40 -07001410}
1411
mflodmancc3d4422017-08-03 08:27:51 -07001412TEST_F(VideoStreamEncoderTest, DropsFramesBeforeFirstOnBitrateUpdated) {
perkj26091b12016-09-01 01:17:40 -07001413 // Dropped since no target bitrate has been set.
Niels Möllerc572ff32018-11-07 08:43:50 +01001414 rtc::Event frame_destroyed_event;
Sebastian Janssona3177052018-04-10 13:05:49 +02001415 // The encoder will cache up to one frame for a short duration. Adding two
1416 // frames means that the first frame will be dropped and the second frame will
1417 // be sent when the encoder is enabled.
perkja49cbd32016-09-16 07:53:41 -07001418 video_source_.IncomingCapturedFrame(CreateFrame(1, &frame_destroyed_event));
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02001419 AdvanceTime(TimeDelta::Millis(10));
Sebastian Janssona3177052018-04-10 13:05:49 +02001420 video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
perkja49cbd32016-09-16 07:53:41 -07001421 EXPECT_TRUE(frame_destroyed_event.Wait(kDefaultTimeoutMs));
perkj26091b12016-09-01 01:17:40 -07001422
Henrik Boström381d1092020-05-12 18:49:07 +02001423 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001424 DataRate::BitsPerSec(kTargetBitrateBps),
1425 DataRate::BitsPerSec(kTargetBitrateBps),
1426 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
perkj26091b12016-09-01 01:17:40 -07001427
Sebastian Janssona3177052018-04-10 13:05:49 +02001428 // The pending frame should be received.
sprang4847ae62017-06-27 07:06:52 -07001429 WaitForEncodedFrame(2);
Sebastian Janssona3177052018-04-10 13:05:49 +02001430 video_source_.IncomingCapturedFrame(CreateFrame(3, nullptr));
1431
1432 WaitForEncodedFrame(3);
mflodmancc3d4422017-08-03 08:27:51 -07001433 video_stream_encoder_->Stop();
perkj26091b12016-09-01 01:17:40 -07001434}
1435
mflodmancc3d4422017-08-03 08:27:51 -07001436TEST_F(VideoStreamEncoderTest, DropsFramesWhenRateSetToZero) {
Henrik Boström381d1092020-05-12 18:49:07 +02001437 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001438 DataRate::BitsPerSec(kTargetBitrateBps),
1439 DataRate::BitsPerSec(kTargetBitrateBps),
1440 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
perkja49cbd32016-09-16 07:53:41 -07001441 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
sprang4847ae62017-06-27 07:06:52 -07001442 WaitForEncodedFrame(1);
perkj26091b12016-09-01 01:17:40 -07001443
Henrik Boström381d1092020-05-12 18:49:07 +02001444 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
1445 DataRate::BitsPerSec(0), DataRate::BitsPerSec(0), DataRate::BitsPerSec(0),
1446 0, 0, 0);
Sebastian Janssona3177052018-04-10 13:05:49 +02001447 // The encoder will cache up to one frame for a short duration. Adding two
1448 // frames means that the first frame will be dropped and the second frame will
1449 // be sent when the encoder is resumed.
perkja49cbd32016-09-16 07:53:41 -07001450 video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
Sebastian Janssona3177052018-04-10 13:05:49 +02001451 video_source_.IncomingCapturedFrame(CreateFrame(3, nullptr));
perkj26091b12016-09-01 01:17:40 -07001452
Henrik Boström381d1092020-05-12 18:49:07 +02001453 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001454 DataRate::BitsPerSec(kTargetBitrateBps),
1455 DataRate::BitsPerSec(kTargetBitrateBps),
1456 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
sprang4847ae62017-06-27 07:06:52 -07001457 WaitForEncodedFrame(3);
Sebastian Janssona3177052018-04-10 13:05:49 +02001458 video_source_.IncomingCapturedFrame(CreateFrame(4, nullptr));
1459 WaitForEncodedFrame(4);
mflodmancc3d4422017-08-03 08:27:51 -07001460 video_stream_encoder_->Stop();
perkj26091b12016-09-01 01:17:40 -07001461}
1462
mflodmancc3d4422017-08-03 08:27:51 -07001463TEST_F(VideoStreamEncoderTest, DropsFramesWithSameOrOldNtpTimestamp) {
Henrik Boström381d1092020-05-12 18:49:07 +02001464 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001465 DataRate::BitsPerSec(kTargetBitrateBps),
1466 DataRate::BitsPerSec(kTargetBitrateBps),
1467 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
perkja49cbd32016-09-16 07:53:41 -07001468 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
sprang4847ae62017-06-27 07:06:52 -07001469 WaitForEncodedFrame(1);
perkj26091b12016-09-01 01:17:40 -07001470
1471 // This frame will be dropped since it has the same ntp timestamp.
perkja49cbd32016-09-16 07:53:41 -07001472 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
perkj26091b12016-09-01 01:17:40 -07001473
perkja49cbd32016-09-16 07:53:41 -07001474 video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
sprang4847ae62017-06-27 07:06:52 -07001475 WaitForEncodedFrame(2);
mflodmancc3d4422017-08-03 08:27:51 -07001476 video_stream_encoder_->Stop();
perkj26091b12016-09-01 01:17:40 -07001477}
1478
mflodmancc3d4422017-08-03 08:27:51 -07001479TEST_F(VideoStreamEncoderTest, DropsFrameAfterStop) {
Henrik Boström381d1092020-05-12 18:49:07 +02001480 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001481 DataRate::BitsPerSec(kTargetBitrateBps),
1482 DataRate::BitsPerSec(kTargetBitrateBps),
1483 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
perkj26091b12016-09-01 01:17:40 -07001484
perkja49cbd32016-09-16 07:53:41 -07001485 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
sprang4847ae62017-06-27 07:06:52 -07001486 WaitForEncodedFrame(1);
perkj26091b12016-09-01 01:17:40 -07001487
mflodmancc3d4422017-08-03 08:27:51 -07001488 video_stream_encoder_->Stop();
perkj26091b12016-09-01 01:17:40 -07001489 sink_.SetExpectNoFrames();
Niels Möllerc572ff32018-11-07 08:43:50 +01001490 rtc::Event frame_destroyed_event;
perkja49cbd32016-09-16 07:53:41 -07001491 video_source_.IncomingCapturedFrame(CreateFrame(2, &frame_destroyed_event));
1492 EXPECT_TRUE(frame_destroyed_event.Wait(kDefaultTimeoutMs));
perkj26091b12016-09-01 01:17:40 -07001493}
1494
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02001495class VideoStreamEncoderBlockedTest : public VideoStreamEncoderTest {
1496 public:
1497 VideoStreamEncoderBlockedTest() {}
1498
1499 TaskQueueFactory* GetTaskQueueFactory() override {
1500 return task_queue_factory_.get();
1501 }
1502
1503 private:
1504 std::unique_ptr<TaskQueueFactory> task_queue_factory_ =
1505 CreateDefaultTaskQueueFactory();
1506};
1507
1508TEST_F(VideoStreamEncoderBlockedTest, DropsPendingFramesOnSlowEncode) {
Henrik Boström381d1092020-05-12 18:49:07 +02001509 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001510 DataRate::BitsPerSec(kTargetBitrateBps),
1511 DataRate::BitsPerSec(kTargetBitrateBps),
1512 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
perkj26091b12016-09-01 01:17:40 -07001513
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02001514 int dropped_count = 0;
1515 stats_proxy_->SetDroppedFrameCallback(
1516 [&dropped_count](VideoStreamEncoderObserver::DropReason) {
1517 ++dropped_count;
1518 });
1519
perkj26091b12016-09-01 01:17:40 -07001520 fake_encoder_.BlockNextEncode();
perkja49cbd32016-09-16 07:53:41 -07001521 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
sprang4847ae62017-06-27 07:06:52 -07001522 WaitForEncodedFrame(1);
perkj26091b12016-09-01 01:17:40 -07001523 // Here, the encoder thread will be blocked in the TestEncoder waiting for a
1524 // call to ContinueEncode.
perkja49cbd32016-09-16 07:53:41 -07001525 video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
1526 video_source_.IncomingCapturedFrame(CreateFrame(3, nullptr));
perkj26091b12016-09-01 01:17:40 -07001527 fake_encoder_.ContinueEncode();
sprang4847ae62017-06-27 07:06:52 -07001528 WaitForEncodedFrame(3);
perkj26091b12016-09-01 01:17:40 -07001529
mflodmancc3d4422017-08-03 08:27:51 -07001530 video_stream_encoder_->Stop();
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02001531
1532 EXPECT_EQ(1, dropped_count);
perkj26091b12016-09-01 01:17:40 -07001533}
1534
Noah Richards51db4212019-06-12 06:59:12 -07001535TEST_F(VideoStreamEncoderTest, DropFrameWithFailedI420Conversion) {
Henrik Boström381d1092020-05-12 18:49:07 +02001536 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001537 DataRate::BitsPerSec(kTargetBitrateBps),
1538 DataRate::BitsPerSec(kTargetBitrateBps),
1539 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Noah Richards51db4212019-06-12 06:59:12 -07001540
1541 rtc::Event frame_destroyed_event;
1542 video_source_.IncomingCapturedFrame(
1543 CreateFakeNativeFrame(1, &frame_destroyed_event));
1544 ExpectDroppedFrame();
1545 EXPECT_TRUE(frame_destroyed_event.Wait(kDefaultTimeoutMs));
1546 video_stream_encoder_->Stop();
1547}
1548
1549TEST_F(VideoStreamEncoderTest, DropFrameWithFailedI420ConversionWithCrop) {
1550 // Use the cropping factory.
1551 video_encoder_config_.video_stream_factory =
1552 new rtc::RefCountedObject<CroppingVideoStreamFactory>(1, 30);
1553 video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config_),
1554 kMaxPayloadLength);
1555 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
1556
1557 // Capture a frame at codec_width_/codec_height_.
Henrik Boström381d1092020-05-12 18:49:07 +02001558 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001559 DataRate::BitsPerSec(kTargetBitrateBps),
1560 DataRate::BitsPerSec(kTargetBitrateBps),
1561 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Noah Richards51db4212019-06-12 06:59:12 -07001562 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
1563 WaitForEncodedFrame(1);
1564 // The encoder will have been configured once.
1565 EXPECT_EQ(1, sink_.number_of_reconfigurations());
1566 EXPECT_EQ(codec_width_, fake_encoder_.codec_config().width);
1567 EXPECT_EQ(codec_height_, fake_encoder_.codec_config().height);
1568
1569 // Now send in a fake frame that needs to be cropped as the width/height
1570 // aren't divisible by 4 (see CreateEncoderStreams above).
1571 rtc::Event frame_destroyed_event;
1572 video_source_.IncomingCapturedFrame(CreateFakeNativeFrame(
1573 2, &frame_destroyed_event, codec_width_ + 1, codec_height_ + 1));
1574 ExpectDroppedFrame();
1575 EXPECT_TRUE(frame_destroyed_event.Wait(kDefaultTimeoutMs));
1576 video_stream_encoder_->Stop();
1577}
1578
Evan Shrubsole895556e2020-10-05 09:15:13 +02001579TEST_F(VideoStreamEncoderTest, NonI420FramesShouldNotBeConvertedToI420) {
1580 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
1581 DataRate::BitsPerSec(kTargetBitrateBps),
1582 DataRate::BitsPerSec(kTargetBitrateBps),
1583 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
1584
1585 video_source_.IncomingCapturedFrame(
1586 CreateNV12Frame(1, codec_width_, codec_height_));
1587 WaitForEncodedFrame(1);
1588 EXPECT_EQ(VideoFrameBuffer::Type::kNV12,
1589 fake_encoder_.GetLastInputPixelFormat());
1590 video_stream_encoder_->Stop();
1591}
1592
Evan Shrubsoleb556b082020-10-08 14:56:45 +02001593TEST_F(VideoStreamEncoderTest,
1594 NativeFrameIsConvertedToI420IfNoFrameTypePreference) {
1595 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
1596 DataRate::BitsPerSec(kTargetBitrateBps),
1597 DataRate::BitsPerSec(kTargetBitrateBps),
1598 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
1599
1600 fake_encoder_.SetPreferredPixelFormats({});
1601
1602 rtc::Event frame_destroyed_event;
1603 video_source_.IncomingCapturedFrame(CreateFakeNV12NativeFrame(
1604 1, &frame_destroyed_event, codec_width_, codec_height_));
1605 WaitForEncodedFrame(1);
1606 EXPECT_EQ(VideoFrameBuffer::Type::kI420,
1607 fake_encoder_.GetLastInputPixelFormat());
1608 video_stream_encoder_->Stop();
1609}
1610
1611TEST_F(VideoStreamEncoderTest, NativeFrameMappedToPreferredPixelFormat) {
1612 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
1613 DataRate::BitsPerSec(kTargetBitrateBps),
1614 DataRate::BitsPerSec(kTargetBitrateBps),
1615 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
1616
1617 fake_encoder_.SetPreferredPixelFormats({VideoFrameBuffer::Type::kNV12});
1618
1619 rtc::Event frame_destroyed_event;
1620 video_source_.IncomingCapturedFrame(CreateFakeNV12NativeFrame(
1621 1, &frame_destroyed_event, codec_width_, codec_height_));
1622 WaitForEncodedFrame(1);
1623 EXPECT_EQ(VideoFrameBuffer::Type::kNV12,
1624 fake_encoder_.GetLastInputPixelFormat());
1625 video_stream_encoder_->Stop();
1626}
1627
1628TEST_F(VideoStreamEncoderTest, NativeFrameConvertedToI420IfMappingNotFeasible) {
1629 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
1630 DataRate::BitsPerSec(kTargetBitrateBps),
1631 DataRate::BitsPerSec(kTargetBitrateBps),
1632 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
1633
1634 // Fake NV12 native frame does not allow mapping to I444.
1635 fake_encoder_.SetPreferredPixelFormats({VideoFrameBuffer::Type::kI444});
1636
1637 rtc::Event frame_destroyed_event;
1638 video_source_.IncomingCapturedFrame(CreateFakeNV12NativeFrame(
1639 1, &frame_destroyed_event, codec_width_, codec_height_));
1640 WaitForEncodedFrame(1);
1641 EXPECT_EQ(VideoFrameBuffer::Type::kI420,
1642 fake_encoder_.GetLastInputPixelFormat());
1643 video_stream_encoder_->Stop();
1644}
1645
Evan Shrubsole895556e2020-10-05 09:15:13 +02001646TEST_F(VideoStreamEncoderTest, NativeFrameBackedByNV12FrameIsEncodedFromI420) {
1647 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
1648 DataRate::BitsPerSec(kTargetBitrateBps),
1649 DataRate::BitsPerSec(kTargetBitrateBps),
1650 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
1651
1652 rtc::Event frame_destroyed_event;
1653 video_source_.IncomingCapturedFrame(CreateFakeNV12NativeFrame(
1654 1, &frame_destroyed_event, codec_width_, codec_height_));
1655 WaitForEncodedFrame(1);
1656 EXPECT_EQ(VideoFrameBuffer::Type::kI420,
1657 fake_encoder_.GetLastInputPixelFormat());
1658 video_stream_encoder_->Stop();
1659}
1660
Ying Wang9b881ab2020-02-07 14:29:32 +01001661TEST_F(VideoStreamEncoderTest, DropsFramesWhenCongestionWindowPushbackSet) {
Henrik Boström381d1092020-05-12 18:49:07 +02001662 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001663 DataRate::BitsPerSec(kTargetBitrateBps),
1664 DataRate::BitsPerSec(kTargetBitrateBps),
1665 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Ying Wang9b881ab2020-02-07 14:29:32 +01001666 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
1667 WaitForEncodedFrame(1);
1668
Henrik Boström381d1092020-05-12 18:49:07 +02001669 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001670 DataRate::BitsPerSec(kTargetBitrateBps),
1671 DataRate::BitsPerSec(kTargetBitrateBps),
1672 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0.5);
Ying Wang9b881ab2020-02-07 14:29:32 +01001673 // The congestion window pushback is set to 0.5, which will drop 1/2 of
1674 // frames. Adding two frames means that the first frame will be dropped and
1675 // the second frame will be sent to the encoder.
1676 video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
1677 video_source_.IncomingCapturedFrame(CreateFrame(3, nullptr));
1678 WaitForEncodedFrame(3);
1679 video_source_.IncomingCapturedFrame(CreateFrame(4, nullptr));
1680 video_source_.IncomingCapturedFrame(CreateFrame(5, nullptr));
1681 WaitForEncodedFrame(5);
1682 EXPECT_EQ(2u, stats_proxy_->GetStats().frames_dropped_by_congestion_window);
1683 video_stream_encoder_->Stop();
1684}
1685
mflodmancc3d4422017-08-03 08:27:51 -07001686TEST_F(VideoStreamEncoderTest,
1687 ConfigureEncoderTriggersOnEncoderConfigurationChanged) {
Henrik Boström381d1092020-05-12 18:49:07 +02001688 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001689 DataRate::BitsPerSec(kTargetBitrateBps),
1690 DataRate::BitsPerSec(kTargetBitrateBps),
1691 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Per21d45d22016-10-30 21:37:57 +01001692 EXPECT_EQ(0, sink_.number_of_reconfigurations());
Per512ecb32016-09-23 15:52:06 +02001693
1694 // Capture a frame and wait for it to synchronize with the encoder thread.
Perf8c5f2b2016-09-23 16:24:55 +02001695 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
sprang4847ae62017-06-27 07:06:52 -07001696 WaitForEncodedFrame(1);
Per21d45d22016-10-30 21:37:57 +01001697 // The encoder will have been configured once when the first frame is
1698 // received.
1699 EXPECT_EQ(1, sink_.number_of_reconfigurations());
Per512ecb32016-09-23 15:52:06 +02001700
1701 VideoEncoderConfig video_encoder_config;
Niels Möller259a4972018-04-05 15:36:51 +02001702 test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
Per512ecb32016-09-23 15:52:06 +02001703 video_encoder_config.min_transmit_bitrate_bps = 9999;
mflodmancc3d4422017-08-03 08:27:51 -07001704 video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config),
Niels Möllerf1338562018-04-26 09:51:47 +02001705 kMaxPayloadLength);
Per512ecb32016-09-23 15:52:06 +02001706
1707 // Capture a frame and wait for it to synchronize with the encoder thread.
Perf8c5f2b2016-09-23 16:24:55 +02001708 video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
sprang4847ae62017-06-27 07:06:52 -07001709 WaitForEncodedFrame(2);
Per21d45d22016-10-30 21:37:57 +01001710 EXPECT_EQ(2, sink_.number_of_reconfigurations());
perkj3b703ed2016-09-29 23:25:40 -07001711 EXPECT_EQ(9999, sink_.last_min_transmit_bitrate());
perkj26105b42016-09-29 22:39:10 -07001712
mflodmancc3d4422017-08-03 08:27:51 -07001713 video_stream_encoder_->Stop();
perkj26105b42016-09-29 22:39:10 -07001714}
1715
mflodmancc3d4422017-08-03 08:27:51 -07001716TEST_F(VideoStreamEncoderTest, FrameResolutionChangeReconfigureEncoder) {
Henrik Boström381d1092020-05-12 18:49:07 +02001717 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001718 DataRate::BitsPerSec(kTargetBitrateBps),
1719 DataRate::BitsPerSec(kTargetBitrateBps),
1720 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
perkjfa10b552016-10-02 23:45:26 -07001721
1722 // Capture a frame and wait for it to synchronize with the encoder thread.
1723 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
sprang4847ae62017-06-27 07:06:52 -07001724 WaitForEncodedFrame(1);
Per21d45d22016-10-30 21:37:57 +01001725 // The encoder will have been configured once.
1726 EXPECT_EQ(1, sink_.number_of_reconfigurations());
perkjfa10b552016-10-02 23:45:26 -07001727 EXPECT_EQ(codec_width_, fake_encoder_.codec_config().width);
1728 EXPECT_EQ(codec_height_, fake_encoder_.codec_config().height);
1729
1730 codec_width_ *= 2;
1731 codec_height_ *= 2;
1732 // Capture a frame with a higher resolution and wait for it to synchronize
1733 // with the encoder thread.
1734 video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
sprang4847ae62017-06-27 07:06:52 -07001735 WaitForEncodedFrame(2);
perkjfa10b552016-10-02 23:45:26 -07001736 EXPECT_EQ(codec_width_, fake_encoder_.codec_config().width);
1737 EXPECT_EQ(codec_height_, fake_encoder_.codec_config().height);
Per21d45d22016-10-30 21:37:57 +01001738 EXPECT_EQ(2, sink_.number_of_reconfigurations());
perkjfa10b552016-10-02 23:45:26 -07001739
mflodmancc3d4422017-08-03 08:27:51 -07001740 video_stream_encoder_->Stop();
perkjfa10b552016-10-02 23:45:26 -07001741}
1742
Sergey Silkin443b7ee2019-06-28 12:53:07 +02001743TEST_F(VideoStreamEncoderTest,
1744 EncoderInstanceDestroyedBeforeAnotherInstanceCreated) {
Henrik Boström381d1092020-05-12 18:49:07 +02001745 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001746 DataRate::BitsPerSec(kTargetBitrateBps),
1747 DataRate::BitsPerSec(kTargetBitrateBps),
1748 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Sergey Silkin443b7ee2019-06-28 12:53:07 +02001749
1750 // Capture a frame and wait for it to synchronize with the encoder thread.
1751 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
1752 WaitForEncodedFrame(1);
1753
1754 VideoEncoderConfig video_encoder_config;
1755 test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
1756 // Changing the max payload data length recreates encoder.
1757 video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config),
1758 kMaxPayloadLength / 2);
1759
1760 // Capture a frame and wait for it to synchronize with the encoder thread.
1761 video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
1762 WaitForEncodedFrame(2);
1763 EXPECT_EQ(1, encoder_factory_.GetMaxNumberOfSimultaneousEncoderInstances());
1764
1765 video_stream_encoder_->Stop();
1766}
1767
Sergey Silkin5ee69672019-07-02 14:18:34 +02001768TEST_F(VideoStreamEncoderTest, BitrateLimitsChangeReconfigureRateAllocator) {
Henrik Boström381d1092020-05-12 18:49:07 +02001769 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001770 DataRate::BitsPerSec(kTargetBitrateBps),
1771 DataRate::BitsPerSec(kTargetBitrateBps),
1772 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Sergey Silkin5ee69672019-07-02 14:18:34 +02001773
1774 VideoEncoderConfig video_encoder_config;
1775 test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
1776 video_encoder_config.max_bitrate_bps = kTargetBitrateBps;
1777 video_stream_encoder_->SetStartBitrate(kStartBitrateBps);
1778 video_stream_encoder_->ConfigureEncoder(video_encoder_config.Copy(),
1779 kMaxPayloadLength);
1780
1781 // Capture a frame and wait for it to synchronize with the encoder thread.
1782 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
1783 WaitForEncodedFrame(1);
1784 // The encoder will have been configured once when the first frame is
1785 // received.
1786 EXPECT_EQ(1, sink_.number_of_reconfigurations());
1787 EXPECT_EQ(kTargetBitrateBps,
1788 bitrate_allocator_factory_.codec_config().maxBitrate * 1000);
1789 EXPECT_EQ(kStartBitrateBps,
1790 bitrate_allocator_factory_.codec_config().startBitrate * 1000);
1791
Sergey Silkin6456e352019-07-08 17:56:40 +02001792 test::FillEncoderConfiguration(kVideoCodecVP8, 1,
1793 &video_encoder_config); //???
Sergey Silkin5ee69672019-07-02 14:18:34 +02001794 video_encoder_config.max_bitrate_bps = kTargetBitrateBps * 2;
1795 video_stream_encoder_->SetStartBitrate(kStartBitrateBps * 2);
1796 video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config),
1797 kMaxPayloadLength);
1798
1799 // Capture a frame and wait for it to synchronize with the encoder thread.
1800 video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
1801 WaitForEncodedFrame(2);
1802 EXPECT_EQ(2, sink_.number_of_reconfigurations());
1803 // Bitrate limits have changed - rate allocator should be reconfigured,
1804 // encoder should not be reconfigured.
1805 EXPECT_EQ(kTargetBitrateBps * 2,
1806 bitrate_allocator_factory_.codec_config().maxBitrate * 1000);
1807 EXPECT_EQ(kStartBitrateBps * 2,
1808 bitrate_allocator_factory_.codec_config().startBitrate * 1000);
1809 EXPECT_EQ(1, fake_encoder_.GetNumEncoderInitializations());
1810
1811 video_stream_encoder_->Stop();
1812}
1813
Sergey Silkin6456e352019-07-08 17:56:40 +02001814TEST_F(VideoStreamEncoderTest,
Sergey Silkincd02eba2020-01-20 14:48:40 +01001815 IntersectionOfEncoderAndAppBitrateLimitsUsedWhenBothProvided) {
Henrik Boström381d1092020-05-12 18:49:07 +02001816 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001817 DataRate::BitsPerSec(kTargetBitrateBps),
1818 DataRate::BitsPerSec(kTargetBitrateBps),
1819 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Sergey Silkin6456e352019-07-08 17:56:40 +02001820
Sergey Silkincd02eba2020-01-20 14:48:40 +01001821 const uint32_t kMinEncBitrateKbps = 100;
1822 const uint32_t kMaxEncBitrateKbps = 1000;
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001823 const VideoEncoder::ResolutionBitrateLimits encoder_bitrate_limits(
Sergey Silkincd02eba2020-01-20 14:48:40 +01001824 /*frame_size_pixels=*/codec_width_ * codec_height_,
1825 /*min_start_bitrate_bps=*/0,
1826 /*min_bitrate_bps=*/kMinEncBitrateKbps * 1000,
1827 /*max_bitrate_bps=*/kMaxEncBitrateKbps * 1000);
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001828 fake_encoder_.SetResolutionBitrateLimits({encoder_bitrate_limits});
1829
Sergey Silkincd02eba2020-01-20 14:48:40 +01001830 VideoEncoderConfig video_encoder_config;
1831 test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
1832 video_encoder_config.max_bitrate_bps = (kMaxEncBitrateKbps + 1) * 1000;
1833 video_encoder_config.simulcast_layers[0].min_bitrate_bps =
1834 (kMinEncBitrateKbps + 1) * 1000;
1835 video_stream_encoder_->ConfigureEncoder(video_encoder_config.Copy(),
1836 kMaxPayloadLength);
1837
1838 // When both encoder and app provide bitrate limits, the intersection of
1839 // provided sets should be used.
1840 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
1841 WaitForEncodedFrame(1);
1842 EXPECT_EQ(kMaxEncBitrateKbps,
1843 bitrate_allocator_factory_.codec_config().maxBitrate);
1844 EXPECT_EQ(kMinEncBitrateKbps + 1,
1845 bitrate_allocator_factory_.codec_config().minBitrate);
1846
1847 video_encoder_config.max_bitrate_bps = (kMaxEncBitrateKbps - 1) * 1000;
1848 video_encoder_config.simulcast_layers[0].min_bitrate_bps =
1849 (kMinEncBitrateKbps - 1) * 1000;
1850 video_stream_encoder_->ConfigureEncoder(video_encoder_config.Copy(),
1851 kMaxPayloadLength);
1852 video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001853 WaitForEncodedFrame(2);
Sergey Silkincd02eba2020-01-20 14:48:40 +01001854 EXPECT_EQ(kMaxEncBitrateKbps - 1,
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001855 bitrate_allocator_factory_.codec_config().maxBitrate);
Sergey Silkincd02eba2020-01-20 14:48:40 +01001856 EXPECT_EQ(kMinEncBitrateKbps,
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001857 bitrate_allocator_factory_.codec_config().minBitrate);
1858
Sergey Silkincd02eba2020-01-20 14:48:40 +01001859 video_stream_encoder_->Stop();
1860}
1861
1862TEST_F(VideoStreamEncoderTest,
1863 EncoderAndAppLimitsDontIntersectEncoderLimitsIgnored) {
Henrik Boström381d1092020-05-12 18:49:07 +02001864 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001865 DataRate::BitsPerSec(kTargetBitrateBps),
1866 DataRate::BitsPerSec(kTargetBitrateBps),
1867 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Sergey Silkincd02eba2020-01-20 14:48:40 +01001868
1869 const uint32_t kMinAppBitrateKbps = 100;
1870 const uint32_t kMaxAppBitrateKbps = 200;
1871 const uint32_t kMinEncBitrateKbps = kMaxAppBitrateKbps + 1;
1872 const uint32_t kMaxEncBitrateKbps = kMaxAppBitrateKbps * 2;
1873 const VideoEncoder::ResolutionBitrateLimits encoder_bitrate_limits(
1874 /*frame_size_pixels=*/codec_width_ * codec_height_,
1875 /*min_start_bitrate_bps=*/0,
1876 /*min_bitrate_bps=*/kMinEncBitrateKbps * 1000,
1877 /*max_bitrate_bps=*/kMaxEncBitrateKbps * 1000);
1878 fake_encoder_.SetResolutionBitrateLimits({encoder_bitrate_limits});
1879
1880 VideoEncoderConfig video_encoder_config;
1881 test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
1882 video_encoder_config.max_bitrate_bps = kMaxAppBitrateKbps * 1000;
1883 video_encoder_config.simulcast_layers[0].min_bitrate_bps =
1884 kMinAppBitrateKbps * 1000;
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001885 video_stream_encoder_->ConfigureEncoder(video_encoder_config.Copy(),
1886 kMaxPayloadLength);
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001887
Sergey Silkincd02eba2020-01-20 14:48:40 +01001888 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
1889 WaitForEncodedFrame(1);
1890 EXPECT_EQ(kMaxAppBitrateKbps,
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001891 bitrate_allocator_factory_.codec_config().maxBitrate);
Sergey Silkincd02eba2020-01-20 14:48:40 +01001892 EXPECT_EQ(kMinAppBitrateKbps,
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001893 bitrate_allocator_factory_.codec_config().minBitrate);
Sergey Silkin6456e352019-07-08 17:56:40 +02001894
1895 video_stream_encoder_->Stop();
1896}
1897
1898TEST_F(VideoStreamEncoderTest,
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001899 EncoderRecommendedMaxAndMinBitratesUsedForGivenResolution) {
Henrik Boström381d1092020-05-12 18:49:07 +02001900 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001901 DataRate::BitsPerSec(kTargetBitrateBps),
1902 DataRate::BitsPerSec(kTargetBitrateBps),
1903 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Sergey Silkin6456e352019-07-08 17:56:40 +02001904
1905 const VideoEncoder::ResolutionBitrateLimits encoder_bitrate_limits_270p(
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001906 480 * 270, 34 * 1000, 12 * 1000, 1234 * 1000);
Sergey Silkin6456e352019-07-08 17:56:40 +02001907 const VideoEncoder::ResolutionBitrateLimits encoder_bitrate_limits_360p(
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001908 640 * 360, 43 * 1000, 21 * 1000, 2345 * 1000);
Sergey Silkin6456e352019-07-08 17:56:40 +02001909 fake_encoder_.SetResolutionBitrateLimits(
1910 {encoder_bitrate_limits_270p, encoder_bitrate_limits_360p});
1911
1912 VideoEncoderConfig video_encoder_config;
1913 test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
1914 video_encoder_config.max_bitrate_bps = 0;
1915 video_stream_encoder_->ConfigureEncoder(video_encoder_config.Copy(),
1916 kMaxPayloadLength);
1917
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001918 // 270p. The bitrate limits recommended by encoder for 270p should be used.
Sergey Silkin6456e352019-07-08 17:56:40 +02001919 video_source_.IncomingCapturedFrame(CreateFrame(1, 480, 270));
1920 WaitForEncodedFrame(1);
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001921 EXPECT_EQ(static_cast<uint32_t>(encoder_bitrate_limits_270p.min_bitrate_bps),
1922 bitrate_allocator_factory_.codec_config().minBitrate * 1000);
Sergey Silkin6456e352019-07-08 17:56:40 +02001923 EXPECT_EQ(static_cast<uint32_t>(encoder_bitrate_limits_270p.max_bitrate_bps),
1924 bitrate_allocator_factory_.codec_config().maxBitrate * 1000);
1925
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001926 // 360p. The bitrate limits recommended by encoder for 360p should be used.
Sergey Silkin6456e352019-07-08 17:56:40 +02001927 video_source_.IncomingCapturedFrame(CreateFrame(2, 640, 360));
1928 WaitForEncodedFrame(2);
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001929 EXPECT_EQ(static_cast<uint32_t>(encoder_bitrate_limits_360p.min_bitrate_bps),
1930 bitrate_allocator_factory_.codec_config().minBitrate * 1000);
Sergey Silkin6456e352019-07-08 17:56:40 +02001931 EXPECT_EQ(static_cast<uint32_t>(encoder_bitrate_limits_360p.max_bitrate_bps),
1932 bitrate_allocator_factory_.codec_config().maxBitrate * 1000);
1933
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001934 // Resolution between 270p and 360p. The bitrate limits recommended by
Sergey Silkin6456e352019-07-08 17:56:40 +02001935 // encoder for 360p should be used.
1936 video_source_.IncomingCapturedFrame(
1937 CreateFrame(3, (640 + 480) / 2, (360 + 270) / 2));
1938 WaitForEncodedFrame(3);
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001939 EXPECT_EQ(static_cast<uint32_t>(encoder_bitrate_limits_360p.min_bitrate_bps),
1940 bitrate_allocator_factory_.codec_config().minBitrate * 1000);
Sergey Silkin6456e352019-07-08 17:56:40 +02001941 EXPECT_EQ(static_cast<uint32_t>(encoder_bitrate_limits_360p.max_bitrate_bps),
1942 bitrate_allocator_factory_.codec_config().maxBitrate * 1000);
1943
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001944 // Resolution higher than 360p. The caps recommended by encoder should be
Sergey Silkin6456e352019-07-08 17:56:40 +02001945 // ignored.
1946 video_source_.IncomingCapturedFrame(CreateFrame(4, 960, 540));
1947 WaitForEncodedFrame(4);
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001948 EXPECT_NE(static_cast<uint32_t>(encoder_bitrate_limits_270p.min_bitrate_bps),
1949 bitrate_allocator_factory_.codec_config().minBitrate * 1000);
Sergey Silkin6456e352019-07-08 17:56:40 +02001950 EXPECT_NE(static_cast<uint32_t>(encoder_bitrate_limits_270p.max_bitrate_bps),
1951 bitrate_allocator_factory_.codec_config().maxBitrate * 1000);
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001952 EXPECT_NE(static_cast<uint32_t>(encoder_bitrate_limits_360p.min_bitrate_bps),
1953 bitrate_allocator_factory_.codec_config().minBitrate * 1000);
Sergey Silkin6456e352019-07-08 17:56:40 +02001954 EXPECT_NE(static_cast<uint32_t>(encoder_bitrate_limits_360p.max_bitrate_bps),
1955 bitrate_allocator_factory_.codec_config().maxBitrate * 1000);
1956
1957 // Resolution lower than 270p. The max bitrate limit recommended by encoder
1958 // for 270p should be used.
1959 video_source_.IncomingCapturedFrame(CreateFrame(5, 320, 180));
1960 WaitForEncodedFrame(5);
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001961 EXPECT_EQ(static_cast<uint32_t>(encoder_bitrate_limits_270p.min_bitrate_bps),
1962 bitrate_allocator_factory_.codec_config().minBitrate * 1000);
Sergey Silkin6456e352019-07-08 17:56:40 +02001963 EXPECT_EQ(static_cast<uint32_t>(encoder_bitrate_limits_270p.max_bitrate_bps),
1964 bitrate_allocator_factory_.codec_config().maxBitrate * 1000);
1965
1966 video_stream_encoder_->Stop();
1967}
1968
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001969TEST_F(VideoStreamEncoderTest, EncoderRecommendedMaxBitrateCapsTargetBitrate) {
Henrik Boström381d1092020-05-12 18:49:07 +02001970 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001971 DataRate::BitsPerSec(kTargetBitrateBps),
1972 DataRate::BitsPerSec(kTargetBitrateBps),
1973 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001974
1975 VideoEncoderConfig video_encoder_config;
1976 test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
1977 video_encoder_config.max_bitrate_bps = 0;
1978 video_stream_encoder_->ConfigureEncoder(video_encoder_config.Copy(),
1979 kMaxPayloadLength);
1980
1981 // Encode 720p frame to get the default encoder target bitrate.
1982 video_source_.IncomingCapturedFrame(CreateFrame(1, 1280, 720));
1983 WaitForEncodedFrame(1);
1984 const uint32_t kDefaultTargetBitrateFor720pKbps =
1985 bitrate_allocator_factory_.codec_config()
1986 .simulcastStream[0]
1987 .targetBitrate;
1988
1989 // Set the max recommended encoder bitrate to something lower than the default
1990 // target bitrate.
1991 const VideoEncoder::ResolutionBitrateLimits encoder_bitrate_limits(
1992 1280 * 720, 10 * 1000, 10 * 1000,
1993 kDefaultTargetBitrateFor720pKbps / 2 * 1000);
1994 fake_encoder_.SetResolutionBitrateLimits({encoder_bitrate_limits});
1995
1996 // Change resolution to trigger encoder reinitialization.
1997 video_source_.IncomingCapturedFrame(CreateFrame(2, 640, 360));
1998 WaitForEncodedFrame(2);
1999 video_source_.IncomingCapturedFrame(CreateFrame(3, 1280, 720));
2000 WaitForEncodedFrame(3);
2001
2002 // Ensure the target bitrate is capped by the max bitrate.
2003 EXPECT_EQ(bitrate_allocator_factory_.codec_config().maxBitrate * 1000,
2004 static_cast<uint32_t>(encoder_bitrate_limits.max_bitrate_bps));
2005 EXPECT_EQ(bitrate_allocator_factory_.codec_config()
2006 .simulcastStream[0]
2007 .targetBitrate *
2008 1000,
2009 static_cast<uint32_t>(encoder_bitrate_limits.max_bitrate_bps));
2010
2011 video_stream_encoder_->Stop();
2012}
2013
mflodmancc3d4422017-08-03 08:27:51 -07002014TEST_F(VideoStreamEncoderTest, SwitchSourceDeregisterEncoderAsSink) {
perkj803d97f2016-11-01 11:45:46 -07002015 EXPECT_TRUE(video_source_.has_sinks());
2016 test::FrameForwarder new_video_source;
mflodmancc3d4422017-08-03 08:27:51 -07002017 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002018 &new_video_source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
perkj803d97f2016-11-01 11:45:46 -07002019 EXPECT_FALSE(video_source_.has_sinks());
2020 EXPECT_TRUE(new_video_source.has_sinks());
2021
mflodmancc3d4422017-08-03 08:27:51 -07002022 video_stream_encoder_->Stop();
perkj803d97f2016-11-01 11:45:46 -07002023}
2024
mflodmancc3d4422017-08-03 08:27:51 -07002025TEST_F(VideoStreamEncoderTest, SinkWantsRotationApplied) {
perkj803d97f2016-11-01 11:45:46 -07002026 EXPECT_FALSE(video_source_.sink_wants().rotation_applied);
mflodmancc3d4422017-08-03 08:27:51 -07002027 video_stream_encoder_->SetSink(&sink_, true /*rotation_applied*/);
perkj803d97f2016-11-01 11:45:46 -07002028 EXPECT_TRUE(video_source_.sink_wants().rotation_applied);
mflodmancc3d4422017-08-03 08:27:51 -07002029 video_stream_encoder_->Stop();
perkj803d97f2016-11-01 11:45:46 -07002030}
2031
Åsa Perssonc5a74ff2020-09-20 17:50:00 +02002032class ResolutionAlignmentTest
2033 : public VideoStreamEncoderTest,
2034 public ::testing::WithParamInterface<
2035 ::testing::tuple<int, std::vector<double>>> {
2036 public:
2037 ResolutionAlignmentTest()
2038 : requested_alignment_(::testing::get<0>(GetParam())),
2039 scale_factors_(::testing::get<1>(GetParam())) {}
2040
2041 protected:
2042 const int requested_alignment_;
2043 const std::vector<double> scale_factors_;
2044};
2045
2046INSTANTIATE_TEST_SUITE_P(
2047 AlignmentAndScaleFactors,
2048 ResolutionAlignmentTest,
2049 ::testing::Combine(
2050 ::testing::Values(1, 2, 3, 4, 5, 6, 16, 22), // requested_alignment_
2051 ::testing::Values(std::vector<double>{-1.0}, // scale_factors_
2052 std::vector<double>{-1.0, -1.0},
2053 std::vector<double>{-1.0, -1.0, -1.0},
2054 std::vector<double>{4.0, 2.0, 1.0},
2055 std::vector<double>{9999.0, -1.0, 1.0},
2056 std::vector<double>{3.99, 2.01, 1.0},
2057 std::vector<double>{4.9, 1.7, 1.25},
2058 std::vector<double>{10.0, 4.0, 3.0},
2059 std::vector<double>{1.75, 3.5},
2060 std::vector<double>{1.5, 2.5},
2061 std::vector<double>{1.3, 1.0})));
2062
2063TEST_P(ResolutionAlignmentTest, SinkWantsAlignmentApplied) {
2064 // Set requested resolution alignment.
Rasmus Brandt5cad55b2019-12-19 09:47:11 +01002065 video_source_.set_adaptation_enabled(true);
Åsa Perssonc5a74ff2020-09-20 17:50:00 +02002066 fake_encoder_.SetRequestedResolutionAlignment(requested_alignment_);
2067 fake_encoder_.SetApplyAlignmentToAllSimulcastLayers(true);
2068
2069 // Fill config with the scaling factor by which to reduce encoding size.
2070 const int num_streams = scale_factors_.size();
2071 VideoEncoderConfig config;
2072 test::FillEncoderConfiguration(kVideoCodecVP8, num_streams, &config);
2073 for (int i = 0; i < num_streams; ++i) {
2074 config.simulcast_layers[i].scale_resolution_down_by = scale_factors_[i];
2075 }
2076 config.video_stream_factory =
2077 new rtc::RefCountedObject<cricket::EncoderStreamFactory>(
2078 "VP8", /*max qp*/ 56, /*screencast*/ false,
2079 /*screenshare enabled*/ false);
2080 video_stream_encoder_->ConfigureEncoder(std::move(config), kMaxPayloadLength);
2081
Henrik Boström381d1092020-05-12 18:49:07 +02002082 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Åsa Perssonc5a74ff2020-09-20 17:50:00 +02002083 DataRate::BitsPerSec(kSimulcastTargetBitrateBps),
2084 DataRate::BitsPerSec(kSimulcastTargetBitrateBps),
2085 DataRate::BitsPerSec(kSimulcastTargetBitrateBps), 0, 0, 0);
2086 // Wait for all layers before triggering event.
2087 sink_.SetNumExpectedLayers(num_streams);
Rasmus Brandt5cad55b2019-12-19 09:47:11 +01002088
2089 // On the 1st frame, we should have initialized the encoder and
2090 // asked for its resolution requirements.
Åsa Perssonc5a74ff2020-09-20 17:50:00 +02002091 int64_t timestamp_ms = kFrameIntervalMs;
2092 video_source_.IncomingCapturedFrame(CreateFrame(timestamp_ms, 1280, 720));
2093 WaitForEncodedFrame(timestamp_ms);
2094 EXPECT_EQ(1, fake_encoder_.GetNumEncoderInitializations());
Rasmus Brandt5cad55b2019-12-19 09:47:11 +01002095
2096 // On the 2nd frame, we should be receiving a correctly aligned resolution.
2097 // (It's up the to the encoder to potentially drop the previous frame,
2098 // to avoid coding back-to-back keyframes.)
Åsa Perssonc5a74ff2020-09-20 17:50:00 +02002099 timestamp_ms += kFrameIntervalMs;
2100 video_source_.IncomingCapturedFrame(CreateFrame(timestamp_ms, 1280, 720));
2101 WaitForEncodedFrame(timestamp_ms);
2102 EXPECT_GE(fake_encoder_.GetNumEncoderInitializations(), 1);
2103
2104 VideoCodec codec = fake_encoder_.video_codec();
2105 EXPECT_EQ(codec.numberOfSimulcastStreams, num_streams);
2106 // Frame size should be a multiple of the requested alignment.
2107 for (int i = 0; i < codec.numberOfSimulcastStreams; ++i) {
2108 EXPECT_EQ(codec.simulcastStream[i].width % requested_alignment_, 0);
2109 EXPECT_EQ(codec.simulcastStream[i].height % requested_alignment_, 0);
2110 // Aspect ratio should match.
2111 EXPECT_EQ(codec.width * codec.simulcastStream[i].height,
2112 codec.height * codec.simulcastStream[i].width);
2113 }
Rasmus Brandt5cad55b2019-12-19 09:47:11 +01002114
2115 video_stream_encoder_->Stop();
2116}
2117
Jonathan Yubc771b72017-12-08 17:04:29 -08002118TEST_F(VideoStreamEncoderTest, TestCpuDowngrades_BalancedMode) {
2119 const int kFramerateFps = 30;
asaperssonf7e294d2017-06-13 23:25:22 -07002120 const int kWidth = 1280;
2121 const int kHeight = 720;
Jonathan Yubc771b72017-12-08 17:04:29 -08002122
2123 // We rely on the automatic resolution adaptation, but we handle framerate
2124 // adaptation manually by mocking the stats proxy.
2125 video_source_.set_adaptation_enabled(true);
asaperssonf7e294d2017-06-13 23:25:22 -07002126
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002127 // Enable BALANCED preference, no initial limitation.
Henrik Boström381d1092020-05-12 18:49:07 +02002128 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01002129 DataRate::BitsPerSec(kTargetBitrateBps),
2130 DataRate::BitsPerSec(kTargetBitrateBps),
2131 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002132 video_stream_encoder_->SetSource(&video_source_,
2133 webrtc::DegradationPreference::BALANCED);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02002134 EXPECT_THAT(video_source_.sink_wants(), UnlimitedSinkWants());
asaperssonf7e294d2017-06-13 23:25:22 -07002135 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
Jonathan Yubc771b72017-12-08 17:04:29 -08002136 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
asaperssonf7e294d2017-06-13 23:25:22 -07002137 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
2138
Jonathan Yubc771b72017-12-08 17:04:29 -08002139 // Adapt down as far as possible.
2140 rtc::VideoSinkWants last_wants;
2141 int64_t t = 1;
2142 int loop_count = 0;
2143 do {
2144 ++loop_count;
2145 last_wants = video_source_.sink_wants();
2146
2147 // Simulate the framerate we've been asked to adapt to.
2148 const int fps = std::min(kFramerateFps, last_wants.max_framerate_fps);
2149 const int frame_interval_ms = rtc::kNumMillisecsPerSec / fps;
2150 VideoSendStream::Stats mock_stats = stats_proxy_->GetStats();
2151 mock_stats.input_frame_rate = fps;
2152 stats_proxy_->SetMockStats(mock_stats);
2153
2154 video_source_.IncomingCapturedFrame(CreateFrame(t, kWidth, kHeight));
2155 sink_.WaitForEncodedFrame(t);
2156 t += frame_interval_ms;
2157
mflodmancc3d4422017-08-03 08:27:51 -07002158 video_stream_encoder_->TriggerCpuOveruse();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02002159 EXPECT_THAT(
Jonathan Yubc771b72017-12-08 17:04:29 -08002160 video_source_.sink_wants(),
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02002161 FpsInRangeForPixelsInBalanced(*video_source_.last_sent_width() *
2162 *video_source_.last_sent_height()));
Jonathan Yubc771b72017-12-08 17:04:29 -08002163 } while (video_source_.sink_wants().max_pixel_count <
2164 last_wants.max_pixel_count ||
2165 video_source_.sink_wants().max_framerate_fps <
2166 last_wants.max_framerate_fps);
asaperssonf7e294d2017-06-13 23:25:22 -07002167
Jonathan Yubc771b72017-12-08 17:04:29 -08002168 // Verify that we've adapted all the way down.
2169 stats_proxy_->ResetMockStats();
asaperssonf7e294d2017-06-13 23:25:22 -07002170 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
Jonathan Yubc771b72017-12-08 17:04:29 -08002171 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_framerate);
2172 EXPECT_EQ(loop_count - 1,
asaperssonf7e294d2017-06-13 23:25:22 -07002173 stats_proxy_->GetStats().number_of_cpu_adapt_changes);
Jonathan Yubc771b72017-12-08 17:04:29 -08002174 EXPECT_EQ(kMinPixelsPerFrame, *video_source_.last_sent_width() *
2175 *video_source_.last_sent_height());
2176 EXPECT_EQ(kMinBalancedFramerateFps,
2177 video_source_.sink_wants().max_framerate_fps);
asaperssonf7e294d2017-06-13 23:25:22 -07002178
Jonathan Yubc771b72017-12-08 17:04:29 -08002179 // Adapt back up the same number of times we adapted down.
2180 for (int i = 0; i < loop_count - 1; ++i) {
2181 last_wants = video_source_.sink_wants();
2182
2183 // Simulate the framerate we've been asked to adapt to.
2184 const int fps = std::min(kFramerateFps, last_wants.max_framerate_fps);
2185 const int frame_interval_ms = rtc::kNumMillisecsPerSec / fps;
2186 VideoSendStream::Stats mock_stats = stats_proxy_->GetStats();
2187 mock_stats.input_frame_rate = fps;
2188 stats_proxy_->SetMockStats(mock_stats);
2189
2190 video_source_.IncomingCapturedFrame(CreateFrame(t, kWidth, kHeight));
2191 sink_.WaitForEncodedFrame(t);
2192 t += frame_interval_ms;
2193
Henrik Boström91aa7322020-04-28 12:24:33 +02002194 video_stream_encoder_->TriggerCpuUnderuse();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02002195 EXPECT_THAT(
Jonathan Yubc771b72017-12-08 17:04:29 -08002196 video_source_.sink_wants(),
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02002197 FpsInRangeForPixelsInBalanced(*video_source_.last_sent_width() *
2198 *video_source_.last_sent_height()));
Jonathan Yubc771b72017-12-08 17:04:29 -08002199 EXPECT_TRUE(video_source_.sink_wants().max_pixel_count >
2200 last_wants.max_pixel_count ||
2201 video_source_.sink_wants().max_framerate_fps >
2202 last_wants.max_framerate_fps);
asaperssonf7e294d2017-06-13 23:25:22 -07002203 }
2204
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02002205 EXPECT_THAT(video_source_.sink_wants(), FpsMaxResolutionMax());
Jonathan Yubc771b72017-12-08 17:04:29 -08002206 stats_proxy_->ResetMockStats();
asaperssonf7e294d2017-06-13 23:25:22 -07002207 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
Jonathan Yubc771b72017-12-08 17:04:29 -08002208 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
2209 EXPECT_EQ((loop_count - 1) * 2,
2210 stats_proxy_->GetStats().number_of_cpu_adapt_changes);
asaperssonf7e294d2017-06-13 23:25:22 -07002211
mflodmancc3d4422017-08-03 08:27:51 -07002212 video_stream_encoder_->Stop();
asaperssonf7e294d2017-06-13 23:25:22 -07002213}
Rasmus Brandt5cad55b2019-12-19 09:47:11 +01002214
Evan Shrubsole2e2f6742020-05-14 10:41:15 +02002215TEST_F(VideoStreamEncoderTest,
2216 SinkWantsNotChangedByResourceLimitedBeforeDegradationPreferenceChange) {
2217 video_stream_encoder_->OnBitrateUpdated(
2218 DataRate::BitsPerSec(kTargetBitrateBps),
2219 DataRate::BitsPerSec(kTargetBitrateBps),
2220 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02002221 EXPECT_THAT(video_source_.sink_wants(), UnlimitedSinkWants());
Evan Shrubsole2e2f6742020-05-14 10:41:15 +02002222
2223 const int kFrameWidth = 1280;
2224 const int kFrameHeight = 720;
2225
2226 int64_t ntp_time = kFrameIntervalMs;
2227
2228 // Force an input frame rate to be available, or the adaptation call won't
2229 // know what framerate to adapt form.
2230 const int kInputFps = 30;
2231 VideoSendStream::Stats stats = stats_proxy_->GetStats();
2232 stats.input_frame_rate = kInputFps;
2233 stats_proxy_->SetMockStats(stats);
2234
2235 video_source_.set_adaptation_enabled(true);
2236 video_stream_encoder_->SetSource(
2237 &video_source_, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02002238 EXPECT_THAT(video_source_.sink_wants(), UnlimitedSinkWants());
Evan Shrubsole2e2f6742020-05-14 10:41:15 +02002239 video_source_.IncomingCapturedFrame(
2240 CreateFrame(ntp_time, kFrameWidth, kFrameHeight));
2241 sink_.WaitForEncodedFrame(ntp_time);
2242 ntp_time += kFrameIntervalMs;
2243
2244 // Trigger CPU overuse.
2245 video_stream_encoder_->TriggerCpuOveruse();
2246 video_source_.IncomingCapturedFrame(
2247 CreateFrame(ntp_time, kFrameWidth, kFrameHeight));
2248 sink_.WaitForEncodedFrame(ntp_time);
2249 ntp_time += kFrameIntervalMs;
2250
2251 EXPECT_FALSE(video_source_.sink_wants().target_pixel_count);
2252 EXPECT_EQ(std::numeric_limits<int>::max(),
2253 video_source_.sink_wants().max_pixel_count);
2254 // Some framerate constraint should be set.
2255 int restricted_fps = video_source_.sink_wants().max_framerate_fps;
2256 EXPECT_LT(restricted_fps, kInputFps);
2257 video_source_.IncomingCapturedFrame(
2258 CreateFrame(ntp_time, kFrameWidth, kFrameHeight));
2259 sink_.WaitForEncodedFrame(ntp_time);
2260 ntp_time += 100;
2261
Henrik Boström2671dac2020-05-19 16:29:09 +02002262 video_stream_encoder_->SetSourceAndWaitForRestrictionsUpdated(
Evan Shrubsole2e2f6742020-05-14 10:41:15 +02002263 &video_source_, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
2264 // Give the encoder queue time to process the change in degradation preference
2265 // by waiting for an encoded frame.
2266 video_source_.IncomingCapturedFrame(
2267 CreateFrame(ntp_time, kFrameWidth, kFrameHeight));
2268 sink_.WaitForEncodedFrame(ntp_time);
2269 ntp_time += kFrameIntervalMs;
2270
2271 video_stream_encoder_->TriggerQualityLow();
2272 video_source_.IncomingCapturedFrame(
2273 CreateFrame(ntp_time, kFrameWidth, kFrameHeight));
2274 sink_.WaitForEncodedFrame(ntp_time);
2275 ntp_time += kFrameIntervalMs;
2276
2277 // Some resolution constraint should be set.
2278 EXPECT_FALSE(video_source_.sink_wants().target_pixel_count);
2279 EXPECT_LT(video_source_.sink_wants().max_pixel_count,
2280 kFrameWidth * kFrameHeight);
2281 EXPECT_EQ(video_source_.sink_wants().max_framerate_fps, kInputFps);
2282
2283 int pixel_count = video_source_.sink_wants().max_pixel_count;
2284 // Triggering a CPU underuse should not change the sink wants since it has
2285 // not been overused for resolution since we changed degradation preference.
2286 video_stream_encoder_->TriggerCpuUnderuse();
2287 video_source_.IncomingCapturedFrame(
2288 CreateFrame(ntp_time, kFrameWidth, kFrameHeight));
2289 sink_.WaitForEncodedFrame(ntp_time);
2290 ntp_time += kFrameIntervalMs;
2291 EXPECT_EQ(video_source_.sink_wants().max_pixel_count, pixel_count);
2292 EXPECT_EQ(video_source_.sink_wants().max_framerate_fps, kInputFps);
2293
Evan Shrubsole64469032020-06-11 10:45:29 +02002294 // Change the degradation preference back. CPU underuse should not adapt since
2295 // QP is most limited.
Henrik Boström2671dac2020-05-19 16:29:09 +02002296 video_stream_encoder_->SetSourceAndWaitForRestrictionsUpdated(
Evan Shrubsole2e2f6742020-05-14 10:41:15 +02002297 &video_source_, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
2298 video_source_.IncomingCapturedFrame(
2299 CreateFrame(ntp_time, kFrameWidth, kFrameHeight));
2300 sink_.WaitForEncodedFrame(ntp_time);
2301 ntp_time += 100;
2302 // Resolution adaptations is gone after changing degradation preference.
2303 EXPECT_FALSE(video_source_.sink_wants().target_pixel_count);
2304 EXPECT_EQ(std::numeric_limits<int>::max(),
2305 video_source_.sink_wants().max_pixel_count);
2306 // The fps adaptation from above is now back.
2307 EXPECT_EQ(video_source_.sink_wants().max_framerate_fps, restricted_fps);
2308
2309 // Trigger CPU underuse.
2310 video_stream_encoder_->TriggerCpuUnderuse();
2311 video_source_.IncomingCapturedFrame(
2312 CreateFrame(ntp_time, kFrameWidth, kFrameHeight));
2313 sink_.WaitForEncodedFrame(ntp_time);
2314 ntp_time += kFrameIntervalMs;
Evan Shrubsole64469032020-06-11 10:45:29 +02002315 EXPECT_EQ(video_source_.sink_wants().max_framerate_fps, restricted_fps);
2316
2317 // Trigger QP underuse, fps should return to normal.
2318 video_stream_encoder_->TriggerQualityHigh();
2319 video_source_.IncomingCapturedFrame(
2320 CreateFrame(ntp_time, kFrameWidth, kFrameHeight));
2321 sink_.WaitForEncodedFrame(ntp_time);
2322 ntp_time += kFrameIntervalMs;
2323 EXPECT_THAT(video_source_.sink_wants(), FpsMax());
Evan Shrubsole2e2f6742020-05-14 10:41:15 +02002324
2325 video_stream_encoder_->Stop();
2326}
2327
mflodmancc3d4422017-08-03 08:27:51 -07002328TEST_F(VideoStreamEncoderTest, SinkWantsStoredByDegradationPreference) {
Henrik Boström381d1092020-05-12 18:49:07 +02002329 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01002330 DataRate::BitsPerSec(kTargetBitrateBps),
2331 DataRate::BitsPerSec(kTargetBitrateBps),
2332 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02002333 EXPECT_THAT(video_source_.sink_wants(), UnlimitedSinkWants());
perkj803d97f2016-11-01 11:45:46 -07002334
sprangc5d62e22017-04-02 23:53:04 -07002335 const int kFrameWidth = 1280;
2336 const int kFrameHeight = 720;
sprangc5d62e22017-04-02 23:53:04 -07002337
Åsa Persson8c1bf952018-09-13 10:42:19 +02002338 int64_t frame_timestamp = 1;
perkj803d97f2016-11-01 11:45:46 -07002339
kthelgason5e13d412016-12-01 03:59:51 -08002340 video_source_.IncomingCapturedFrame(
sprangc5d62e22017-04-02 23:53:04 -07002341 CreateFrame(frame_timestamp, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 07:06:52 -07002342 WaitForEncodedFrame(frame_timestamp);
sprangc5d62e22017-04-02 23:53:04 -07002343 frame_timestamp += kFrameIntervalMs;
2344
perkj803d97f2016-11-01 11:45:46 -07002345 // Trigger CPU overuse.
mflodmancc3d4422017-08-03 08:27:51 -07002346 video_stream_encoder_->TriggerCpuOveruse();
perkj803d97f2016-11-01 11:45:46 -07002347 video_source_.IncomingCapturedFrame(
sprangc5d62e22017-04-02 23:53:04 -07002348 CreateFrame(frame_timestamp, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 07:06:52 -07002349 WaitForEncodedFrame(frame_timestamp);
sprangc5d62e22017-04-02 23:53:04 -07002350 frame_timestamp += kFrameIntervalMs;
sprang3ea3c772017-03-30 07:23:48 -07002351
asapersson0944a802017-04-07 00:57:58 -07002352 // Default degradation preference is maintain-framerate, so will lower max
sprangc5d62e22017-04-02 23:53:04 -07002353 // wanted resolution.
2354 EXPECT_FALSE(video_source_.sink_wants().target_pixel_count);
2355 EXPECT_LT(video_source_.sink_wants().max_pixel_count,
2356 kFrameWidth * kFrameHeight);
Åsa Persson8c1bf952018-09-13 10:42:19 +02002357 EXPECT_EQ(kDefaultFramerate, video_source_.sink_wants().max_framerate_fps);
sprangc5d62e22017-04-02 23:53:04 -07002358
2359 // Set new source, switch to maintain-resolution.
perkj803d97f2016-11-01 11:45:46 -07002360 test::FrameForwarder new_video_source;
Henrik Boström381d1092020-05-12 18:49:07 +02002361 video_stream_encoder_->SetSourceAndWaitForRestrictionsUpdated(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002362 &new_video_source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
Henrik Boström07b17df2020-01-15 11:42:12 +01002363 // Give the encoder queue time to process the change in degradation preference
2364 // by waiting for an encoded frame.
2365 new_video_source.IncomingCapturedFrame(
2366 CreateFrame(frame_timestamp, kFrameWidth, kFrameWidth));
2367 sink_.WaitForEncodedFrame(frame_timestamp);
2368 frame_timestamp += kFrameIntervalMs;
sprangc5d62e22017-04-02 23:53:04 -07002369 // Initially no degradation registered.
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02002370 EXPECT_THAT(new_video_source.sink_wants(), FpsMaxResolutionMax());
perkj803d97f2016-11-01 11:45:46 -07002371
sprangc5d62e22017-04-02 23:53:04 -07002372 // Force an input frame rate to be available, or the adaptation call won't
2373 // know what framerate to adapt form.
asapersson02465b82017-04-10 01:12:52 -07002374 const int kInputFps = 30;
sprangc5d62e22017-04-02 23:53:04 -07002375 VideoSendStream::Stats stats = stats_proxy_->GetStats();
asapersson02465b82017-04-10 01:12:52 -07002376 stats.input_frame_rate = kInputFps;
sprangc5d62e22017-04-02 23:53:04 -07002377 stats_proxy_->SetMockStats(stats);
2378
mflodmancc3d4422017-08-03 08:27:51 -07002379 video_stream_encoder_->TriggerCpuOveruse();
perkj803d97f2016-11-01 11:45:46 -07002380 new_video_source.IncomingCapturedFrame(
sprangc5d62e22017-04-02 23:53:04 -07002381 CreateFrame(frame_timestamp, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 07:06:52 -07002382 WaitForEncodedFrame(frame_timestamp);
sprangc5d62e22017-04-02 23:53:04 -07002383 frame_timestamp += kFrameIntervalMs;
2384
2385 // Some framerate constraint should be set.
sprang84a37592017-02-10 07:04:27 -08002386 EXPECT_FALSE(new_video_source.sink_wants().target_pixel_count);
sprangc5d62e22017-04-02 23:53:04 -07002387 EXPECT_EQ(std::numeric_limits<int>::max(),
2388 new_video_source.sink_wants().max_pixel_count);
asapersson02465b82017-04-10 01:12:52 -07002389 EXPECT_LT(new_video_source.sink_wants().max_framerate_fps, kInputFps);
sprangc5d62e22017-04-02 23:53:04 -07002390
asapersson02465b82017-04-10 01:12:52 -07002391 // Turn off degradation completely.
Henrik Boström381d1092020-05-12 18:49:07 +02002392 video_stream_encoder_->SetSourceAndWaitForRestrictionsUpdated(
2393 &new_video_source, webrtc::DegradationPreference::DISABLED);
Henrik Boström07b17df2020-01-15 11:42:12 +01002394 // Give the encoder queue time to process the change in degradation preference
2395 // by waiting for an encoded frame.
2396 new_video_source.IncomingCapturedFrame(
2397 CreateFrame(frame_timestamp, kFrameWidth, kFrameWidth));
2398 sink_.WaitForEncodedFrame(frame_timestamp);
2399 frame_timestamp += kFrameIntervalMs;
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02002400 EXPECT_THAT(new_video_source.sink_wants(), FpsMaxResolutionMax());
sprangc5d62e22017-04-02 23:53:04 -07002401
mflodmancc3d4422017-08-03 08:27:51 -07002402 video_stream_encoder_->TriggerCpuOveruse();
sprangc5d62e22017-04-02 23:53:04 -07002403 new_video_source.IncomingCapturedFrame(
2404 CreateFrame(frame_timestamp, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 07:06:52 -07002405 WaitForEncodedFrame(frame_timestamp);
sprangc5d62e22017-04-02 23:53:04 -07002406 frame_timestamp += kFrameIntervalMs;
2407
2408 // Still no degradation.
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02002409 EXPECT_THAT(new_video_source.sink_wants(), FpsMaxResolutionMax());
perkj803d97f2016-11-01 11:45:46 -07002410
2411 // Calling SetSource with resolution scaling enabled apply the old SinkWants.
Henrik Boström381d1092020-05-12 18:49:07 +02002412 video_stream_encoder_->SetSourceAndWaitForRestrictionsUpdated(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002413 &new_video_source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
Henrik Boström07b17df2020-01-15 11:42:12 +01002414 // Give the encoder queue time to process the change in degradation preference
2415 // by waiting for an encoded frame.
2416 new_video_source.IncomingCapturedFrame(
2417 CreateFrame(frame_timestamp, kFrameWidth, kFrameWidth));
2418 sink_.WaitForEncodedFrame(frame_timestamp);
2419 frame_timestamp += kFrameIntervalMs;
sprangc5d62e22017-04-02 23:53:04 -07002420 EXPECT_LT(new_video_source.sink_wants().max_pixel_count,
2421 kFrameWidth * kFrameHeight);
sprang84a37592017-02-10 07:04:27 -08002422 EXPECT_FALSE(new_video_source.sink_wants().target_pixel_count);
Åsa Persson8c1bf952018-09-13 10:42:19 +02002423 EXPECT_EQ(kDefaultFramerate, new_video_source.sink_wants().max_framerate_fps);
sprangc5d62e22017-04-02 23:53:04 -07002424
2425 // Calling SetSource with framerate scaling enabled apply the old SinkWants.
Henrik Boström381d1092020-05-12 18:49:07 +02002426 video_stream_encoder_->SetSourceAndWaitForRestrictionsUpdated(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002427 &new_video_source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
Henrik Boström07b17df2020-01-15 11:42:12 +01002428 // Give the encoder queue time to process the change in degradation preference
2429 // by waiting for an encoded frame.
2430 new_video_source.IncomingCapturedFrame(
2431 CreateFrame(frame_timestamp, kFrameWidth, kFrameWidth));
2432 sink_.WaitForEncodedFrame(frame_timestamp);
2433 frame_timestamp += kFrameIntervalMs;
sprangc5d62e22017-04-02 23:53:04 -07002434 EXPECT_FALSE(new_video_source.sink_wants().target_pixel_count);
2435 EXPECT_EQ(std::numeric_limits<int>::max(),
2436 new_video_source.sink_wants().max_pixel_count);
asapersson02465b82017-04-10 01:12:52 -07002437 EXPECT_LT(new_video_source.sink_wants().max_framerate_fps, kInputFps);
perkj803d97f2016-11-01 11:45:46 -07002438
mflodmancc3d4422017-08-03 08:27:51 -07002439 video_stream_encoder_->Stop();
perkj803d97f2016-11-01 11:45:46 -07002440}
2441
mflodmancc3d4422017-08-03 08:27:51 -07002442TEST_F(VideoStreamEncoderTest, StatsTracksQualityAdaptationStats) {
Henrik Boström381d1092020-05-12 18:49:07 +02002443 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01002444 DataRate::BitsPerSec(kTargetBitrateBps),
2445 DataRate::BitsPerSec(kTargetBitrateBps),
2446 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
perkj803d97f2016-11-01 11:45:46 -07002447
asaperssonfab67072017-04-04 05:51:49 -07002448 const int kWidth = 1280;
2449 const int kHeight = 720;
asaperssonfab67072017-04-04 05:51:49 -07002450 video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002451 WaitForEncodedFrame(1);
asaperssonfab67072017-04-04 05:51:49 -07002452 VideoSendStream::Stats stats = stats_proxy_->GetStats();
2453 EXPECT_FALSE(stats.bw_limited_resolution);
2454 EXPECT_EQ(0, stats.number_of_quality_adapt_changes);
2455
2456 // Trigger adapt down.
mflodmancc3d4422017-08-03 08:27:51 -07002457 video_stream_encoder_->TriggerQualityLow();
asaperssonfab67072017-04-04 05:51:49 -07002458 video_source_.IncomingCapturedFrame(CreateFrame(2, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002459 WaitForEncodedFrame(2);
asaperssonfab67072017-04-04 05:51:49 -07002460
2461 stats = stats_proxy_->GetStats();
2462 EXPECT_TRUE(stats.bw_limited_resolution);
2463 EXPECT_EQ(1, stats.number_of_quality_adapt_changes);
2464
2465 // Trigger adapt up.
mflodmancc3d4422017-08-03 08:27:51 -07002466 video_stream_encoder_->TriggerQualityHigh();
asaperssonfab67072017-04-04 05:51:49 -07002467 video_source_.IncomingCapturedFrame(CreateFrame(3, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002468 WaitForEncodedFrame(3);
asaperssonfab67072017-04-04 05:51:49 -07002469
2470 stats = stats_proxy_->GetStats();
2471 EXPECT_FALSE(stats.bw_limited_resolution);
2472 EXPECT_EQ(2, stats.number_of_quality_adapt_changes);
2473 EXPECT_EQ(0, stats.number_of_cpu_adapt_changes);
2474
mflodmancc3d4422017-08-03 08:27:51 -07002475 video_stream_encoder_->Stop();
asaperssonfab67072017-04-04 05:51:49 -07002476}
2477
mflodmancc3d4422017-08-03 08:27:51 -07002478TEST_F(VideoStreamEncoderTest, StatsTracksCpuAdaptationStats) {
Henrik Boström381d1092020-05-12 18:49:07 +02002479 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01002480 DataRate::BitsPerSec(kTargetBitrateBps),
2481 DataRate::BitsPerSec(kTargetBitrateBps),
2482 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asaperssonfab67072017-04-04 05:51:49 -07002483
2484 const int kWidth = 1280;
2485 const int kHeight = 720;
asaperssonfab67072017-04-04 05:51:49 -07002486 video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002487 WaitForEncodedFrame(1);
perkj803d97f2016-11-01 11:45:46 -07002488 VideoSendStream::Stats stats = stats_proxy_->GetStats();
2489 EXPECT_FALSE(stats.cpu_limited_resolution);
2490 EXPECT_EQ(0, stats.number_of_cpu_adapt_changes);
2491
2492 // Trigger CPU overuse.
mflodmancc3d4422017-08-03 08:27:51 -07002493 video_stream_encoder_->TriggerCpuOveruse();
asaperssonfab67072017-04-04 05:51:49 -07002494 video_source_.IncomingCapturedFrame(CreateFrame(2, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002495 WaitForEncodedFrame(2);
perkj803d97f2016-11-01 11:45:46 -07002496
2497 stats = stats_proxy_->GetStats();
2498 EXPECT_TRUE(stats.cpu_limited_resolution);
2499 EXPECT_EQ(1, stats.number_of_cpu_adapt_changes);
2500
2501 // Trigger CPU normal use.
Henrik Boström91aa7322020-04-28 12:24:33 +02002502 video_stream_encoder_->TriggerCpuUnderuse();
asaperssonfab67072017-04-04 05:51:49 -07002503 video_source_.IncomingCapturedFrame(CreateFrame(3, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002504 WaitForEncodedFrame(3);
perkj803d97f2016-11-01 11:45:46 -07002505
2506 stats = stats_proxy_->GetStats();
2507 EXPECT_FALSE(stats.cpu_limited_resolution);
2508 EXPECT_EQ(2, stats.number_of_cpu_adapt_changes);
asaperssonfab67072017-04-04 05:51:49 -07002509 EXPECT_EQ(0, stats.number_of_quality_adapt_changes);
perkj803d97f2016-11-01 11:45:46 -07002510
mflodmancc3d4422017-08-03 08:27:51 -07002511 video_stream_encoder_->Stop();
perkj803d97f2016-11-01 11:45:46 -07002512}
2513
mflodmancc3d4422017-08-03 08:27:51 -07002514TEST_F(VideoStreamEncoderTest, SwitchingSourceKeepsCpuAdaptation) {
Henrik Boström381d1092020-05-12 18:49:07 +02002515 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01002516 DataRate::BitsPerSec(kTargetBitrateBps),
2517 DataRate::BitsPerSec(kTargetBitrateBps),
2518 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
kthelgason876222f2016-11-29 01:44:11 -08002519
asaperssonfab67072017-04-04 05:51:49 -07002520 const int kWidth = 1280;
2521 const int kHeight = 720;
2522 video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002523 WaitForEncodedFrame(1);
kthelgason876222f2016-11-29 01:44:11 -08002524 VideoSendStream::Stats stats = stats_proxy_->GetStats();
asapersson09f05612017-05-15 23:40:18 -07002525 EXPECT_FALSE(stats.bw_limited_resolution);
kthelgason876222f2016-11-29 01:44:11 -08002526 EXPECT_FALSE(stats.cpu_limited_resolution);
2527 EXPECT_EQ(0, stats.number_of_cpu_adapt_changes);
2528
asaperssonfab67072017-04-04 05:51:49 -07002529 // Trigger CPU overuse.
mflodmancc3d4422017-08-03 08:27:51 -07002530 video_stream_encoder_->TriggerCpuOveruse();
asaperssonfab67072017-04-04 05:51:49 -07002531 video_source_.IncomingCapturedFrame(CreateFrame(2, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002532 WaitForEncodedFrame(2);
kthelgason876222f2016-11-29 01:44:11 -08002533 stats = stats_proxy_->GetStats();
asapersson09f05612017-05-15 23:40:18 -07002534 EXPECT_FALSE(stats.bw_limited_resolution);
kthelgason876222f2016-11-29 01:44:11 -08002535 EXPECT_TRUE(stats.cpu_limited_resolution);
2536 EXPECT_EQ(1, stats.number_of_cpu_adapt_changes);
2537
2538 // Set new source with adaptation still enabled.
2539 test::FrameForwarder new_video_source;
mflodmancc3d4422017-08-03 08:27:51 -07002540 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002541 &new_video_source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
kthelgason876222f2016-11-29 01:44:11 -08002542
asaperssonfab67072017-04-04 05:51:49 -07002543 new_video_source.IncomingCapturedFrame(CreateFrame(3, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002544 WaitForEncodedFrame(3);
kthelgason876222f2016-11-29 01:44:11 -08002545 stats = stats_proxy_->GetStats();
asapersson09f05612017-05-15 23:40:18 -07002546 EXPECT_FALSE(stats.bw_limited_resolution);
kthelgason876222f2016-11-29 01:44:11 -08002547 EXPECT_TRUE(stats.cpu_limited_resolution);
2548 EXPECT_EQ(1, stats.number_of_cpu_adapt_changes);
2549
2550 // Set adaptation disabled.
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002551 video_stream_encoder_->SetSource(&new_video_source,
2552 webrtc::DegradationPreference::DISABLED);
kthelgason876222f2016-11-29 01:44:11 -08002553
asaperssonfab67072017-04-04 05:51:49 -07002554 new_video_source.IncomingCapturedFrame(CreateFrame(4, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002555 WaitForEncodedFrame(4);
kthelgason876222f2016-11-29 01:44:11 -08002556 stats = stats_proxy_->GetStats();
asapersson09f05612017-05-15 23:40:18 -07002557 EXPECT_FALSE(stats.bw_limited_resolution);
kthelgason876222f2016-11-29 01:44:11 -08002558 EXPECT_FALSE(stats.cpu_limited_resolution);
2559 EXPECT_EQ(1, stats.number_of_cpu_adapt_changes);
2560
2561 // Set adaptation back to enabled.
mflodmancc3d4422017-08-03 08:27:51 -07002562 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002563 &new_video_source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
kthelgason876222f2016-11-29 01:44:11 -08002564
asaperssonfab67072017-04-04 05:51:49 -07002565 new_video_source.IncomingCapturedFrame(CreateFrame(5, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002566 WaitForEncodedFrame(5);
kthelgason876222f2016-11-29 01:44:11 -08002567 stats = stats_proxy_->GetStats();
asapersson09f05612017-05-15 23:40:18 -07002568 EXPECT_FALSE(stats.bw_limited_resolution);
kthelgason876222f2016-11-29 01:44:11 -08002569 EXPECT_TRUE(stats.cpu_limited_resolution);
2570 EXPECT_EQ(1, stats.number_of_cpu_adapt_changes);
2571
asaperssonfab67072017-04-04 05:51:49 -07002572 // Trigger CPU normal use.
Henrik Boström91aa7322020-04-28 12:24:33 +02002573 video_stream_encoder_->TriggerCpuUnderuse();
asaperssonfab67072017-04-04 05:51:49 -07002574 new_video_source.IncomingCapturedFrame(CreateFrame(6, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002575 WaitForEncodedFrame(6);
kthelgason876222f2016-11-29 01:44:11 -08002576 stats = stats_proxy_->GetStats();
asapersson09f05612017-05-15 23:40:18 -07002577 EXPECT_FALSE(stats.bw_limited_resolution);
kthelgason876222f2016-11-29 01:44:11 -08002578 EXPECT_FALSE(stats.cpu_limited_resolution);
2579 EXPECT_EQ(2, stats.number_of_cpu_adapt_changes);
asapersson02465b82017-04-10 01:12:52 -07002580 EXPECT_EQ(0, stats.number_of_quality_adapt_changes);
kthelgason876222f2016-11-29 01:44:11 -08002581
mflodmancc3d4422017-08-03 08:27:51 -07002582 video_stream_encoder_->Stop();
kthelgason876222f2016-11-29 01:44:11 -08002583}
2584
mflodmancc3d4422017-08-03 08:27:51 -07002585TEST_F(VideoStreamEncoderTest, SwitchingSourceKeepsQualityAdaptation) {
Henrik Boström381d1092020-05-12 18:49:07 +02002586 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01002587 DataRate::BitsPerSec(kTargetBitrateBps),
2588 DataRate::BitsPerSec(kTargetBitrateBps),
2589 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
kthelgason876222f2016-11-29 01:44:11 -08002590
asaperssonfab67072017-04-04 05:51:49 -07002591 const int kWidth = 1280;
2592 const int kHeight = 720;
2593 video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002594 WaitForEncodedFrame(1);
kthelgason876222f2016-11-29 01:44:11 -08002595 VideoSendStream::Stats stats = stats_proxy_->GetStats();
kthelgason876222f2016-11-29 01:44:11 -08002596 EXPECT_FALSE(stats.bw_limited_resolution);
asapersson13874762017-06-07 00:01:02 -07002597 EXPECT_FALSE(stats.bw_limited_framerate);
asaperssonfab67072017-04-04 05:51:49 -07002598 EXPECT_EQ(0, stats.number_of_quality_adapt_changes);
kthelgason876222f2016-11-29 01:44:11 -08002599
2600 // Set new source with adaptation still enabled.
2601 test::FrameForwarder new_video_source;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002602 video_stream_encoder_->SetSource(&new_video_source,
2603 webrtc::DegradationPreference::BALANCED);
kthelgason876222f2016-11-29 01:44:11 -08002604
asaperssonfab67072017-04-04 05:51:49 -07002605 new_video_source.IncomingCapturedFrame(CreateFrame(2, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002606 WaitForEncodedFrame(2);
kthelgason876222f2016-11-29 01:44:11 -08002607 stats = stats_proxy_->GetStats();
kthelgason876222f2016-11-29 01:44:11 -08002608 EXPECT_FALSE(stats.bw_limited_resolution);
asapersson13874762017-06-07 00:01:02 -07002609 EXPECT_FALSE(stats.bw_limited_framerate);
asaperssonfab67072017-04-04 05:51:49 -07002610 EXPECT_EQ(0, stats.number_of_quality_adapt_changes);
kthelgason876222f2016-11-29 01:44:11 -08002611
asaperssonfab67072017-04-04 05:51:49 -07002612 // Trigger adapt down.
mflodmancc3d4422017-08-03 08:27:51 -07002613 video_stream_encoder_->TriggerQualityLow();
asaperssonfab67072017-04-04 05:51:49 -07002614 new_video_source.IncomingCapturedFrame(CreateFrame(3, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002615 WaitForEncodedFrame(3);
kthelgason876222f2016-11-29 01:44:11 -08002616 stats = stats_proxy_->GetStats();
kthelgason876222f2016-11-29 01:44:11 -08002617 EXPECT_TRUE(stats.bw_limited_resolution);
asapersson13874762017-06-07 00:01:02 -07002618 EXPECT_FALSE(stats.bw_limited_framerate);
asaperssonfab67072017-04-04 05:51:49 -07002619 EXPECT_EQ(1, stats.number_of_quality_adapt_changes);
kthelgason876222f2016-11-29 01:44:11 -08002620
asaperssonfab67072017-04-04 05:51:49 -07002621 // Set new source with adaptation still enabled.
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002622 video_stream_encoder_->SetSource(&new_video_source,
2623 webrtc::DegradationPreference::BALANCED);
kthelgason876222f2016-11-29 01:44:11 -08002624
asaperssonfab67072017-04-04 05:51:49 -07002625 new_video_source.IncomingCapturedFrame(CreateFrame(4, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002626 WaitForEncodedFrame(4);
kthelgason876222f2016-11-29 01:44:11 -08002627 stats = stats_proxy_->GetStats();
kthelgason876222f2016-11-29 01:44:11 -08002628 EXPECT_TRUE(stats.bw_limited_resolution);
asapersson13874762017-06-07 00:01:02 -07002629 EXPECT_FALSE(stats.bw_limited_framerate);
asaperssonfab67072017-04-04 05:51:49 -07002630 EXPECT_EQ(1, stats.number_of_quality_adapt_changes);
kthelgason876222f2016-11-29 01:44:11 -08002631
asapersson02465b82017-04-10 01:12:52 -07002632 // Disable resolution scaling.
mflodmancc3d4422017-08-03 08:27:51 -07002633 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002634 &new_video_source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
kthelgason876222f2016-11-29 01:44:11 -08002635
asaperssonfab67072017-04-04 05:51:49 -07002636 new_video_source.IncomingCapturedFrame(CreateFrame(5, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002637 WaitForEncodedFrame(5);
kthelgason876222f2016-11-29 01:44:11 -08002638 stats = stats_proxy_->GetStats();
kthelgason876222f2016-11-29 01:44:11 -08002639 EXPECT_FALSE(stats.bw_limited_resolution);
asapersson13874762017-06-07 00:01:02 -07002640 EXPECT_FALSE(stats.bw_limited_framerate);
asaperssonfab67072017-04-04 05:51:49 -07002641 EXPECT_EQ(1, stats.number_of_quality_adapt_changes);
2642 EXPECT_EQ(0, stats.number_of_cpu_adapt_changes);
kthelgason876222f2016-11-29 01:44:11 -08002643
mflodmancc3d4422017-08-03 08:27:51 -07002644 video_stream_encoder_->Stop();
kthelgason876222f2016-11-29 01:44:11 -08002645}
2646
mflodmancc3d4422017-08-03 08:27:51 -07002647TEST_F(VideoStreamEncoderTest,
2648 QualityAdaptationStatsAreResetWhenScalerIsDisabled) {
Henrik Boström381d1092020-05-12 18:49:07 +02002649 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01002650 DataRate::BitsPerSec(kTargetBitrateBps),
2651 DataRate::BitsPerSec(kTargetBitrateBps),
2652 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asapersson36e9eb42017-03-31 05:29:12 -07002653
2654 const int kWidth = 1280;
2655 const int kHeight = 720;
Åsa Persson8c1bf952018-09-13 10:42:19 +02002656 int64_t timestamp_ms = kFrameIntervalMs;
asapersson36e9eb42017-03-31 05:29:12 -07002657 video_source_.set_adaptation_enabled(true);
Åsa Persson8c1bf952018-09-13 10:42:19 +02002658 video_source_.IncomingCapturedFrame(
2659 CreateFrame(timestamp_ms, kWidth, kHeight));
2660 WaitForEncodedFrame(timestamp_ms);
asapersson36e9eb42017-03-31 05:29:12 -07002661 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
2662 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
2663 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
2664
2665 // Trigger adapt down.
mflodmancc3d4422017-08-03 08:27:51 -07002666 video_stream_encoder_->TriggerQualityLow();
Åsa Persson8c1bf952018-09-13 10:42:19 +02002667 timestamp_ms += kFrameIntervalMs;
2668 video_source_.IncomingCapturedFrame(
2669 CreateFrame(timestamp_ms, kWidth, kHeight));
2670 WaitForEncodedFrame(timestamp_ms);
asapersson36e9eb42017-03-31 05:29:12 -07002671 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
2672 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
2673 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
2674
2675 // Trigger overuse.
mflodmancc3d4422017-08-03 08:27:51 -07002676 video_stream_encoder_->TriggerCpuOveruse();
Åsa Persson8c1bf952018-09-13 10:42:19 +02002677 timestamp_ms += kFrameIntervalMs;
2678 video_source_.IncomingCapturedFrame(
2679 CreateFrame(timestamp_ms, kWidth, kHeight));
2680 WaitForEncodedFrame(timestamp_ms);
asapersson36e9eb42017-03-31 05:29:12 -07002681 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
2682 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
2683 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
2684
Niels Möller4db138e2018-04-19 09:04:13 +02002685 // Leave source unchanged, but disable quality scaler.
asapersson36e9eb42017-03-31 05:29:12 -07002686 fake_encoder_.SetQualityScaling(false);
Niels Möller4db138e2018-04-19 09:04:13 +02002687
2688 VideoEncoderConfig video_encoder_config;
2689 test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
2690 // Make format different, to force recreation of encoder.
2691 video_encoder_config.video_format.parameters["foo"] = "foo";
2692 video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config),
Niels Möllerf1338562018-04-26 09:51:47 +02002693 kMaxPayloadLength);
Åsa Persson8c1bf952018-09-13 10:42:19 +02002694 timestamp_ms += kFrameIntervalMs;
2695 video_source_.IncomingCapturedFrame(
2696 CreateFrame(timestamp_ms, kWidth, kHeight));
2697 WaitForEncodedFrame(timestamp_ms);
asapersson36e9eb42017-03-31 05:29:12 -07002698 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
2699 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
2700 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
2701
mflodmancc3d4422017-08-03 08:27:51 -07002702 video_stream_encoder_->Stop();
asapersson36e9eb42017-03-31 05:29:12 -07002703}
2704
mflodmancc3d4422017-08-03 08:27:51 -07002705TEST_F(VideoStreamEncoderTest,
Evan Shrubsole33be9df2020-03-05 18:39:32 +01002706 StatsTracksCpuAdaptationStatsWhenSwitchingSource_Balanced) {
Henrik Boström381d1092020-05-12 18:49:07 +02002707 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Evan Shrubsole33be9df2020-03-05 18:39:32 +01002708 DataRate::BitsPerSec(kTargetBitrateBps),
2709 DataRate::BitsPerSec(kTargetBitrateBps),
2710 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
2711
2712 const int kWidth = 1280;
2713 const int kHeight = 720;
2714 int sequence = 1;
2715
2716 // Enable BALANCED preference, no initial limitation.
2717 test::FrameForwarder source;
2718 video_stream_encoder_->SetSource(&source,
2719 webrtc::DegradationPreference::BALANCED);
2720 source.IncomingCapturedFrame(CreateFrame(sequence, kWidth, kHeight));
2721 WaitForEncodedFrame(sequence++);
2722 VideoSendStream::Stats stats = stats_proxy_->GetStats();
2723 EXPECT_FALSE(stats.cpu_limited_resolution);
2724 EXPECT_FALSE(stats.cpu_limited_framerate);
2725 EXPECT_EQ(0, stats.number_of_cpu_adapt_changes);
2726
2727 // Trigger CPU overuse, should now adapt down.
2728 video_stream_encoder_->TriggerCpuOveruse();
2729 source.IncomingCapturedFrame(CreateFrame(sequence, kWidth, kHeight));
2730 WaitForEncodedFrame(sequence++);
2731 stats = stats_proxy_->GetStats();
2732 EXPECT_EQ(1, stats.number_of_cpu_adapt_changes);
2733
2734 // Set new degradation preference should clear restrictions since we changed
2735 // from BALANCED.
Evan Shrubsolede2049e2020-05-25 16:54:21 +02002736 video_stream_encoder_->SetSourceAndWaitForRestrictionsUpdated(
Evan Shrubsole33be9df2020-03-05 18:39:32 +01002737 &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
2738 source.IncomingCapturedFrame(CreateFrame(sequence, kWidth, kHeight));
2739 WaitForEncodedFrame(sequence++);
2740 stats = stats_proxy_->GetStats();
2741 EXPECT_FALSE(stats.cpu_limited_resolution);
2742 EXPECT_FALSE(stats.cpu_limited_framerate);
2743 EXPECT_EQ(1, stats.number_of_cpu_adapt_changes);
2744
2745 // Force an input frame rate to be available, or the adaptation call won't
2746 // know what framerate to adapt from.
2747 VideoSendStream::Stats mock_stats = stats_proxy_->GetStats();
2748 mock_stats.input_frame_rate = 30;
2749 stats_proxy_->SetMockStats(mock_stats);
2750 video_stream_encoder_->TriggerCpuOveruse();
2751 stats_proxy_->ResetMockStats();
2752 source.IncomingCapturedFrame(CreateFrame(sequence, kWidth, kHeight));
2753 WaitForEncodedFrame(sequence++);
2754
2755 // We have now adapted once.
2756 stats = stats_proxy_->GetStats();
2757 EXPECT_EQ(2, stats.number_of_cpu_adapt_changes);
2758
2759 // Back to BALANCED, should clear the restrictions again.
Evan Shrubsolede2049e2020-05-25 16:54:21 +02002760 video_stream_encoder_->SetSourceAndWaitForRestrictionsUpdated(
2761 &source, webrtc::DegradationPreference::BALANCED);
Evan Shrubsole33be9df2020-03-05 18:39:32 +01002762 source.IncomingCapturedFrame(CreateFrame(sequence, kWidth, kHeight));
2763 WaitForEncodedFrame(sequence++);
2764 stats = stats_proxy_->GetStats();
2765 EXPECT_FALSE(stats.cpu_limited_resolution);
2766 EXPECT_FALSE(stats.cpu_limited_framerate);
2767 EXPECT_EQ(2, stats.number_of_cpu_adapt_changes);
2768
2769 video_stream_encoder_->Stop();
2770}
2771
2772TEST_F(VideoStreamEncoderTest,
mflodmancc3d4422017-08-03 08:27:51 -07002773 StatsTracksCpuAdaptationStatsWhenSwitchingSource) {
Henrik Boström381d1092020-05-12 18:49:07 +02002774 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01002775 DataRate::BitsPerSec(kTargetBitrateBps),
2776 DataRate::BitsPerSec(kTargetBitrateBps),
2777 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
perkj803d97f2016-11-01 11:45:46 -07002778
asapersson0944a802017-04-07 00:57:58 -07002779 const int kWidth = 1280;
2780 const int kHeight = 720;
sprang84a37592017-02-10 07:04:27 -08002781 int sequence = 1;
perkj803d97f2016-11-01 11:45:46 -07002782
asaperssonfab67072017-04-04 05:51:49 -07002783 video_source_.IncomingCapturedFrame(CreateFrame(sequence, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002784 WaitForEncodedFrame(sequence++);
perkj803d97f2016-11-01 11:45:46 -07002785 VideoSendStream::Stats stats = stats_proxy_->GetStats();
sprang84a37592017-02-10 07:04:27 -08002786 EXPECT_FALSE(stats.cpu_limited_resolution);
asapersson13874762017-06-07 00:01:02 -07002787 EXPECT_FALSE(stats.cpu_limited_framerate);
sprang84a37592017-02-10 07:04:27 -08002788 EXPECT_EQ(0, stats.number_of_cpu_adapt_changes);
2789
asapersson02465b82017-04-10 01:12:52 -07002790 // Trigger CPU overuse, should now adapt down.
mflodmancc3d4422017-08-03 08:27:51 -07002791 video_stream_encoder_->TriggerCpuOveruse();
asaperssonfab67072017-04-04 05:51:49 -07002792 video_source_.IncomingCapturedFrame(CreateFrame(sequence, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002793 WaitForEncodedFrame(sequence++);
sprang84a37592017-02-10 07:04:27 -08002794 stats = stats_proxy_->GetStats();
perkj803d97f2016-11-01 11:45:46 -07002795 EXPECT_TRUE(stats.cpu_limited_resolution);
asapersson13874762017-06-07 00:01:02 -07002796 EXPECT_FALSE(stats.cpu_limited_framerate);
perkj803d97f2016-11-01 11:45:46 -07002797 EXPECT_EQ(1, stats.number_of_cpu_adapt_changes);
2798
2799 // Set new source with adaptation still enabled.
2800 test::FrameForwarder new_video_source;
mflodmancc3d4422017-08-03 08:27:51 -07002801 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002802 &new_video_source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
perkj803d97f2016-11-01 11:45:46 -07002803
2804 new_video_source.IncomingCapturedFrame(
asaperssonfab67072017-04-04 05:51:49 -07002805 CreateFrame(sequence, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002806 WaitForEncodedFrame(sequence++);
perkj803d97f2016-11-01 11:45:46 -07002807 stats = stats_proxy_->GetStats();
2808 EXPECT_TRUE(stats.cpu_limited_resolution);
asapersson09f05612017-05-15 23:40:18 -07002809 EXPECT_FALSE(stats.cpu_limited_framerate);
perkj803d97f2016-11-01 11:45:46 -07002810 EXPECT_EQ(1, stats.number_of_cpu_adapt_changes);
2811
sprangc5d62e22017-04-02 23:53:04 -07002812 // Set cpu adaptation by frame dropping.
mflodmancc3d4422017-08-03 08:27:51 -07002813 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002814 &new_video_source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
perkj803d97f2016-11-01 11:45:46 -07002815 new_video_source.IncomingCapturedFrame(
asaperssonfab67072017-04-04 05:51:49 -07002816 CreateFrame(sequence, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002817 WaitForEncodedFrame(sequence++);
perkj803d97f2016-11-01 11:45:46 -07002818 stats = stats_proxy_->GetStats();
sprangc5d62e22017-04-02 23:53:04 -07002819 // Not adapted at first.
perkj803d97f2016-11-01 11:45:46 -07002820 EXPECT_FALSE(stats.cpu_limited_resolution);
asapersson09f05612017-05-15 23:40:18 -07002821 EXPECT_FALSE(stats.cpu_limited_framerate);
perkj803d97f2016-11-01 11:45:46 -07002822 EXPECT_EQ(1, stats.number_of_cpu_adapt_changes);
2823
sprangc5d62e22017-04-02 23:53:04 -07002824 // Force an input frame rate to be available, or the adaptation call won't
asapersson09f05612017-05-15 23:40:18 -07002825 // know what framerate to adapt from.
sprangc5d62e22017-04-02 23:53:04 -07002826 VideoSendStream::Stats mock_stats = stats_proxy_->GetStats();
2827 mock_stats.input_frame_rate = 30;
2828 stats_proxy_->SetMockStats(mock_stats);
mflodmancc3d4422017-08-03 08:27:51 -07002829 video_stream_encoder_->TriggerCpuOveruse();
sprangc5d62e22017-04-02 23:53:04 -07002830 stats_proxy_->ResetMockStats();
2831
2832 new_video_source.IncomingCapturedFrame(
asaperssonfab67072017-04-04 05:51:49 -07002833 CreateFrame(sequence, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002834 WaitForEncodedFrame(sequence++);
sprangc5d62e22017-04-02 23:53:04 -07002835
2836 // Framerate now adapted.
2837 stats = stats_proxy_->GetStats();
asapersson09f05612017-05-15 23:40:18 -07002838 EXPECT_FALSE(stats.cpu_limited_resolution);
2839 EXPECT_TRUE(stats.cpu_limited_framerate);
sprangc5d62e22017-04-02 23:53:04 -07002840 EXPECT_EQ(2, stats.number_of_cpu_adapt_changes);
2841
2842 // Disable CPU adaptation.
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002843 video_stream_encoder_->SetSource(&new_video_source,
2844 webrtc::DegradationPreference::DISABLED);
sprangc5d62e22017-04-02 23:53:04 -07002845 new_video_source.IncomingCapturedFrame(
asaperssonfab67072017-04-04 05:51:49 -07002846 CreateFrame(sequence, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002847 WaitForEncodedFrame(sequence++);
sprangc5d62e22017-04-02 23:53:04 -07002848
2849 stats = stats_proxy_->GetStats();
2850 EXPECT_FALSE(stats.cpu_limited_resolution);
asapersson13874762017-06-07 00:01:02 -07002851 EXPECT_FALSE(stats.cpu_limited_framerate);
sprangc5d62e22017-04-02 23:53:04 -07002852 EXPECT_EQ(2, stats.number_of_cpu_adapt_changes);
2853
2854 // Try to trigger overuse. Should not succeed.
2855 stats_proxy_->SetMockStats(mock_stats);
mflodmancc3d4422017-08-03 08:27:51 -07002856 video_stream_encoder_->TriggerCpuOveruse();
sprangc5d62e22017-04-02 23:53:04 -07002857 stats_proxy_->ResetMockStats();
2858
2859 stats = stats_proxy_->GetStats();
2860 EXPECT_FALSE(stats.cpu_limited_resolution);
asapersson13874762017-06-07 00:01:02 -07002861 EXPECT_FALSE(stats.cpu_limited_framerate);
sprangc5d62e22017-04-02 23:53:04 -07002862 EXPECT_EQ(2, stats.number_of_cpu_adapt_changes);
2863
2864 // Switch back the source with resolution adaptation enabled.
mflodmancc3d4422017-08-03 08:27:51 -07002865 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002866 &video_source_, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
asaperssonfab67072017-04-04 05:51:49 -07002867 video_source_.IncomingCapturedFrame(CreateFrame(sequence, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002868 WaitForEncodedFrame(sequence++);
perkj803d97f2016-11-01 11:45:46 -07002869 stats = stats_proxy_->GetStats();
2870 EXPECT_TRUE(stats.cpu_limited_resolution);
asapersson13874762017-06-07 00:01:02 -07002871 EXPECT_FALSE(stats.cpu_limited_framerate);
sprangc5d62e22017-04-02 23:53:04 -07002872 EXPECT_EQ(2, stats.number_of_cpu_adapt_changes);
perkj803d97f2016-11-01 11:45:46 -07002873
2874 // Trigger CPU normal usage.
Henrik Boström91aa7322020-04-28 12:24:33 +02002875 video_stream_encoder_->TriggerCpuUnderuse();
asaperssonfab67072017-04-04 05:51:49 -07002876 video_source_.IncomingCapturedFrame(CreateFrame(sequence, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002877 WaitForEncodedFrame(sequence++);
perkj803d97f2016-11-01 11:45:46 -07002878 stats = stats_proxy_->GetStats();
2879 EXPECT_FALSE(stats.cpu_limited_resolution);
asapersson13874762017-06-07 00:01:02 -07002880 EXPECT_FALSE(stats.cpu_limited_framerate);
sprangc5d62e22017-04-02 23:53:04 -07002881 EXPECT_EQ(3, stats.number_of_cpu_adapt_changes);
2882
2883 // Back to the source with adaptation off, set it back to maintain-resolution.
mflodmancc3d4422017-08-03 08:27:51 -07002884 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002885 &new_video_source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
sprangc5d62e22017-04-02 23:53:04 -07002886 new_video_source.IncomingCapturedFrame(
asaperssonfab67072017-04-04 05:51:49 -07002887 CreateFrame(sequence, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002888 WaitForEncodedFrame(sequence++);
sprangc5d62e22017-04-02 23:53:04 -07002889 stats = stats_proxy_->GetStats();
asapersson13874762017-06-07 00:01:02 -07002890 // Disabled, since we previously switched the source to disabled.
sprangc5d62e22017-04-02 23:53:04 -07002891 EXPECT_FALSE(stats.cpu_limited_resolution);
asapersson13874762017-06-07 00:01:02 -07002892 EXPECT_TRUE(stats.cpu_limited_framerate);
sprangc5d62e22017-04-02 23:53:04 -07002893 EXPECT_EQ(3, stats.number_of_cpu_adapt_changes);
2894
2895 // Trigger CPU normal usage.
Henrik Boström91aa7322020-04-28 12:24:33 +02002896 video_stream_encoder_->TriggerCpuUnderuse();
sprangc5d62e22017-04-02 23:53:04 -07002897 new_video_source.IncomingCapturedFrame(
asaperssonfab67072017-04-04 05:51:49 -07002898 CreateFrame(sequence, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002899 WaitForEncodedFrame(sequence++);
sprangc5d62e22017-04-02 23:53:04 -07002900 stats = stats_proxy_->GetStats();
2901 EXPECT_FALSE(stats.cpu_limited_resolution);
asapersson13874762017-06-07 00:01:02 -07002902 EXPECT_FALSE(stats.cpu_limited_framerate);
sprangc5d62e22017-04-02 23:53:04 -07002903 EXPECT_EQ(4, stats.number_of_cpu_adapt_changes);
asapersson02465b82017-04-10 01:12:52 -07002904 EXPECT_EQ(0, stats.number_of_quality_adapt_changes);
perkj803d97f2016-11-01 11:45:46 -07002905
mflodmancc3d4422017-08-03 08:27:51 -07002906 video_stream_encoder_->Stop();
perkj803d97f2016-11-01 11:45:46 -07002907}
2908
mflodmancc3d4422017-08-03 08:27:51 -07002909TEST_F(VideoStreamEncoderTest,
2910 ScalingUpAndDownDoesNothingWithMaintainResolution) {
asaperssonfab67072017-04-04 05:51:49 -07002911 const int kWidth = 1280;
2912 const int kHeight = 720;
Henrik Boström381d1092020-05-12 18:49:07 +02002913 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01002914 DataRate::BitsPerSec(kTargetBitrateBps),
2915 DataRate::BitsPerSec(kTargetBitrateBps),
2916 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
kthelgason876222f2016-11-29 01:44:11 -08002917
asaperssonfab67072017-04-04 05:51:49 -07002918 // Expect no scaling to begin with.
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02002919 EXPECT_THAT(video_source_.sink_wants(), UnlimitedSinkWants());
kthelgason876222f2016-11-29 01:44:11 -08002920
asaperssonfab67072017-04-04 05:51:49 -07002921 video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002922 WaitForEncodedFrame(1);
kthelgason876222f2016-11-29 01:44:11 -08002923
asaperssonfab67072017-04-04 05:51:49 -07002924 // Trigger scale down.
mflodmancc3d4422017-08-03 08:27:51 -07002925 video_stream_encoder_->TriggerQualityLow();
kthelgason5e13d412016-12-01 03:59:51 -08002926
asaperssonfab67072017-04-04 05:51:49 -07002927 video_source_.IncomingCapturedFrame(CreateFrame(2, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002928 WaitForEncodedFrame(2);
kthelgason5e13d412016-12-01 03:59:51 -08002929
kthelgason876222f2016-11-29 01:44:11 -08002930 // Expect a scale down.
2931 EXPECT_TRUE(video_source_.sink_wants().max_pixel_count);
asaperssonfab67072017-04-04 05:51:49 -07002932 EXPECT_LT(video_source_.sink_wants().max_pixel_count, kWidth * kHeight);
kthelgason876222f2016-11-29 01:44:11 -08002933
asapersson02465b82017-04-10 01:12:52 -07002934 // Set resolution scaling disabled.
kthelgason876222f2016-11-29 01:44:11 -08002935 test::FrameForwarder new_video_source;
mflodmancc3d4422017-08-03 08:27:51 -07002936 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002937 &new_video_source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
kthelgason876222f2016-11-29 01:44:11 -08002938
asaperssonfab67072017-04-04 05:51:49 -07002939 // Trigger scale down.
mflodmancc3d4422017-08-03 08:27:51 -07002940 video_stream_encoder_->TriggerQualityLow();
asaperssonfab67072017-04-04 05:51:49 -07002941 new_video_source.IncomingCapturedFrame(CreateFrame(3, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002942 WaitForEncodedFrame(3);
kthelgason876222f2016-11-29 01:44:11 -08002943
asaperssonfab67072017-04-04 05:51:49 -07002944 // Expect no scaling.
sprangc5d62e22017-04-02 23:53:04 -07002945 EXPECT_EQ(std::numeric_limits<int>::max(),
2946 new_video_source.sink_wants().max_pixel_count);
kthelgason876222f2016-11-29 01:44:11 -08002947
asaperssonfab67072017-04-04 05:51:49 -07002948 // Trigger scale up.
mflodmancc3d4422017-08-03 08:27:51 -07002949 video_stream_encoder_->TriggerQualityHigh();
asaperssonfab67072017-04-04 05:51:49 -07002950 new_video_source.IncomingCapturedFrame(CreateFrame(4, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002951 WaitForEncodedFrame(4);
kthelgason876222f2016-11-29 01:44:11 -08002952
asapersson02465b82017-04-10 01:12:52 -07002953 // Expect nothing to change, still no scaling.
sprangc5d62e22017-04-02 23:53:04 -07002954 EXPECT_EQ(std::numeric_limits<int>::max(),
2955 new_video_source.sink_wants().max_pixel_count);
kthelgason876222f2016-11-29 01:44:11 -08002956
mflodmancc3d4422017-08-03 08:27:51 -07002957 video_stream_encoder_->Stop();
kthelgason876222f2016-11-29 01:44:11 -08002958}
2959
mflodmancc3d4422017-08-03 08:27:51 -07002960TEST_F(VideoStreamEncoderTest,
2961 SkipsSameAdaptDownRequest_MaintainFramerateMode) {
asapersson02465b82017-04-10 01:12:52 -07002962 const int kWidth = 1280;
2963 const int kHeight = 720;
Henrik Boström381d1092020-05-12 18:49:07 +02002964 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01002965 DataRate::BitsPerSec(kTargetBitrateBps),
2966 DataRate::BitsPerSec(kTargetBitrateBps),
2967 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asapersson02465b82017-04-10 01:12:52 -07002968
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002969 // Enable MAINTAIN_FRAMERATE preference, no initial limitation.
asapersson02465b82017-04-10 01:12:52 -07002970 test::FrameForwarder source;
mflodmancc3d4422017-08-03 08:27:51 -07002971 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002972 &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
asapersson02465b82017-04-10 01:12:52 -07002973
2974 source.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002975 WaitForEncodedFrame(1);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02002976 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asapersson02465b82017-04-10 01:12:52 -07002977 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
2978 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
2979
2980 // Trigger adapt down, expect scaled down resolution.
mflodmancc3d4422017-08-03 08:27:51 -07002981 video_stream_encoder_->TriggerCpuOveruse();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02002982 EXPECT_THAT(source.sink_wants(),
2983 FpsMaxResolutionMatches(Lt(kWidth * kHeight)));
asapersson02465b82017-04-10 01:12:52 -07002984 const int kLastMaxPixelCount = source.sink_wants().max_pixel_count;
2985 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
2986 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
2987
2988 // Trigger adapt down for same input resolution, expect no change.
mflodmancc3d4422017-08-03 08:27:51 -07002989 video_stream_encoder_->TriggerCpuOveruse();
asapersson02465b82017-04-10 01:12:52 -07002990 EXPECT_EQ(kLastMaxPixelCount, source.sink_wants().max_pixel_count);
2991 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
2992 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
2993
mflodmancc3d4422017-08-03 08:27:51 -07002994 video_stream_encoder_->Stop();
asapersson02465b82017-04-10 01:12:52 -07002995}
2996
mflodmancc3d4422017-08-03 08:27:51 -07002997TEST_F(VideoStreamEncoderTest, SkipsSameOrLargerAdaptDownRequest_BalancedMode) {
asaperssonf7e294d2017-06-13 23:25:22 -07002998 const int kWidth = 1280;
2999 const int kHeight = 720;
Henrik Boström381d1092020-05-12 18:49:07 +02003000 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01003001 DataRate::BitsPerSec(kTargetBitrateBps),
3002 DataRate::BitsPerSec(kTargetBitrateBps),
3003 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asaperssonf7e294d2017-06-13 23:25:22 -07003004
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003005 // Enable BALANCED preference, no initial limitation.
asaperssonf7e294d2017-06-13 23:25:22 -07003006 test::FrameForwarder source;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003007 video_stream_encoder_->SetSource(&source,
3008 webrtc::DegradationPreference::BALANCED);
asaperssonf7e294d2017-06-13 23:25:22 -07003009 source.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
3010 sink_.WaitForEncodedFrame(1);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003011 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-13 23:25:22 -07003012
3013 // Trigger adapt down, expect scaled down resolution.
mflodmancc3d4422017-08-03 08:27:51 -07003014 video_stream_encoder_->TriggerQualityLow();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003015 EXPECT_THAT(source.sink_wants(),
3016 FpsMaxResolutionMatches(Lt(kWidth * kHeight)));
asaperssonf7e294d2017-06-13 23:25:22 -07003017 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
3018 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3019 const int kLastMaxPixelCount = source.sink_wants().max_pixel_count;
3020
3021 // Trigger adapt down for same input resolution, expect no change.
3022 source.IncomingCapturedFrame(CreateFrame(2, kWidth, kHeight));
3023 sink_.WaitForEncodedFrame(2);
mflodmancc3d4422017-08-03 08:27:51 -07003024 video_stream_encoder_->TriggerQualityLow();
asaperssonf7e294d2017-06-13 23:25:22 -07003025 EXPECT_EQ(kLastMaxPixelCount, source.sink_wants().max_pixel_count);
3026 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
3027 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3028
3029 // Trigger adapt down for larger input resolution, expect no change.
3030 source.IncomingCapturedFrame(CreateFrame(3, kWidth + 1, kHeight + 1));
3031 sink_.WaitForEncodedFrame(3);
mflodmancc3d4422017-08-03 08:27:51 -07003032 video_stream_encoder_->TriggerQualityLow();
asaperssonf7e294d2017-06-13 23:25:22 -07003033 EXPECT_EQ(kLastMaxPixelCount, source.sink_wants().max_pixel_count);
3034 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
3035 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3036
mflodmancc3d4422017-08-03 08:27:51 -07003037 video_stream_encoder_->Stop();
asaperssonf7e294d2017-06-13 23:25:22 -07003038}
3039
mflodmancc3d4422017-08-03 08:27:51 -07003040TEST_F(VideoStreamEncoderTest,
3041 NoChangeForInitialNormalUsage_MaintainFramerateMode) {
asapersson02465b82017-04-10 01:12:52 -07003042 const int kWidth = 1280;
3043 const int kHeight = 720;
Henrik Boström381d1092020-05-12 18:49:07 +02003044 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01003045 DataRate::BitsPerSec(kTargetBitrateBps),
3046 DataRate::BitsPerSec(kTargetBitrateBps),
3047 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asapersson02465b82017-04-10 01:12:52 -07003048
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003049 // Enable MAINTAIN_FRAMERATE preference, no initial limitation.
asapersson02465b82017-04-10 01:12:52 -07003050 test::FrameForwarder source;
mflodmancc3d4422017-08-03 08:27:51 -07003051 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003052 &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
asapersson02465b82017-04-10 01:12:52 -07003053
3054 source.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07003055 WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003056 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asapersson02465b82017-04-10 01:12:52 -07003057 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
3058 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3059
3060 // Trigger adapt up, expect no change.
Henrik Boström91aa7322020-04-28 12:24:33 +02003061 video_stream_encoder_->TriggerCpuUnderuse();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003062 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asapersson02465b82017-04-10 01:12:52 -07003063 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
3064 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3065
mflodmancc3d4422017-08-03 08:27:51 -07003066 video_stream_encoder_->Stop();
asapersson02465b82017-04-10 01:12:52 -07003067}
3068
mflodmancc3d4422017-08-03 08:27:51 -07003069TEST_F(VideoStreamEncoderTest,
3070 NoChangeForInitialNormalUsage_MaintainResolutionMode) {
asapersson02465b82017-04-10 01:12:52 -07003071 const int kWidth = 1280;
3072 const int kHeight = 720;
Henrik Boström381d1092020-05-12 18:49:07 +02003073 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01003074 DataRate::BitsPerSec(kTargetBitrateBps),
3075 DataRate::BitsPerSec(kTargetBitrateBps),
3076 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asapersson02465b82017-04-10 01:12:52 -07003077
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003078 // Enable MAINTAIN_RESOLUTION preference, no initial limitation.
asapersson02465b82017-04-10 01:12:52 -07003079 test::FrameForwarder source;
mflodmancc3d4422017-08-03 08:27:51 -07003080 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003081 &source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
asapersson02465b82017-04-10 01:12:52 -07003082
3083 source.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07003084 WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003085 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asapersson09f05612017-05-15 23:40:18 -07003086 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
asapersson02465b82017-04-10 01:12:52 -07003087 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3088
3089 // Trigger adapt up, expect no change.
Henrik Boström91aa7322020-04-28 12:24:33 +02003090 video_stream_encoder_->TriggerCpuUnderuse();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003091 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asapersson09f05612017-05-15 23:40:18 -07003092 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
asapersson02465b82017-04-10 01:12:52 -07003093 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3094
mflodmancc3d4422017-08-03 08:27:51 -07003095 video_stream_encoder_->Stop();
asapersson02465b82017-04-10 01:12:52 -07003096}
3097
mflodmancc3d4422017-08-03 08:27:51 -07003098TEST_F(VideoStreamEncoderTest, NoChangeForInitialNormalUsage_BalancedMode) {
asaperssonf7e294d2017-06-13 23:25:22 -07003099 const int kWidth = 1280;
3100 const int kHeight = 720;
Henrik Boström381d1092020-05-12 18:49:07 +02003101 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01003102 DataRate::BitsPerSec(kTargetBitrateBps),
3103 DataRate::BitsPerSec(kTargetBitrateBps),
3104 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asaperssonf7e294d2017-06-13 23:25:22 -07003105
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003106 // Enable BALANCED preference, no initial limitation.
asaperssonf7e294d2017-06-13 23:25:22 -07003107 test::FrameForwarder source;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003108 video_stream_encoder_->SetSource(&source,
3109 webrtc::DegradationPreference::BALANCED);
asaperssonf7e294d2017-06-13 23:25:22 -07003110
3111 source.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
3112 sink_.WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003113 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-13 23:25:22 -07003114 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
3115 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
3116 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3117
3118 // Trigger adapt up, expect no change.
mflodmancc3d4422017-08-03 08:27:51 -07003119 video_stream_encoder_->TriggerQualityHigh();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003120 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-13 23:25:22 -07003121 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
3122 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
3123 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3124
mflodmancc3d4422017-08-03 08:27:51 -07003125 video_stream_encoder_->Stop();
asaperssonf7e294d2017-06-13 23:25:22 -07003126}
3127
mflodmancc3d4422017-08-03 08:27:51 -07003128TEST_F(VideoStreamEncoderTest, NoChangeForInitialNormalUsage_DisabledMode) {
asapersson09f05612017-05-15 23:40:18 -07003129 const int kWidth = 1280;
3130 const int kHeight = 720;
Henrik Boström381d1092020-05-12 18:49:07 +02003131 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01003132 DataRate::BitsPerSec(kTargetBitrateBps),
3133 DataRate::BitsPerSec(kTargetBitrateBps),
3134 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asapersson09f05612017-05-15 23:40:18 -07003135
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003136 // Enable DISABLED preference, no initial limitation.
asapersson09f05612017-05-15 23:40:18 -07003137 test::FrameForwarder source;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003138 video_stream_encoder_->SetSource(&source,
3139 webrtc::DegradationPreference::DISABLED);
asapersson09f05612017-05-15 23:40:18 -07003140
3141 source.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
3142 sink_.WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003143 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asapersson09f05612017-05-15 23:40:18 -07003144 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
3145 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
3146 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3147
3148 // Trigger adapt up, expect no change.
mflodmancc3d4422017-08-03 08:27:51 -07003149 video_stream_encoder_->TriggerQualityHigh();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003150 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asapersson09f05612017-05-15 23:40:18 -07003151 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
3152 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
3153 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3154
mflodmancc3d4422017-08-03 08:27:51 -07003155 video_stream_encoder_->Stop();
asapersson09f05612017-05-15 23:40:18 -07003156}
3157
mflodmancc3d4422017-08-03 08:27:51 -07003158TEST_F(VideoStreamEncoderTest,
3159 AdaptsResolutionForLowQuality_MaintainFramerateMode) {
asapersson02465b82017-04-10 01:12:52 -07003160 const int kWidth = 1280;
3161 const int kHeight = 720;
Henrik Boström381d1092020-05-12 18:49:07 +02003162 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01003163 DataRate::BitsPerSec(kTargetBitrateBps),
3164 DataRate::BitsPerSec(kTargetBitrateBps),
3165 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asapersson02465b82017-04-10 01:12:52 -07003166
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003167 // Enable MAINTAIN_FRAMERATE preference, no initial limitation.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02003168 AdaptingFrameForwarder source(&time_controller_);
asapersson02465b82017-04-10 01:12:52 -07003169 source.set_adaptation_enabled(true);
mflodmancc3d4422017-08-03 08:27:51 -07003170 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003171 &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
asapersson02465b82017-04-10 01:12:52 -07003172
3173 source.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07003174 WaitForEncodedFrame(1);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003175 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asapersson02465b82017-04-10 01:12:52 -07003176 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
3177 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3178
3179 // Trigger adapt down, expect scaled down resolution.
mflodmancc3d4422017-08-03 08:27:51 -07003180 video_stream_encoder_->TriggerQualityLow();
asapersson02465b82017-04-10 01:12:52 -07003181 source.IncomingCapturedFrame(CreateFrame(2, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07003182 WaitForEncodedFrame(2);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003183 EXPECT_THAT(source.sink_wants(),
3184 FpsMaxResolutionMatches(Lt(kWidth * kHeight)));
asapersson02465b82017-04-10 01:12:52 -07003185 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
3186 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3187
3188 // Trigger adapt up, expect no restriction.
mflodmancc3d4422017-08-03 08:27:51 -07003189 video_stream_encoder_->TriggerQualityHigh();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003190 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asapersson02465b82017-04-10 01:12:52 -07003191 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
3192 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3193 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3194
mflodmancc3d4422017-08-03 08:27:51 -07003195 video_stream_encoder_->Stop();
asapersson02465b82017-04-10 01:12:52 -07003196}
3197
mflodmancc3d4422017-08-03 08:27:51 -07003198TEST_F(VideoStreamEncoderTest,
3199 AdaptsFramerateForLowQuality_MaintainResolutionMode) {
asapersson09f05612017-05-15 23:40:18 -07003200 const int kWidth = 1280;
3201 const int kHeight = 720;
3202 const int kInputFps = 30;
Henrik Boström381d1092020-05-12 18:49:07 +02003203 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01003204 DataRate::BitsPerSec(kTargetBitrateBps),
3205 DataRate::BitsPerSec(kTargetBitrateBps),
3206 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asapersson09f05612017-05-15 23:40:18 -07003207
3208 VideoSendStream::Stats stats = stats_proxy_->GetStats();
3209 stats.input_frame_rate = kInputFps;
3210 stats_proxy_->SetMockStats(stats);
3211
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003212 // Expect no scaling to begin with (preference: MAINTAIN_FRAMERATE).
asapersson09f05612017-05-15 23:40:18 -07003213 video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
3214 sink_.WaitForEncodedFrame(1);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003215 EXPECT_THAT(video_source_.sink_wants(), FpsMaxResolutionMax());
asapersson09f05612017-05-15 23:40:18 -07003216
3217 // Trigger adapt down, expect scaled down resolution.
mflodmancc3d4422017-08-03 08:27:51 -07003218 video_stream_encoder_->TriggerQualityLow();
asapersson09f05612017-05-15 23:40:18 -07003219 video_source_.IncomingCapturedFrame(CreateFrame(2, kWidth, kHeight));
3220 sink_.WaitForEncodedFrame(2);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003221 EXPECT_THAT(video_source_.sink_wants(),
3222 FpsMaxResolutionMatches(Lt(kWidth * kHeight)));
asapersson09f05612017-05-15 23:40:18 -07003223
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003224 // Enable MAINTAIN_RESOLUTION preference.
asapersson09f05612017-05-15 23:40:18 -07003225 test::FrameForwarder new_video_source;
Henrik Boström2671dac2020-05-19 16:29:09 +02003226 video_stream_encoder_->SetSourceAndWaitForRestrictionsUpdated(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003227 &new_video_source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
Henrik Boström07b17df2020-01-15 11:42:12 +01003228 // Give the encoder queue time to process the change in degradation preference
3229 // by waiting for an encoded frame.
3230 new_video_source.IncomingCapturedFrame(CreateFrame(3, kWidth, kHeight));
3231 sink_.WaitForEncodedFrame(3);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003232 EXPECT_THAT(new_video_source.sink_wants(), FpsMaxResolutionMax());
asapersson09f05612017-05-15 23:40:18 -07003233
3234 // Trigger adapt down, expect reduced framerate.
mflodmancc3d4422017-08-03 08:27:51 -07003235 video_stream_encoder_->TriggerQualityLow();
Henrik Boström07b17df2020-01-15 11:42:12 +01003236 new_video_source.IncomingCapturedFrame(CreateFrame(4, kWidth, kHeight));
3237 sink_.WaitForEncodedFrame(4);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003238 EXPECT_THAT(new_video_source.sink_wants(),
3239 FpsMatchesResolutionMax(Lt(kInputFps)));
asapersson09f05612017-05-15 23:40:18 -07003240
3241 // Trigger adapt up, expect no restriction.
mflodmancc3d4422017-08-03 08:27:51 -07003242 video_stream_encoder_->TriggerQualityHigh();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003243 EXPECT_THAT(new_video_source.sink_wants(), FpsMaxResolutionMax());
asapersson09f05612017-05-15 23:40:18 -07003244
mflodmancc3d4422017-08-03 08:27:51 -07003245 video_stream_encoder_->Stop();
asapersson09f05612017-05-15 23:40:18 -07003246}
3247
mflodmancc3d4422017-08-03 08:27:51 -07003248TEST_F(VideoStreamEncoderTest, DoesNotScaleBelowSetResolutionLimit) {
asaperssond0de2952017-04-21 01:47:31 -07003249 const int kWidth = 1280;
3250 const int kHeight = 720;
3251 const size_t kNumFrames = 10;
3252
Henrik Boström381d1092020-05-12 18:49:07 +02003253 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01003254 DataRate::BitsPerSec(kTargetBitrateBps),
3255 DataRate::BitsPerSec(kTargetBitrateBps),
3256 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
kthelgason5e13d412016-12-01 03:59:51 -08003257
asaperssond0de2952017-04-21 01:47:31 -07003258 // Enable adapter, expected input resolutions when downscaling:
asapersson142fcc92017-08-17 08:58:54 -07003259 // 1280x720 -> 960x540 -> 640x360 -> 480x270 -> 320x180 (kMinPixelsPerFrame)
asaperssond0de2952017-04-21 01:47:31 -07003260 video_source_.set_adaptation_enabled(true);
3261
3262 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
3263 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3264
3265 int downscales = 0;
3266 for (size_t i = 1; i <= kNumFrames; i++) {
Åsa Persson8c1bf952018-09-13 10:42:19 +02003267 video_source_.IncomingCapturedFrame(
3268 CreateFrame(i * kFrameIntervalMs, kWidth, kHeight));
3269 WaitForEncodedFrame(i * kFrameIntervalMs);
asaperssond0de2952017-04-21 01:47:31 -07003270
asaperssonfab67072017-04-04 05:51:49 -07003271 // Trigger scale down.
asaperssond0de2952017-04-21 01:47:31 -07003272 rtc::VideoSinkWants last_wants = video_source_.sink_wants();
mflodmancc3d4422017-08-03 08:27:51 -07003273 video_stream_encoder_->TriggerQualityLow();
sprangc5d62e22017-04-02 23:53:04 -07003274 EXPECT_GE(video_source_.sink_wants().max_pixel_count, kMinPixelsPerFrame);
asaperssond0de2952017-04-21 01:47:31 -07003275
3276 if (video_source_.sink_wants().max_pixel_count < last_wants.max_pixel_count)
3277 ++downscales;
3278
3279 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
3280 EXPECT_EQ(downscales,
3281 stats_proxy_->GetStats().number_of_quality_adapt_changes);
3282 EXPECT_GT(downscales, 0);
kthelgason5e13d412016-12-01 03:59:51 -08003283 }
mflodmancc3d4422017-08-03 08:27:51 -07003284 video_stream_encoder_->Stop();
asaperssond0de2952017-04-21 01:47:31 -07003285}
3286
mflodmancc3d4422017-08-03 08:27:51 -07003287TEST_F(VideoStreamEncoderTest,
asaperssond0de2952017-04-21 01:47:31 -07003288 AdaptsResolutionUpAndDownTwiceOnOveruse_MaintainFramerateMode) {
3289 const int kWidth = 1280;
3290 const int kHeight = 720;
Henrik Boström381d1092020-05-12 18:49:07 +02003291 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01003292 DataRate::BitsPerSec(kTargetBitrateBps),
3293 DataRate::BitsPerSec(kTargetBitrateBps),
3294 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asaperssond0de2952017-04-21 01:47:31 -07003295
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003296 // Enable MAINTAIN_FRAMERATE preference, no initial limitation.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02003297 AdaptingFrameForwarder source(&time_controller_);
asaperssond0de2952017-04-21 01:47:31 -07003298 source.set_adaptation_enabled(true);
mflodmancc3d4422017-08-03 08:27:51 -07003299 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003300 &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
asaperssond0de2952017-04-21 01:47:31 -07003301
Åsa Persson8c1bf952018-09-13 10:42:19 +02003302 int64_t timestamp_ms = kFrameIntervalMs;
3303 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07003304 WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003305 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssond0de2952017-04-21 01:47:31 -07003306 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
3307 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3308
3309 // Trigger adapt down, expect scaled down resolution.
mflodmancc3d4422017-08-03 08:27:51 -07003310 video_stream_encoder_->TriggerCpuOveruse();
Åsa Persson8c1bf952018-09-13 10:42:19 +02003311 timestamp_ms += kFrameIntervalMs;
3312 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
3313 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003314 EXPECT_THAT(source.sink_wants(),
3315 FpsMaxResolutionMatches(Lt(kWidth * kHeight)));
asaperssond0de2952017-04-21 01:47:31 -07003316 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
3317 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3318
3319 // Trigger adapt up, expect no restriction.
Henrik Boström91aa7322020-04-28 12:24:33 +02003320 video_stream_encoder_->TriggerCpuUnderuse();
Åsa Persson8c1bf952018-09-13 10:42:19 +02003321 timestamp_ms += kFrameIntervalMs;
3322 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07003323 WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003324 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssond0de2952017-04-21 01:47:31 -07003325 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
3326 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3327
3328 // Trigger adapt down, expect scaled down resolution.
mflodmancc3d4422017-08-03 08:27:51 -07003329 video_stream_encoder_->TriggerCpuOveruse();
Åsa Persson8c1bf952018-09-13 10:42:19 +02003330 timestamp_ms += kFrameIntervalMs;
3331 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
3332 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003333 EXPECT_THAT(source.sink_wants(),
3334 FpsMaxResolutionMatches(Lt(kWidth * kHeight)));
asaperssond0de2952017-04-21 01:47:31 -07003335 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
3336 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3337
3338 // Trigger adapt up, expect no restriction.
Henrik Boström91aa7322020-04-28 12:24:33 +02003339 video_stream_encoder_->TriggerCpuUnderuse();
Åsa Persson8c1bf952018-09-13 10:42:19 +02003340 timestamp_ms += kFrameIntervalMs;
3341 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
asapersson09f05612017-05-15 23:40:18 -07003342 sink_.WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003343 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssond0de2952017-04-21 01:47:31 -07003344 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
3345 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3346
mflodmancc3d4422017-08-03 08:27:51 -07003347 video_stream_encoder_->Stop();
asaperssond0de2952017-04-21 01:47:31 -07003348}
3349
mflodmancc3d4422017-08-03 08:27:51 -07003350TEST_F(VideoStreamEncoderTest,
asaperssonf7e294d2017-06-13 23:25:22 -07003351 AdaptsResolutionUpAndDownTwiceForLowQuality_BalancedMode_NoFpsLimit) {
3352 const int kWidth = 1280;
3353 const int kHeight = 720;
Henrik Boström381d1092020-05-12 18:49:07 +02003354 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01003355 DataRate::BitsPerSec(kTargetBitrateBps),
3356 DataRate::BitsPerSec(kTargetBitrateBps),
3357 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asaperssonf7e294d2017-06-13 23:25:22 -07003358
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003359 // Enable BALANCED preference, no initial limitation.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02003360 AdaptingFrameForwarder source(&time_controller_);
asaperssonf7e294d2017-06-13 23:25:22 -07003361 source.set_adaptation_enabled(true);
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003362 video_stream_encoder_->SetSource(&source,
3363 webrtc::DegradationPreference::BALANCED);
asaperssonf7e294d2017-06-13 23:25:22 -07003364
Åsa Persson8c1bf952018-09-13 10:42:19 +02003365 int64_t timestamp_ms = kFrameIntervalMs;
3366 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
asaperssonf7e294d2017-06-13 23:25:22 -07003367 sink_.WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003368 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-13 23:25:22 -07003369 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
3370 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3371
3372 // Trigger adapt down, expect scaled down resolution.
mflodmancc3d4422017-08-03 08:27:51 -07003373 video_stream_encoder_->TriggerQualityLow();
Åsa Persson8c1bf952018-09-13 10:42:19 +02003374 timestamp_ms += kFrameIntervalMs;
3375 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
3376 sink_.WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003377 EXPECT_THAT(source.sink_wants(),
3378 FpsMaxResolutionMatches(Lt(kWidth * kHeight)));
asaperssonf7e294d2017-06-13 23:25:22 -07003379 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
3380 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3381
3382 // Trigger adapt up, expect no restriction.
mflodmancc3d4422017-08-03 08:27:51 -07003383 video_stream_encoder_->TriggerQualityHigh();
Åsa Persson8c1bf952018-09-13 10:42:19 +02003384 timestamp_ms += kFrameIntervalMs;
3385 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
asaperssonf7e294d2017-06-13 23:25:22 -07003386 sink_.WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003387 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-13 23:25:22 -07003388 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
3389 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3390
3391 // Trigger adapt down, expect scaled down resolution.
mflodmancc3d4422017-08-03 08:27:51 -07003392 video_stream_encoder_->TriggerQualityLow();
Åsa Persson8c1bf952018-09-13 10:42:19 +02003393 timestamp_ms += kFrameIntervalMs;
3394 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
3395 sink_.WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003396 EXPECT_THAT(source.sink_wants(),
3397 FpsMaxResolutionMatches(Lt(kWidth * kHeight)));
asaperssonf7e294d2017-06-13 23:25:22 -07003398 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
3399 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3400
3401 // Trigger adapt up, expect no restriction.
mflodmancc3d4422017-08-03 08:27:51 -07003402 video_stream_encoder_->TriggerQualityHigh();
Åsa Persson8c1bf952018-09-13 10:42:19 +02003403 timestamp_ms += kFrameIntervalMs;
3404 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
asaperssonf7e294d2017-06-13 23:25:22 -07003405 sink_.WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003406 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-13 23:25:22 -07003407 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
3408 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3409
mflodmancc3d4422017-08-03 08:27:51 -07003410 video_stream_encoder_->Stop();
asaperssonf7e294d2017-06-13 23:25:22 -07003411}
3412
Sergey Silkin41c650b2019-10-14 13:12:19 +02003413TEST_F(VideoStreamEncoderTest, AdaptUpIfBwEstimateIsHigherThanMinBitrate) {
3414 fake_encoder_.SetResolutionBitrateLimits(
3415 {kEncoderBitrateLimits540p, kEncoderBitrateLimits720p});
3416
Henrik Boström381d1092020-05-12 18:49:07 +02003417 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01003418 DataRate::BitsPerSec(kEncoderBitrateLimits720p.min_start_bitrate_bps),
3419 DataRate::BitsPerSec(kEncoderBitrateLimits720p.min_start_bitrate_bps),
3420 DataRate::BitsPerSec(kEncoderBitrateLimits720p.min_start_bitrate_bps), 0,
3421 0, 0);
Sergey Silkin41c650b2019-10-14 13:12:19 +02003422
3423 // Enable MAINTAIN_FRAMERATE preference, no initial limitation.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02003424 AdaptingFrameForwarder source(&time_controller_);
Sergey Silkin41c650b2019-10-14 13:12:19 +02003425 source.set_adaptation_enabled(true);
3426 video_stream_encoder_->SetSource(
3427 &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
3428
3429 // Insert 720p frame.
3430 int64_t timestamp_ms = kFrameIntervalMs;
3431 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, 1280, 720));
3432 WaitForEncodedFrame(1280, 720);
3433
3434 // Reduce bitrate and trigger adapt down.
Henrik Boström381d1092020-05-12 18:49:07 +02003435 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01003436 DataRate::BitsPerSec(kEncoderBitrateLimits540p.min_start_bitrate_bps),
3437 DataRate::BitsPerSec(kEncoderBitrateLimits540p.min_start_bitrate_bps),
3438 DataRate::BitsPerSec(kEncoderBitrateLimits540p.min_start_bitrate_bps), 0,
3439 0, 0);
Sergey Silkin41c650b2019-10-14 13:12:19 +02003440 video_stream_encoder_->TriggerQualityLow();
3441
3442 // Insert 720p frame. It should be downscaled and encoded.
3443 timestamp_ms += kFrameIntervalMs;
3444 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, 1280, 720));
3445 WaitForEncodedFrame(960, 540);
3446
3447 // Trigger adapt up. Higher resolution should not be requested duo to lack
3448 // of bitrate.
3449 video_stream_encoder_->TriggerQualityHigh();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003450 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMatches(Lt(1280 * 720)));
Sergey Silkin41c650b2019-10-14 13:12:19 +02003451
3452 // Increase bitrate.
Henrik Boström381d1092020-05-12 18:49:07 +02003453 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01003454 DataRate::BitsPerSec(kEncoderBitrateLimits720p.min_start_bitrate_bps),
3455 DataRate::BitsPerSec(kEncoderBitrateLimits720p.min_start_bitrate_bps),
3456 DataRate::BitsPerSec(kEncoderBitrateLimits720p.min_start_bitrate_bps), 0,
3457 0, 0);
Sergey Silkin41c650b2019-10-14 13:12:19 +02003458
3459 // Trigger adapt up. Higher resolution should be requested.
3460 video_stream_encoder_->TriggerQualityHigh();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003461 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
Sergey Silkin41c650b2019-10-14 13:12:19 +02003462
3463 video_stream_encoder_->Stop();
3464}
3465
3466TEST_F(VideoStreamEncoderTest, DropFirstFramesIfBwEstimateIsTooLow) {
3467 fake_encoder_.SetResolutionBitrateLimits(
3468 {kEncoderBitrateLimits540p, kEncoderBitrateLimits720p});
3469
3470 // Set bitrate equal to min bitrate of 540p.
Henrik Boström381d1092020-05-12 18:49:07 +02003471 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01003472 DataRate::BitsPerSec(kEncoderBitrateLimits540p.min_start_bitrate_bps),
3473 DataRate::BitsPerSec(kEncoderBitrateLimits540p.min_start_bitrate_bps),
3474 DataRate::BitsPerSec(kEncoderBitrateLimits540p.min_start_bitrate_bps), 0,
3475 0, 0);
Sergey Silkin41c650b2019-10-14 13:12:19 +02003476
3477 // Enable MAINTAIN_FRAMERATE preference, no initial limitation.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02003478 AdaptingFrameForwarder source(&time_controller_);
Sergey Silkin41c650b2019-10-14 13:12:19 +02003479 source.set_adaptation_enabled(true);
3480 video_stream_encoder_->SetSource(
3481 &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
3482
3483 // Insert 720p frame. It should be dropped and lower resolution should be
3484 // requested.
3485 int64_t timestamp_ms = kFrameIntervalMs;
3486 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, 1280, 720));
3487 ExpectDroppedFrame();
Henrik Boström2671dac2020-05-19 16:29:09 +02003488 EXPECT_TRUE_WAIT(source.sink_wants().max_pixel_count < 1280 * 720, 5000);
Sergey Silkin41c650b2019-10-14 13:12:19 +02003489
3490 // Insert 720p frame. It should be downscaled and encoded.
3491 timestamp_ms += kFrameIntervalMs;
3492 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, 1280, 720));
3493 WaitForEncodedFrame(960, 540);
3494
3495 video_stream_encoder_->Stop();
3496}
3497
Åsa Perssonb67c44c2019-09-24 15:25:32 +02003498class BalancedDegradationTest : public VideoStreamEncoderTest {
3499 protected:
3500 void SetupTest() {
3501 // Reset encoder for field trials to take effect.
3502 ConfigureEncoder(video_encoder_config_.Copy());
Åsa Perssonccfb3402019-09-25 15:13:04 +02003503 OnBitrateUpdated(kTargetBitrateBps);
Åsa Perssonb67c44c2019-09-24 15:25:32 +02003504
3505 // Enable BALANCED preference.
3506 source_.set_adaptation_enabled(true);
Åsa Perssonccfb3402019-09-25 15:13:04 +02003507 video_stream_encoder_->SetSource(&source_, DegradationPreference::BALANCED);
3508 }
3509
3510 void OnBitrateUpdated(int bitrate_bps) {
Henrik Boström381d1092020-05-12 18:49:07 +02003511 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01003512 DataRate::BitsPerSec(bitrate_bps), DataRate::BitsPerSec(bitrate_bps),
3513 DataRate::BitsPerSec(bitrate_bps), 0, 0, 0);
Åsa Perssonb67c44c2019-09-24 15:25:32 +02003514 }
3515
Åsa Persson45b176f2019-09-30 11:19:05 +02003516 void InsertFrame() {
Åsa Perssonb67c44c2019-09-24 15:25:32 +02003517 timestamp_ms_ += kFrameIntervalMs;
3518 source_.IncomingCapturedFrame(CreateFrame(timestamp_ms_, kWidth, kHeight));
Åsa Persson45b176f2019-09-30 11:19:05 +02003519 }
3520
3521 void InsertFrameAndWaitForEncoded() {
3522 InsertFrame();
Åsa Perssonb67c44c2019-09-24 15:25:32 +02003523 sink_.WaitForEncodedFrame(timestamp_ms_);
3524 }
3525
3526 const int kWidth = 640; // pixels:640x360=230400
3527 const int kHeight = 360;
3528 const int64_t kFrameIntervalMs = 150; // Use low fps to not drop any frame.
3529 int64_t timestamp_ms_ = 0;
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02003530 AdaptingFrameForwarder source_{&time_controller_};
Åsa Perssonb67c44c2019-09-24 15:25:32 +02003531};
3532
Evan Shrubsolea1c77f62020-08-10 11:01:06 +02003533TEST_F(BalancedDegradationTest, AdaptDownTwiceIfMinFpsDiffLtThreshold) {
Åsa Perssonb67c44c2019-09-24 15:25:32 +02003534 test::ScopedFieldTrials field_trials(
3535 "WebRTC-Video-BalancedDegradationSettings/"
3536 "pixels:57600|129600|230400,fps:7|10|24,fps_diff:1|1|1/");
3537 SetupTest();
3538
3539 // Force input frame rate.
3540 const int kInputFps = 24;
3541 VideoSendStream::Stats stats = stats_proxy_->GetStats();
3542 stats.input_frame_rate = kInputFps;
3543 stats_proxy_->SetMockStats(stats);
3544
Åsa Persson45b176f2019-09-30 11:19:05 +02003545 InsertFrameAndWaitForEncoded();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003546 EXPECT_THAT(source_.sink_wants(), FpsMaxResolutionMax());
Åsa Perssonb67c44c2019-09-24 15:25:32 +02003547
Evan Shrubsolea1c77f62020-08-10 11:01:06 +02003548 // Trigger adapt down, expect scaled down framerate and resolution,
3549 // since Fps diff (input-requested:0) < threshold.
3550 video_stream_encoder_->TriggerQualityLow();
3551 EXPECT_THAT(source_.sink_wants(),
3552 AllOf(WantsFps(Eq(24)), WantsMaxPixels(Le(230400))));
Åsa Perssonb67c44c2019-09-24 15:25:32 +02003553
3554 video_stream_encoder_->Stop();
3555}
3556
Evan Shrubsolea1c77f62020-08-10 11:01:06 +02003557TEST_F(BalancedDegradationTest, AdaptDownOnceIfFpsDiffGeThreshold) {
Åsa Perssonb67c44c2019-09-24 15:25:32 +02003558 test::ScopedFieldTrials field_trials(
3559 "WebRTC-Video-BalancedDegradationSettings/"
3560 "pixels:57600|129600|230400,fps:7|10|24,fps_diff:1|1|1/");
3561 SetupTest();
3562
3563 // Force input frame rate.
3564 const int kInputFps = 25;
3565 VideoSendStream::Stats stats = stats_proxy_->GetStats();
3566 stats.input_frame_rate = kInputFps;
3567 stats_proxy_->SetMockStats(stats);
3568
Åsa Persson45b176f2019-09-30 11:19:05 +02003569 InsertFrameAndWaitForEncoded();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003570 EXPECT_THAT(source_.sink_wants(), FpsMaxResolutionMax());
Åsa Perssonb67c44c2019-09-24 15:25:32 +02003571
Evan Shrubsolea1c77f62020-08-10 11:01:06 +02003572 // Trigger adapt down, expect scaled down framerate only (640x360@24fps).
3573 // Fps diff (input-requested:1) == threshold.
3574 video_stream_encoder_->TriggerQualityLow();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003575 EXPECT_THAT(source_.sink_wants(), FpsMatchesResolutionMax(Eq(24)));
Åsa Perssonb67c44c2019-09-24 15:25:32 +02003576
3577 video_stream_encoder_->Stop();
3578}
3579
3580TEST_F(BalancedDegradationTest, AdaptDownUsesCodecSpecificFps) {
3581 test::ScopedFieldTrials field_trials(
3582 "WebRTC-Video-BalancedDegradationSettings/"
3583 "pixels:57600|129600|230400,fps:7|10|24,vp8_fps:8|11|22/");
3584 SetupTest();
3585
3586 EXPECT_EQ(kVideoCodecVP8, video_encoder_config_.codec_type);
3587
Åsa Persson45b176f2019-09-30 11:19:05 +02003588 InsertFrameAndWaitForEncoded();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003589 EXPECT_THAT(source_.sink_wants(), FpsMaxResolutionMax());
Åsa Perssonb67c44c2019-09-24 15:25:32 +02003590
3591 // Trigger adapt down, expect scaled down framerate (640x360@22fps).
3592 video_stream_encoder_->TriggerQualityLow();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003593 EXPECT_THAT(source_.sink_wants(), FpsMatchesResolutionMax(Eq(22)));
Åsa Perssonb67c44c2019-09-24 15:25:32 +02003594
3595 video_stream_encoder_->Stop();
3596}
3597
Åsa Perssonccfb3402019-09-25 15:13:04 +02003598TEST_F(BalancedDegradationTest, NoAdaptUpIfBwEstimateIsLessThanMinBitrate) {
Åsa Perssonb67c44c2019-09-24 15:25:32 +02003599 test::ScopedFieldTrials field_trials(
Åsa Persson1b247f12019-08-14 17:26:39 +02003600 "WebRTC-Video-BalancedDegradationSettings/"
3601 "pixels:57600|129600|230400,fps:7|10|14,kbps:0|0|425/");
Åsa Perssonccfb3402019-09-25 15:13:04 +02003602 SetupTest();
Åsa Persson1b247f12019-08-14 17:26:39 +02003603
Åsa Persson1b247f12019-08-14 17:26:39 +02003604 const int kMinBitrateBps = 425000;
3605 const int kTooLowMinBitrateBps = 424000;
Åsa Perssonccfb3402019-09-25 15:13:04 +02003606 OnBitrateUpdated(kTooLowMinBitrateBps);
Åsa Persson1b247f12019-08-14 17:26:39 +02003607
Åsa Persson45b176f2019-09-30 11:19:05 +02003608 InsertFrameAndWaitForEncoded();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003609 EXPECT_THAT(source_.sink_wants(), FpsMaxResolutionMax());
Åsa Persson1b247f12019-08-14 17:26:39 +02003610 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3611
3612 // Trigger adapt down, expect scaled down framerate (640x360@14fps).
3613 video_stream_encoder_->TriggerQualityLow();
Åsa Persson45b176f2019-09-30 11:19:05 +02003614 InsertFrameAndWaitForEncoded();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003615 EXPECT_THAT(source_.sink_wants(), FpsMatchesResolutionMax(Eq(14)));
Åsa Persson1b247f12019-08-14 17:26:39 +02003616 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3617
3618 // Trigger adapt down, expect scaled down resolution (480x270@14fps).
3619 video_stream_encoder_->TriggerQualityLow();
Åsa Persson45b176f2019-09-30 11:19:05 +02003620 InsertFrameAndWaitForEncoded();
Evan Shrubsole5fd40602020-05-25 16:19:54 +02003621 EXPECT_THAT(source_.sink_wants(), FpsEqResolutionLt(source_.last_wants()));
Åsa Persson1b247f12019-08-14 17:26:39 +02003622 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3623
Åsa Persson30ab0152019-08-27 12:22:33 +02003624 // Trigger adapt down, expect scaled down framerate (480x270@10fps).
3625 video_stream_encoder_->TriggerQualityLow();
Åsa Persson45b176f2019-09-30 11:19:05 +02003626 InsertFrameAndWaitForEncoded();
Evan Shrubsole5fd40602020-05-25 16:19:54 +02003627 EXPECT_THAT(source_.sink_wants(), FpsLtResolutionEq(source_.last_wants()));
Åsa Perssonccfb3402019-09-25 15:13:04 +02003628 EXPECT_EQ(source_.sink_wants().max_framerate_fps, 10);
Åsa Persson30ab0152019-08-27 12:22:33 +02003629 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3630
3631 // Trigger adapt up, expect no upscale in fps (target bitrate < min bitrate).
Åsa Persson1b247f12019-08-14 17:26:39 +02003632 video_stream_encoder_->TriggerQualityHigh();
Åsa Persson45b176f2019-09-30 11:19:05 +02003633 InsertFrameAndWaitForEncoded();
Åsa Persson30ab0152019-08-27 12:22:33 +02003634 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_quality_adapt_changes);
Åsa Persson1b247f12019-08-14 17:26:39 +02003635
Åsa Persson30ab0152019-08-27 12:22:33 +02003636 // Trigger adapt up, expect upscaled fps (target bitrate == min bitrate).
Åsa Perssonccfb3402019-09-25 15:13:04 +02003637 OnBitrateUpdated(kMinBitrateBps);
Åsa Persson1b247f12019-08-14 17:26:39 +02003638 video_stream_encoder_->TriggerQualityHigh();
Åsa Persson45b176f2019-09-30 11:19:05 +02003639 InsertFrameAndWaitForEncoded();
Åsa Perssonccfb3402019-09-25 15:13:04 +02003640 EXPECT_EQ(source_.sink_wants().max_framerate_fps, 14);
Åsa Persson30ab0152019-08-27 12:22:33 +02003641 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3642
3643 video_stream_encoder_->Stop();
3644}
3645
Åsa Perssonccfb3402019-09-25 15:13:04 +02003646TEST_F(BalancedDegradationTest,
Åsa Persson45b176f2019-09-30 11:19:05 +02003647 InitialFrameDropAdaptsFpsAndResolutionInOneStep) {
3648 test::ScopedFieldTrials field_trials(
3649 "WebRTC-Video-BalancedDegradationSettings/"
3650 "pixels:57600|129600|230400,fps:7|24|24/");
3651 SetupTest();
3652 OnBitrateUpdated(kLowTargetBitrateBps);
3653
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003654 EXPECT_THAT(source_.sink_wants(), UnlimitedSinkWants());
Åsa Persson45b176f2019-09-30 11:19:05 +02003655
3656 // Insert frame, expect scaled down:
3657 // framerate (640x360@24fps) -> resolution (480x270@24fps).
3658 InsertFrame();
3659 EXPECT_FALSE(WaitForFrame(1000));
3660 EXPECT_LT(source_.sink_wants().max_pixel_count, kWidth * kHeight);
3661 EXPECT_EQ(source_.sink_wants().max_framerate_fps, 24);
3662
3663 // Insert frame, expect scaled down:
3664 // resolution (320x180@24fps).
3665 InsertFrame();
3666 EXPECT_FALSE(WaitForFrame(1000));
3667 EXPECT_LT(source_.sink_wants().max_pixel_count,
3668 source_.last_wants().max_pixel_count);
3669 EXPECT_EQ(source_.sink_wants().max_framerate_fps, 24);
3670
3671 // Frame should not be dropped (min pixels per frame reached).
3672 InsertFrameAndWaitForEncoded();
3673
3674 video_stream_encoder_->Stop();
3675}
3676
3677TEST_F(BalancedDegradationTest,
Åsa Persson30ab0152019-08-27 12:22:33 +02003678 NoAdaptUpInResolutionIfBwEstimateIsLessThanMinBitrate) {
Åsa Perssonb67c44c2019-09-24 15:25:32 +02003679 test::ScopedFieldTrials field_trials(
Åsa Persson30ab0152019-08-27 12:22:33 +02003680 "WebRTC-Video-BalancedDegradationSettings/"
3681 "pixels:57600|129600|230400,fps:7|10|14,kbps_res:0|0|435/");
Åsa Perssonccfb3402019-09-25 15:13:04 +02003682 SetupTest();
Åsa Persson30ab0152019-08-27 12:22:33 +02003683
Åsa Persson30ab0152019-08-27 12:22:33 +02003684 const int kResolutionMinBitrateBps = 435000;
3685 const int kTooLowMinResolutionBitrateBps = 434000;
Åsa Perssonccfb3402019-09-25 15:13:04 +02003686 OnBitrateUpdated(kTooLowMinResolutionBitrateBps);
Åsa Persson30ab0152019-08-27 12:22:33 +02003687
Åsa Persson45b176f2019-09-30 11:19:05 +02003688 InsertFrameAndWaitForEncoded();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003689 EXPECT_THAT(source_.sink_wants(), FpsMaxResolutionMax());
Åsa Persson30ab0152019-08-27 12:22:33 +02003690 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3691
3692 // Trigger adapt down, expect scaled down framerate (640x360@14fps).
3693 video_stream_encoder_->TriggerQualityLow();
Åsa Persson45b176f2019-09-30 11:19:05 +02003694 InsertFrameAndWaitForEncoded();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003695 EXPECT_THAT(source_.sink_wants(), FpsMatchesResolutionMax(Eq(14)));
Åsa Persson30ab0152019-08-27 12:22:33 +02003696 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3697
3698 // Trigger adapt down, expect scaled down resolution (480x270@14fps).
3699 video_stream_encoder_->TriggerQualityLow();
Åsa Persson45b176f2019-09-30 11:19:05 +02003700 InsertFrameAndWaitForEncoded();
Evan Shrubsole5fd40602020-05-25 16:19:54 +02003701 EXPECT_THAT(source_.sink_wants(), FpsEqResolutionLt(source_.last_wants()));
Åsa Persson30ab0152019-08-27 12:22:33 +02003702 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3703
3704 // Trigger adapt down, expect scaled down framerate (480x270@10fps).
3705 video_stream_encoder_->TriggerQualityLow();
Åsa Persson45b176f2019-09-30 11:19:05 +02003706 InsertFrameAndWaitForEncoded();
Evan Shrubsole5fd40602020-05-25 16:19:54 +02003707 EXPECT_THAT(source_.sink_wants(), FpsLtResolutionEq(source_.last_wants()));
Åsa Persson1b247f12019-08-14 17:26:39 +02003708 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3709
Åsa Persson30ab0152019-08-27 12:22:33 +02003710 // Trigger adapt up, expect upscaled fps (no bitrate limit) (480x270@14fps).
3711 video_stream_encoder_->TriggerQualityHigh();
Åsa Persson45b176f2019-09-30 11:19:05 +02003712 InsertFrameAndWaitForEncoded();
Evan Shrubsole5fd40602020-05-25 16:19:54 +02003713 EXPECT_THAT(source_.sink_wants(), FpsGtResolutionEq(source_.last_wants()));
Åsa Persson30ab0152019-08-27 12:22:33 +02003714 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3715
3716 // Trigger adapt up, expect no upscale in res (target bitrate < min bitrate).
3717 video_stream_encoder_->TriggerQualityHigh();
Åsa Persson45b176f2019-09-30 11:19:05 +02003718 InsertFrameAndWaitForEncoded();
Åsa Persson30ab0152019-08-27 12:22:33 +02003719 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3720
3721 // Trigger adapt up, expect upscaled res (target bitrate == min bitrate).
Åsa Perssonccfb3402019-09-25 15:13:04 +02003722 OnBitrateUpdated(kResolutionMinBitrateBps);
Åsa Persson30ab0152019-08-27 12:22:33 +02003723 video_stream_encoder_->TriggerQualityHigh();
Åsa Persson45b176f2019-09-30 11:19:05 +02003724 InsertFrameAndWaitForEncoded();
Evan Shrubsole5fd40602020-05-25 16:19:54 +02003725 EXPECT_THAT(source_.sink_wants(), FpsEqResolutionGt(source_.last_wants()));
Åsa Persson30ab0152019-08-27 12:22:33 +02003726 EXPECT_EQ(5, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3727
3728 video_stream_encoder_->Stop();
3729}
3730
Åsa Perssonccfb3402019-09-25 15:13:04 +02003731TEST_F(BalancedDegradationTest,
Åsa Persson30ab0152019-08-27 12:22:33 +02003732 NoAdaptUpInFpsAndResolutionIfBwEstimateIsLessThanMinBitrate) {
Åsa Perssonb67c44c2019-09-24 15:25:32 +02003733 test::ScopedFieldTrials field_trials(
Åsa Persson30ab0152019-08-27 12:22:33 +02003734 "WebRTC-Video-BalancedDegradationSettings/"
3735 "pixels:57600|129600|230400,fps:7|10|14,kbps:0|0|425,kbps_res:0|0|435/");
Åsa Perssonccfb3402019-09-25 15:13:04 +02003736 SetupTest();
Åsa Persson30ab0152019-08-27 12:22:33 +02003737
Åsa Persson30ab0152019-08-27 12:22:33 +02003738 const int kMinBitrateBps = 425000;
3739 const int kTooLowMinBitrateBps = 424000;
3740 const int kResolutionMinBitrateBps = 435000;
3741 const int kTooLowMinResolutionBitrateBps = 434000;
Åsa Perssonccfb3402019-09-25 15:13:04 +02003742 OnBitrateUpdated(kTooLowMinBitrateBps);
Åsa Persson30ab0152019-08-27 12:22:33 +02003743
Åsa Persson45b176f2019-09-30 11:19:05 +02003744 InsertFrameAndWaitForEncoded();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003745 EXPECT_THAT(source_.sink_wants(), FpsMaxResolutionMax());
Åsa Persson30ab0152019-08-27 12:22:33 +02003746 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3747
3748 // Trigger adapt down, expect scaled down framerate (640x360@14fps).
3749 video_stream_encoder_->TriggerQualityLow();
Åsa Persson45b176f2019-09-30 11:19:05 +02003750 InsertFrameAndWaitForEncoded();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003751 EXPECT_THAT(source_.sink_wants(), FpsMatchesResolutionMax(Eq(14)));
Åsa Persson30ab0152019-08-27 12:22:33 +02003752 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3753
3754 // Trigger adapt down, expect scaled down resolution (480x270@14fps).
3755 video_stream_encoder_->TriggerQualityLow();
Åsa Persson45b176f2019-09-30 11:19:05 +02003756 InsertFrameAndWaitForEncoded();
Evan Shrubsole5fd40602020-05-25 16:19:54 +02003757 EXPECT_THAT(source_.sink_wants(), FpsEqResolutionLt(source_.last_wants()));
Åsa Persson30ab0152019-08-27 12:22:33 +02003758 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3759
3760 // Trigger adapt down, expect scaled down framerate (480x270@10fps).
3761 video_stream_encoder_->TriggerQualityLow();
Åsa Persson45b176f2019-09-30 11:19:05 +02003762 InsertFrameAndWaitForEncoded();
Evan Shrubsole5fd40602020-05-25 16:19:54 +02003763 EXPECT_THAT(source_.sink_wants(), FpsLtResolutionEq(source_.last_wants()));
Åsa Persson30ab0152019-08-27 12:22:33 +02003764 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3765
3766 // Trigger adapt up, expect no upscale (target bitrate < min bitrate).
3767 video_stream_encoder_->TriggerQualityHigh();
Åsa Persson45b176f2019-09-30 11:19:05 +02003768 InsertFrameAndWaitForEncoded();
Åsa Persson30ab0152019-08-27 12:22:33 +02003769 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3770
3771 // Trigger adapt up, expect upscaled fps (target bitrate == min bitrate).
Åsa Perssonccfb3402019-09-25 15:13:04 +02003772 OnBitrateUpdated(kMinBitrateBps);
Åsa Persson30ab0152019-08-27 12:22:33 +02003773 video_stream_encoder_->TriggerQualityHigh();
Åsa Persson45b176f2019-09-30 11:19:05 +02003774 InsertFrameAndWaitForEncoded();
Evan Shrubsole5fd40602020-05-25 16:19:54 +02003775 EXPECT_THAT(source_.sink_wants(), FpsGtResolutionEq(source_.last_wants()));
Åsa Persson30ab0152019-08-27 12:22:33 +02003776 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3777
3778 // Trigger adapt up, expect no upscale in res (target bitrate < min bitrate).
Åsa Perssonccfb3402019-09-25 15:13:04 +02003779 OnBitrateUpdated(kTooLowMinResolutionBitrateBps);
Åsa Persson30ab0152019-08-27 12:22:33 +02003780 video_stream_encoder_->TriggerQualityHigh();
Åsa Persson45b176f2019-09-30 11:19:05 +02003781 InsertFrameAndWaitForEncoded();
Åsa Persson30ab0152019-08-27 12:22:33 +02003782 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3783
3784 // Trigger adapt up, expect upscaled res (target bitrate == min bitrate).
Åsa Perssonccfb3402019-09-25 15:13:04 +02003785 OnBitrateUpdated(kResolutionMinBitrateBps);
Åsa Persson30ab0152019-08-27 12:22:33 +02003786 video_stream_encoder_->TriggerQualityHigh();
Åsa Persson45b176f2019-09-30 11:19:05 +02003787 InsertFrameAndWaitForEncoded();
Evan Shrubsole5fd40602020-05-25 16:19:54 +02003788 EXPECT_THAT(source_.sink_wants(), FpsEqResolutionGt(source_.last_wants()));
Åsa Persson30ab0152019-08-27 12:22:33 +02003789 EXPECT_EQ(5, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3790
Åsa Persson1b247f12019-08-14 17:26:39 +02003791 video_stream_encoder_->Stop();
3792}
3793
mflodmancc3d4422017-08-03 08:27:51 -07003794TEST_F(VideoStreamEncoderTest,
asaperssond0de2952017-04-21 01:47:31 -07003795 AdaptsResolutionOnOveruseAndLowQuality_MaintainFramerateMode) {
3796 const int kWidth = 1280;
3797 const int kHeight = 720;
Henrik Boström381d1092020-05-12 18:49:07 +02003798 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01003799 DataRate::BitsPerSec(kTargetBitrateBps),
3800 DataRate::BitsPerSec(kTargetBitrateBps),
3801 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asaperssond0de2952017-04-21 01:47:31 -07003802
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003803 // Enable MAINTAIN_FRAMERATE preference, no initial limitation.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02003804 AdaptingFrameForwarder source(&time_controller_);
asaperssond0de2952017-04-21 01:47:31 -07003805 source.set_adaptation_enabled(true);
mflodmancc3d4422017-08-03 08:27:51 -07003806 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003807 &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
asaperssond0de2952017-04-21 01:47:31 -07003808
Åsa Persson8c1bf952018-09-13 10:42:19 +02003809 int64_t timestamp_ms = kFrameIntervalMs;
3810 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07003811 WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003812 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssond0de2952017-04-21 01:47:31 -07003813 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
3814 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
3815 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3816 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3817
3818 // Trigger cpu adapt down, expect scaled down resolution (960x540).
mflodmancc3d4422017-08-03 08:27:51 -07003819 video_stream_encoder_->TriggerCpuOveruse();
Åsa Persson8c1bf952018-09-13 10:42:19 +02003820 timestamp_ms += kFrameIntervalMs;
3821 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
3822 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003823 EXPECT_THAT(source.sink_wants(),
3824 FpsMaxResolutionMatches(Lt(kWidth * kHeight)));
asaperssond0de2952017-04-21 01:47:31 -07003825 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
3826 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
3827 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3828 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3829
3830 // Trigger cpu adapt down, expect scaled down resolution (640x360).
mflodmancc3d4422017-08-03 08:27:51 -07003831 video_stream_encoder_->TriggerCpuOveruse();
Åsa Persson8c1bf952018-09-13 10:42:19 +02003832 timestamp_ms += kFrameIntervalMs;
3833 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
3834 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02003835 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionLt(source.last_wants()));
asaperssond0de2952017-04-21 01:47:31 -07003836 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
3837 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
3838 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3839 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3840
Jonathan Yubc771b72017-12-08 17:04:29 -08003841 // Trigger cpu adapt down, expect scaled down resolution (480x270).
mflodmancc3d4422017-08-03 08:27:51 -07003842 video_stream_encoder_->TriggerCpuOveruse();
Åsa Persson8c1bf952018-09-13 10:42:19 +02003843 timestamp_ms += kFrameIntervalMs;
3844 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
3845 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02003846 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionLt(source.last_wants()));
asaperssond0de2952017-04-21 01:47:31 -07003847 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
3848 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
Jonathan Yubc771b72017-12-08 17:04:29 -08003849 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
asaperssond0de2952017-04-21 01:47:31 -07003850 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3851
Jonathan Yubc771b72017-12-08 17:04:29 -08003852 // Trigger quality adapt down, expect scaled down resolution (320x180).
mflodmancc3d4422017-08-03 08:27:51 -07003853 video_stream_encoder_->TriggerQualityLow();
Åsa Persson8c1bf952018-09-13 10:42:19 +02003854 timestamp_ms += kFrameIntervalMs;
3855 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
3856 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02003857 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionLt(source.last_wants()));
Jonathan Yubc771b72017-12-08 17:04:29 -08003858 rtc::VideoSinkWants last_wants = source.sink_wants();
asaperssond0de2952017-04-21 01:47:31 -07003859 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
3860 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
3861 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3862 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3863
Jonathan Yubc771b72017-12-08 17:04:29 -08003864 // Trigger quality adapt down, expect no change (min resolution reached).
3865 video_stream_encoder_->TriggerQualityLow();
Åsa Persson8c1bf952018-09-13 10:42:19 +02003866 timestamp_ms += kFrameIntervalMs;
3867 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
3868 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02003869 EXPECT_THAT(source.sink_wants(), FpsMax());
3870 EXPECT_EQ(source.sink_wants().max_pixel_count, last_wants.max_pixel_count);
Jonathan Yubc771b72017-12-08 17:04:29 -08003871 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
3872 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
3873 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3874 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3875
Evan Shrubsole64469032020-06-11 10:45:29 +02003876 // Trigger quality adapt up, expect upscaled resolution (480x270).
3877 video_stream_encoder_->TriggerQualityHigh();
3878 timestamp_ms += kFrameIntervalMs;
3879 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
3880 WaitForEncodedFrame(timestamp_ms);
3881 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionGt(source.last_wants()));
3882 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
3883 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
3884 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3885 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3886
3887 // Trigger quality and cpu adapt up since both are most limited, expect
3888 // upscaled resolution (640x360).
Henrik Boström91aa7322020-04-28 12:24:33 +02003889 video_stream_encoder_->TriggerCpuUnderuse();
Evan Shrubsole64469032020-06-11 10:45:29 +02003890 video_stream_encoder_->TriggerQualityHigh();
Åsa Persson8c1bf952018-09-13 10:42:19 +02003891 timestamp_ms += kFrameIntervalMs;
3892 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
3893 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02003894 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionGt(source.last_wants()));
Jonathan Yubc771b72017-12-08 17:04:29 -08003895 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
3896 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
3897 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
Evan Shrubsole64469032020-06-11 10:45:29 +02003898 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_quality_adapt_changes);
Jonathan Yubc771b72017-12-08 17:04:29 -08003899
Evan Shrubsole64469032020-06-11 10:45:29 +02003900 // Trigger quality and cpu adapt up since both are most limited, expect
3901 // upscaled resolution (960x540).
Henrik Boström91aa7322020-04-28 12:24:33 +02003902 video_stream_encoder_->TriggerCpuUnderuse();
Evan Shrubsole64469032020-06-11 10:45:29 +02003903 video_stream_encoder_->TriggerQualityHigh();
Åsa Persson8c1bf952018-09-13 10:42:19 +02003904 timestamp_ms += kFrameIntervalMs;
3905 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
3906 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02003907 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionGt(source.last_wants()));
asaperssond0de2952017-04-21 01:47:31 -07003908 last_wants = source.sink_wants();
Evan Shrubsole64469032020-06-11 10:45:29 +02003909 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
asaperssond0de2952017-04-21 01:47:31 -07003910 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
Evan Shrubsole64469032020-06-11 10:45:29 +02003911 EXPECT_EQ(5, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3912 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_quality_adapt_changes);
asaperssond0de2952017-04-21 01:47:31 -07003913
Evan Shrubsole64469032020-06-11 10:45:29 +02003914 // Trigger cpu adapt up, expect no change since not most limited (960x540).
3915 // However the stats will change since the CPU resource is no longer limited.
Henrik Boström91aa7322020-04-28 12:24:33 +02003916 video_stream_encoder_->TriggerCpuUnderuse();
Åsa Persson8c1bf952018-09-13 10:42:19 +02003917 timestamp_ms += kFrameIntervalMs;
3918 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
3919 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02003920 EXPECT_THAT(source.sink_wants(), FpsEqResolutionEqTo(last_wants));
asaperssond0de2952017-04-21 01:47:31 -07003921 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
3922 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
Jonathan Yubc771b72017-12-08 17:04:29 -08003923 EXPECT_EQ(6, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
Evan Shrubsole64469032020-06-11 10:45:29 +02003924 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_quality_adapt_changes);
asaperssond0de2952017-04-21 01:47:31 -07003925
3926 // Trigger quality adapt up, expect no restriction (1280x720).
mflodmancc3d4422017-08-03 08:27:51 -07003927 video_stream_encoder_->TriggerQualityHigh();
Åsa Persson8c1bf952018-09-13 10:42:19 +02003928 timestamp_ms += kFrameIntervalMs;
3929 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07003930 WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02003931 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionGt(source.last_wants()));
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003932 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssond0de2952017-04-21 01:47:31 -07003933 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
3934 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
Jonathan Yubc771b72017-12-08 17:04:29 -08003935 EXPECT_EQ(6, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
Evan Shrubsole64469032020-06-11 10:45:29 +02003936 EXPECT_EQ(5, stats_proxy_->GetStats().number_of_quality_adapt_changes);
kthelgason5e13d412016-12-01 03:59:51 -08003937
mflodmancc3d4422017-08-03 08:27:51 -07003938 video_stream_encoder_->Stop();
kthelgason5e13d412016-12-01 03:59:51 -08003939}
3940
mflodmancc3d4422017-08-03 08:27:51 -07003941TEST_F(VideoStreamEncoderTest, CpuLimitedHistogramIsReported) {
asaperssonfab67072017-04-04 05:51:49 -07003942 const int kWidth = 640;
3943 const int kHeight = 360;
perkj803d97f2016-11-01 11:45:46 -07003944
Henrik Boström381d1092020-05-12 18:49:07 +02003945 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01003946 DataRate::BitsPerSec(kTargetBitrateBps),
3947 DataRate::BitsPerSec(kTargetBitrateBps),
3948 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
sprang4847ae62017-06-27 07:06:52 -07003949
perkj803d97f2016-11-01 11:45:46 -07003950 for (int i = 1; i <= SendStatisticsProxy::kMinRequiredMetricsSamples; ++i) {
asaperssonfab67072017-04-04 05:51:49 -07003951 video_source_.IncomingCapturedFrame(CreateFrame(i, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07003952 WaitForEncodedFrame(i);
perkj803d97f2016-11-01 11:45:46 -07003953 }
3954
mflodmancc3d4422017-08-03 08:27:51 -07003955 video_stream_encoder_->TriggerCpuOveruse();
perkj803d97f2016-11-01 11:45:46 -07003956 for (int i = 1; i <= SendStatisticsProxy::kMinRequiredMetricsSamples; ++i) {
asaperssonfab67072017-04-04 05:51:49 -07003957 video_source_.IncomingCapturedFrame(CreateFrame(
3958 SendStatisticsProxy::kMinRequiredMetricsSamples + i, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07003959 WaitForEncodedFrame(SendStatisticsProxy::kMinRequiredMetricsSamples + i);
perkj803d97f2016-11-01 11:45:46 -07003960 }
3961
mflodmancc3d4422017-08-03 08:27:51 -07003962 video_stream_encoder_->Stop();
3963 video_stream_encoder_.reset();
perkj803d97f2016-11-01 11:45:46 -07003964 stats_proxy_.reset();
sprangf8ee65e2017-02-28 08:49:33 -08003965
Ying Wangef3998f2019-12-09 13:06:53 +01003966 EXPECT_METRIC_EQ(
3967 1, metrics::NumSamples("WebRTC.Video.CpuLimitedResolutionInPercent"));
3968 EXPECT_METRIC_EQ(
perkj803d97f2016-11-01 11:45:46 -07003969 1, metrics::NumEvents("WebRTC.Video.CpuLimitedResolutionInPercent", 50));
3970}
3971
mflodmancc3d4422017-08-03 08:27:51 -07003972TEST_F(VideoStreamEncoderTest,
3973 CpuLimitedHistogramIsNotReportedForDisabledDegradation) {
Henrik Boström381d1092020-05-12 18:49:07 +02003974 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01003975 DataRate::BitsPerSec(kTargetBitrateBps),
3976 DataRate::BitsPerSec(kTargetBitrateBps),
3977 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asaperssonf4e44af2017-04-19 02:01:06 -07003978 const int kWidth = 640;
3979 const int kHeight = 360;
3980
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003981 video_stream_encoder_->SetSource(&video_source_,
3982 webrtc::DegradationPreference::DISABLED);
asaperssonf4e44af2017-04-19 02:01:06 -07003983
3984 for (int i = 1; i <= SendStatisticsProxy::kMinRequiredMetricsSamples; ++i) {
3985 video_source_.IncomingCapturedFrame(CreateFrame(i, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07003986 WaitForEncodedFrame(i);
asaperssonf4e44af2017-04-19 02:01:06 -07003987 }
3988
mflodmancc3d4422017-08-03 08:27:51 -07003989 video_stream_encoder_->Stop();
3990 video_stream_encoder_.reset();
asaperssonf4e44af2017-04-19 02:01:06 -07003991 stats_proxy_.reset();
3992
3993 EXPECT_EQ(0,
3994 metrics::NumSamples("WebRTC.Video.CpuLimitedResolutionInPercent"));
3995}
3996
Per Kjellanderdcef6412020-10-07 15:09:05 +02003997TEST_F(VideoStreamEncoderTest, ReportsVideoBitrateAllocation) {
3998 ResetEncoder("FAKE", 1, 1, 1, /*screenshare*/ false,
3999 VideoStreamEncoderSettings::BitrateAllocationCallbackType::
4000 kVideoBitrateAllocation);
sprang57c2fff2017-01-16 06:24:02 -08004001
4002 const int kDefaultFps = 30;
Erik Språng566124a2018-04-23 12:32:22 +02004003 const VideoBitrateAllocation expected_bitrate =
Mirta Dvornicic6799d732020-02-12 15:36:49 +01004004 SimulcastRateAllocator(fake_encoder_.codec_config())
Florent Castelli8bbdb5b2019-08-02 15:16:28 +02004005 .Allocate(VideoBitrateAllocationParameters(kLowTargetBitrateBps,
4006 kDefaultFps));
sprang57c2fff2017-01-16 06:24:02 -08004007
Henrik Boström381d1092020-05-12 18:49:07 +02004008 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01004009 DataRate::BitsPerSec(kLowTargetBitrateBps),
4010 DataRate::BitsPerSec(kLowTargetBitrateBps),
4011 DataRate::BitsPerSec(kLowTargetBitrateBps), 0, 0, 0);
sprang57c2fff2017-01-16 06:24:02 -08004012
sprang57c2fff2017-01-16 06:24:02 -08004013 video_source_.IncomingCapturedFrame(
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02004014 CreateFrame(CurrentTimeMs(), codec_width_, codec_height_));
4015 WaitForEncodedFrame(CurrentTimeMs());
Per Kjellanderdcef6412020-10-07 15:09:05 +02004016 EXPECT_EQ(sink_.GetLastVideoBitrateAllocation(), expected_bitrate);
4017 EXPECT_EQ(sink_.number_of_bitrate_allocations(), 1);
4018
Erik Språngd7329ca2019-02-21 21:19:53 +01004019 // Check that encoder has been updated too, not just allocation observer.
Erik Språng9d69cbe2020-10-22 17:44:42 +02004020 EXPECT_TRUE(fake_encoder_.GetAndResetLastRateControlSettings().has_value());
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02004021 AdvanceTime(TimeDelta::Seconds(1) / kDefaultFps);
sprang57c2fff2017-01-16 06:24:02 -08004022
Per Kjellanderdcef6412020-10-07 15:09:05 +02004023 // VideoBitrateAllocation not updated on second frame.
sprang57c2fff2017-01-16 06:24:02 -08004024 video_source_.IncomingCapturedFrame(
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02004025 CreateFrame(CurrentTimeMs(), codec_width_, codec_height_));
4026 WaitForEncodedFrame(CurrentTimeMs());
Per Kjellanderdcef6412020-10-07 15:09:05 +02004027 EXPECT_EQ(sink_.number_of_bitrate_allocations(), 1);
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02004028 AdvanceTime(TimeDelta::Millis(1) / kDefaultFps);
sprang57c2fff2017-01-16 06:24:02 -08004029
Per Kjellanderdcef6412020-10-07 15:09:05 +02004030 // VideoBitrateAllocation updated after a process interval.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02004031 const int64_t start_time_ms = CurrentTimeMs();
Per Kjellanderd0a8f512020-10-07 11:28:41 +02004032 while (CurrentTimeMs() - start_time_ms < 5 * kProcessIntervalMs) {
Erik Språngd7329ca2019-02-21 21:19:53 +01004033 video_source_.IncomingCapturedFrame(
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02004034 CreateFrame(CurrentTimeMs(), codec_width_, codec_height_));
4035 WaitForEncodedFrame(CurrentTimeMs());
4036 AdvanceTime(TimeDelta::Millis(1) / kDefaultFps);
Erik Språngd7329ca2019-02-21 21:19:53 +01004037 }
Per Kjellanderdcef6412020-10-07 15:09:05 +02004038 EXPECT_GT(sink_.number_of_bitrate_allocations(), 3);
Erik Språngd7329ca2019-02-21 21:19:53 +01004039
mflodmancc3d4422017-08-03 08:27:51 -07004040 video_stream_encoder_->Stop();
sprang57c2fff2017-01-16 06:24:02 -08004041}
4042
Per Kjellandera9434842020-10-15 17:53:22 +02004043TEST_F(VideoStreamEncoderTest, ReportsVideoLayersAllocationForV8Simulcast) {
4044 ResetEncoder("VP8", /*num_streams*/ 2, 1, 1, /*screenshare*/ false,
4045 VideoStreamEncoderSettings::BitrateAllocationCallbackType::
4046 kVideoLayersAllocation);
4047
4048 const int kDefaultFps = 30;
4049
4050 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
4051 DataRate::BitsPerSec(kLowTargetBitrateBps),
4052 DataRate::BitsPerSec(kLowTargetBitrateBps),
4053 DataRate::BitsPerSec(kLowTargetBitrateBps), 0, 0, 0);
4054
4055 video_source_.IncomingCapturedFrame(
4056 CreateFrame(CurrentTimeMs(), codec_width_, codec_height_));
4057 WaitForEncodedFrame(CurrentTimeMs());
4058 EXPECT_EQ(sink_.number_of_layers_allocations(), 1);
4059 VideoLayersAllocation last_layer_allocation =
4060 sink_.GetLastVideoLayersAllocation();
4061 // kLowTargetBitrateBps is only enough for one spatial layer.
4062 ASSERT_EQ(last_layer_allocation.active_spatial_layers.size(), 1u);
4063
4064 VideoBitrateAllocation bitrate_allocation =
Erik Språng9d69cbe2020-10-22 17:44:42 +02004065 fake_encoder_.GetAndResetLastRateControlSettings()->target_bitrate;
Per Kjellandera9434842020-10-15 17:53:22 +02004066 // Check that encoder has been updated too, not just allocation observer.
4067 EXPECT_EQ(bitrate_allocation.get_sum_bps(), kLowTargetBitrateBps);
4068 AdvanceTime(TimeDelta::Seconds(1) / kDefaultFps);
4069
Erik Språng9d69cbe2020-10-22 17:44:42 +02004070 // VideoLayersAllocation might be updated if frame rate changes.
Per Kjellandera9434842020-10-15 17:53:22 +02004071 int number_of_layers_allocation = 1;
4072 const int64_t start_time_ms = CurrentTimeMs();
4073 while (CurrentTimeMs() - start_time_ms < 10 * kProcessIntervalMs) {
4074 video_source_.IncomingCapturedFrame(
4075 CreateFrame(CurrentTimeMs(), codec_width_, codec_height_));
4076 WaitForEncodedFrame(CurrentTimeMs());
Per Kjellandera9434842020-10-15 17:53:22 +02004077 if (number_of_layers_allocation != sink_.number_of_layers_allocations()) {
4078 number_of_layers_allocation = sink_.number_of_layers_allocations();
4079 VideoLayersAllocation new_allocation =
4080 sink_.GetLastVideoLayersAllocation();
4081 ASSERT_EQ(new_allocation.active_spatial_layers.size(), 1u);
4082 EXPECT_NE(new_allocation.active_spatial_layers[0].frame_rate_fps,
4083 last_layer_allocation.active_spatial_layers[0].frame_rate_fps);
4084 EXPECT_EQ(new_allocation.active_spatial_layers[0]
4085 .target_bitrate_per_temporal_layer,
4086 last_layer_allocation.active_spatial_layers[0]
4087 .target_bitrate_per_temporal_layer);
4088 last_layer_allocation = new_allocation;
4089 }
4090 }
4091 EXPECT_LE(sink_.number_of_layers_allocations(), 3);
4092 video_stream_encoder_->Stop();
4093}
4094
4095TEST_F(VideoStreamEncoderTest,
4096 ReportsUpdatedVideoLayersAllocationWhenBweChanges) {
4097 ResetEncoder("VP8", /*num_streams*/ 2, 1, 1, /*screenshare*/ false,
4098 VideoStreamEncoderSettings::BitrateAllocationCallbackType::
4099 kVideoLayersAllocation);
4100
4101 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
4102 DataRate::BitsPerSec(kLowTargetBitrateBps),
4103 DataRate::BitsPerSec(kLowTargetBitrateBps),
4104 DataRate::BitsPerSec(kLowTargetBitrateBps), 0, 0, 0);
4105
4106 video_source_.IncomingCapturedFrame(
4107 CreateFrame(CurrentTimeMs(), codec_width_, codec_height_));
4108 WaitForEncodedFrame(CurrentTimeMs());
4109 EXPECT_EQ(sink_.number_of_layers_allocations(), 1);
4110 VideoLayersAllocation last_layer_allocation =
4111 sink_.GetLastVideoLayersAllocation();
4112 // kLowTargetBitrateBps is only enough for one spatial layer.
4113 ASSERT_EQ(last_layer_allocation.active_spatial_layers.size(), 1u);
4114 EXPECT_EQ(last_layer_allocation.active_spatial_layers[0]
4115 .target_bitrate_per_temporal_layer[0],
4116 DataRate::BitsPerSec(kLowTargetBitrateBps));
4117
4118 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
4119 DataRate::BitsPerSec(kSimulcastTargetBitrateBps),
4120 DataRate::BitsPerSec(kSimulcastTargetBitrateBps),
4121 DataRate::BitsPerSec(kSimulcastTargetBitrateBps), 0, 0, 0);
4122 video_source_.IncomingCapturedFrame(
4123 CreateFrame(CurrentTimeMs(), codec_width_, codec_height_));
4124 WaitForEncodedFrame(CurrentTimeMs());
4125
4126 EXPECT_EQ(sink_.number_of_layers_allocations(), 2);
4127 last_layer_allocation = sink_.GetLastVideoLayersAllocation();
4128 ASSERT_EQ(last_layer_allocation.active_spatial_layers.size(), 2u);
4129 EXPECT_GT(last_layer_allocation.active_spatial_layers[1]
4130 .target_bitrate_per_temporal_layer[0],
4131 DataRate::Zero());
4132
4133 video_stream_encoder_->Stop();
4134}
4135
Åsa Perssonc29cb2c2019-03-25 12:06:59 +01004136TEST_F(VideoStreamEncoderTest, TemporalLayersNotDisabledIfSupported) {
4137 // 2 TLs configured, temporal layers supported by encoder.
4138 const int kNumTemporalLayers = 2;
Per Kjellanderdcef6412020-10-07 15:09:05 +02004139 ResetEncoder("VP8", 1, kNumTemporalLayers, 1, /*screenshare*/ false,
4140 VideoStreamEncoderSettings::BitrateAllocationCallbackType::
4141 kVideoBitrateAllocation);
Åsa Perssonc29cb2c2019-03-25 12:06:59 +01004142 fake_encoder_.SetTemporalLayersSupported(0, true);
4143
4144 // Bitrate allocated across temporal layers.
4145 const int kTl0Bps = kTargetBitrateBps *
4146 webrtc::SimulcastRateAllocator::GetTemporalRateAllocation(
Rasmus Brandt2b9317a2019-10-30 13:01:46 +01004147 kNumTemporalLayers, /*temporal_id*/ 0,
4148 /*base_heavy_tl3_alloc*/ false);
Åsa Perssonc29cb2c2019-03-25 12:06:59 +01004149 const int kTl1Bps = kTargetBitrateBps *
4150 webrtc::SimulcastRateAllocator::GetTemporalRateAllocation(
Rasmus Brandt2b9317a2019-10-30 13:01:46 +01004151 kNumTemporalLayers, /*temporal_id*/ 1,
4152 /*base_heavy_tl3_alloc*/ false);
Åsa Perssonc29cb2c2019-03-25 12:06:59 +01004153 VideoBitrateAllocation expected_bitrate;
4154 expected_bitrate.SetBitrate(/*si*/ 0, /*ti*/ 0, kTl0Bps);
4155 expected_bitrate.SetBitrate(/*si*/ 0, /*ti*/ 1, kTl1Bps - kTl0Bps);
4156
4157 VerifyAllocatedBitrate(expected_bitrate);
4158 video_stream_encoder_->Stop();
4159}
4160
4161TEST_F(VideoStreamEncoderTest, TemporalLayersDisabledIfNotSupported) {
4162 // 2 TLs configured, temporal layers not supported by encoder.
Per Kjellanderdcef6412020-10-07 15:09:05 +02004163 ResetEncoder("VP8", 1, /*num_temporal_layers*/ 2, 1, /*screenshare*/ false,
4164 VideoStreamEncoderSettings::BitrateAllocationCallbackType::
4165 kVideoBitrateAllocation);
Åsa Perssonc29cb2c2019-03-25 12:06:59 +01004166 fake_encoder_.SetTemporalLayersSupported(0, false);
4167
4168 // Temporal layers not supported by the encoder.
4169 // Total bitrate should be at ti:0.
4170 VideoBitrateAllocation expected_bitrate;
4171 expected_bitrate.SetBitrate(/*si*/ 0, /*ti*/ 0, kTargetBitrateBps);
4172
4173 VerifyAllocatedBitrate(expected_bitrate);
4174 video_stream_encoder_->Stop();
4175}
4176
4177TEST_F(VideoStreamEncoderTest, VerifyBitrateAllocationForTwoStreams) {
Per Kjellanderdcef6412020-10-07 15:09:05 +02004178 webrtc::test::ScopedFieldTrials field_trials(
4179 "WebRTC-Video-QualityScalerSettings/"
4180 "initial_bitrate_interval_ms:1000,initial_bitrate_factor:0.2/");
4181 // Reset encoder for field trials to take effect.
4182 ConfigureEncoder(video_encoder_config_.Copy());
4183
Åsa Perssonc29cb2c2019-03-25 12:06:59 +01004184 // 2 TLs configured, temporal layers only supported for first stream.
Per Kjellanderdcef6412020-10-07 15:09:05 +02004185 ResetEncoder("VP8", 2, /*num_temporal_layers*/ 2, 1, /*screenshare*/ false,
4186 VideoStreamEncoderSettings::BitrateAllocationCallbackType::
4187 kVideoBitrateAllocation);
Åsa Perssonc29cb2c2019-03-25 12:06:59 +01004188 fake_encoder_.SetTemporalLayersSupported(0, true);
4189 fake_encoder_.SetTemporalLayersSupported(1, false);
4190
4191 const int kS0Bps = 150000;
4192 const int kS0Tl0Bps =
Rasmus Brandt2b9317a2019-10-30 13:01:46 +01004193 kS0Bps *
4194 webrtc::SimulcastRateAllocator::GetTemporalRateAllocation(
4195 /*num_layers*/ 2, /*temporal_id*/ 0, /*base_heavy_tl3_alloc*/ false);
Åsa Perssonc29cb2c2019-03-25 12:06:59 +01004196 const int kS0Tl1Bps =
Rasmus Brandt2b9317a2019-10-30 13:01:46 +01004197 kS0Bps *
4198 webrtc::SimulcastRateAllocator::GetTemporalRateAllocation(
4199 /*num_layers*/ 2, /*temporal_id*/ 1, /*base_heavy_tl3_alloc*/ false);
Åsa Perssonc29cb2c2019-03-25 12:06:59 +01004200 const int kS1Bps = kTargetBitrateBps - kS0Tl1Bps;
4201 // Temporal layers not supported by si:1.
4202 VideoBitrateAllocation expected_bitrate;
4203 expected_bitrate.SetBitrate(/*si*/ 0, /*ti*/ 0, kS0Tl0Bps);
4204 expected_bitrate.SetBitrate(/*si*/ 0, /*ti*/ 1, kS0Tl1Bps - kS0Tl0Bps);
4205 expected_bitrate.SetBitrate(/*si*/ 1, /*ti*/ 0, kS1Bps);
4206
4207 VerifyAllocatedBitrate(expected_bitrate);
4208 video_stream_encoder_->Stop();
4209}
4210
Niels Möller7dc26b72017-12-06 10:27:48 +01004211TEST_F(VideoStreamEncoderTest, OveruseDetectorUpdatedOnReconfigureAndAdaption) {
4212 const int kFrameWidth = 1280;
4213 const int kFrameHeight = 720;
4214 const int kFramerate = 24;
4215
Henrik Boström381d1092020-05-12 18:49:07 +02004216 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01004217 DataRate::BitsPerSec(kTargetBitrateBps),
4218 DataRate::BitsPerSec(kTargetBitrateBps),
4219 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Niels Möller7dc26b72017-12-06 10:27:48 +01004220 test::FrameForwarder source;
4221 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07004222 &source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
Niels Möller7dc26b72017-12-06 10:27:48 +01004223
4224 // Insert a single frame, triggering initial configuration.
4225 source.IncomingCapturedFrame(CreateFrame(1, kFrameWidth, kFrameHeight));
4226 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
4227
4228 EXPECT_EQ(
4229 video_stream_encoder_->overuse_detector_proxy_->GetLastTargetFramerate(),
4230 kDefaultFramerate);
4231
4232 // Trigger reconfigure encoder (without resetting the entire instance).
4233 VideoEncoderConfig video_encoder_config;
Åsa Persson17107062020-10-08 08:57:51 +02004234 test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
4235 video_encoder_config.simulcast_layers[0].max_framerate = kFramerate;
Niels Möller7dc26b72017-12-06 10:27:48 +01004236 video_encoder_config.max_bitrate_bps = kTargetBitrateBps;
Niels Möller7dc26b72017-12-06 10:27:48 +01004237 video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config),
Niels Möllerf1338562018-04-26 09:51:47 +02004238 kMaxPayloadLength);
Niels Möller7dc26b72017-12-06 10:27:48 +01004239 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
4240
4241 // Detector should be updated with fps limit from codec config.
4242 EXPECT_EQ(
4243 video_stream_encoder_->overuse_detector_proxy_->GetLastTargetFramerate(),
4244 kFramerate);
4245
4246 // Trigger overuse, max framerate should be reduced.
4247 VideoSendStream::Stats stats = stats_proxy_->GetStats();
4248 stats.input_frame_rate = kFramerate;
4249 stats_proxy_->SetMockStats(stats);
4250 video_stream_encoder_->TriggerCpuOveruse();
4251 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
4252 int adapted_framerate =
4253 video_stream_encoder_->overuse_detector_proxy_->GetLastTargetFramerate();
4254 EXPECT_LT(adapted_framerate, kFramerate);
4255
4256 // Trigger underuse, max framerate should go back to codec configured fps.
4257 // Set extra low fps, to make sure it's actually reset, not just incremented.
4258 stats = stats_proxy_->GetStats();
4259 stats.input_frame_rate = adapted_framerate / 2;
4260 stats_proxy_->SetMockStats(stats);
Henrik Boström91aa7322020-04-28 12:24:33 +02004261 video_stream_encoder_->TriggerCpuUnderuse();
Niels Möller7dc26b72017-12-06 10:27:48 +01004262 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
4263 EXPECT_EQ(
4264 video_stream_encoder_->overuse_detector_proxy_->GetLastTargetFramerate(),
4265 kFramerate);
4266
4267 video_stream_encoder_->Stop();
4268}
4269
4270TEST_F(VideoStreamEncoderTest,
4271 OveruseDetectorUpdatedRespectsFramerateAfterUnderuse) {
4272 const int kFrameWidth = 1280;
4273 const int kFrameHeight = 720;
4274 const int kLowFramerate = 15;
4275 const int kHighFramerate = 25;
4276
Henrik Boström381d1092020-05-12 18:49:07 +02004277 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01004278 DataRate::BitsPerSec(kTargetBitrateBps),
4279 DataRate::BitsPerSec(kTargetBitrateBps),
4280 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Niels Möller7dc26b72017-12-06 10:27:48 +01004281 test::FrameForwarder source;
4282 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07004283 &source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
Niels Möller7dc26b72017-12-06 10:27:48 +01004284
4285 // Trigger initial configuration.
4286 VideoEncoderConfig video_encoder_config;
Åsa Persson17107062020-10-08 08:57:51 +02004287 test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
4288 video_encoder_config.simulcast_layers[0].max_framerate = kLowFramerate;
Niels Möller7dc26b72017-12-06 10:27:48 +01004289 video_encoder_config.max_bitrate_bps = kTargetBitrateBps;
Niels Möller7dc26b72017-12-06 10:27:48 +01004290 source.IncomingCapturedFrame(CreateFrame(1, kFrameWidth, kFrameHeight));
Åsa Persson17107062020-10-08 08:57:51 +02004291 video_stream_encoder_->ConfigureEncoder(video_encoder_config.Copy(),
Niels Möllerf1338562018-04-26 09:51:47 +02004292 kMaxPayloadLength);
Niels Möller7dc26b72017-12-06 10:27:48 +01004293 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
4294
4295 EXPECT_EQ(
4296 video_stream_encoder_->overuse_detector_proxy_->GetLastTargetFramerate(),
4297 kLowFramerate);
4298
4299 // Trigger overuse, max framerate should be reduced.
4300 VideoSendStream::Stats stats = stats_proxy_->GetStats();
4301 stats.input_frame_rate = kLowFramerate;
4302 stats_proxy_->SetMockStats(stats);
4303 video_stream_encoder_->TriggerCpuOveruse();
4304 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
4305 int adapted_framerate =
4306 video_stream_encoder_->overuse_detector_proxy_->GetLastTargetFramerate();
4307 EXPECT_LT(adapted_framerate, kLowFramerate);
4308
4309 // Reconfigure the encoder with a new (higher max framerate), max fps should
4310 // still respect the adaptation.
Åsa Persson17107062020-10-08 08:57:51 +02004311 video_encoder_config.simulcast_layers[0].max_framerate = kHighFramerate;
Niels Möller7dc26b72017-12-06 10:27:48 +01004312 source.IncomingCapturedFrame(CreateFrame(1, kFrameWidth, kFrameHeight));
4313 video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config),
Niels Möllerf1338562018-04-26 09:51:47 +02004314 kMaxPayloadLength);
Niels Möller7dc26b72017-12-06 10:27:48 +01004315 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
4316
4317 EXPECT_EQ(
4318 video_stream_encoder_->overuse_detector_proxy_->GetLastTargetFramerate(),
4319 adapted_framerate);
4320
4321 // Trigger underuse, max framerate should go back to codec configured fps.
4322 stats = stats_proxy_->GetStats();
4323 stats.input_frame_rate = adapted_framerate;
4324 stats_proxy_->SetMockStats(stats);
Henrik Boström91aa7322020-04-28 12:24:33 +02004325 video_stream_encoder_->TriggerCpuUnderuse();
Niels Möller7dc26b72017-12-06 10:27:48 +01004326 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
4327 EXPECT_EQ(
4328 video_stream_encoder_->overuse_detector_proxy_->GetLastTargetFramerate(),
4329 kHighFramerate);
4330
4331 video_stream_encoder_->Stop();
4332}
4333
mflodmancc3d4422017-08-03 08:27:51 -07004334TEST_F(VideoStreamEncoderTest,
4335 OveruseDetectorUpdatedOnDegradationPreferenceChange) {
sprangfda496a2017-06-15 04:21:07 -07004336 const int kFrameWidth = 1280;
4337 const int kFrameHeight = 720;
4338 const int kFramerate = 24;
4339
Henrik Boström381d1092020-05-12 18:49:07 +02004340 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01004341 DataRate::BitsPerSec(kTargetBitrateBps),
4342 DataRate::BitsPerSec(kTargetBitrateBps),
4343 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
sprangfda496a2017-06-15 04:21:07 -07004344 test::FrameForwarder source;
mflodmancc3d4422017-08-03 08:27:51 -07004345 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07004346 &source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
sprangfda496a2017-06-15 04:21:07 -07004347
4348 // Trigger initial configuration.
4349 VideoEncoderConfig video_encoder_config;
Åsa Persson17107062020-10-08 08:57:51 +02004350 test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
4351 video_encoder_config.simulcast_layers[0].max_framerate = kFramerate;
sprangfda496a2017-06-15 04:21:07 -07004352 video_encoder_config.max_bitrate_bps = kTargetBitrateBps;
sprangfda496a2017-06-15 04:21:07 -07004353 source.IncomingCapturedFrame(CreateFrame(1, kFrameWidth, kFrameHeight));
mflodmancc3d4422017-08-03 08:27:51 -07004354 video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config),
Niels Möllerf1338562018-04-26 09:51:47 +02004355 kMaxPayloadLength);
mflodmancc3d4422017-08-03 08:27:51 -07004356 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
sprangfda496a2017-06-15 04:21:07 -07004357
Niels Möller7dc26b72017-12-06 10:27:48 +01004358 EXPECT_EQ(
4359 video_stream_encoder_->overuse_detector_proxy_->GetLastTargetFramerate(),
4360 kFramerate);
sprangfda496a2017-06-15 04:21:07 -07004361
4362 // Trigger overuse, max framerate should be reduced.
4363 VideoSendStream::Stats stats = stats_proxy_->GetStats();
4364 stats.input_frame_rate = kFramerate;
4365 stats_proxy_->SetMockStats(stats);
mflodmancc3d4422017-08-03 08:27:51 -07004366 video_stream_encoder_->TriggerCpuOveruse();
4367 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
Niels Möller7dc26b72017-12-06 10:27:48 +01004368 int adapted_framerate =
4369 video_stream_encoder_->overuse_detector_proxy_->GetLastTargetFramerate();
sprangfda496a2017-06-15 04:21:07 -07004370 EXPECT_LT(adapted_framerate, kFramerate);
4371
4372 // Change degradation preference to not enable framerate scaling. Target
4373 // framerate should be changed to codec defined limit.
Henrik Boström381d1092020-05-12 18:49:07 +02004374 video_stream_encoder_->SetSourceAndWaitForFramerateUpdated(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07004375 &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
Niels Möller7dc26b72017-12-06 10:27:48 +01004376 EXPECT_EQ(
4377 video_stream_encoder_->overuse_detector_proxy_->GetLastTargetFramerate(),
4378 kFramerate);
sprangfda496a2017-06-15 04:21:07 -07004379
mflodmancc3d4422017-08-03 08:27:51 -07004380 video_stream_encoder_->Stop();
sprangfda496a2017-06-15 04:21:07 -07004381}
4382
mflodmancc3d4422017-08-03 08:27:51 -07004383TEST_F(VideoStreamEncoderTest, DropsFramesAndScalesWhenBitrateIsTooLow) {
asaperssonfab67072017-04-04 05:51:49 -07004384 const int kTooLowBitrateForFrameSizeBps = 10000;
Henrik Boström381d1092020-05-12 18:49:07 +02004385 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01004386 DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps),
4387 DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps),
4388 DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps), 0, 0, 0);
asaperssonfab67072017-04-04 05:51:49 -07004389 const int kWidth = 640;
4390 const int kHeight = 360;
kthelgason2bc68642017-02-07 07:02:22 -08004391
asaperssonfab67072017-04-04 05:51:49 -07004392 video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
kthelgason2bc68642017-02-07 07:02:22 -08004393
4394 // Expect to drop this frame, the wait should time out.
sprang4847ae62017-06-27 07:06:52 -07004395 ExpectDroppedFrame();
kthelgason2bc68642017-02-07 07:02:22 -08004396
4397 // Expect the sink_wants to specify a scaled frame.
Henrik Boström2671dac2020-05-19 16:29:09 +02004398 EXPECT_TRUE_WAIT(
4399 video_source_.sink_wants().max_pixel_count < kWidth * kHeight, 5000);
kthelgason2bc68642017-02-07 07:02:22 -08004400
sprangc5d62e22017-04-02 23:53:04 -07004401 int last_pixel_count = video_source_.sink_wants().max_pixel_count;
kthelgason2bc68642017-02-07 07:02:22 -08004402
asaperssonfab67072017-04-04 05:51:49 -07004403 // Next frame is scaled.
kthelgason2bc68642017-02-07 07:02:22 -08004404 video_source_.IncomingCapturedFrame(
asaperssonfab67072017-04-04 05:51:49 -07004405 CreateFrame(2, kWidth * 3 / 4, kHeight * 3 / 4));
kthelgason2bc68642017-02-07 07:02:22 -08004406
4407 // Expect to drop this frame, the wait should time out.
sprang4847ae62017-06-27 07:06:52 -07004408 ExpectDroppedFrame();
kthelgason2bc68642017-02-07 07:02:22 -08004409
Henrik Boström2671dac2020-05-19 16:29:09 +02004410 EXPECT_TRUE_WAIT(
4411 video_source_.sink_wants().max_pixel_count < last_pixel_count, 5000);
kthelgason2bc68642017-02-07 07:02:22 -08004412
mflodmancc3d4422017-08-03 08:27:51 -07004413 video_stream_encoder_->Stop();
kthelgason2bc68642017-02-07 07:02:22 -08004414}
4415
mflodmancc3d4422017-08-03 08:27:51 -07004416TEST_F(VideoStreamEncoderTest,
4417 NumberOfDroppedFramesLimitedWhenBitrateIsTooLow) {
asaperssonfab67072017-04-04 05:51:49 -07004418 const int kTooLowBitrateForFrameSizeBps = 10000;
Henrik Boström381d1092020-05-12 18:49:07 +02004419 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01004420 DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps),
4421 DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps),
4422 DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps), 0, 0, 0);
asaperssonfab67072017-04-04 05:51:49 -07004423 const int kWidth = 640;
4424 const int kHeight = 360;
kthelgason2bc68642017-02-07 07:02:22 -08004425
4426 // We expect the n initial frames to get dropped.
4427 int i;
4428 for (i = 1; i <= kMaxInitialFramedrop; ++i) {
asaperssonfab67072017-04-04 05:51:49 -07004429 video_source_.IncomingCapturedFrame(CreateFrame(i, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07004430 ExpectDroppedFrame();
kthelgason2bc68642017-02-07 07:02:22 -08004431 }
4432 // The n+1th frame should not be dropped, even though it's size is too large.
asaperssonfab67072017-04-04 05:51:49 -07004433 video_source_.IncomingCapturedFrame(CreateFrame(i, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07004434 WaitForEncodedFrame(i);
kthelgason2bc68642017-02-07 07:02:22 -08004435
4436 // Expect the sink_wants to specify a scaled frame.
asaperssonfab67072017-04-04 05:51:49 -07004437 EXPECT_LT(video_source_.sink_wants().max_pixel_count, kWidth * kHeight);
kthelgason2bc68642017-02-07 07:02:22 -08004438
mflodmancc3d4422017-08-03 08:27:51 -07004439 video_stream_encoder_->Stop();
kthelgason2bc68642017-02-07 07:02:22 -08004440}
4441
mflodmancc3d4422017-08-03 08:27:51 -07004442TEST_F(VideoStreamEncoderTest,
4443 InitialFrameDropOffWithMaintainResolutionPreference) {
asaperssonfab67072017-04-04 05:51:49 -07004444 const int kWidth = 640;
4445 const int kHeight = 360;
Henrik Boström381d1092020-05-12 18:49:07 +02004446 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01004447 DataRate::BitsPerSec(kLowTargetBitrateBps),
4448 DataRate::BitsPerSec(kLowTargetBitrateBps),
4449 DataRate::BitsPerSec(kLowTargetBitrateBps), 0, 0, 0);
kthelgason2bc68642017-02-07 07:02:22 -08004450
4451 // Set degradation preference.
mflodmancc3d4422017-08-03 08:27:51 -07004452 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07004453 &video_source_, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
kthelgason2bc68642017-02-07 07:02:22 -08004454
asaperssonfab67072017-04-04 05:51:49 -07004455 video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
kthelgason2bc68642017-02-07 07:02:22 -08004456 // Frame should not be dropped, even if it's too large.
sprang4847ae62017-06-27 07:06:52 -07004457 WaitForEncodedFrame(1);
kthelgason2bc68642017-02-07 07:02:22 -08004458
mflodmancc3d4422017-08-03 08:27:51 -07004459 video_stream_encoder_->Stop();
kthelgason2bc68642017-02-07 07:02:22 -08004460}
4461
mflodmancc3d4422017-08-03 08:27:51 -07004462TEST_F(VideoStreamEncoderTest, InitialFrameDropOffWhenEncoderDisabledScaling) {
asaperssonfab67072017-04-04 05:51:49 -07004463 const int kWidth = 640;
4464 const int kHeight = 360;
kthelgasonad9010c2017-02-14 00:46:51 -08004465 fake_encoder_.SetQualityScaling(false);
Niels Möller4db138e2018-04-19 09:04:13 +02004466
4467 VideoEncoderConfig video_encoder_config;
4468 test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
4469 // Make format different, to force recreation of encoder.
4470 video_encoder_config.video_format.parameters["foo"] = "foo";
4471 video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config),
Niels Möllerf1338562018-04-26 09:51:47 +02004472 kMaxPayloadLength);
Henrik Boström381d1092020-05-12 18:49:07 +02004473 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01004474 DataRate::BitsPerSec(kLowTargetBitrateBps),
4475 DataRate::BitsPerSec(kLowTargetBitrateBps),
4476 DataRate::BitsPerSec(kLowTargetBitrateBps), 0, 0, 0);
asapersson09f05612017-05-15 23:40:18 -07004477
kthelgasonb83797b2017-02-14 11:57:25 -08004478 // Force quality scaler reconfiguration by resetting the source.
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07004479 video_stream_encoder_->SetSource(&video_source_,
4480 webrtc::DegradationPreference::BALANCED);
kthelgasonad9010c2017-02-14 00:46:51 -08004481
asaperssonfab67072017-04-04 05:51:49 -07004482 video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
kthelgasonad9010c2017-02-14 00:46:51 -08004483 // Frame should not be dropped, even if it's too large.
sprang4847ae62017-06-27 07:06:52 -07004484 WaitForEncodedFrame(1);
kthelgasonad9010c2017-02-14 00:46:51 -08004485
mflodmancc3d4422017-08-03 08:27:51 -07004486 video_stream_encoder_->Stop();
kthelgasonad9010c2017-02-14 00:46:51 -08004487 fake_encoder_.SetQualityScaling(true);
4488}
4489
Åsa Persson139f4dc2019-08-02 09:29:58 +02004490TEST_F(VideoStreamEncoderTest, InitialFrameDropActivatesWhenBweDrops) {
4491 webrtc::test::ScopedFieldTrials field_trials(
4492 "WebRTC-Video-QualityScalerSettings/"
4493 "initial_bitrate_interval_ms:1000,initial_bitrate_factor:0.2/");
4494 // Reset encoder for field trials to take effect.
4495 ConfigureEncoder(video_encoder_config_.Copy());
4496 const int kNotTooLowBitrateForFrameSizeBps = kTargetBitrateBps * 0.2;
4497 const int kTooLowBitrateForFrameSizeBps = kTargetBitrateBps * 0.19;
4498 const int kWidth = 640;
4499 const int kHeight = 360;
4500
Henrik Boström381d1092020-05-12 18:49:07 +02004501 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01004502 DataRate::BitsPerSec(kTargetBitrateBps),
4503 DataRate::BitsPerSec(kTargetBitrateBps),
4504 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Åsa Persson139f4dc2019-08-02 09:29:58 +02004505 video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
4506 // Frame should not be dropped.
4507 WaitForEncodedFrame(1);
4508
Henrik Boström381d1092020-05-12 18:49:07 +02004509 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01004510 DataRate::BitsPerSec(kNotTooLowBitrateForFrameSizeBps),
4511 DataRate::BitsPerSec(kNotTooLowBitrateForFrameSizeBps),
4512 DataRate::BitsPerSec(kNotTooLowBitrateForFrameSizeBps), 0, 0, 0);
Åsa Persson139f4dc2019-08-02 09:29:58 +02004513 video_source_.IncomingCapturedFrame(CreateFrame(2, kWidth, kHeight));
4514 // Frame should not be dropped.
4515 WaitForEncodedFrame(2);
4516
Henrik Boström381d1092020-05-12 18:49:07 +02004517 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01004518 DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps),
4519 DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps),
4520 DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps), 0, 0, 0);
Åsa Persson139f4dc2019-08-02 09:29:58 +02004521 video_source_.IncomingCapturedFrame(CreateFrame(3, kWidth, kHeight));
4522 // Expect to drop this frame, the wait should time out.
4523 ExpectDroppedFrame();
4524
4525 // Expect the sink_wants to specify a scaled frame.
Henrik Boström2671dac2020-05-19 16:29:09 +02004526 EXPECT_TRUE_WAIT(
4527 video_source_.sink_wants().max_pixel_count < kWidth * kHeight, 5000);
Åsa Persson139f4dc2019-08-02 09:29:58 +02004528 video_stream_encoder_->Stop();
4529}
4530
Evan Shrubsolee3da1d32020-08-14 15:58:33 +02004531TEST_F(VideoStreamEncoderTest,
4532 InitialFrameDropNotReactivatedWhenBweDropsWhenScalingDisabled) {
4533 webrtc::test::ScopedFieldTrials field_trials(
4534 "WebRTC-Video-QualityScalerSettings/"
4535 "initial_bitrate_interval_ms:1000,initial_bitrate_factor:0.2/");
4536 fake_encoder_.SetQualityScaling(false);
4537 ConfigureEncoder(video_encoder_config_.Copy());
4538 const int kNotTooLowBitrateForFrameSizeBps = kTargetBitrateBps * 0.2;
4539 const int kTooLowBitrateForFrameSizeBps = kTargetBitrateBps * 0.19;
4540 const int kWidth = 640;
4541 const int kHeight = 360;
4542
4543 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
4544 DataRate::BitsPerSec(kTargetBitrateBps),
4545 DataRate::BitsPerSec(kTargetBitrateBps),
4546 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
4547 video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
4548 // Frame should not be dropped.
4549 WaitForEncodedFrame(1);
4550
4551 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
4552 DataRate::BitsPerSec(kNotTooLowBitrateForFrameSizeBps),
4553 DataRate::BitsPerSec(kNotTooLowBitrateForFrameSizeBps),
4554 DataRate::BitsPerSec(kNotTooLowBitrateForFrameSizeBps), 0, 0, 0);
4555 video_source_.IncomingCapturedFrame(CreateFrame(2, kWidth, kHeight));
4556 // Frame should not be dropped.
4557 WaitForEncodedFrame(2);
4558
4559 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
4560 DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps),
4561 DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps),
4562 DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps), 0, 0, 0);
4563 video_source_.IncomingCapturedFrame(CreateFrame(3, kWidth, kHeight));
4564 // Not dropped since quality scaling is disabled.
4565 WaitForEncodedFrame(3);
4566
4567 // Expect the sink_wants to specify a scaled frame.
Evan Shrubsole85728412020-08-25 13:12:12 +02004568 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
Evan Shrubsolee3da1d32020-08-14 15:58:33 +02004569 EXPECT_THAT(video_source_.sink_wants(), ResolutionMax());
4570
4571 video_stream_encoder_->Stop();
4572}
4573
Åsa Perssone644a032019-11-08 15:56:00 +01004574TEST_F(VideoStreamEncoderTest, RampsUpInQualityWhenBwIsHigh) {
4575 webrtc::test::ScopedFieldTrials field_trials(
4576 "WebRTC-Video-QualityRampupSettings/min_pixels:1,min_duration_ms:2000/");
4577
4578 // Reset encoder for field trials to take effect.
4579 VideoEncoderConfig config = video_encoder_config_.Copy();
4580 config.max_bitrate_bps = kTargetBitrateBps;
Evan Shrubsoledff79252020-04-16 11:34:32 +02004581 DataRate max_bitrate = DataRate::BitsPerSec(config.max_bitrate_bps);
Åsa Perssone644a032019-11-08 15:56:00 +01004582 ConfigureEncoder(std::move(config));
4583 fake_encoder_.SetQp(kQpLow);
4584
4585 // Enable MAINTAIN_FRAMERATE preference.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02004586 AdaptingFrameForwarder source(&time_controller_);
Åsa Perssone644a032019-11-08 15:56:00 +01004587 source.set_adaptation_enabled(true);
4588 video_stream_encoder_->SetSource(&source,
4589 DegradationPreference::MAINTAIN_FRAMERATE);
4590
4591 // Start at low bitrate.
4592 const int kLowBitrateBps = 200000;
Henrik Boström381d1092020-05-12 18:49:07 +02004593 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
4594 DataRate::BitsPerSec(kLowBitrateBps),
4595 DataRate::BitsPerSec(kLowBitrateBps),
4596 DataRate::BitsPerSec(kLowBitrateBps), 0, 0, 0);
Åsa Perssone644a032019-11-08 15:56:00 +01004597
4598 // Expect first frame to be dropped and resolution to be limited.
4599 const int kWidth = 1280;
4600 const int kHeight = 720;
4601 const int64_t kFrameIntervalMs = 100;
4602 int64_t timestamp_ms = kFrameIntervalMs;
4603 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
4604 ExpectDroppedFrame();
Henrik Boström2671dac2020-05-19 16:29:09 +02004605 EXPECT_TRUE_WAIT(source.sink_wants().max_pixel_count < kWidth * kHeight,
4606 5000);
Åsa Perssone644a032019-11-08 15:56:00 +01004607
4608 // Increase bitrate to encoder max.
Henrik Boström381d1092020-05-12 18:49:07 +02004609 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
4610 max_bitrate, max_bitrate, max_bitrate, 0, 0, 0);
Åsa Perssone644a032019-11-08 15:56:00 +01004611
4612 // Insert frames and advance |min_duration_ms|.
4613 for (size_t i = 1; i <= 10; i++) {
4614 timestamp_ms += kFrameIntervalMs;
4615 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
4616 WaitForEncodedFrame(timestamp_ms);
4617 }
4618 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
4619 EXPECT_LT(source.sink_wants().max_pixel_count, kWidth * kHeight);
4620
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02004621 AdvanceTime(TimeDelta::Millis(2000));
Åsa Perssone644a032019-11-08 15:56:00 +01004622
4623 // Insert frame should trigger high BW and release quality limitation.
4624 timestamp_ms += kFrameIntervalMs;
4625 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
4626 WaitForEncodedFrame(timestamp_ms);
Henrik Boström381d1092020-05-12 18:49:07 +02004627 // The ramp-up code involves the adaptation queue, give it time to execute.
4628 // TODO(hbos): Can we await an appropriate event instead?
Evan Shrubsole85728412020-08-25 13:12:12 +02004629 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02004630 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
Åsa Perssone644a032019-11-08 15:56:00 +01004631
4632 // Frame should not be adapted.
4633 timestamp_ms += kFrameIntervalMs;
4634 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
4635 WaitForEncodedFrame(kWidth, kHeight);
4636 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
4637
4638 video_stream_encoder_->Stop();
4639}
4640
mflodmancc3d4422017-08-03 08:27:51 -07004641TEST_F(VideoStreamEncoderTest,
Evan Shrubsole99b0f8d2020-08-25 13:12:28 +02004642 QualityScalerAdaptationsRemovedWhenQualityScalingDisabled) {
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02004643 AdaptingFrameForwarder source(&time_controller_);
Evan Shrubsole99b0f8d2020-08-25 13:12:28 +02004644 source.set_adaptation_enabled(true);
4645 video_stream_encoder_->SetSource(&source,
4646 DegradationPreference::MAINTAIN_FRAMERATE);
4647 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
4648 DataRate::BitsPerSec(kTargetBitrateBps),
4649 DataRate::BitsPerSec(kTargetBitrateBps),
4650 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
4651 fake_encoder_.SetQp(kQpHigh + 1);
4652 const int kWidth = 1280;
4653 const int kHeight = 720;
4654 const int64_t kFrameIntervalMs = 100;
4655 int64_t timestamp_ms = kFrameIntervalMs;
4656 for (size_t i = 1; i <= 100; i++) {
4657 timestamp_ms += kFrameIntervalMs;
4658 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
4659 WaitForEncodedFrame(timestamp_ms);
4660 }
4661 // Wait for QualityScaler, which will wait for 2000*2.5 ms until checking QP
4662 // for the first time.
4663 // TODO(eshr): We should avoid these waits by using threads with simulated
4664 // time.
4665 EXPECT_TRUE_WAIT(stats_proxy_->GetStats().bw_limited_resolution,
4666 2000 * 2.5 * 2);
4667 timestamp_ms += kFrameIntervalMs;
4668 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
4669 WaitForEncodedFrame(timestamp_ms);
4670 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
4671 EXPECT_THAT(source.sink_wants(), WantsMaxPixels(Lt(kWidth * kHeight)));
4672 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
4673
4674 // Disable Quality scaling by turning off scaler on the encoder and
4675 // reconfiguring.
4676 fake_encoder_.SetQualityScaling(false);
4677 video_stream_encoder_->ConfigureEncoder(video_encoder_config_.Copy(),
4678 kMaxPayloadLength);
4679 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02004680 AdvanceTime(TimeDelta::Millis(0));
Evan Shrubsole99b0f8d2020-08-25 13:12:28 +02004681 // Since we turned off the quality scaler, the adaptations made by it are
4682 // removed.
4683 EXPECT_THAT(source.sink_wants(), ResolutionMax());
4684 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
4685
4686 video_stream_encoder_->Stop();
4687}
4688
4689TEST_F(VideoStreamEncoderTest,
asaperssond0de2952017-04-21 01:47:31 -07004690 ResolutionNotAdaptedForTooSmallFrame_MaintainFramerateMode) {
4691 const int kTooSmallWidth = 10;
4692 const int kTooSmallHeight = 10;
Henrik Boström381d1092020-05-12 18:49:07 +02004693 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01004694 DataRate::BitsPerSec(kTargetBitrateBps),
4695 DataRate::BitsPerSec(kTargetBitrateBps),
4696 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asaperssond0de2952017-04-21 01:47:31 -07004697
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07004698 // Enable MAINTAIN_FRAMERATE preference, no initial limitation.
asaperssond0de2952017-04-21 01:47:31 -07004699 test::FrameForwarder source;
mflodmancc3d4422017-08-03 08:27:51 -07004700 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07004701 &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02004702 EXPECT_THAT(source.sink_wants(), UnlimitedSinkWants());
asaperssond0de2952017-04-21 01:47:31 -07004703 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
4704
4705 // Trigger adapt down, too small frame, expect no change.
4706 source.IncomingCapturedFrame(CreateFrame(1, kTooSmallWidth, kTooSmallHeight));
sprang4847ae62017-06-27 07:06:52 -07004707 WaitForEncodedFrame(1);
mflodmancc3d4422017-08-03 08:27:51 -07004708 video_stream_encoder_->TriggerCpuOveruse();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02004709 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssond0de2952017-04-21 01:47:31 -07004710 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
4711 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
4712
mflodmancc3d4422017-08-03 08:27:51 -07004713 video_stream_encoder_->Stop();
asaperssond0de2952017-04-21 01:47:31 -07004714}
4715
mflodmancc3d4422017-08-03 08:27:51 -07004716TEST_F(VideoStreamEncoderTest,
4717 ResolutionNotAdaptedForTooSmallFrame_BalancedMode) {
asaperssonf7e294d2017-06-13 23:25:22 -07004718 const int kTooSmallWidth = 10;
4719 const int kTooSmallHeight = 10;
4720 const int kFpsLimit = 7;
Henrik Boström381d1092020-05-12 18:49:07 +02004721 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01004722 DataRate::BitsPerSec(kTargetBitrateBps),
4723 DataRate::BitsPerSec(kTargetBitrateBps),
4724 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asaperssonf7e294d2017-06-13 23:25:22 -07004725
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07004726 // Enable BALANCED preference, no initial limitation.
asaperssonf7e294d2017-06-13 23:25:22 -07004727 test::FrameForwarder source;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07004728 video_stream_encoder_->SetSource(&source,
4729 webrtc::DegradationPreference::BALANCED);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02004730 EXPECT_THAT(source.sink_wants(), UnlimitedSinkWants());
asaperssonf7e294d2017-06-13 23:25:22 -07004731 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
4732 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
4733
4734 // Trigger adapt down, expect limited framerate.
4735 source.IncomingCapturedFrame(CreateFrame(1, kTooSmallWidth, kTooSmallHeight));
sprang4847ae62017-06-27 07:06:52 -07004736 WaitForEncodedFrame(1);
mflodmancc3d4422017-08-03 08:27:51 -07004737 video_stream_encoder_->TriggerQualityLow();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02004738 EXPECT_THAT(source.sink_wants(), FpsMatchesResolutionMax(Eq(kFpsLimit)));
asaperssonf7e294d2017-06-13 23:25:22 -07004739 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
4740 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
4741 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
4742
4743 // Trigger adapt down, too small frame, expect no change.
4744 source.IncomingCapturedFrame(CreateFrame(2, kTooSmallWidth, kTooSmallHeight));
sprang4847ae62017-06-27 07:06:52 -07004745 WaitForEncodedFrame(2);
mflodmancc3d4422017-08-03 08:27:51 -07004746 video_stream_encoder_->TriggerQualityLow();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02004747 EXPECT_THAT(source.sink_wants(), FpsMatchesResolutionMax(Eq(kFpsLimit)));
asaperssonf7e294d2017-06-13 23:25:22 -07004748 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
4749 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
4750 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
4751
mflodmancc3d4422017-08-03 08:27:51 -07004752 video_stream_encoder_->Stop();
asaperssonf7e294d2017-06-13 23:25:22 -07004753}
4754
mflodmancc3d4422017-08-03 08:27:51 -07004755TEST_F(VideoStreamEncoderTest, FailingInitEncodeDoesntCauseCrash) {
asapersson02465b82017-04-10 01:12:52 -07004756 fake_encoder_.ForceInitEncodeFailure(true);
Henrik Boström381d1092020-05-12 18:49:07 +02004757 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01004758 DataRate::BitsPerSec(kTargetBitrateBps),
4759 DataRate::BitsPerSec(kTargetBitrateBps),
4760 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Niels Möllerf1338562018-04-26 09:51:47 +02004761 ResetEncoder("VP8", 2, 1, 1, false);
asapersson02465b82017-04-10 01:12:52 -07004762 const int kFrameWidth = 1280;
4763 const int kFrameHeight = 720;
4764 video_source_.IncomingCapturedFrame(
4765 CreateFrame(1, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 07:06:52 -07004766 ExpectDroppedFrame();
mflodmancc3d4422017-08-03 08:27:51 -07004767 video_stream_encoder_->Stop();
asapersson02465b82017-04-10 01:12:52 -07004768}
4769
sprangb1ca0732017-02-01 08:38:12 -08004770// TODO(sprang): Extend this with fps throttling and any "balanced" extensions.
mflodmancc3d4422017-08-03 08:27:51 -07004771TEST_F(VideoStreamEncoderTest,
4772 AdaptsResolutionOnOveruse_MaintainFramerateMode) {
Henrik Boström381d1092020-05-12 18:49:07 +02004773 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01004774 DataRate::BitsPerSec(kTargetBitrateBps),
4775 DataRate::BitsPerSec(kTargetBitrateBps),
4776 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
sprangb1ca0732017-02-01 08:38:12 -08004777
4778 const int kFrameWidth = 1280;
4779 const int kFrameHeight = 720;
4780 // Enabled default VideoAdapter downscaling. First step is 3/4, not 3/5 as
mflodmancc3d4422017-08-03 08:27:51 -07004781 // requested by
4782 // VideoStreamEncoder::VideoSourceProxy::RequestResolutionLowerThan().
sprangb1ca0732017-02-01 08:38:12 -08004783 video_source_.set_adaptation_enabled(true);
4784
4785 video_source_.IncomingCapturedFrame(
Åsa Persson8c1bf952018-09-13 10:42:19 +02004786 CreateFrame(1 * kFrameIntervalMs, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 07:06:52 -07004787 WaitForEncodedFrame(kFrameWidth, kFrameHeight);
sprangb1ca0732017-02-01 08:38:12 -08004788
4789 // Trigger CPU overuse, downscale by 3/4.
mflodmancc3d4422017-08-03 08:27:51 -07004790 video_stream_encoder_->TriggerCpuOveruse();
sprangb1ca0732017-02-01 08:38:12 -08004791 video_source_.IncomingCapturedFrame(
Åsa Persson8c1bf952018-09-13 10:42:19 +02004792 CreateFrame(2 * kFrameIntervalMs, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 07:06:52 -07004793 WaitForEncodedFrame((kFrameWidth * 3) / 4, (kFrameHeight * 3) / 4);
sprangb1ca0732017-02-01 08:38:12 -08004794
asaperssonfab67072017-04-04 05:51:49 -07004795 // Trigger CPU normal use, return to original resolution.
Henrik Boström91aa7322020-04-28 12:24:33 +02004796 video_stream_encoder_->TriggerCpuUnderuse();
sprangb1ca0732017-02-01 08:38:12 -08004797 video_source_.IncomingCapturedFrame(
Åsa Persson8c1bf952018-09-13 10:42:19 +02004798 CreateFrame(3 * kFrameIntervalMs, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 07:06:52 -07004799 WaitForEncodedFrame(kFrameWidth, kFrameHeight);
sprangb1ca0732017-02-01 08:38:12 -08004800
mflodmancc3d4422017-08-03 08:27:51 -07004801 video_stream_encoder_->Stop();
sprangb1ca0732017-02-01 08:38:12 -08004802}
sprangfe627f32017-03-29 08:24:59 -07004803
mflodmancc3d4422017-08-03 08:27:51 -07004804TEST_F(VideoStreamEncoderTest,
4805 AdaptsFramerateOnOveruse_MaintainResolutionMode) {
sprangc5d62e22017-04-02 23:53:04 -07004806 const int kFrameWidth = 1280;
4807 const int kFrameHeight = 720;
sprangc5d62e22017-04-02 23:53:04 -07004808
Henrik Boström381d1092020-05-12 18:49:07 +02004809 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01004810 DataRate::BitsPerSec(kTargetBitrateBps),
4811 DataRate::BitsPerSec(kTargetBitrateBps),
4812 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
mflodmancc3d4422017-08-03 08:27:51 -07004813 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07004814 &video_source_, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
sprangc5d62e22017-04-02 23:53:04 -07004815 video_source_.set_adaptation_enabled(true);
4816
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02004817 int64_t timestamp_ms = CurrentTimeMs();
sprangc5d62e22017-04-02 23:53:04 -07004818
4819 video_source_.IncomingCapturedFrame(
4820 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 07:06:52 -07004821 WaitForEncodedFrame(timestamp_ms);
sprangc5d62e22017-04-02 23:53:04 -07004822
4823 // Try to trigger overuse. No fps estimate available => no effect.
mflodmancc3d4422017-08-03 08:27:51 -07004824 video_stream_encoder_->TriggerCpuOveruse();
sprangc5d62e22017-04-02 23:53:04 -07004825
4826 // Insert frames for one second to get a stable estimate.
sprang4847ae62017-06-27 07:06:52 -07004827 for (int i = 0; i < max_framerate_; ++i) {
sprangc5d62e22017-04-02 23:53:04 -07004828 timestamp_ms += kFrameIntervalMs;
sprangc5d62e22017-04-02 23:53:04 -07004829 video_source_.IncomingCapturedFrame(
4830 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 07:06:52 -07004831 WaitForEncodedFrame(timestamp_ms);
sprangc5d62e22017-04-02 23:53:04 -07004832 }
4833
4834 // Trigger CPU overuse, reduce framerate by 2/3.
mflodmancc3d4422017-08-03 08:27:51 -07004835 video_stream_encoder_->TriggerCpuOveruse();
sprangc5d62e22017-04-02 23:53:04 -07004836 int num_frames_dropped = 0;
sprang4847ae62017-06-27 07:06:52 -07004837 for (int i = 0; i < max_framerate_; ++i) {
sprangc5d62e22017-04-02 23:53:04 -07004838 timestamp_ms += kFrameIntervalMs;
sprangc5d62e22017-04-02 23:53:04 -07004839 video_source_.IncomingCapturedFrame(
4840 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 07:06:52 -07004841 if (!WaitForFrame(kFrameTimeoutMs)) {
sprangc5d62e22017-04-02 23:53:04 -07004842 ++num_frames_dropped;
4843 } else {
Åsa Perssonc74d8da2017-12-04 14:13:56 +01004844 sink_.CheckLastFrameSizeMatches(kFrameWidth, kFrameHeight);
sprangc5d62e22017-04-02 23:53:04 -07004845 }
4846 }
4847
sprang4847ae62017-06-27 07:06:52 -07004848 // Add some slack to account for frames dropped by the frame dropper.
4849 const int kErrorMargin = 1;
4850 EXPECT_NEAR(num_frames_dropped, max_framerate_ - (max_framerate_ * 2 / 3),
sprangc5d62e22017-04-02 23:53:04 -07004851 kErrorMargin);
4852
4853 // Trigger CPU overuse, reduce framerate by 2/3 again.
mflodmancc3d4422017-08-03 08:27:51 -07004854 video_stream_encoder_->TriggerCpuOveruse();
sprangc5d62e22017-04-02 23:53:04 -07004855 num_frames_dropped = 0;
Åsa Persson8c1bf952018-09-13 10:42:19 +02004856 for (int i = 0; i <= max_framerate_; ++i) {
sprangc5d62e22017-04-02 23:53:04 -07004857 timestamp_ms += kFrameIntervalMs;
sprangc5d62e22017-04-02 23:53:04 -07004858 video_source_.IncomingCapturedFrame(
4859 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 07:06:52 -07004860 if (!WaitForFrame(kFrameTimeoutMs)) {
sprangc5d62e22017-04-02 23:53:04 -07004861 ++num_frames_dropped;
4862 } else {
Åsa Perssonc74d8da2017-12-04 14:13:56 +01004863 sink_.CheckLastFrameSizeMatches(kFrameWidth, kFrameHeight);
sprangc5d62e22017-04-02 23:53:04 -07004864 }
4865 }
sprang4847ae62017-06-27 07:06:52 -07004866 EXPECT_NEAR(num_frames_dropped, max_framerate_ - (max_framerate_ * 4 / 9),
sprangc5d62e22017-04-02 23:53:04 -07004867 kErrorMargin);
4868
4869 // Go back up one step.
Henrik Boström91aa7322020-04-28 12:24:33 +02004870 video_stream_encoder_->TriggerCpuUnderuse();
sprangc5d62e22017-04-02 23:53:04 -07004871 num_frames_dropped = 0;
sprang4847ae62017-06-27 07:06:52 -07004872 for (int i = 0; i < max_framerate_; ++i) {
sprangc5d62e22017-04-02 23:53:04 -07004873 timestamp_ms += kFrameIntervalMs;
sprangc5d62e22017-04-02 23:53:04 -07004874 video_source_.IncomingCapturedFrame(
4875 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 07:06:52 -07004876 if (!WaitForFrame(kFrameTimeoutMs)) {
sprangc5d62e22017-04-02 23:53:04 -07004877 ++num_frames_dropped;
4878 } else {
Åsa Perssonc74d8da2017-12-04 14:13:56 +01004879 sink_.CheckLastFrameSizeMatches(kFrameWidth, kFrameHeight);
sprangc5d62e22017-04-02 23:53:04 -07004880 }
4881 }
sprang4847ae62017-06-27 07:06:52 -07004882 EXPECT_NEAR(num_frames_dropped, max_framerate_ - (max_framerate_ * 2 / 3),
sprangc5d62e22017-04-02 23:53:04 -07004883 kErrorMargin);
4884
4885 // Go back up to original mode.
Henrik Boström91aa7322020-04-28 12:24:33 +02004886 video_stream_encoder_->TriggerCpuUnderuse();
sprangc5d62e22017-04-02 23:53:04 -07004887 num_frames_dropped = 0;
sprang4847ae62017-06-27 07:06:52 -07004888 for (int i = 0; i < max_framerate_; ++i) {
sprangc5d62e22017-04-02 23:53:04 -07004889 timestamp_ms += kFrameIntervalMs;
sprangc5d62e22017-04-02 23:53:04 -07004890 video_source_.IncomingCapturedFrame(
4891 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 07:06:52 -07004892 if (!WaitForFrame(kFrameTimeoutMs)) {
sprangc5d62e22017-04-02 23:53:04 -07004893 ++num_frames_dropped;
4894 } else {
Åsa Perssonc74d8da2017-12-04 14:13:56 +01004895 sink_.CheckLastFrameSizeMatches(kFrameWidth, kFrameHeight);
sprangc5d62e22017-04-02 23:53:04 -07004896 }
4897 }
4898 EXPECT_NEAR(num_frames_dropped, 0, kErrorMargin);
4899
mflodmancc3d4422017-08-03 08:27:51 -07004900 video_stream_encoder_->Stop();
sprangc5d62e22017-04-02 23:53:04 -07004901}
4902
mflodmancc3d4422017-08-03 08:27:51 -07004903TEST_F(VideoStreamEncoderTest, DoesntAdaptDownPastMinFramerate) {
sprangc5d62e22017-04-02 23:53:04 -07004904 const int kFramerateFps = 5;
4905 const int kFrameIntervalMs = rtc::kNumMillisecsPerSec / kFramerateFps;
sprangc5d62e22017-04-02 23:53:04 -07004906 const int kFrameWidth = 1280;
4907 const int kFrameHeight = 720;
4908
sprang4847ae62017-06-27 07:06:52 -07004909 // Reconfigure encoder with two temporal layers and screensharing, which will
4910 // disable frame dropping and make testing easier.
Niels Möllerf1338562018-04-26 09:51:47 +02004911 ResetEncoder("VP8", 1, 2, 1, true);
sprang4847ae62017-06-27 07:06:52 -07004912
Henrik Boström381d1092020-05-12 18:49:07 +02004913 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01004914 DataRate::BitsPerSec(kTargetBitrateBps),
4915 DataRate::BitsPerSec(kTargetBitrateBps),
4916 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
mflodmancc3d4422017-08-03 08:27:51 -07004917 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07004918 &video_source_, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
sprangc5d62e22017-04-02 23:53:04 -07004919 video_source_.set_adaptation_enabled(true);
4920
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02004921 int64_t timestamp_ms = CurrentTimeMs();
sprangc5d62e22017-04-02 23:53:04 -07004922
4923 // Trigger overuse as much as we can.
Jonathan Yubc771b72017-12-08 17:04:29 -08004924 rtc::VideoSinkWants last_wants;
4925 do {
4926 last_wants = video_source_.sink_wants();
4927
sprangc5d62e22017-04-02 23:53:04 -07004928 // Insert frames to get a new fps estimate...
4929 for (int j = 0; j < kFramerateFps; ++j) {
4930 video_source_.IncomingCapturedFrame(
4931 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
Jonathan Yubc771b72017-12-08 17:04:29 -08004932 if (video_source_.last_sent_width()) {
4933 sink_.WaitForEncodedFrame(timestamp_ms);
4934 }
sprangc5d62e22017-04-02 23:53:04 -07004935 timestamp_ms += kFrameIntervalMs;
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02004936 AdvanceTime(TimeDelta::Millis(kFrameIntervalMs));
sprangc5d62e22017-04-02 23:53:04 -07004937 }
4938 // ...and then try to adapt again.
mflodmancc3d4422017-08-03 08:27:51 -07004939 video_stream_encoder_->TriggerCpuOveruse();
Jonathan Yubc771b72017-12-08 17:04:29 -08004940 } while (video_source_.sink_wants().max_framerate_fps <
4941 last_wants.max_framerate_fps);
sprangc5d62e22017-04-02 23:53:04 -07004942
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02004943 EXPECT_THAT(video_source_.sink_wants(),
4944 FpsMatchesResolutionMax(Eq(kMinFramerateFps)));
asaperssonf7e294d2017-06-13 23:25:22 -07004945
mflodmancc3d4422017-08-03 08:27:51 -07004946 video_stream_encoder_->Stop();
sprangc5d62e22017-04-02 23:53:04 -07004947}
asaperssonf7e294d2017-06-13 23:25:22 -07004948
mflodmancc3d4422017-08-03 08:27:51 -07004949TEST_F(VideoStreamEncoderTest,
4950 AdaptsResolutionAndFramerateForLowQuality_BalancedMode) {
asaperssonf7e294d2017-06-13 23:25:22 -07004951 const int kWidth = 1280;
4952 const int kHeight = 720;
4953 const int64_t kFrameIntervalMs = 150;
4954 int64_t timestamp_ms = kFrameIntervalMs;
Henrik Boström381d1092020-05-12 18:49:07 +02004955 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01004956 DataRate::BitsPerSec(kTargetBitrateBps),
4957 DataRate::BitsPerSec(kTargetBitrateBps),
4958 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asaperssonf7e294d2017-06-13 23:25:22 -07004959
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07004960 // Enable BALANCED preference, no initial limitation.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02004961 AdaptingFrameForwarder source(&time_controller_);
asaperssonf7e294d2017-06-13 23:25:22 -07004962 source.set_adaptation_enabled(true);
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07004963 video_stream_encoder_->SetSource(&source,
4964 webrtc::DegradationPreference::BALANCED);
asaperssonf7e294d2017-06-13 23:25:22 -07004965 timestamp_ms += kFrameIntervalMs;
4966 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07004967 WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02004968 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-13 23:25:22 -07004969 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
4970 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
4971 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
4972
4973 // Trigger adapt down, expect scaled down resolution (960x540@30fps).
mflodmancc3d4422017-08-03 08:27:51 -07004974 video_stream_encoder_->TriggerQualityLow();
asaperssonf7e294d2017-06-13 23:25:22 -07004975 timestamp_ms += kFrameIntervalMs;
4976 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07004977 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02004978 EXPECT_THAT(source.sink_wants(),
4979 FpsMaxResolutionMatches(Lt(kWidth * kHeight)));
asaperssonf7e294d2017-06-13 23:25:22 -07004980 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
4981 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
4982 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
4983
4984 // Trigger adapt down, expect scaled down resolution (640x360@30fps).
mflodmancc3d4422017-08-03 08:27:51 -07004985 video_stream_encoder_->TriggerQualityLow();
asaperssonf7e294d2017-06-13 23:25:22 -07004986 timestamp_ms += kFrameIntervalMs;
4987 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07004988 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02004989 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionLt(source.last_wants()));
asaperssonf7e294d2017-06-13 23:25:22 -07004990 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
4991 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
4992 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_quality_adapt_changes);
4993
4994 // Trigger adapt down, expect reduced fps (640x360@15fps).
mflodmancc3d4422017-08-03 08:27:51 -07004995 video_stream_encoder_->TriggerQualityLow();
asaperssonf7e294d2017-06-13 23:25:22 -07004996 timestamp_ms += kFrameIntervalMs;
4997 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07004998 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02004999 EXPECT_THAT(source.sink_wants(), FpsLtResolutionEq(source.last_wants()));
asaperssonf7e294d2017-06-13 23:25:22 -07005000 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5001 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
5002 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5003
5004 // Trigger adapt down, expect scaled down resolution (480x270@15fps).
mflodmancc3d4422017-08-03 08:27:51 -07005005 video_stream_encoder_->TriggerQualityLow();
asaperssonf7e294d2017-06-13 23:25:22 -07005006 timestamp_ms += kFrameIntervalMs;
5007 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005008 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02005009 EXPECT_THAT(source.sink_wants(), FpsEqResolutionLt(source.last_wants()));
asaperssonf7e294d2017-06-13 23:25:22 -07005010 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5011 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
5012 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5013
5014 // Restrict bitrate, trigger adapt down, expect reduced fps (480x270@10fps).
mflodmancc3d4422017-08-03 08:27:51 -07005015 video_stream_encoder_->TriggerQualityLow();
asaperssonf7e294d2017-06-13 23:25:22 -07005016 timestamp_ms += kFrameIntervalMs;
5017 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005018 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02005019 EXPECT_THAT(source.sink_wants(), FpsLtResolutionEq(source.last_wants()));
asaperssonf7e294d2017-06-13 23:25:22 -07005020 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5021 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
5022 EXPECT_EQ(5, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5023
5024 // Trigger adapt down, expect scaled down resolution (320x180@10fps).
mflodmancc3d4422017-08-03 08:27:51 -07005025 video_stream_encoder_->TriggerQualityLow();
asaperssonf7e294d2017-06-13 23:25:22 -07005026 timestamp_ms += kFrameIntervalMs;
5027 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005028 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02005029 EXPECT_THAT(source.sink_wants(), FpsEqResolutionLt(source.last_wants()));
asaperssonf7e294d2017-06-13 23:25:22 -07005030 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5031 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
5032 EXPECT_EQ(6, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5033
5034 // Trigger adapt down, expect reduced fps (320x180@7fps).
mflodmancc3d4422017-08-03 08:27:51 -07005035 video_stream_encoder_->TriggerQualityLow();
asaperssonf7e294d2017-06-13 23:25:22 -07005036 timestamp_ms += kFrameIntervalMs;
5037 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005038 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02005039 EXPECT_THAT(source.sink_wants(), FpsLtResolutionEq(source.last_wants()));
asaperssonf7e294d2017-06-13 23:25:22 -07005040 rtc::VideoSinkWants last_wants = source.sink_wants();
5041 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5042 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
5043 EXPECT_EQ(7, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5044
5045 // Trigger adapt down, min resolution reached, expect no change.
mflodmancc3d4422017-08-03 08:27:51 -07005046 video_stream_encoder_->TriggerQualityLow();
asaperssonf7e294d2017-06-13 23:25:22 -07005047 timestamp_ms += kFrameIntervalMs;
5048 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005049 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02005050 EXPECT_THAT(source.sink_wants(), FpsEqResolutionEqTo(last_wants));
asaperssonf7e294d2017-06-13 23:25:22 -07005051 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5052 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
5053 EXPECT_EQ(7, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5054
Evan Shrubsole64469032020-06-11 10:45:29 +02005055 // Trigger adapt up, expect expect increased fps (320x180@10fps).
mflodmancc3d4422017-08-03 08:27:51 -07005056 video_stream_encoder_->TriggerQualityHigh();
asaperssonf7e294d2017-06-13 23:25:22 -07005057 timestamp_ms += kFrameIntervalMs;
5058 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005059 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02005060 EXPECT_THAT(source.sink_wants(), FpsGtResolutionEq(source.last_wants()));
asaperssonf7e294d2017-06-13 23:25:22 -07005061 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5062 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
5063 EXPECT_EQ(8, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5064
5065 // Trigger adapt up, expect upscaled resolution (480x270@10fps).
mflodmancc3d4422017-08-03 08:27:51 -07005066 video_stream_encoder_->TriggerQualityHigh();
asaperssonf7e294d2017-06-13 23:25:22 -07005067 timestamp_ms += kFrameIntervalMs;
5068 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005069 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02005070 EXPECT_THAT(source.sink_wants(), FpsEqResolutionGt(source.last_wants()));
asaperssonf7e294d2017-06-13 23:25:22 -07005071 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5072 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
5073 EXPECT_EQ(9, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5074
5075 // Increase bitrate, trigger adapt up, expect increased fps (480x270@15fps).
mflodmancc3d4422017-08-03 08:27:51 -07005076 video_stream_encoder_->TriggerQualityHigh();
asaperssonf7e294d2017-06-13 23:25:22 -07005077 timestamp_ms += kFrameIntervalMs;
5078 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005079 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02005080 EXPECT_THAT(source.sink_wants(), FpsGtResolutionEq(source.last_wants()));
asaperssonf7e294d2017-06-13 23:25:22 -07005081 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5082 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
5083 EXPECT_EQ(10, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5084
5085 // Trigger adapt up, expect upscaled resolution (640x360@15fps).
mflodmancc3d4422017-08-03 08:27:51 -07005086 video_stream_encoder_->TriggerQualityHigh();
asaperssonf7e294d2017-06-13 23:25:22 -07005087 timestamp_ms += kFrameIntervalMs;
5088 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005089 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02005090 EXPECT_THAT(source.sink_wants(), FpsEqResolutionGt(source.last_wants()));
asaperssonf7e294d2017-06-13 23:25:22 -07005091 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5092 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
5093 EXPECT_EQ(11, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5094
5095 // Trigger adapt up, expect increased fps (640x360@30fps).
mflodmancc3d4422017-08-03 08:27:51 -07005096 video_stream_encoder_->TriggerQualityHigh();
asaperssonf7e294d2017-06-13 23:25:22 -07005097 timestamp_ms += kFrameIntervalMs;
5098 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005099 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02005100 EXPECT_THAT(source.sink_wants(), FpsMax());
5101 EXPECT_EQ(source.sink_wants().max_pixel_count,
5102 source.last_wants().max_pixel_count);
asaperssonf7e294d2017-06-13 23:25:22 -07005103 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5104 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
5105 EXPECT_EQ(12, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5106
5107 // Trigger adapt up, expect upscaled resolution (960x540@30fps).
mflodmancc3d4422017-08-03 08:27:51 -07005108 video_stream_encoder_->TriggerQualityHigh();
asaperssonf7e294d2017-06-13 23:25:22 -07005109 timestamp_ms += kFrameIntervalMs;
5110 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005111 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02005112 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionGt(source.last_wants()));
asaperssonf7e294d2017-06-13 23:25:22 -07005113 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5114 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
5115 EXPECT_EQ(13, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5116
Åsa Persson30ab0152019-08-27 12:22:33 +02005117 // Trigger adapt up, expect no restriction (1280x720fps@30fps).
mflodmancc3d4422017-08-03 08:27:51 -07005118 video_stream_encoder_->TriggerQualityHigh();
asaperssonf7e294d2017-06-13 23:25:22 -07005119 timestamp_ms += kFrameIntervalMs;
5120 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005121 WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02005122 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionGt(source.last_wants()));
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02005123 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-13 23:25:22 -07005124 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
5125 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
5126 EXPECT_EQ(14, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5127
5128 // Trigger adapt up, expect no change.
mflodmancc3d4422017-08-03 08:27:51 -07005129 video_stream_encoder_->TriggerQualityHigh();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02005130 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-13 23:25:22 -07005131 EXPECT_EQ(14, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5132
mflodmancc3d4422017-08-03 08:27:51 -07005133 video_stream_encoder_->Stop();
asaperssonf7e294d2017-06-13 23:25:22 -07005134}
5135
mflodmancc3d4422017-08-03 08:27:51 -07005136TEST_F(VideoStreamEncoderTest, AdaptWithTwoReasonsAndDifferentOrder_Framerate) {
asaperssonf7e294d2017-06-13 23:25:22 -07005137 const int kWidth = 1280;
5138 const int kHeight = 720;
5139 const int64_t kFrameIntervalMs = 150;
5140 int64_t timestamp_ms = kFrameIntervalMs;
Henrik Boström381d1092020-05-12 18:49:07 +02005141 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005142 DataRate::BitsPerSec(kTargetBitrateBps),
5143 DataRate::BitsPerSec(kTargetBitrateBps),
5144 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asaperssonf7e294d2017-06-13 23:25:22 -07005145
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07005146 // Enable BALANCED preference, no initial limitation.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02005147 AdaptingFrameForwarder source(&time_controller_);
asaperssonf7e294d2017-06-13 23:25:22 -07005148 source.set_adaptation_enabled(true);
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07005149 video_stream_encoder_->SetSource(&source,
5150 webrtc::DegradationPreference::BALANCED);
asaperssonf7e294d2017-06-13 23:25:22 -07005151 timestamp_ms += kFrameIntervalMs;
5152 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005153 WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02005154 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-13 23:25:22 -07005155 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
5156 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
5157 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
5158 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
5159 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
5160 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5161
5162 // Trigger cpu adapt down, expect scaled down resolution (960x540@30fps).
mflodmancc3d4422017-08-03 08:27:51 -07005163 video_stream_encoder_->TriggerCpuOveruse();
asaperssonf7e294d2017-06-13 23:25:22 -07005164 timestamp_ms += kFrameIntervalMs;
5165 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005166 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02005167 EXPECT_THAT(source.sink_wants(),
5168 FpsMaxResolutionMatches(Lt(kWidth * kHeight)));
asaperssonf7e294d2017-06-13 23:25:22 -07005169 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
5170 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
5171 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
5172 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
5173 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
5174 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5175
5176 // Trigger cpu adapt down, expect scaled down resolution (640x360@30fps).
mflodmancc3d4422017-08-03 08:27:51 -07005177 video_stream_encoder_->TriggerCpuOveruse();
asaperssonf7e294d2017-06-13 23:25:22 -07005178 timestamp_ms += kFrameIntervalMs;
5179 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005180 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02005181 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionLt(source.last_wants()));
asaperssonf7e294d2017-06-13 23:25:22 -07005182 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
5183 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
5184 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
5185 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
5186 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
5187 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5188
5189 // Trigger quality adapt down, expect reduced fps (640x360@15fps).
mflodmancc3d4422017-08-03 08:27:51 -07005190 video_stream_encoder_->TriggerQualityLow();
asaperssonf7e294d2017-06-13 23:25:22 -07005191 timestamp_ms += kFrameIntervalMs;
5192 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005193 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02005194 EXPECT_THAT(source.sink_wants(), FpsLtResolutionEq(source.last_wants()));
Evan Shrubsole64469032020-06-11 10:45:29 +02005195 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
asaperssonf7e294d2017-06-13 23:25:22 -07005196 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
5197 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
5198 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
5199 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
5200 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5201
Evan Shrubsole64469032020-06-11 10:45:29 +02005202 // Trigger cpu adapt up, expect no change since QP is most limited.
5203 {
5204 // Store current sink wants since we expect no change and if there is no
5205 // change then last_wants() is not updated.
5206 auto previous_sink_wants = source.sink_wants();
5207 video_stream_encoder_->TriggerCpuUnderuse();
5208 timestamp_ms += kFrameIntervalMs;
5209 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
5210 WaitForEncodedFrame(timestamp_ms);
5211 EXPECT_THAT(source.sink_wants(), FpsEqResolutionEqTo(previous_sink_wants));
5212 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
5213 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5214 }
5215
5216 // Trigger quality adapt up, expect increased fps (640x360@30fps).
5217 video_stream_encoder_->TriggerQualityHigh();
5218 timestamp_ms += kFrameIntervalMs;
5219 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
5220 WaitForEncodedFrame(timestamp_ms);
5221 EXPECT_THAT(source.sink_wants(), FpsGtResolutionEq(source.last_wants()));
5222 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5223 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
5224 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
5225 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
5226 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
5227 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5228
5229 // Trigger quality adapt up and Cpu adapt up since both are most limited,
5230 // expect increased resolution (960x540@30fps).
5231 video_stream_encoder_->TriggerQualityHigh();
Henrik Boström91aa7322020-04-28 12:24:33 +02005232 video_stream_encoder_->TriggerCpuUnderuse();
asaperssonf7e294d2017-06-13 23:25:22 -07005233 timestamp_ms += kFrameIntervalMs;
5234 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005235 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole64469032020-06-11 10:45:29 +02005236 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionGt(source.last_wants()));
asaperssonf7e294d2017-06-13 23:25:22 -07005237 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5238 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
5239 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
5240 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
5241 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
Evan Shrubsole64469032020-06-11 10:45:29 +02005242 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_quality_adapt_changes);
asaperssonf7e294d2017-06-13 23:25:22 -07005243
Evan Shrubsole64469032020-06-11 10:45:29 +02005244 // Trigger quality adapt up and Cpu adapt up since both are most limited,
5245 // expect no restriction (1280x720fps@30fps).
mflodmancc3d4422017-08-03 08:27:51 -07005246 video_stream_encoder_->TriggerQualityHigh();
Henrik Boström91aa7322020-04-28 12:24:33 +02005247 video_stream_encoder_->TriggerCpuUnderuse();
asaperssonf7e294d2017-06-13 23:25:22 -07005248 timestamp_ms += kFrameIntervalMs;
5249 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005250 WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02005251 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionGt(source.last_wants()));
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02005252 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-13 23:25:22 -07005253 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
5254 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
5255 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
5256 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
5257 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
Evan Shrubsole64469032020-06-11 10:45:29 +02005258 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_quality_adapt_changes);
asaperssonf7e294d2017-06-13 23:25:22 -07005259
5260 // Trigger adapt up, expect no change.
mflodmancc3d4422017-08-03 08:27:51 -07005261 video_stream_encoder_->TriggerQualityHigh();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02005262 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-13 23:25:22 -07005263 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
Evan Shrubsole64469032020-06-11 10:45:29 +02005264 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_quality_adapt_changes);
asaperssonf7e294d2017-06-13 23:25:22 -07005265
mflodmancc3d4422017-08-03 08:27:51 -07005266 video_stream_encoder_->Stop();
asaperssonf7e294d2017-06-13 23:25:22 -07005267}
5268
mflodmancc3d4422017-08-03 08:27:51 -07005269TEST_F(VideoStreamEncoderTest,
5270 AdaptWithTwoReasonsAndDifferentOrder_Resolution) {
asaperssonf7e294d2017-06-13 23:25:22 -07005271 const int kWidth = 640;
5272 const int kHeight = 360;
5273 const int kFpsLimit = 15;
5274 const int64_t kFrameIntervalMs = 150;
5275 int64_t timestamp_ms = kFrameIntervalMs;
Henrik Boström381d1092020-05-12 18:49:07 +02005276 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005277 DataRate::BitsPerSec(kTargetBitrateBps),
5278 DataRate::BitsPerSec(kTargetBitrateBps),
5279 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asaperssonf7e294d2017-06-13 23:25:22 -07005280
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07005281 // Enable BALANCED preference, no initial limitation.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02005282 AdaptingFrameForwarder source(&time_controller_);
asaperssonf7e294d2017-06-13 23:25:22 -07005283 source.set_adaptation_enabled(true);
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07005284 video_stream_encoder_->SetSource(&source,
5285 webrtc::DegradationPreference::BALANCED);
asaperssonf7e294d2017-06-13 23:25:22 -07005286 timestamp_ms += kFrameIntervalMs;
5287 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005288 WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02005289 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-13 23:25:22 -07005290 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
5291 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
5292 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
5293 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
5294 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
5295 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5296
5297 // Trigger cpu adapt down, expect scaled down framerate (640x360@15fps).
mflodmancc3d4422017-08-03 08:27:51 -07005298 video_stream_encoder_->TriggerCpuOveruse();
asaperssonf7e294d2017-06-13 23:25:22 -07005299 timestamp_ms += kFrameIntervalMs;
5300 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005301 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02005302 EXPECT_THAT(source.sink_wants(), FpsMatchesResolutionMax(Eq(kFpsLimit)));
asaperssonf7e294d2017-06-13 23:25:22 -07005303 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
5304 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
5305 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
5306 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_framerate);
5307 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
5308 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5309
5310 // Trigger quality adapt down, expect scaled down resolution (480x270@15fps).
mflodmancc3d4422017-08-03 08:27:51 -07005311 video_stream_encoder_->TriggerQualityLow();
asaperssonf7e294d2017-06-13 23:25:22 -07005312 timestamp_ms += kFrameIntervalMs;
5313 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005314 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02005315 EXPECT_THAT(source.sink_wants(), FpsEqResolutionLt(source.last_wants()));
asaperssonf7e294d2017-06-13 23:25:22 -07005316 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
Evan Shrubsole64469032020-06-11 10:45:29 +02005317 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
asaperssonf7e294d2017-06-13 23:25:22 -07005318 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
5319 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_framerate);
5320 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
5321 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5322
Evan Shrubsole64469032020-06-11 10:45:29 +02005323 // Trigger cpu adapt up, expect no change because quality is most limited.
5324 {
5325 auto previous_sink_wants = source.sink_wants();
5326 // Store current sink wants since we expect no change ind if there is no
5327 // change then last__wants() is not updated.
5328 video_stream_encoder_->TriggerCpuUnderuse();
5329 timestamp_ms += kFrameIntervalMs;
5330 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
5331 WaitForEncodedFrame(timestamp_ms);
5332 EXPECT_THAT(source.sink_wants(), FpsEqResolutionEqTo(previous_sink_wants));
5333 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
5334 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5335 }
5336
5337 // Trigger quality adapt up, expect upscaled resolution (640x360@15fps).
5338 video_stream_encoder_->TriggerQualityHigh();
asaperssonf7e294d2017-06-13 23:25:22 -07005339 timestamp_ms += kFrameIntervalMs;
5340 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005341 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02005342 EXPECT_THAT(source.sink_wants(), FpsEqResolutionGt(source.last_wants()));
asaperssonf7e294d2017-06-13 23:25:22 -07005343 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
5344 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
5345 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
Evan Shrubsole64469032020-06-11 10:45:29 +02005346 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_framerate);
5347 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
5348 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_quality_adapt_changes);
asaperssonf7e294d2017-06-13 23:25:22 -07005349
Evan Shrubsole64469032020-06-11 10:45:29 +02005350 // Trigger quality and cpu adapt up, expect increased fps (640x360@30fps).
mflodmancc3d4422017-08-03 08:27:51 -07005351 video_stream_encoder_->TriggerQualityHigh();
Evan Shrubsole64469032020-06-11 10:45:29 +02005352 video_stream_encoder_->TriggerCpuUnderuse();
asaperssonf7e294d2017-06-13 23:25:22 -07005353 timestamp_ms += kFrameIntervalMs;
5354 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005355 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02005356 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-13 23:25:22 -07005357 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
5358 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
5359 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
5360 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
5361 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
Evan Shrubsole64469032020-06-11 10:45:29 +02005362 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_quality_adapt_changes);
asaperssonf7e294d2017-06-13 23:25:22 -07005363
5364 // Trigger adapt up, expect no change.
mflodmancc3d4422017-08-03 08:27:51 -07005365 video_stream_encoder_->TriggerQualityHigh();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02005366 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-13 23:25:22 -07005367 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
Evan Shrubsole64469032020-06-11 10:45:29 +02005368 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_quality_adapt_changes);
asaperssonf7e294d2017-06-13 23:25:22 -07005369
mflodmancc3d4422017-08-03 08:27:51 -07005370 video_stream_encoder_->Stop();
asaperssonf7e294d2017-06-13 23:25:22 -07005371}
5372
mflodmancc3d4422017-08-03 08:27:51 -07005373TEST_F(VideoStreamEncoderTest, AcceptsFullHdAdaptedDownSimulcastFrames) {
ilnik6b826ef2017-06-16 06:53:48 -07005374 const int kFrameWidth = 1920;
5375 const int kFrameHeight = 1080;
5376 // 3/4 of 1920.
5377 const int kAdaptedFrameWidth = 1440;
5378 // 3/4 of 1080 rounded down to multiple of 4.
5379 const int kAdaptedFrameHeight = 808;
5380 const int kFramerate = 24;
5381
Henrik Boström381d1092020-05-12 18:49:07 +02005382 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005383 DataRate::BitsPerSec(kTargetBitrateBps),
5384 DataRate::BitsPerSec(kTargetBitrateBps),
5385 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
ilnik6b826ef2017-06-16 06:53:48 -07005386 // Trigger reconfigure encoder (without resetting the entire instance).
5387 VideoEncoderConfig video_encoder_config;
Niels Möller259a4972018-04-05 15:36:51 +02005388 video_encoder_config.codec_type = kVideoCodecVP8;
ilnik6b826ef2017-06-16 06:53:48 -07005389 video_encoder_config.max_bitrate_bps = kTargetBitrateBps;
5390 video_encoder_config.number_of_streams = 1;
5391 video_encoder_config.video_stream_factory =
5392 new rtc::RefCountedObject<CroppingVideoStreamFactory>(1, kFramerate);
mflodmancc3d4422017-08-03 08:27:51 -07005393 video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config),
Niels Möllerf1338562018-04-26 09:51:47 +02005394 kMaxPayloadLength);
mflodmancc3d4422017-08-03 08:27:51 -07005395 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
ilnik6b826ef2017-06-16 06:53:48 -07005396
5397 video_source_.set_adaptation_enabled(true);
5398
5399 video_source_.IncomingCapturedFrame(
5400 CreateFrame(1, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 07:06:52 -07005401 WaitForEncodedFrame(kFrameWidth, kFrameHeight);
ilnik6b826ef2017-06-16 06:53:48 -07005402
5403 // Trigger CPU overuse, downscale by 3/4.
mflodmancc3d4422017-08-03 08:27:51 -07005404 video_stream_encoder_->TriggerCpuOveruse();
ilnik6b826ef2017-06-16 06:53:48 -07005405 video_source_.IncomingCapturedFrame(
5406 CreateFrame(2, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 07:06:52 -07005407 WaitForEncodedFrame(kAdaptedFrameWidth, kAdaptedFrameHeight);
ilnik6b826ef2017-06-16 06:53:48 -07005408
mflodmancc3d4422017-08-03 08:27:51 -07005409 video_stream_encoder_->Stop();
ilnik6b826ef2017-06-16 06:53:48 -07005410}
5411
mflodmancc3d4422017-08-03 08:27:51 -07005412TEST_F(VideoStreamEncoderTest, PeriodicallyUpdatesChannelParameters) {
sprang4847ae62017-06-27 07:06:52 -07005413 const int kFrameWidth = 1280;
5414 const int kFrameHeight = 720;
5415 const int kLowFps = 2;
5416 const int kHighFps = 30;
5417
Henrik Boström381d1092020-05-12 18:49:07 +02005418 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005419 DataRate::BitsPerSec(kTargetBitrateBps),
5420 DataRate::BitsPerSec(kTargetBitrateBps),
5421 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
sprang4847ae62017-06-27 07:06:52 -07005422
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02005423 int64_t timestamp_ms = CurrentTimeMs();
sprang4847ae62017-06-27 07:06:52 -07005424 max_framerate_ = kLowFps;
5425
5426 // Insert 2 seconds of 2fps video.
5427 for (int i = 0; i < kLowFps * 2; ++i) {
5428 video_source_.IncomingCapturedFrame(
5429 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
5430 WaitForEncodedFrame(timestamp_ms);
5431 timestamp_ms += 1000 / kLowFps;
5432 }
5433
5434 // Make sure encoder is updated with new target.
Henrik Boström381d1092020-05-12 18:49:07 +02005435 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005436 DataRate::BitsPerSec(kTargetBitrateBps),
5437 DataRate::BitsPerSec(kTargetBitrateBps),
5438 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
sprang4847ae62017-06-27 07:06:52 -07005439 video_source_.IncomingCapturedFrame(
5440 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
5441 WaitForEncodedFrame(timestamp_ms);
5442 timestamp_ms += 1000 / kLowFps;
5443
5444 EXPECT_EQ(kLowFps, fake_encoder_.GetConfiguredInputFramerate());
5445
5446 // Insert 30fps frames for just a little more than the forced update period.
Niels Möllerfe407b72019-09-10 10:48:48 +02005447 const int kVcmTimerIntervalFrames = (kProcessIntervalMs * kHighFps) / 1000;
sprang4847ae62017-06-27 07:06:52 -07005448 const int kFrameIntervalMs = 1000 / kHighFps;
5449 max_framerate_ = kHighFps;
5450 for (int i = 0; i < kVcmTimerIntervalFrames + 2; ++i) {
5451 video_source_.IncomingCapturedFrame(
5452 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
5453 // Wait for encoded frame, but skip ahead if it doesn't arrive as it might
5454 // be dropped if the encoder hans't been updated with the new higher target
5455 // framerate yet, causing it to overshoot the target bitrate and then
5456 // suffering the wrath of the media optimizer.
5457 TimedWaitForEncodedFrame(timestamp_ms, 2 * kFrameIntervalMs);
5458 timestamp_ms += kFrameIntervalMs;
5459 }
5460
5461 // Don expect correct measurement just yet, but it should be higher than
5462 // before.
5463 EXPECT_GT(fake_encoder_.GetConfiguredInputFramerate(), kLowFps);
5464
mflodmancc3d4422017-08-03 08:27:51 -07005465 video_stream_encoder_->Stop();
sprang4847ae62017-06-27 07:06:52 -07005466}
5467
mflodmancc3d4422017-08-03 08:27:51 -07005468TEST_F(VideoStreamEncoderTest, DoesNotUpdateBitrateAllocationWhenSuspended) {
sprang4847ae62017-06-27 07:06:52 -07005469 const int kFrameWidth = 1280;
5470 const int kFrameHeight = 720;
5471 const int kTargetBitrateBps = 1000000;
Per Kjellanderdcef6412020-10-07 15:09:05 +02005472 ResetEncoder("FAKE", 1, 1, 1, false,
5473 VideoStreamEncoderSettings::BitrateAllocationCallbackType::
5474 kVideoBitrateAllocation);
sprang4847ae62017-06-27 07:06:52 -07005475
Henrik Boström381d1092020-05-12 18:49:07 +02005476 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005477 DataRate::BitsPerSec(kTargetBitrateBps),
5478 DataRate::BitsPerSec(kTargetBitrateBps),
5479 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
mflodmancc3d4422017-08-03 08:27:51 -07005480 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
sprang4847ae62017-06-27 07:06:52 -07005481
5482 // Insert a first video frame, causes another bitrate update.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02005483 int64_t timestamp_ms = CurrentTimeMs();
sprang4847ae62017-06-27 07:06:52 -07005484 video_source_.IncomingCapturedFrame(
5485 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
5486 WaitForEncodedFrame(timestamp_ms);
Per Kjellanderdcef6412020-10-07 15:09:05 +02005487 EXPECT_EQ(sink_.number_of_bitrate_allocations(), 1);
sprang4847ae62017-06-27 07:06:52 -07005488
5489 // Next, simulate video suspension due to pacer queue overrun.
Henrik Boström381d1092020-05-12 18:49:07 +02005490 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
5491 DataRate::BitsPerSec(0), DataRate::BitsPerSec(0), DataRate::BitsPerSec(0),
5492 0, 1, 0);
sprang4847ae62017-06-27 07:06:52 -07005493
5494 // Skip ahead until a new periodic parameter update should have occured.
Niels Möllerfe407b72019-09-10 10:48:48 +02005495 timestamp_ms += kProcessIntervalMs;
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02005496 AdvanceTime(TimeDelta::Millis(kProcessIntervalMs));
sprang4847ae62017-06-27 07:06:52 -07005497
Per Kjellanderdcef6412020-10-07 15:09:05 +02005498 // No more allocations has been made.
sprang4847ae62017-06-27 07:06:52 -07005499 video_source_.IncomingCapturedFrame(
5500 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
5501 ExpectDroppedFrame();
Per Kjellanderdcef6412020-10-07 15:09:05 +02005502 EXPECT_EQ(sink_.number_of_bitrate_allocations(), 1);
sprang4847ae62017-06-27 07:06:52 -07005503
mflodmancc3d4422017-08-03 08:27:51 -07005504 video_stream_encoder_->Stop();
sprang4847ae62017-06-27 07:06:52 -07005505}
ilnik6b826ef2017-06-16 06:53:48 -07005506
Niels Möller4db138e2018-04-19 09:04:13 +02005507TEST_F(VideoStreamEncoderTest,
5508 DefaultCpuAdaptationThresholdsForSoftwareEncoder) {
5509 const int kFrameWidth = 1280;
5510 const int kFrameHeight = 720;
5511 const CpuOveruseOptions default_options;
Henrik Boström381d1092020-05-12 18:49:07 +02005512 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005513 DataRate::BitsPerSec(kTargetBitrateBps),
5514 DataRate::BitsPerSec(kTargetBitrateBps),
5515 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Niels Möller4db138e2018-04-19 09:04:13 +02005516 video_source_.IncomingCapturedFrame(
5517 CreateFrame(1, kFrameWidth, kFrameHeight));
5518 WaitForEncodedFrame(1);
5519 EXPECT_EQ(video_stream_encoder_->overuse_detector_proxy_->GetOptions()
5520 .low_encode_usage_threshold_percent,
5521 default_options.low_encode_usage_threshold_percent);
5522 EXPECT_EQ(video_stream_encoder_->overuse_detector_proxy_->GetOptions()
5523 .high_encode_usage_threshold_percent,
5524 default_options.high_encode_usage_threshold_percent);
5525 video_stream_encoder_->Stop();
5526}
5527
5528TEST_F(VideoStreamEncoderTest,
5529 HigherCpuAdaptationThresholdsForHardwareEncoder) {
5530 const int kFrameWidth = 1280;
5531 const int kFrameHeight = 720;
5532 CpuOveruseOptions hardware_options;
5533 hardware_options.low_encode_usage_threshold_percent = 150;
5534 hardware_options.high_encode_usage_threshold_percent = 200;
Mirta Dvornicicccc1b572019-01-15 12:42:18 +01005535 fake_encoder_.SetIsHardwareAccelerated(true);
Niels Möller4db138e2018-04-19 09:04:13 +02005536
Henrik Boström381d1092020-05-12 18:49:07 +02005537 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005538 DataRate::BitsPerSec(kTargetBitrateBps),
5539 DataRate::BitsPerSec(kTargetBitrateBps),
5540 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Niels Möller4db138e2018-04-19 09:04:13 +02005541 video_source_.IncomingCapturedFrame(
5542 CreateFrame(1, kFrameWidth, kFrameHeight));
5543 WaitForEncodedFrame(1);
5544 EXPECT_EQ(video_stream_encoder_->overuse_detector_proxy_->GetOptions()
5545 .low_encode_usage_threshold_percent,
5546 hardware_options.low_encode_usage_threshold_percent);
5547 EXPECT_EQ(video_stream_encoder_->overuse_detector_proxy_->GetOptions()
5548 .high_encode_usage_threshold_percent,
5549 hardware_options.high_encode_usage_threshold_percent);
5550 video_stream_encoder_->Stop();
5551}
5552
Niels Möller6bb5ab92019-01-11 11:11:10 +01005553TEST_F(VideoStreamEncoderTest, DropsFramesWhenEncoderOvershoots) {
5554 const int kFrameWidth = 320;
5555 const int kFrameHeight = 240;
5556 const int kFps = 30;
5557 const int kTargetBitrateBps = 120000;
5558 const int kNumFramesInRun = kFps * 5; // Runs of five seconds.
5559
Henrik Boström381d1092020-05-12 18:49:07 +02005560 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005561 DataRate::BitsPerSec(kTargetBitrateBps),
5562 DataRate::BitsPerSec(kTargetBitrateBps),
5563 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Niels Möller6bb5ab92019-01-11 11:11:10 +01005564
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02005565 int64_t timestamp_ms = CurrentTimeMs();
Niels Möller6bb5ab92019-01-11 11:11:10 +01005566 max_framerate_ = kFps;
5567
5568 // Insert 3 seconds of video, verify number of drops with normal bitrate.
5569 fake_encoder_.SimulateOvershoot(1.0);
5570 int num_dropped = 0;
5571 for (int i = 0; i < kNumFramesInRun; ++i) {
5572 video_source_.IncomingCapturedFrame(
5573 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
5574 // Wait up to two frame durations for a frame to arrive.
5575 if (!TimedWaitForEncodedFrame(timestamp_ms, 2 * 1000 / kFps)) {
5576 ++num_dropped;
5577 }
5578 timestamp_ms += 1000 / kFps;
5579 }
5580
Erik Språnga8d48ab2019-02-08 14:17:40 +01005581 // Framerate should be measured to be near the expected target rate.
5582 EXPECT_NEAR(fake_encoder_.GetLastFramerate(), kFps, 1);
5583
5584 // Frame drops should be within 5% of expected 0%.
5585 EXPECT_NEAR(num_dropped, 0, 5 * kNumFramesInRun / 100);
Niels Möller6bb5ab92019-01-11 11:11:10 +01005586
5587 // Make encoder produce frames at double the expected bitrate during 3 seconds
5588 // of video, verify number of drops. Rate needs to be slightly changed in
5589 // order to force the rate to be reconfigured.
Erik Språng7ca375c2019-02-06 16:20:17 +01005590 double overshoot_factor = 2.0;
Erik Språng9d69cbe2020-10-22 17:44:42 +02005591 const RateControlSettings trials =
5592 RateControlSettings::ParseFromFieldTrials();
5593 if (trials.UseEncoderBitrateAdjuster()) {
Erik Språng7ca375c2019-02-06 16:20:17 +01005594 // With bitrate adjuster, when need to overshoot even more to trigger
Erik Språng9d69cbe2020-10-22 17:44:42 +02005595 // frame dropping since the adjuter will try to just lower the target
5596 // bitrate rather than drop frames. If network headroom can be used, it
5597 // doesn't push back as hard so we don't need quite as much overshoot.
5598 // These numbers are unfortunately a bit magical but there's not trivial
5599 // way to algebraically infer them.
5600 if (trials.BitrateAdjusterCanUseNetworkHeadroom()) {
5601 overshoot_factor = 2.4;
5602 } else {
5603 overshoot_factor = 4.0;
5604 }
Erik Språng7ca375c2019-02-06 16:20:17 +01005605 }
5606 fake_encoder_.SimulateOvershoot(overshoot_factor);
Henrik Boström381d1092020-05-12 18:49:07 +02005607 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005608 DataRate::BitsPerSec(kTargetBitrateBps + 1000),
5609 DataRate::BitsPerSec(kTargetBitrateBps + 1000),
5610 DataRate::BitsPerSec(kTargetBitrateBps + 1000), 0, 0, 0);
Niels Möller6bb5ab92019-01-11 11:11:10 +01005611 num_dropped = 0;
5612 for (int i = 0; i < kNumFramesInRun; ++i) {
5613 video_source_.IncomingCapturedFrame(
5614 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
5615 // Wait up to two frame durations for a frame to arrive.
5616 if (!TimedWaitForEncodedFrame(timestamp_ms, 2 * 1000 / kFps)) {
5617 ++num_dropped;
5618 }
5619 timestamp_ms += 1000 / kFps;
5620 }
5621
Henrik Boström381d1092020-05-12 18:49:07 +02005622 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005623 DataRate::BitsPerSec(kTargetBitrateBps),
5624 DataRate::BitsPerSec(kTargetBitrateBps),
5625 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Erik Språnga8d48ab2019-02-08 14:17:40 +01005626
5627 // Target framerate should be still be near the expected target, despite
5628 // the frame drops.
5629 EXPECT_NEAR(fake_encoder_.GetLastFramerate(), kFps, 1);
5630
5631 // Frame drops should be within 5% of expected 50%.
5632 EXPECT_NEAR(num_dropped, kNumFramesInRun / 2, 5 * kNumFramesInRun / 100);
Niels Möller6bb5ab92019-01-11 11:11:10 +01005633
5634 video_stream_encoder_->Stop();
5635}
5636
5637TEST_F(VideoStreamEncoderTest, ConfiguresCorrectFrameRate) {
5638 const int kFrameWidth = 320;
5639 const int kFrameHeight = 240;
5640 const int kActualInputFps = 24;
5641 const int kTargetBitrateBps = 120000;
5642
5643 ASSERT_GT(max_framerate_, kActualInputFps);
5644
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02005645 int64_t timestamp_ms = CurrentTimeMs();
Niels Möller6bb5ab92019-01-11 11:11:10 +01005646 max_framerate_ = kActualInputFps;
Henrik Boström381d1092020-05-12 18:49:07 +02005647 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005648 DataRate::BitsPerSec(kTargetBitrateBps),
5649 DataRate::BitsPerSec(kTargetBitrateBps),
5650 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Niels Möller6bb5ab92019-01-11 11:11:10 +01005651
5652 // Insert 3 seconds of video, with an input fps lower than configured max.
5653 for (int i = 0; i < kActualInputFps * 3; ++i) {
5654 video_source_.IncomingCapturedFrame(
5655 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
5656 // Wait up to two frame durations for a frame to arrive.
5657 WaitForEncodedFrame(timestamp_ms);
5658 timestamp_ms += 1000 / kActualInputFps;
5659 }
5660
5661 EXPECT_NEAR(kActualInputFps, fake_encoder_.GetLastFramerate(), 1);
5662
5663 video_stream_encoder_->Stop();
5664}
5665
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02005666TEST_F(VideoStreamEncoderBlockedTest, AccumulatesUpdateRectOnDroppedFrames) {
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01005667 VideoFrame::UpdateRect rect;
Henrik Boström381d1092020-05-12 18:49:07 +02005668 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005669 DataRate::BitsPerSec(kTargetBitrateBps),
5670 DataRate::BitsPerSec(kTargetBitrateBps),
5671 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01005672
5673 fake_encoder_.BlockNextEncode();
5674 video_source_.IncomingCapturedFrame(
5675 CreateFrameWithUpdatedPixel(1, nullptr, 0));
5676 WaitForEncodedFrame(1);
5677 // On the very first frame full update should be forced.
5678 rect = fake_encoder_.GetLastUpdateRect();
5679 EXPECT_EQ(rect.offset_x, 0);
5680 EXPECT_EQ(rect.offset_y, 0);
5681 EXPECT_EQ(rect.height, codec_height_);
5682 EXPECT_EQ(rect.width, codec_width_);
5683 // Here, the encoder thread will be blocked in the TestEncoder waiting for a
5684 // call to ContinueEncode.
5685 video_source_.IncomingCapturedFrame(
5686 CreateFrameWithUpdatedPixel(2, nullptr, 1));
5687 ExpectDroppedFrame();
5688 video_source_.IncomingCapturedFrame(
5689 CreateFrameWithUpdatedPixel(3, nullptr, 10));
5690 ExpectDroppedFrame();
5691 fake_encoder_.ContinueEncode();
5692 WaitForEncodedFrame(3);
5693 // Updates to pixels 1 and 10 should be accumulated to one 10x1 rect.
5694 rect = fake_encoder_.GetLastUpdateRect();
5695 EXPECT_EQ(rect.offset_x, 1);
5696 EXPECT_EQ(rect.offset_y, 0);
5697 EXPECT_EQ(rect.width, 10);
5698 EXPECT_EQ(rect.height, 1);
5699
5700 video_source_.IncomingCapturedFrame(
5701 CreateFrameWithUpdatedPixel(4, nullptr, 0));
5702 WaitForEncodedFrame(4);
5703 // Previous frame was encoded, so no accumulation should happen.
5704 rect = fake_encoder_.GetLastUpdateRect();
5705 EXPECT_EQ(rect.offset_x, 0);
5706 EXPECT_EQ(rect.offset_y, 0);
5707 EXPECT_EQ(rect.width, 1);
5708 EXPECT_EQ(rect.height, 1);
5709
5710 video_stream_encoder_->Stop();
5711}
5712
Erik Språngd7329ca2019-02-21 21:19:53 +01005713TEST_F(VideoStreamEncoderTest, SetsFrameTypes) {
Henrik Boström381d1092020-05-12 18:49:07 +02005714 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005715 DataRate::BitsPerSec(kTargetBitrateBps),
5716 DataRate::BitsPerSec(kTargetBitrateBps),
5717 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Erik Språngd7329ca2019-02-21 21:19:53 +01005718
5719 // First frame is always keyframe.
5720 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
5721 WaitForEncodedFrame(1);
Niels Möller8f7ce222019-03-21 15:43:58 +01005722 EXPECT_THAT(
5723 fake_encoder_.LastFrameTypes(),
Mirko Bonadei6a489f22019-04-09 15:11:12 +02005724 ::testing::ElementsAre(VideoFrameType{VideoFrameType::kVideoFrameKey}));
Erik Språngd7329ca2019-02-21 21:19:53 +01005725
5726 // Insert delta frame.
5727 video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
5728 WaitForEncodedFrame(2);
Niels Möller8f7ce222019-03-21 15:43:58 +01005729 EXPECT_THAT(
5730 fake_encoder_.LastFrameTypes(),
Mirko Bonadei6a489f22019-04-09 15:11:12 +02005731 ::testing::ElementsAre(VideoFrameType{VideoFrameType::kVideoFrameDelta}));
Erik Språngd7329ca2019-02-21 21:19:53 +01005732
5733 // Request next frame be a key-frame.
5734 video_stream_encoder_->SendKeyFrame();
5735 video_source_.IncomingCapturedFrame(CreateFrame(3, nullptr));
5736 WaitForEncodedFrame(3);
Niels Möller8f7ce222019-03-21 15:43:58 +01005737 EXPECT_THAT(
5738 fake_encoder_.LastFrameTypes(),
Mirko Bonadei6a489f22019-04-09 15:11:12 +02005739 ::testing::ElementsAre(VideoFrameType{VideoFrameType::kVideoFrameKey}));
Erik Språngd7329ca2019-02-21 21:19:53 +01005740
5741 video_stream_encoder_->Stop();
5742}
5743
5744TEST_F(VideoStreamEncoderTest, SetsFrameTypesSimulcast) {
5745 // Setup simulcast with three streams.
5746 ResetEncoder("VP8", 3, 1, 1, false);
Henrik Boström381d1092020-05-12 18:49:07 +02005747 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005748 DataRate::BitsPerSec(kSimulcastTargetBitrateBps),
5749 DataRate::BitsPerSec(kSimulcastTargetBitrateBps),
5750 DataRate::BitsPerSec(kSimulcastTargetBitrateBps), 0, 0, 0);
Erik Språngd7329ca2019-02-21 21:19:53 +01005751 // Wait for all three layers before triggering event.
5752 sink_.SetNumExpectedLayers(3);
5753
5754 // First frame is always keyframe.
5755 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
5756 WaitForEncodedFrame(1);
5757 EXPECT_THAT(fake_encoder_.LastFrameTypes(),
Mirko Bonadei6a489f22019-04-09 15:11:12 +02005758 ::testing::ElementsAreArray({VideoFrameType::kVideoFrameKey,
5759 VideoFrameType::kVideoFrameKey,
5760 VideoFrameType::kVideoFrameKey}));
Erik Språngd7329ca2019-02-21 21:19:53 +01005761
5762 // Insert delta frame.
5763 video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
5764 WaitForEncodedFrame(2);
5765 EXPECT_THAT(fake_encoder_.LastFrameTypes(),
Mirko Bonadei6a489f22019-04-09 15:11:12 +02005766 ::testing::ElementsAreArray({VideoFrameType::kVideoFrameDelta,
5767 VideoFrameType::kVideoFrameDelta,
5768 VideoFrameType::kVideoFrameDelta}));
Erik Språngd7329ca2019-02-21 21:19:53 +01005769
5770 // Request next frame be a key-frame.
5771 // Only first stream is configured to produce key-frame.
5772 video_stream_encoder_->SendKeyFrame();
5773 video_source_.IncomingCapturedFrame(CreateFrame(3, nullptr));
5774 WaitForEncodedFrame(3);
Sergey Silkine62a08a2019-05-13 13:45:39 +02005775
5776 // TODO(webrtc:10615): Map keyframe request to spatial layer. Currently
5777 // keyframe request on any layer triggers keyframe on all layers.
Erik Språngd7329ca2019-02-21 21:19:53 +01005778 EXPECT_THAT(fake_encoder_.LastFrameTypes(),
Mirko Bonadei6a489f22019-04-09 15:11:12 +02005779 ::testing::ElementsAreArray({VideoFrameType::kVideoFrameKey,
Sergey Silkine62a08a2019-05-13 13:45:39 +02005780 VideoFrameType::kVideoFrameKey,
5781 VideoFrameType::kVideoFrameKey}));
Erik Språngd7329ca2019-02-21 21:19:53 +01005782
5783 video_stream_encoder_->Stop();
5784}
5785
5786TEST_F(VideoStreamEncoderTest, RequestKeyframeInternalSource) {
5787 // Configure internal source factory and setup test again.
5788 encoder_factory_.SetHasInternalSource(true);
5789 ResetEncoder("VP8", 1, 1, 1, false);
Henrik Boström381d1092020-05-12 18:49:07 +02005790 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005791 DataRate::BitsPerSec(kTargetBitrateBps),
5792 DataRate::BitsPerSec(kTargetBitrateBps),
5793 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Erik Språngd7329ca2019-02-21 21:19:53 +01005794
5795 // Call encoder directly, simulating internal source where encoded frame
5796 // callback in VideoStreamEncoder is called despite no OnFrame().
5797 fake_encoder_.InjectFrame(CreateFrame(1, nullptr), true);
5798 EXPECT_TRUE(WaitForFrame(kDefaultTimeoutMs));
Niels Möller8f7ce222019-03-21 15:43:58 +01005799 EXPECT_THAT(
5800 fake_encoder_.LastFrameTypes(),
Mirko Bonadei6a489f22019-04-09 15:11:12 +02005801 ::testing::ElementsAre(VideoFrameType{VideoFrameType::kVideoFrameKey}));
Erik Språngd7329ca2019-02-21 21:19:53 +01005802
Niels Möller8f7ce222019-03-21 15:43:58 +01005803 const std::vector<VideoFrameType> kDeltaFrame = {
5804 VideoFrameType::kVideoFrameDelta};
Erik Språngd7329ca2019-02-21 21:19:53 +01005805 // Need to set timestamp manually since manually for injected frame.
5806 VideoFrame frame = CreateFrame(101, nullptr);
5807 frame.set_timestamp(101);
5808 fake_encoder_.InjectFrame(frame, false);
5809 EXPECT_TRUE(WaitForFrame(kDefaultTimeoutMs));
Niels Möller8f7ce222019-03-21 15:43:58 +01005810 EXPECT_THAT(
5811 fake_encoder_.LastFrameTypes(),
Mirko Bonadei6a489f22019-04-09 15:11:12 +02005812 ::testing::ElementsAre(VideoFrameType{VideoFrameType::kVideoFrameDelta}));
Erik Språngd7329ca2019-02-21 21:19:53 +01005813
5814 // Request key-frame. The forces a dummy frame down into the encoder.
5815 fake_encoder_.ExpectNullFrame();
5816 video_stream_encoder_->SendKeyFrame();
5817 EXPECT_TRUE(WaitForFrame(kDefaultTimeoutMs));
Niels Möller8f7ce222019-03-21 15:43:58 +01005818 EXPECT_THAT(
5819 fake_encoder_.LastFrameTypes(),
Mirko Bonadei6a489f22019-04-09 15:11:12 +02005820 ::testing::ElementsAre(VideoFrameType{VideoFrameType::kVideoFrameKey}));
Erik Språngd7329ca2019-02-21 21:19:53 +01005821
5822 video_stream_encoder_->Stop();
5823}
Erik Språngb7cb7b52019-02-26 15:52:33 +01005824
5825TEST_F(VideoStreamEncoderTest, AdjustsTimestampInternalSource) {
5826 // Configure internal source factory and setup test again.
5827 encoder_factory_.SetHasInternalSource(true);
5828 ResetEncoder("VP8", 1, 1, 1, false);
Henrik Boström381d1092020-05-12 18:49:07 +02005829 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005830 DataRate::BitsPerSec(kTargetBitrateBps),
5831 DataRate::BitsPerSec(kTargetBitrateBps),
5832 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Erik Språngb7cb7b52019-02-26 15:52:33 +01005833
5834 int64_t timestamp = 1;
5835 EncodedImage image;
Niels Möller4d504c72019-06-18 15:56:56 +02005836 image.SetEncodedData(
5837 EncodedImageBuffer::Create(kTargetBitrateBps / kDefaultFramerate / 8));
Erik Språngb7cb7b52019-02-26 15:52:33 +01005838 image.capture_time_ms_ = ++timestamp;
5839 image.SetTimestamp(static_cast<uint32_t>(timestamp * 90));
5840 const int64_t kEncodeFinishDelayMs = 10;
5841 image.timing_.encode_start_ms = timestamp;
5842 image.timing_.encode_finish_ms = timestamp + kEncodeFinishDelayMs;
5843 fake_encoder_.InjectEncodedImage(image);
5844 // Wait for frame without incrementing clock.
5845 EXPECT_TRUE(sink_.WaitForFrame(kDefaultTimeoutMs));
5846 // Frame is captured kEncodeFinishDelayMs before it's encoded, so restored
5847 // capture timestamp should be kEncodeFinishDelayMs in the past.
5848 EXPECT_EQ(sink_.GetLastCaptureTimeMs(),
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02005849 CurrentTimeMs() - kEncodeFinishDelayMs);
Erik Språngb7cb7b52019-02-26 15:52:33 +01005850
5851 video_stream_encoder_->Stop();
5852}
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +02005853
5854TEST_F(VideoStreamEncoderTest, DoesNotRewriteH264BitstreamWithOptimalSps) {
Mirta Dvornicic97910da2020-07-14 15:29:23 +02005855 // SPS contains VUI with restrictions on the maximum number of reordered
5856 // pictures, there is no need to rewrite the bitstream to enable faster
5857 // decoding.
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +02005858 ResetEncoder("H264", 1, 1, 1, false);
5859
Mirta Dvornicic97910da2020-07-14 15:29:23 +02005860 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
5861 DataRate::BitsPerSec(kTargetBitrateBps),
5862 DataRate::BitsPerSec(kTargetBitrateBps),
5863 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
5864 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +02005865
Mirta Dvornicic97910da2020-07-14 15:29:23 +02005866 fake_encoder_.SetEncodedImageData(
5867 EncodedImageBuffer::Create(optimal_sps, sizeof(optimal_sps)));
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +02005868
Mirta Dvornicic97910da2020-07-14 15:29:23 +02005869 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
5870 WaitForEncodedFrame(1);
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +02005871
5872 EXPECT_THAT(sink_.GetLastEncodedImageData(),
5873 testing::ElementsAreArray(optimal_sps));
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +02005874
5875 video_stream_encoder_->Stop();
5876}
5877
5878TEST_F(VideoStreamEncoderTest, RewritesH264BitstreamWithNonOptimalSps) {
Mirta Dvornicic97910da2020-07-14 15:29:23 +02005879 // SPS does not contain VUI, the bitstream is will be rewritten with added
5880 // VUI with restrictions on the maximum number of reordered pictures to
5881 // enable faster decoding.
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +02005882 uint8_t original_sps[] = {0, 0, 0, 1, H264::NaluType::kSps,
5883 0x00, 0x00, 0x03, 0x03, 0xF4,
5884 0x05, 0x03, 0xC7, 0xC0};
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +02005885 ResetEncoder("H264", 1, 1, 1, false);
5886
Mirta Dvornicic97910da2020-07-14 15:29:23 +02005887 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
5888 DataRate::BitsPerSec(kTargetBitrateBps),
5889 DataRate::BitsPerSec(kTargetBitrateBps),
5890 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
5891 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +02005892
Mirta Dvornicic97910da2020-07-14 15:29:23 +02005893 fake_encoder_.SetEncodedImageData(
5894 EncodedImageBuffer::Create(original_sps, sizeof(original_sps)));
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +02005895
Mirta Dvornicic97910da2020-07-14 15:29:23 +02005896 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
5897 WaitForEncodedFrame(1);
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +02005898
5899 EXPECT_THAT(sink_.GetLastEncodedImageData(),
5900 testing::ElementsAreArray(optimal_sps));
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +02005901
5902 video_stream_encoder_->Stop();
5903}
5904
Ilya Nikolaevskiyba96e2f2019-06-04 15:15:14 +02005905TEST_F(VideoStreamEncoderTest, CopiesVideoFrameMetadataAfterDownscale) {
5906 const int kFrameWidth = 1280;
5907 const int kFrameHeight = 720;
5908 const int kTargetBitrateBps = 300000; // To low for HD resolution.
5909
Henrik Boström381d1092020-05-12 18:49:07 +02005910 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005911 DataRate::BitsPerSec(kTargetBitrateBps),
5912 DataRate::BitsPerSec(kTargetBitrateBps),
5913 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Ilya Nikolaevskiyba96e2f2019-06-04 15:15:14 +02005914 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
5915
5916 // Insert a first video frame. It should be dropped because of downscale in
5917 // resolution.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02005918 int64_t timestamp_ms = CurrentTimeMs();
Ilya Nikolaevskiyba96e2f2019-06-04 15:15:14 +02005919 VideoFrame frame = CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight);
5920 frame.set_rotation(kVideoRotation_270);
5921 video_source_.IncomingCapturedFrame(frame);
5922
5923 ExpectDroppedFrame();
5924
5925 // Second frame is downscaled.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02005926 timestamp_ms = CurrentTimeMs();
Ilya Nikolaevskiyba96e2f2019-06-04 15:15:14 +02005927 frame = CreateFrame(timestamp_ms, kFrameWidth / 2, kFrameHeight / 2);
5928 frame.set_rotation(kVideoRotation_90);
5929 video_source_.IncomingCapturedFrame(frame);
5930
5931 WaitForEncodedFrame(timestamp_ms);
5932 sink_.CheckLastFrameRotationMatches(kVideoRotation_90);
5933
5934 // Insert another frame, also downscaled.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02005935 timestamp_ms = CurrentTimeMs();
Ilya Nikolaevskiyba96e2f2019-06-04 15:15:14 +02005936 frame = CreateFrame(timestamp_ms, kFrameWidth / 2, kFrameHeight / 2);
5937 frame.set_rotation(kVideoRotation_180);
5938 video_source_.IncomingCapturedFrame(frame);
5939
5940 WaitForEncodedFrame(timestamp_ms);
5941 sink_.CheckLastFrameRotationMatches(kVideoRotation_180);
5942
5943 video_stream_encoder_->Stop();
5944}
5945
Erik Språng5056af02019-09-02 15:53:11 +02005946TEST_F(VideoStreamEncoderTest, BandwidthAllocationLowerBound) {
5947 const int kFrameWidth = 320;
5948 const int kFrameHeight = 180;
5949
5950 // Initial rate.
Henrik Boström381d1092020-05-12 18:49:07 +02005951 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005952 /*target_bitrate=*/DataRate::KilobitsPerSec(300),
5953 /*stable_target_bitrate=*/DataRate::KilobitsPerSec(300),
5954 /*link_allocation=*/DataRate::KilobitsPerSec(300),
Erik Språng5056af02019-09-02 15:53:11 +02005955 /*fraction_lost=*/0,
Ying Wang9b881ab2020-02-07 14:29:32 +01005956 /*rtt_ms=*/0,
5957 /*cwnd_reduce_ratio=*/0);
Erik Språng5056af02019-09-02 15:53:11 +02005958
5959 // Insert a first video frame so that encoder gets configured.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02005960 int64_t timestamp_ms = CurrentTimeMs();
Erik Språng5056af02019-09-02 15:53:11 +02005961 VideoFrame frame = CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight);
5962 frame.set_rotation(kVideoRotation_270);
5963 video_source_.IncomingCapturedFrame(frame);
5964 WaitForEncodedFrame(timestamp_ms);
5965
5966 // Set a target rate below the minimum allowed by the codec settings.
5967 VideoCodec codec_config = fake_encoder_.codec_config();
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005968 DataRate min_rate = DataRate::KilobitsPerSec(codec_config.minBitrate);
5969 DataRate target_rate = min_rate - DataRate::KilobitsPerSec(1);
Henrik Boström381d1092020-05-12 18:49:07 +02005970 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Erik Språng5056af02019-09-02 15:53:11 +02005971 /*target_bitrate=*/target_rate,
Florent Castellia8336d32019-09-09 13:36:55 +02005972 /*stable_target_bitrate=*/target_rate,
Erik Språng5056af02019-09-02 15:53:11 +02005973 /*link_allocation=*/target_rate,
5974 /*fraction_lost=*/0,
Ying Wang9b881ab2020-02-07 14:29:32 +01005975 /*rtt_ms=*/0,
5976 /*cwnd_reduce_ratio=*/0);
Erik Språng5056af02019-09-02 15:53:11 +02005977 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
5978
5979 // Target bitrate and bandwidth allocation should both be capped at min_rate.
5980 auto rate_settings = fake_encoder_.GetAndResetLastRateControlSettings();
5981 ASSERT_TRUE(rate_settings.has_value());
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005982 DataRate allocation_sum =
5983 DataRate::BitsPerSec(rate_settings->bitrate.get_sum_bps());
Erik Språng5056af02019-09-02 15:53:11 +02005984 EXPECT_EQ(min_rate, allocation_sum);
5985 EXPECT_EQ(rate_settings->bandwidth_allocation, min_rate);
5986
5987 video_stream_encoder_->Stop();
5988}
5989
Rasmus Brandt5cad55b2019-12-19 09:47:11 +01005990TEST_F(VideoStreamEncoderTest, EncoderRatesPropagatedOnReconfigure) {
Henrik Boström381d1092020-05-12 18:49:07 +02005991 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005992 DataRate::BitsPerSec(kTargetBitrateBps),
5993 DataRate::BitsPerSec(kTargetBitrateBps),
5994 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Evan Shrubsolee32ae4f2019-09-25 12:50:23 +02005995 // Capture a frame and wait for it to synchronize with the encoder thread.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02005996 int64_t timestamp_ms = CurrentTimeMs();
Evan Shrubsolee32ae4f2019-09-25 12:50:23 +02005997 video_source_.IncomingCapturedFrame(CreateFrame(timestamp_ms, nullptr));
5998 WaitForEncodedFrame(1);
5999
6000 auto prev_rate_settings = fake_encoder_.GetAndResetLastRateControlSettings();
6001 ASSERT_TRUE(prev_rate_settings.has_value());
6002 EXPECT_EQ(static_cast<int>(prev_rate_settings->framerate_fps),
6003 kDefaultFramerate);
6004
6005 // Send 1s of video to ensure the framerate is stable at kDefaultFramerate.
6006 for (int i = 0; i < 2 * kDefaultFramerate; i++) {
6007 timestamp_ms += 1000 / kDefaultFramerate;
6008 video_source_.IncomingCapturedFrame(CreateFrame(timestamp_ms, nullptr));
6009 WaitForEncodedFrame(timestamp_ms);
6010 }
6011 EXPECT_EQ(static_cast<int>(fake_encoder_.GetLastFramerate()),
6012 kDefaultFramerate);
6013 // Capture larger frame to trigger a reconfigure.
6014 codec_height_ *= 2;
6015 codec_width_ *= 2;
6016 timestamp_ms += 1000 / kDefaultFramerate;
6017 video_source_.IncomingCapturedFrame(CreateFrame(timestamp_ms, nullptr));
6018 WaitForEncodedFrame(timestamp_ms);
6019
6020 EXPECT_EQ(2, sink_.number_of_reconfigurations());
6021 auto current_rate_settings =
6022 fake_encoder_.GetAndResetLastRateControlSettings();
6023 // Ensure we have actually reconfigured twice
6024 // The rate settings should have been set again even though
6025 // they haven't changed.
6026 ASSERT_TRUE(current_rate_settings.has_value());
Evan Shrubsole7c079f62019-09-26 09:55:03 +02006027 EXPECT_EQ(prev_rate_settings, current_rate_settings);
Evan Shrubsolee32ae4f2019-09-25 12:50:23 +02006028
6029 video_stream_encoder_->Stop();
6030}
6031
philipeld9cc8c02019-09-16 14:53:40 +02006032struct MockEncoderSwitchRequestCallback : public EncoderSwitchRequestCallback {
Danil Chapovalov91fdc602020-05-14 19:17:51 +02006033 MOCK_METHOD(void, RequestEncoderFallback, (), (override));
6034 MOCK_METHOD(void, RequestEncoderSwitch, (const Config& conf), (override));
6035 MOCK_METHOD(void,
6036 RequestEncoderSwitch,
6037 (const webrtc::SdpVideoFormat& format),
6038 (override));
philipeld9cc8c02019-09-16 14:53:40 +02006039};
6040
6041TEST_F(VideoStreamEncoderTest, BitrateEncoderSwitch) {
6042 constexpr int kDontCare = 100;
6043
6044 StrictMock<MockEncoderSwitchRequestCallback> switch_callback;
6045 video_send_config_.encoder_settings.encoder_switch_request_callback =
6046 &switch_callback;
6047 VideoEncoderConfig encoder_config = video_encoder_config_.Copy();
6048 encoder_config.codec_type = kVideoCodecVP8;
6049 webrtc::test::ScopedFieldTrials field_trial(
6050 "WebRTC-NetworkCondition-EncoderSwitch/"
6051 "codec_thresholds:VP8;100;-1|H264;-1;30000,"
6052 "to_codec:AV1,to_param:ping,to_value:pong,window:2.0/");
6053
6054 // Reset encoder for new configuration to take effect.
6055 ConfigureEncoder(std::move(encoder_config));
6056
6057 // Send one frame to trigger ReconfigureEncoder.
6058 video_source_.IncomingCapturedFrame(
6059 CreateFrame(kDontCare, kDontCare, kDontCare));
6060
6061 using Config = EncoderSwitchRequestCallback::Config;
philipel9b058032020-02-10 11:30:00 +01006062 EXPECT_CALL(switch_callback, RequestEncoderSwitch(Matcher<const Config&>(
6063 AllOf(Field(&Config::codec_name, "AV1"),
philipeld9cc8c02019-09-16 14:53:40 +02006064 Field(&Config::param, "ping"),
philipel9b058032020-02-10 11:30:00 +01006065 Field(&Config::value, "pong")))));
philipeld9cc8c02019-09-16 14:53:40 +02006066
Henrik Boström381d1092020-05-12 18:49:07 +02006067 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01006068 /*target_bitrate=*/DataRate::KilobitsPerSec(50),
6069 /*stable_target_bitrate=*/DataRate::KilobitsPerSec(kDontCare),
6070 /*link_allocation=*/DataRate::KilobitsPerSec(kDontCare),
philipeld9cc8c02019-09-16 14:53:40 +02006071 /*fraction_lost=*/0,
Ying Wang9b881ab2020-02-07 14:29:32 +01006072 /*rtt_ms=*/0,
6073 /*cwnd_reduce_ratio=*/0);
Tomas Gunnarssond41c2a62020-09-21 15:56:42 +02006074 AdvanceTime(TimeDelta::Millis(0));
philipeld9cc8c02019-09-16 14:53:40 +02006075
6076 video_stream_encoder_->Stop();
6077}
6078
Mirta Dvornicic5ed40cf2020-02-21 16:35:51 +01006079TEST_F(VideoStreamEncoderTest, VideoSuspendedNoEncoderSwitch) {
6080 constexpr int kDontCare = 100;
6081
6082 StrictMock<MockEncoderSwitchRequestCallback> switch_callback;
6083 video_send_config_.encoder_settings.encoder_switch_request_callback =
6084 &switch_callback;
6085 VideoEncoderConfig encoder_config = video_encoder_config_.Copy();
6086 encoder_config.codec_type = kVideoCodecVP8;
6087 webrtc::test::ScopedFieldTrials field_trial(
6088 "WebRTC-NetworkCondition-EncoderSwitch/"
6089 "codec_thresholds:VP8;100;-1|H264;-1;30000,"
6090 "to_codec:AV1,to_param:ping,to_value:pong,window:2.0/");
6091
6092 // Reset encoder for new configuration to take effect.
6093 ConfigureEncoder(std::move(encoder_config));
6094
6095 // Send one frame to trigger ReconfigureEncoder.
6096 video_source_.IncomingCapturedFrame(
6097 CreateFrame(kDontCare, kDontCare, kDontCare));
6098
6099 using Config = EncoderSwitchRequestCallback::Config;
6100 EXPECT_CALL(switch_callback, RequestEncoderSwitch(Matcher<const Config&>(_)))
6101 .Times(0);
6102
Henrik Boström381d1092020-05-12 18:49:07 +02006103 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Mirta Dvornicic5ed40cf2020-02-21 16:35:51 +01006104 /*target_bitrate=*/DataRate::KilobitsPerSec(0),
6105 /*stable_target_bitrate=*/DataRate::KilobitsPerSec(0),
6106 /*link_allocation=*/DataRate::KilobitsPerSec(kDontCare),
6107 /*fraction_lost=*/0,
6108 /*rtt_ms=*/0,
6109 /*cwnd_reduce_ratio=*/0);
6110
6111 video_stream_encoder_->Stop();
6112}
6113
philipeld9cc8c02019-09-16 14:53:40 +02006114TEST_F(VideoStreamEncoderTest, ResolutionEncoderSwitch) {
6115 constexpr int kSufficientBitrateToNotDrop = 1000;
6116 constexpr int kHighRes = 500;
6117 constexpr int kLowRes = 100;
6118
6119 StrictMock<MockEncoderSwitchRequestCallback> switch_callback;
6120 video_send_config_.encoder_settings.encoder_switch_request_callback =
6121 &switch_callback;
6122 webrtc::test::ScopedFieldTrials field_trial(
6123 "WebRTC-NetworkCondition-EncoderSwitch/"
6124 "codec_thresholds:VP8;120;-1|H264;-1;30000,"
6125 "to_codec:AV1,to_param:ping,to_value:pong,window:2.0/");
6126 VideoEncoderConfig encoder_config = video_encoder_config_.Copy();
6127 encoder_config.codec_type = kVideoCodecH264;
6128
6129 // Reset encoder for new configuration to take effect.
6130 ConfigureEncoder(std::move(encoder_config));
6131
6132 // The VideoStreamEncoder needs some bitrate before it can start encoding,
6133 // setting some bitrate so that subsequent calls to WaitForEncodedFrame does
6134 // not fail.
Henrik Boström381d1092020-05-12 18:49:07 +02006135 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01006136 /*target_bitrate=*/DataRate::KilobitsPerSec(kSufficientBitrateToNotDrop),
6137 /*stable_target_bitrate=*/
6138 DataRate::KilobitsPerSec(kSufficientBitrateToNotDrop),
6139 /*link_allocation=*/DataRate::KilobitsPerSec(kSufficientBitrateToNotDrop),
philipeld9cc8c02019-09-16 14:53:40 +02006140 /*fraction_lost=*/0,
Ying Wang9b881ab2020-02-07 14:29:32 +01006141 /*rtt_ms=*/0,
6142 /*cwnd_reduce_ratio=*/0);
philipeld9cc8c02019-09-16 14:53:40 +02006143
6144 // Send one frame to trigger ReconfigureEncoder.
6145 video_source_.IncomingCapturedFrame(CreateFrame(1, kHighRes, kHighRes));
6146 WaitForEncodedFrame(1);
6147
6148 using Config = EncoderSwitchRequestCallback::Config;
philipel9b058032020-02-10 11:30:00 +01006149 EXPECT_CALL(switch_callback, RequestEncoderSwitch(Matcher<const Config&>(
6150 AllOf(Field(&Config::codec_name, "AV1"),
philipeld9cc8c02019-09-16 14:53:40 +02006151 Field(&Config::param, "ping"),
philipel9b058032020-02-10 11:30:00 +01006152 Field(&Config::value, "pong")))));
philipeld9cc8c02019-09-16 14:53:40 +02006153
6154 video_source_.IncomingCapturedFrame(CreateFrame(2, kLowRes, kLowRes));
6155 WaitForEncodedFrame(2);
6156
6157 video_stream_encoder_->Stop();
6158}
6159
philipel9b058032020-02-10 11:30:00 +01006160TEST_F(VideoStreamEncoderTest, EncoderSelectorCurrentEncoderIsSignaled) {
6161 constexpr int kDontCare = 100;
6162 StrictMock<MockEncoderSelector> encoder_selector;
6163 auto encoder_factory = std::make_unique<test::VideoEncoderProxyFactory>(
6164 &fake_encoder_, &encoder_selector);
6165 video_send_config_.encoder_settings.encoder_factory = encoder_factory.get();
6166
6167 // Reset encoder for new configuration to take effect.
6168 ConfigureEncoder(video_encoder_config_.Copy());
6169
6170 EXPECT_CALL(encoder_selector, OnCurrentEncoder(_));
6171
6172 video_source_.IncomingCapturedFrame(
6173 CreateFrame(kDontCare, kDontCare, kDontCare));
6174 video_stream_encoder_->Stop();
6175
6176 // The encoders produces by the VideoEncoderProxyFactory have a pointer back
6177 // to it's factory, so in order for the encoder instance in the
6178 // |video_stream_encoder_| to be destroyed before the |encoder_factory| we
6179 // reset the |video_stream_encoder_| here.
6180 video_stream_encoder_.reset();
6181}
6182
6183TEST_F(VideoStreamEncoderTest, EncoderSelectorBitrateSwitch) {
6184 constexpr int kDontCare = 100;
6185
6186 NiceMock<MockEncoderSelector> encoder_selector;
6187 StrictMock<MockEncoderSwitchRequestCallback> switch_callback;
6188 video_send_config_.encoder_settings.encoder_switch_request_callback =
6189 &switch_callback;
6190 auto encoder_factory = std::make_unique<test::VideoEncoderProxyFactory>(
6191 &fake_encoder_, &encoder_selector);
6192 video_send_config_.encoder_settings.encoder_factory = encoder_factory.get();
6193
6194 // Reset encoder for new configuration to take effect.
6195 ConfigureEncoder(video_encoder_config_.Copy());
6196
Mirta Dvornicic4f34d782020-02-26 13:01:19 +01006197 ON_CALL(encoder_selector, OnAvailableBitrate(_))
philipel9b058032020-02-10 11:30:00 +01006198 .WillByDefault(Return(SdpVideoFormat("AV1")));
6199 EXPECT_CALL(switch_callback,
6200 RequestEncoderSwitch(Matcher<const SdpVideoFormat&>(
6201 Field(&SdpVideoFormat::name, "AV1"))));
6202
Henrik Boström381d1092020-05-12 18:49:07 +02006203 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01006204 /*target_bitrate=*/DataRate::KilobitsPerSec(50),
6205 /*stable_target_bitrate=*/DataRate::KilobitsPerSec(kDontCare),
6206 /*link_allocation=*/DataRate::KilobitsPerSec(kDontCare),
philipel9b058032020-02-10 11:30:00 +01006207 /*fraction_lost=*/0,
6208 /*rtt_ms=*/0,
6209 /*cwnd_reduce_ratio=*/0);
Tomas Gunnarssond41c2a62020-09-21 15:56:42 +02006210 AdvanceTime(TimeDelta::Millis(0));
philipel9b058032020-02-10 11:30:00 +01006211
6212 video_stream_encoder_->Stop();
6213}
6214
6215TEST_F(VideoStreamEncoderTest, EncoderSelectorBrokenEncoderSwitch) {
6216 constexpr int kSufficientBitrateToNotDrop = 1000;
6217 constexpr int kDontCare = 100;
6218
6219 NiceMock<MockVideoEncoder> video_encoder;
6220 NiceMock<MockEncoderSelector> encoder_selector;
6221 StrictMock<MockEncoderSwitchRequestCallback> switch_callback;
6222 video_send_config_.encoder_settings.encoder_switch_request_callback =
6223 &switch_callback;
6224 auto encoder_factory = std::make_unique<test::VideoEncoderProxyFactory>(
6225 &video_encoder, &encoder_selector);
6226 video_send_config_.encoder_settings.encoder_factory = encoder_factory.get();
6227
6228 // Reset encoder for new configuration to take effect.
6229 ConfigureEncoder(video_encoder_config_.Copy());
6230
6231 // The VideoStreamEncoder needs some bitrate before it can start encoding,
6232 // setting some bitrate so that subsequent calls to WaitForEncodedFrame does
6233 // not fail.
Henrik Boström381d1092020-05-12 18:49:07 +02006234 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01006235 /*target_bitrate=*/DataRate::KilobitsPerSec(kSufficientBitrateToNotDrop),
6236 /*stable_target_bitrate=*/
6237 DataRate::KilobitsPerSec(kSufficientBitrateToNotDrop),
6238 /*link_allocation=*/DataRate::KilobitsPerSec(kSufficientBitrateToNotDrop),
philipel9b058032020-02-10 11:30:00 +01006239 /*fraction_lost=*/0,
6240 /*rtt_ms=*/0,
6241 /*cwnd_reduce_ratio=*/0);
6242
6243 ON_CALL(video_encoder, Encode(_, _))
6244 .WillByDefault(Return(WEBRTC_VIDEO_CODEC_ENCODER_FAILURE));
6245 ON_CALL(encoder_selector, OnEncoderBroken())
6246 .WillByDefault(Return(SdpVideoFormat("AV2")));
6247
6248 rtc::Event encode_attempted;
6249 EXPECT_CALL(switch_callback,
6250 RequestEncoderSwitch(Matcher<const SdpVideoFormat&>(_)))
6251 .WillOnce([&encode_attempted](const SdpVideoFormat& format) {
6252 EXPECT_EQ(format.name, "AV2");
6253 encode_attempted.Set();
6254 });
6255
6256 video_source_.IncomingCapturedFrame(CreateFrame(1, kDontCare, kDontCare));
6257 encode_attempted.Wait(3000);
6258
Tomas Gunnarssond41c2a62020-09-21 15:56:42 +02006259 AdvanceTime(TimeDelta::Millis(0));
6260
philipel9b058032020-02-10 11:30:00 +01006261 video_stream_encoder_->Stop();
6262
6263 // The encoders produces by the VideoEncoderProxyFactory have a pointer back
6264 // to it's factory, so in order for the encoder instance in the
6265 // |video_stream_encoder_| to be destroyed before the |encoder_factory| we
6266 // reset the |video_stream_encoder_| here.
6267 video_stream_encoder_.reset();
6268}
6269
Evan Shrubsole7c079f62019-09-26 09:55:03 +02006270TEST_F(VideoStreamEncoderTest,
Rasmus Brandt5cad55b2019-12-19 09:47:11 +01006271 AllocationPropagatedToEncoderWhenTargetRateChanged) {
Evan Shrubsole7c079f62019-09-26 09:55:03 +02006272 const int kFrameWidth = 320;
6273 const int kFrameHeight = 180;
6274
6275 // Set initial rate.
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01006276 auto rate = DataRate::KilobitsPerSec(100);
Henrik Boström381d1092020-05-12 18:49:07 +02006277 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Evan Shrubsole7c079f62019-09-26 09:55:03 +02006278 /*target_bitrate=*/rate,
6279 /*stable_target_bitrate=*/rate,
6280 /*link_allocation=*/rate,
6281 /*fraction_lost=*/0,
Ying Wang9b881ab2020-02-07 14:29:32 +01006282 /*rtt_ms=*/0,
6283 /*cwnd_reduce_ratio=*/0);
Evan Shrubsole7c079f62019-09-26 09:55:03 +02006284
6285 // Insert a first video frame so that encoder gets configured.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02006286 int64_t timestamp_ms = CurrentTimeMs();
Evan Shrubsole7c079f62019-09-26 09:55:03 +02006287 VideoFrame frame = CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight);
6288 frame.set_rotation(kVideoRotation_270);
6289 video_source_.IncomingCapturedFrame(frame);
6290 WaitForEncodedFrame(timestamp_ms);
6291 EXPECT_EQ(1, fake_encoder_.GetNumSetRates());
6292
6293 // Change of target bitrate propagates to the encoder.
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01006294 auto new_stable_rate = rate - DataRate::KilobitsPerSec(5);
Henrik Boström381d1092020-05-12 18:49:07 +02006295 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Evan Shrubsole7c079f62019-09-26 09:55:03 +02006296 /*target_bitrate=*/new_stable_rate,
6297 /*stable_target_bitrate=*/new_stable_rate,
6298 /*link_allocation=*/rate,
6299 /*fraction_lost=*/0,
Ying Wang9b881ab2020-02-07 14:29:32 +01006300 /*rtt_ms=*/0,
6301 /*cwnd_reduce_ratio=*/0);
Evan Shrubsole7c079f62019-09-26 09:55:03 +02006302 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
6303 EXPECT_EQ(2, fake_encoder_.GetNumSetRates());
6304 video_stream_encoder_->Stop();
6305}
6306
6307TEST_F(VideoStreamEncoderTest,
Rasmus Brandt5cad55b2019-12-19 09:47:11 +01006308 AllocationNotPropagatedToEncoderWhenTargetRateUnchanged) {
Evan Shrubsole7c079f62019-09-26 09:55:03 +02006309 const int kFrameWidth = 320;
6310 const int kFrameHeight = 180;
6311
6312 // Set initial rate.
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01006313 auto rate = DataRate::KilobitsPerSec(100);
Henrik Boström381d1092020-05-12 18:49:07 +02006314 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Evan Shrubsole7c079f62019-09-26 09:55:03 +02006315 /*target_bitrate=*/rate,
6316 /*stable_target_bitrate=*/rate,
6317 /*link_allocation=*/rate,
6318 /*fraction_lost=*/0,
Ying Wang9b881ab2020-02-07 14:29:32 +01006319 /*rtt_ms=*/0,
6320 /*cwnd_reduce_ratio=*/0);
Evan Shrubsole7c079f62019-09-26 09:55:03 +02006321
6322 // Insert a first video frame so that encoder gets configured.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02006323 int64_t timestamp_ms = CurrentTimeMs();
Evan Shrubsole7c079f62019-09-26 09:55:03 +02006324 VideoFrame frame = CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight);
6325 frame.set_rotation(kVideoRotation_270);
6326 video_source_.IncomingCapturedFrame(frame);
6327 WaitForEncodedFrame(timestamp_ms);
6328 EXPECT_EQ(1, fake_encoder_.GetNumSetRates());
6329
6330 // Set a higher target rate without changing the link_allocation. Should not
6331 // reset encoder's rate.
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01006332 auto new_stable_rate = rate - DataRate::KilobitsPerSec(5);
Henrik Boström381d1092020-05-12 18:49:07 +02006333 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Evan Shrubsole7c079f62019-09-26 09:55:03 +02006334 /*target_bitrate=*/rate,
6335 /*stable_target_bitrate=*/new_stable_rate,
6336 /*link_allocation=*/rate,
6337 /*fraction_lost=*/0,
Ying Wang9b881ab2020-02-07 14:29:32 +01006338 /*rtt_ms=*/0,
6339 /*cwnd_reduce_ratio=*/0);
Evan Shrubsole7c079f62019-09-26 09:55:03 +02006340 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
6341 EXPECT_EQ(1, fake_encoder_.GetNumSetRates());
6342 video_stream_encoder_->Stop();
6343}
6344
Ilya Nikolaevskiy648b9d72019-12-03 16:54:17 +01006345TEST_F(VideoStreamEncoderTest, AutomaticAnimationDetection) {
6346 test::ScopedFieldTrials field_trials(
6347 "WebRTC-AutomaticAnimationDetectionScreenshare/"
6348 "enabled:true,min_fps:20,min_duration_ms:1000,min_area_ratio:0.8/");
6349 const int kFramerateFps = 30;
6350 const int kWidth = 1920;
6351 const int kHeight = 1080;
6352 const int kNumFrames = 2 * kFramerateFps; // >1 seconds of frames.
6353 // Works on screenshare mode.
6354 ResetEncoder("VP8", 1, 1, 1, /*screenshare*/ true);
6355 // We rely on the automatic resolution adaptation, but we handle framerate
6356 // adaptation manually by mocking the stats proxy.
6357 video_source_.set_adaptation_enabled(true);
6358
6359 // BALANCED degradation preference is required for this feature.
Henrik Boström381d1092020-05-12 18:49:07 +02006360 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01006361 DataRate::BitsPerSec(kTargetBitrateBps),
6362 DataRate::BitsPerSec(kTargetBitrateBps),
6363 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Ilya Nikolaevskiy648b9d72019-12-03 16:54:17 +01006364 video_stream_encoder_->SetSource(&video_source_,
6365 webrtc::DegradationPreference::BALANCED);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02006366 EXPECT_THAT(video_source_.sink_wants(), UnlimitedSinkWants());
Ilya Nikolaevskiy648b9d72019-12-03 16:54:17 +01006367
6368 VideoFrame frame = CreateFrame(1, kWidth, kHeight);
6369 frame.set_update_rect(VideoFrame::UpdateRect{0, 0, kWidth, kHeight});
6370
6371 // Pass enough frames with the full update to trigger animation detection.
6372 for (int i = 0; i < kNumFrames; ++i) {
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02006373 int64_t timestamp_ms = CurrentTimeMs();
Ilya Nikolaevskiy648b9d72019-12-03 16:54:17 +01006374 frame.set_ntp_time_ms(timestamp_ms);
6375 frame.set_timestamp_us(timestamp_ms * 1000);
6376 video_source_.IncomingCapturedFrame(frame);
6377 WaitForEncodedFrame(timestamp_ms);
6378 }
6379
6380 // Resolution should be limited.
6381 rtc::VideoSinkWants expected;
6382 expected.max_framerate_fps = kFramerateFps;
6383 expected.max_pixel_count = 1280 * 720 + 1;
Evan Shrubsole5fd40602020-05-25 16:19:54 +02006384 EXPECT_THAT(video_source_.sink_wants(), FpsEqResolutionLt(expected));
Ilya Nikolaevskiy648b9d72019-12-03 16:54:17 +01006385
6386 // Pass one frame with no known update.
6387 // Resolution cap should be removed immediately.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02006388 int64_t timestamp_ms = CurrentTimeMs();
Ilya Nikolaevskiy648b9d72019-12-03 16:54:17 +01006389 frame.set_ntp_time_ms(timestamp_ms);
6390 frame.set_timestamp_us(timestamp_ms * 1000);
6391 frame.clear_update_rect();
6392
6393 video_source_.IncomingCapturedFrame(frame);
6394 WaitForEncodedFrame(timestamp_ms);
6395
6396 // Resolution should be unlimited now.
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02006397 EXPECT_THAT(video_source_.sink_wants(),
6398 FpsMatchesResolutionMax(Eq(kFramerateFps)));
Ilya Nikolaevskiy648b9d72019-12-03 16:54:17 +01006399
6400 video_stream_encoder_->Stop();
6401}
6402
Ilya Nikolaevskiy09eb6e22020-06-05 12:36:32 +02006403TEST_F(VideoStreamEncoderTest, ConfiguresVp9SvcAtOddResolutions) {
6404 const int kWidth = 720; // 540p adapted down.
6405 const int kHeight = 405;
6406 const int kNumFrames = 3;
6407 // Works on screenshare mode.
6408 ResetEncoder("VP9", /*num_streams=*/1, /*num_temporal_layers=*/1,
6409 /*num_spatial_layers=*/2, /*screenshare=*/true);
6410
6411 video_source_.set_adaptation_enabled(true);
6412
6413 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
6414 DataRate::BitsPerSec(kTargetBitrateBps),
6415 DataRate::BitsPerSec(kTargetBitrateBps),
6416 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
6417
6418 VideoFrame frame = CreateFrame(1, kWidth, kHeight);
6419
6420 // Pass enough frames with the full update to trigger animation detection.
6421 for (int i = 0; i < kNumFrames; ++i) {
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02006422 int64_t timestamp_ms = CurrentTimeMs();
Ilya Nikolaevskiy09eb6e22020-06-05 12:36:32 +02006423 frame.set_ntp_time_ms(timestamp_ms);
6424 frame.set_timestamp_us(timestamp_ms * 1000);
6425 video_source_.IncomingCapturedFrame(frame);
6426 WaitForEncodedFrame(timestamp_ms);
6427 }
6428
6429 video_stream_encoder_->Stop();
6430}
6431
Yun Zhang1e4d4fd2020-09-30 00:22:46 -07006432TEST_F(VideoStreamEncoderTest, EncoderResetAccordingToParameterChange) {
6433 const float downscale_factors[] = {4.0, 2.0, 1.0};
6434 const int number_layers =
6435 sizeof(downscale_factors) / sizeof(downscale_factors[0]);
6436 VideoEncoderConfig config;
6437 test::FillEncoderConfiguration(kVideoCodecVP8, number_layers, &config);
6438 for (int i = 0; i < number_layers; ++i) {
6439 config.simulcast_layers[i].scale_resolution_down_by = downscale_factors[i];
6440 config.simulcast_layers[i].active = true;
6441 }
6442 config.video_stream_factory =
6443 new rtc::RefCountedObject<cricket::EncoderStreamFactory>(
6444 "VP8", /*max qp*/ 56, /*screencast*/ false,
6445 /*screenshare enabled*/ false);
6446 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
6447 DataRate::BitsPerSec(kSimulcastTargetBitrateBps),
6448 DataRate::BitsPerSec(kSimulcastTargetBitrateBps),
6449 DataRate::BitsPerSec(kSimulcastTargetBitrateBps), 0, 0, 0);
6450
6451 // First initialization.
6452 // Encoder should be initialized. Next frame should be key frame.
6453 video_stream_encoder_->ConfigureEncoder(config.Copy(), kMaxPayloadLength);
6454 sink_.SetNumExpectedLayers(number_layers);
6455 int64_t timestamp_ms = kFrameIntervalMs;
6456 video_source_.IncomingCapturedFrame(CreateFrame(timestamp_ms, 1280, 720));
6457 WaitForEncodedFrame(timestamp_ms);
6458 EXPECT_EQ(1, fake_encoder_.GetNumEncoderInitializations());
6459 EXPECT_THAT(fake_encoder_.LastFrameTypes(),
6460 ::testing::ElementsAreArray({VideoFrameType::kVideoFrameKey,
6461 VideoFrameType::kVideoFrameKey,
6462 VideoFrameType::kVideoFrameKey}));
6463
6464 // Disable top layer.
6465 // Encoder shouldn't be re-initialized. Next frame should be delta frame.
6466 config.simulcast_layers[number_layers - 1].active = false;
6467 video_stream_encoder_->ConfigureEncoder(config.Copy(), kMaxPayloadLength);
6468 sink_.SetNumExpectedLayers(number_layers - 1);
6469 timestamp_ms += kFrameIntervalMs;
6470 video_source_.IncomingCapturedFrame(CreateFrame(timestamp_ms, 1280, 720));
6471 WaitForEncodedFrame(timestamp_ms);
6472 EXPECT_EQ(1, fake_encoder_.GetNumEncoderInitializations());
6473 EXPECT_THAT(fake_encoder_.LastFrameTypes(),
6474 ::testing::ElementsAreArray({VideoFrameType::kVideoFrameDelta,
6475 VideoFrameType::kVideoFrameDelta,
6476 VideoFrameType::kVideoFrameDelta}));
6477
6478 // Re-enable top layer.
6479 // Encoder should be re-initialized. Next frame should be key frame.
6480 config.simulcast_layers[number_layers - 1].active = true;
6481 video_stream_encoder_->ConfigureEncoder(config.Copy(), kMaxPayloadLength);
6482 sink_.SetNumExpectedLayers(number_layers);
6483 timestamp_ms += kFrameIntervalMs;
6484 video_source_.IncomingCapturedFrame(CreateFrame(timestamp_ms, 1280, 720));
6485 WaitForEncodedFrame(timestamp_ms);
6486 EXPECT_EQ(2, fake_encoder_.GetNumEncoderInitializations());
6487 EXPECT_THAT(fake_encoder_.LastFrameTypes(),
6488 ::testing::ElementsAreArray({VideoFrameType::kVideoFrameKey,
6489 VideoFrameType::kVideoFrameKey,
6490 VideoFrameType::kVideoFrameKey}));
6491
6492 // Top layer max rate change.
6493 // Encoder shouldn't be re-initialized. Next frame should be delta frame.
6494 config.simulcast_layers[number_layers - 1].max_bitrate_bps -= 100;
6495 video_stream_encoder_->ConfigureEncoder(config.Copy(), kMaxPayloadLength);
6496 sink_.SetNumExpectedLayers(number_layers);
6497 timestamp_ms += kFrameIntervalMs;
6498 video_source_.IncomingCapturedFrame(CreateFrame(timestamp_ms, 1280, 720));
6499 WaitForEncodedFrame(timestamp_ms);
6500 EXPECT_EQ(2, fake_encoder_.GetNumEncoderInitializations());
6501 EXPECT_THAT(fake_encoder_.LastFrameTypes(),
6502 ::testing::ElementsAreArray({VideoFrameType::kVideoFrameDelta,
6503 VideoFrameType::kVideoFrameDelta,
6504 VideoFrameType::kVideoFrameDelta}));
6505
6506 // Top layer resolution change.
6507 // Encoder should be re-initialized. Next frame should be key frame.
6508 config.simulcast_layers[number_layers - 1].scale_resolution_down_by += 0.1;
6509 video_stream_encoder_->ConfigureEncoder(config.Copy(), kMaxPayloadLength);
6510 sink_.SetNumExpectedLayers(number_layers);
6511 timestamp_ms += kFrameIntervalMs;
6512 video_source_.IncomingCapturedFrame(CreateFrame(timestamp_ms, 1280, 720));
6513 WaitForEncodedFrame(timestamp_ms);
6514 EXPECT_EQ(3, fake_encoder_.GetNumEncoderInitializations());
6515 EXPECT_THAT(fake_encoder_.LastFrameTypes(),
6516 ::testing::ElementsAreArray({VideoFrameType::kVideoFrameKey,
6517 VideoFrameType::kVideoFrameKey,
6518 VideoFrameType::kVideoFrameKey}));
6519 video_stream_encoder_->Stop();
6520}
6521
perkj26091b12016-09-01 01:17:40 -07006522} // namespace webrtc