blob: cb73fac842ff83ba19745d46a62997c0dbecdd27 [file] [log] [blame]
perkj26091b12016-09-01 01:17:40 -07001/*
2 * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
Erik Språng4529fbc2018-10-12 10:30:31 +020011#include "video/video_stream_encoder.h"
12
sprangfe627f32017-03-29 08:24:59 -070013#include <algorithm>
perkj803d97f2016-11-01 11:45:46 -070014#include <limits>
Danil Chapovalovd3ba2362019-04-10 17:01:23 +020015#include <memory>
Per512ecb32016-09-23 15:52:06 +020016#include <utility>
17
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +020018#include "absl/memory/memory.h"
Danil Chapovalovd3ba2362019-04-10 17:01:23 +020019#include "api/task_queue/default_task_queue_factory.h"
Elad Alon45befc52019-07-02 11:20:09 +020020#include "api/test/mock_fec_controller_override.h"
philipel9b058032020-02-10 11:30:00 +010021#include "api/test/mock_video_encoder.h"
Jiawei Ouc2ebe212018-11-08 10:02:56 -080022#include "api/video/builtin_video_bitrate_allocator_factory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020023#include "api/video/i420_buffer.h"
Evan Shrubsole895556e2020-10-05 09:15:13 +020024#include "api/video/nv12_buffer.h"
Evan Shrubsolece0a11d2020-04-16 11:36:55 +020025#include "api/video/video_adaptation_reason.h"
Erik Språngf93eda12019-01-16 17:10:57 +010026#include "api/video/video_bitrate_allocation.h"
Elad Alon370f93a2019-06-11 14:57:57 +020027#include "api/video_codecs/video_encoder.h"
Erik Språng4529fbc2018-10-12 10:30:31 +020028#include "api/video_codecs/vp8_temporal_layers.h"
Elad Aloncde8ab22019-03-20 11:56:20 +010029#include "api/video_codecs/vp8_temporal_layers_factory.h"
Henrik Boström0f0aa9c2020-06-02 13:02:36 +020030#include "call/adaptation/test/fake_adaptation_constraint.h"
Evan Shrubsoleaa6fbc12020-02-25 16:26:01 +010031#include "call/adaptation/test/fake_resource.h"
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +020032#include "common_video/h264/h264_common.h"
Noah Richards51db4212019-06-12 06:59:12 -070033#include "common_video/include/video_frame_buffer.h"
Steve Anton10542f22019-01-11 09:11:00 -080034#include "media/base/video_adapter.h"
Åsa Perssonc5a74ff2020-09-20 17:50:00 +020035#include "media/engine/webrtc_video_engine.h"
Sergey Silkin86684962018-03-28 19:32:37 +020036#include "modules/video_coding/codecs/vp9/include/vp9_globals.h"
Henrik Boström91aa7322020-04-28 12:24:33 +020037#include "modules/video_coding/utility/quality_scaler.h"
Åsa Perssonc29cb2c2019-03-25 12:06:59 +010038#include "modules/video_coding/utility/simulcast_rate_allocator.h"
Tomas Gunnarsson612445e2020-09-21 14:31:23 +020039#include "rtc_base/event.h"
Henrik Boström2671dac2020-05-19 16:29:09 +020040#include "rtc_base/gunit.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020041#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 09:11:00 -080042#include "rtc_base/ref_counted_object.h"
Markus Handella3765182020-07-08 13:13:32 +020043#include "rtc_base/synchronization/mutex.h"
Erik Språng7ca375c2019-02-06 16:20:17 +010044#include "system_wrappers/include/field_trial.h"
Mirko Bonadei17f48782018-09-28 08:51:10 +020045#include "system_wrappers/include/metrics.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020046#include "system_wrappers/include/sleep.h"
47#include "test/encoder_settings.h"
48#include "test/fake_encoder.h"
Kári Tristan Helgason639602a2018-08-02 10:51:40 +020049#include "test/field_trial.h"
Artem Titov33f9d2b2019-12-05 15:59:00 +010050#include "test/frame_forwarder.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020051#include "test/gmock.h"
52#include "test/gtest.h"
Tomas Gunnarsson612445e2020-09-21 14:31:23 +020053#include "test/time_controller/simulated_time_controller.h"
Niels Möllercbcbc222018-09-28 09:07:24 +020054#include "test/video_encoder_proxy_factory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020055#include "video/send_statistics_proxy.h"
perkj26091b12016-09-01 01:17:40 -070056
57namespace webrtc {
58
sprang57c2fff2017-01-16 06:24:02 -080059using ::testing::_;
philipeld9cc8c02019-09-16 14:53:40 +020060using ::testing::AllOf;
Per Kjellanderd0a8f512020-10-07 11:28:41 +020061using ::testing::AtLeast;
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +020062using ::testing::Eq;
philipeld9cc8c02019-09-16 14:53:40 +020063using ::testing::Field;
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +020064using ::testing::Ge;
65using ::testing::Gt;
66using ::testing::Le;
67using ::testing::Lt;
philipel9b058032020-02-10 11:30:00 +010068using ::testing::Matcher;
69using ::testing::NiceMock;
70using ::testing::Return;
philipeld9cc8c02019-09-16 14:53:40 +020071using ::testing::StrictMock;
kthelgason876222f2016-11-29 01:44:11 -080072
perkj803d97f2016-11-01 11:45:46 -070073namespace {
Åsa Persson8c1bf952018-09-13 10:42:19 +020074const int kMinPixelsPerFrame = 320 * 180;
Åsa Perssone644a032019-11-08 15:56:00 +010075const int kQpLow = 1;
76const int kQpHigh = 2;
Åsa Persson8c1bf952018-09-13 10:42:19 +020077const int kMinFramerateFps = 2;
78const int kMinBalancedFramerateFps = 7;
79const int64_t kFrameTimeoutMs = 100;
asapersson5f7226f2016-11-25 04:37:00 -080080const size_t kMaxPayloadLength = 1440;
Erik Språngd7329ca2019-02-21 21:19:53 +010081const uint32_t kTargetBitrateBps = 1000000;
Sergey Silkin5ee69672019-07-02 14:18:34 +020082const uint32_t kStartBitrateBps = 600000;
Erik Språngd7329ca2019-02-21 21:19:53 +010083const uint32_t kSimulcastTargetBitrateBps = 3150000;
84const uint32_t kLowTargetBitrateBps = kTargetBitrateBps / 10;
kthelgason2bc68642017-02-07 07:02:22 -080085const int kMaxInitialFramedrop = 4;
sprangfda496a2017-06-15 04:21:07 -070086const int kDefaultFramerate = 30;
Åsa Persson8c1bf952018-09-13 10:42:19 +020087const int64_t kFrameIntervalMs = rtc::kNumMillisecsPerSec / kDefaultFramerate;
Niels Möllerfe407b72019-09-10 10:48:48 +020088const int64_t kProcessIntervalMs = 1000;
Sergey Silkin41c650b2019-10-14 13:12:19 +020089const VideoEncoder::ResolutionBitrateLimits
90 kEncoderBitrateLimits540p(960 * 540, 100 * 1000, 100 * 1000, 2000 * 1000);
91const VideoEncoder::ResolutionBitrateLimits
92 kEncoderBitrateLimits720p(1280 * 720, 200 * 1000, 200 * 1000, 4000 * 1000);
asapersson5f7226f2016-11-25 04:37:00 -080093
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +020094uint8_t optimal_sps[] = {0, 0, 0, 1, H264::NaluType::kSps,
95 0x00, 0x00, 0x03, 0x03, 0xF4,
96 0x05, 0x03, 0xC7, 0xE0, 0x1B,
97 0x41, 0x10, 0x8D, 0x00};
98
perkj803d97f2016-11-01 11:45:46 -070099class TestBuffer : public webrtc::I420Buffer {
100 public:
101 TestBuffer(rtc::Event* event, int width, int height)
102 : I420Buffer(width, height), event_(event) {}
103
104 private:
105 friend class rtc::RefCountedObject<TestBuffer>;
106 ~TestBuffer() override {
107 if (event_)
108 event_->Set();
109 }
110 rtc::Event* const event_;
111};
112
Noah Richards51db4212019-06-12 06:59:12 -0700113// A fake native buffer that can't be converted to I420.
114class FakeNativeBuffer : public webrtc::VideoFrameBuffer {
115 public:
116 FakeNativeBuffer(rtc::Event* event, int width, int height)
117 : event_(event), width_(width), height_(height) {}
118 webrtc::VideoFrameBuffer::Type type() const override { return Type::kNative; }
119 int width() const override { return width_; }
120 int height() const override { return height_; }
121 rtc::scoped_refptr<webrtc::I420BufferInterface> ToI420() override {
122 return nullptr;
123 }
124
125 private:
126 friend class rtc::RefCountedObject<FakeNativeBuffer>;
127 ~FakeNativeBuffer() override {
128 if (event_)
129 event_->Set();
130 }
131 rtc::Event* const event_;
132 const int width_;
133 const int height_;
134};
135
Evan Shrubsole895556e2020-10-05 09:15:13 +0200136// A fake native buffer that is backed by an NV12 buffer.
137class FakeNV12NativeBuffer : public webrtc::VideoFrameBuffer {
138 public:
139 FakeNV12NativeBuffer(rtc::Event* event, int width, int height)
140 : nv12_buffer_(NV12Buffer::Create(width, height)), event_(event) {}
141
142 webrtc::VideoFrameBuffer::Type type() const override { return Type::kNative; }
143 int width() const override { return nv12_buffer_->width(); }
144 int height() const override { return nv12_buffer_->height(); }
145 rtc::scoped_refptr<webrtc::I420BufferInterface> ToI420() override {
146 return nv12_buffer_->ToI420();
147 }
Evan Shrubsoleb556b082020-10-08 14:56:45 +0200148 rtc::scoped_refptr<VideoFrameBuffer> GetMappedFrameBuffer(
149 rtc::ArrayView<VideoFrameBuffer::Type> types) override {
150 if (absl::c_find(types, Type::kNV12) != types.end()) {
151 return nv12_buffer_;
152 }
153 return nullptr;
154 }
Evan Shrubsole895556e2020-10-05 09:15:13 +0200155 const NV12BufferInterface* GetNV12() const { return nv12_buffer_; }
156
157 private:
158 friend class rtc::RefCountedObject<FakeNV12NativeBuffer>;
159 ~FakeNV12NativeBuffer() override {
160 if (event_)
161 event_->Set();
162 }
163 rtc::scoped_refptr<NV12Buffer> nv12_buffer_;
164 rtc::Event* const event_;
165};
166
Niels Möller7dc26b72017-12-06 10:27:48 +0100167class CpuOveruseDetectorProxy : public OveruseFrameDetector {
168 public:
Niels Möllerd1f7eb62018-03-28 16:40:58 +0200169 explicit CpuOveruseDetectorProxy(CpuOveruseMetricsObserver* metrics_observer)
170 : OveruseFrameDetector(metrics_observer),
Henrik Boström381d1092020-05-12 18:49:07 +0200171 last_target_framerate_fps_(-1),
172 framerate_updated_event_(true /* manual_reset */,
173 false /* initially_signaled */) {}
Niels Möller7dc26b72017-12-06 10:27:48 +0100174 virtual ~CpuOveruseDetectorProxy() {}
175
176 void OnTargetFramerateUpdated(int framerate_fps) override {
Markus Handella3765182020-07-08 13:13:32 +0200177 MutexLock lock(&lock_);
Niels Möller7dc26b72017-12-06 10:27:48 +0100178 last_target_framerate_fps_ = framerate_fps;
179 OveruseFrameDetector::OnTargetFramerateUpdated(framerate_fps);
Henrik Boström381d1092020-05-12 18:49:07 +0200180 framerate_updated_event_.Set();
Niels Möller7dc26b72017-12-06 10:27:48 +0100181 }
182
183 int GetLastTargetFramerate() {
Markus Handella3765182020-07-08 13:13:32 +0200184 MutexLock lock(&lock_);
Niels Möller7dc26b72017-12-06 10:27:48 +0100185 return last_target_framerate_fps_;
186 }
187
Niels Möller4db138e2018-04-19 09:04:13 +0200188 CpuOveruseOptions GetOptions() { return options_; }
189
Henrik Boström381d1092020-05-12 18:49:07 +0200190 rtc::Event* framerate_updated_event() { return &framerate_updated_event_; }
191
Niels Möller7dc26b72017-12-06 10:27:48 +0100192 private:
Markus Handella3765182020-07-08 13:13:32 +0200193 Mutex lock_;
Niels Möller7dc26b72017-12-06 10:27:48 +0100194 int last_target_framerate_fps_ RTC_GUARDED_BY(lock_);
Henrik Boström381d1092020-05-12 18:49:07 +0200195 rtc::Event framerate_updated_event_;
Niels Möller7dc26b72017-12-06 10:27:48 +0100196};
197
Henrik Boström0f0aa9c2020-06-02 13:02:36 +0200198class FakeVideoSourceRestrictionsListener
199 : public VideoSourceRestrictionsListener {
Henrik Boström381d1092020-05-12 18:49:07 +0200200 public:
Henrik Boström0f0aa9c2020-06-02 13:02:36 +0200201 FakeVideoSourceRestrictionsListener()
Henrik Boström381d1092020-05-12 18:49:07 +0200202 : was_restrictions_updated_(false), restrictions_updated_event_() {}
Henrik Boström0f0aa9c2020-06-02 13:02:36 +0200203 ~FakeVideoSourceRestrictionsListener() override {
Henrik Boström381d1092020-05-12 18:49:07 +0200204 RTC_DCHECK(was_restrictions_updated_);
205 }
206
207 rtc::Event* restrictions_updated_event() {
208 return &restrictions_updated_event_;
209 }
210
Henrik Boström0f0aa9c2020-06-02 13:02:36 +0200211 // VideoSourceRestrictionsListener implementation.
Henrik Boström381d1092020-05-12 18:49:07 +0200212 void OnVideoSourceRestrictionsUpdated(
213 VideoSourceRestrictions restrictions,
214 const VideoAdaptationCounters& adaptation_counters,
Evan Shrubsoleec0af262020-07-01 11:47:46 +0200215 rtc::scoped_refptr<Resource> reason,
216 const VideoSourceRestrictions& unfiltered_restrictions) override {
Henrik Boström381d1092020-05-12 18:49:07 +0200217 was_restrictions_updated_ = true;
218 restrictions_updated_event_.Set();
219 }
220
221 private:
222 bool was_restrictions_updated_;
223 rtc::Event restrictions_updated_event_;
224};
225
Evan Shrubsole5fd40602020-05-25 16:19:54 +0200226auto WantsFps(Matcher<int> fps_matcher) {
227 return Field("max_framerate_fps", &rtc::VideoSinkWants::max_framerate_fps,
228 fps_matcher);
229}
230
231auto WantsMaxPixels(Matcher<int> max_pixel_matcher) {
232 return Field("max_pixel_count", &rtc::VideoSinkWants::max_pixel_count,
233 AllOf(max_pixel_matcher, Gt(0)));
234}
235
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +0200236auto ResolutionMax() {
237 return AllOf(
Evan Shrubsole5fd40602020-05-25 16:19:54 +0200238 WantsMaxPixels(Eq(std::numeric_limits<int>::max())),
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +0200239 Field("target_pixel_count", &rtc::VideoSinkWants::target_pixel_count,
240 Eq(absl::nullopt)));
241}
242
243auto FpsMax() {
Evan Shrubsole5fd40602020-05-25 16:19:54 +0200244 return WantsFps(Eq(kDefaultFramerate));
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +0200245}
246
247auto FpsUnlimited() {
Evan Shrubsole5fd40602020-05-25 16:19:54 +0200248 return WantsFps(Eq(std::numeric_limits<int>::max()));
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +0200249}
250
251auto FpsMatchesResolutionMax(Matcher<int> fps_matcher) {
Evan Shrubsole5fd40602020-05-25 16:19:54 +0200252 return AllOf(WantsFps(fps_matcher), ResolutionMax());
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +0200253}
254
255auto FpsMaxResolutionMatches(Matcher<int> pixel_matcher) {
Evan Shrubsole5fd40602020-05-25 16:19:54 +0200256 return AllOf(FpsMax(), WantsMaxPixels(pixel_matcher));
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +0200257}
258
259auto FpsMaxResolutionMax() {
260 return AllOf(FpsMax(), ResolutionMax());
261}
262
263auto UnlimitedSinkWants() {
264 return AllOf(FpsUnlimited(), ResolutionMax());
265}
266
267auto FpsInRangeForPixelsInBalanced(int last_frame_pixels) {
268 Matcher<int> fps_range_matcher;
269
270 if (last_frame_pixels <= 320 * 240) {
271 fps_range_matcher = AllOf(Ge(7), Le(10));
Åsa Perssonc5a74ff2020-09-20 17:50:00 +0200272 } else if (last_frame_pixels <= 480 * 360) {
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +0200273 fps_range_matcher = AllOf(Ge(10), Le(15));
274 } else if (last_frame_pixels <= 640 * 480) {
275 fps_range_matcher = Ge(15);
276 } else {
277 fps_range_matcher = Eq(kDefaultFramerate);
278 }
279 return Field("max_framerate_fps", &rtc::VideoSinkWants::max_framerate_fps,
280 fps_range_matcher);
281}
282
Evan Shrubsole5fd40602020-05-25 16:19:54 +0200283auto FpsEqResolutionEqTo(const rtc::VideoSinkWants& other_wants) {
284 return AllOf(WantsFps(Eq(other_wants.max_framerate_fps)),
285 WantsMaxPixels(Eq(other_wants.max_pixel_count)));
286}
287
288auto FpsMaxResolutionLt(const rtc::VideoSinkWants& other_wants) {
289 return AllOf(FpsMax(), WantsMaxPixels(Lt(other_wants.max_pixel_count)));
290}
291
292auto FpsMaxResolutionGt(const rtc::VideoSinkWants& other_wants) {
293 return AllOf(FpsMax(), WantsMaxPixels(Gt(other_wants.max_pixel_count)));
294}
295
296auto FpsLtResolutionEq(const rtc::VideoSinkWants& other_wants) {
297 return AllOf(WantsFps(Lt(other_wants.max_framerate_fps)),
298 WantsMaxPixels(Eq(other_wants.max_pixel_count)));
299}
300
301auto FpsGtResolutionEq(const rtc::VideoSinkWants& other_wants) {
302 return AllOf(WantsFps(Gt(other_wants.max_framerate_fps)),
303 WantsMaxPixels(Eq(other_wants.max_pixel_count)));
304}
305
306auto FpsEqResolutionLt(const rtc::VideoSinkWants& other_wants) {
307 return AllOf(WantsFps(Eq(other_wants.max_framerate_fps)),
308 WantsMaxPixels(Lt(other_wants.max_pixel_count)));
309}
310
311auto FpsEqResolutionGt(const rtc::VideoSinkWants& other_wants) {
312 return AllOf(WantsFps(Eq(other_wants.max_framerate_fps)),
313 WantsMaxPixels(Gt(other_wants.max_pixel_count)));
314}
315
mflodmancc3d4422017-08-03 08:27:51 -0700316class VideoStreamEncoderUnderTest : public VideoStreamEncoder {
perkj803d97f2016-11-01 11:45:46 -0700317 public:
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200318 VideoStreamEncoderUnderTest(TimeController* time_controller,
319 TaskQueueFactory* task_queue_factory,
320 SendStatisticsProxy* stats_proxy,
321 const VideoStreamEncoderSettings& settings)
322 : VideoStreamEncoder(time_controller->GetClock(),
Sebastian Jansson572c60f2019-03-04 18:30:41 +0100323 1 /* number_of_cores */,
Yves Gerey665174f2018-06-19 15:03:05 +0200324 stats_proxy,
325 settings,
Yves Gerey665174f2018-06-19 15:03:05 +0200326 std::unique_ptr<OveruseFrameDetector>(
327 overuse_detector_proxy_ =
Sebastian Jansson74682c12019-03-01 11:50:20 +0100328 new CpuOveruseDetectorProxy(stats_proxy)),
Evan Shrubsoleaa6fbc12020-02-25 16:26:01 +0100329 task_queue_factory),
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200330 time_controller_(time_controller),
Henrik Boström5cc28b02020-06-01 17:59:05 +0200331 fake_cpu_resource_(FakeResource::Create("FakeResource[CPU]")),
Henrik Boström0f0aa9c2020-06-02 13:02:36 +0200332 fake_quality_resource_(FakeResource::Create("FakeResource[QP]")),
Evan Shrubsoledc4d4222020-07-09 11:47:10 +0200333 fake_adaptation_constraint_("FakeAdaptationConstraint") {
Henrik Boströmc55516d2020-05-11 16:29:22 +0200334 InjectAdaptationResource(fake_quality_resource_,
Evan Shrubsolece0a11d2020-04-16 11:36:55 +0200335 VideoAdaptationReason::kQuality);
Henrik Boströmc55516d2020-05-11 16:29:22 +0200336 InjectAdaptationResource(fake_cpu_resource_, VideoAdaptationReason::kCpu);
Henrik Boström0f0aa9c2020-06-02 13:02:36 +0200337 InjectAdaptationConstraint(&fake_adaptation_constraint_);
Evan Shrubsoleaa6fbc12020-02-25 16:26:01 +0100338 }
perkj803d97f2016-11-01 11:45:46 -0700339
Henrik Boström381d1092020-05-12 18:49:07 +0200340 void SetSourceAndWaitForRestrictionsUpdated(
341 rtc::VideoSourceInterface<VideoFrame>* source,
342 const DegradationPreference& degradation_preference) {
Henrik Boström0f0aa9c2020-06-02 13:02:36 +0200343 FakeVideoSourceRestrictionsListener listener;
344 AddRestrictionsListenerForTesting(&listener);
Henrik Boström381d1092020-05-12 18:49:07 +0200345 SetSource(source, degradation_preference);
346 listener.restrictions_updated_event()->Wait(5000);
Henrik Boström0f0aa9c2020-06-02 13:02:36 +0200347 RemoveRestrictionsListenerForTesting(&listener);
Henrik Boström381d1092020-05-12 18:49:07 +0200348 }
349
350 void SetSourceAndWaitForFramerateUpdated(
351 rtc::VideoSourceInterface<VideoFrame>* source,
352 const DegradationPreference& degradation_preference) {
353 overuse_detector_proxy_->framerate_updated_event()->Reset();
354 SetSource(source, degradation_preference);
355 overuse_detector_proxy_->framerate_updated_event()->Wait(5000);
356 }
357
358 void OnBitrateUpdatedAndWaitForManagedResources(
359 DataRate target_bitrate,
360 DataRate stable_target_bitrate,
361 DataRate link_allocation,
362 uint8_t fraction_lost,
363 int64_t round_trip_time_ms,
364 double cwnd_reduce_ratio) {
365 OnBitrateUpdated(target_bitrate, stable_target_bitrate, link_allocation,
366 fraction_lost, round_trip_time_ms, cwnd_reduce_ratio);
367 // Bitrate is updated on the encoder queue.
368 WaitUntilTaskQueueIsIdle();
Henrik Boström381d1092020-05-12 18:49:07 +0200369 }
370
kthelgason2fc52542017-03-03 00:24:41 -0800371 // This is used as a synchronisation mechanism, to make sure that the
372 // encoder queue is not blocked before we start sending it frames.
373 void WaitUntilTaskQueueIsIdle() {
Niels Möllerc572ff32018-11-07 08:43:50 +0100374 rtc::Event event;
Yves Gerey665174f2018-06-19 15:03:05 +0200375 encoder_queue()->PostTask([&event] { event.Set(); });
kthelgason2fc52542017-03-03 00:24:41 -0800376 ASSERT_TRUE(event.Wait(5000));
377 }
378
Henrik Boström91aa7322020-04-28 12:24:33 +0200379 // Triggers resource usage measurements on the fake CPU resource.
Åsa Perssonb67c44c2019-09-24 15:25:32 +0200380 void TriggerCpuOveruse() {
Henrik Boström91aa7322020-04-28 12:24:33 +0200381 rtc::Event event;
Evan Shrubsole85728412020-08-25 13:12:12 +0200382 encoder_queue()->PostTask([this, &event] {
Henrik Boström0f0aa9c2020-06-02 13:02:36 +0200383 fake_cpu_resource_->SetUsageState(ResourceUsageState::kOveruse);
Henrik Boström91aa7322020-04-28 12:24:33 +0200384 event.Set();
385 });
386 ASSERT_TRUE(event.Wait(5000));
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200387 time_controller_->AdvanceTime(TimeDelta::Millis(0));
Henrik Boström91aa7322020-04-28 12:24:33 +0200388 }
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200389
Henrik Boström91aa7322020-04-28 12:24:33 +0200390 void TriggerCpuUnderuse() {
391 rtc::Event event;
Evan Shrubsole85728412020-08-25 13:12:12 +0200392 encoder_queue()->PostTask([this, &event] {
Henrik Boström0f0aa9c2020-06-02 13:02:36 +0200393 fake_cpu_resource_->SetUsageState(ResourceUsageState::kUnderuse);
Henrik Boström91aa7322020-04-28 12:24:33 +0200394 event.Set();
395 });
396 ASSERT_TRUE(event.Wait(5000));
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200397 time_controller_->AdvanceTime(TimeDelta::Millis(0));
Åsa Perssonb67c44c2019-09-24 15:25:32 +0200398 }
kthelgason876222f2016-11-29 01:44:11 -0800399
Henrik Boström91aa7322020-04-28 12:24:33 +0200400 // Triggers resource usage measurements on the fake quality resource.
Åsa Perssonb67c44c2019-09-24 15:25:32 +0200401 void TriggerQualityLow() {
Henrik Boström91aa7322020-04-28 12:24:33 +0200402 rtc::Event event;
Evan Shrubsole85728412020-08-25 13:12:12 +0200403 encoder_queue()->PostTask([this, &event] {
Henrik Boström0f0aa9c2020-06-02 13:02:36 +0200404 fake_quality_resource_->SetUsageState(ResourceUsageState::kOveruse);
Henrik Boström91aa7322020-04-28 12:24:33 +0200405 event.Set();
406 });
407 ASSERT_TRUE(event.Wait(5000));
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200408 time_controller_->AdvanceTime(TimeDelta::Millis(0));
Åsa Perssonb67c44c2019-09-24 15:25:32 +0200409 }
Åsa Perssonb67c44c2019-09-24 15:25:32 +0200410 void TriggerQualityHigh() {
Henrik Boström91aa7322020-04-28 12:24:33 +0200411 rtc::Event event;
Evan Shrubsole85728412020-08-25 13:12:12 +0200412 encoder_queue()->PostTask([this, &event] {
Henrik Boström0f0aa9c2020-06-02 13:02:36 +0200413 fake_quality_resource_->SetUsageState(ResourceUsageState::kUnderuse);
Henrik Boström91aa7322020-04-28 12:24:33 +0200414 event.Set();
415 });
416 ASSERT_TRUE(event.Wait(5000));
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200417 time_controller_->AdvanceTime(TimeDelta::Millis(0));
Henrik Boström91aa7322020-04-28 12:24:33 +0200418 }
419
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200420 TimeController* const time_controller_;
Niels Möller7dc26b72017-12-06 10:27:48 +0100421 CpuOveruseDetectorProxy* overuse_detector_proxy_;
Henrik Boströmc55516d2020-05-11 16:29:22 +0200422 rtc::scoped_refptr<FakeResource> fake_cpu_resource_;
423 rtc::scoped_refptr<FakeResource> fake_quality_resource_;
Henrik Boström0f0aa9c2020-06-02 13:02:36 +0200424 FakeAdaptationConstraint fake_adaptation_constraint_;
perkj803d97f2016-11-01 11:45:46 -0700425};
426
Noah Richards51db4212019-06-12 06:59:12 -0700427// Simulates simulcast behavior and makes highest stream resolutions divisible
428// by 4.
429class CroppingVideoStreamFactory
430 : public VideoEncoderConfig::VideoStreamFactoryInterface {
431 public:
432 explicit CroppingVideoStreamFactory(size_t num_temporal_layers, int framerate)
433 : num_temporal_layers_(num_temporal_layers), framerate_(framerate) {
434 EXPECT_GT(num_temporal_layers, 0u);
435 EXPECT_GT(framerate, 0);
436 }
437
438 private:
439 std::vector<VideoStream> CreateEncoderStreams(
440 int width,
441 int height,
442 const VideoEncoderConfig& encoder_config) override {
443 std::vector<VideoStream> streams = test::CreateVideoStreams(
444 width - width % 4, height - height % 4, encoder_config);
445 for (VideoStream& stream : streams) {
446 stream.num_temporal_layers = num_temporal_layers_;
447 stream.max_framerate = framerate_;
448 }
449 return streams;
450 }
451
452 const size_t num_temporal_layers_;
453 const int framerate_;
454};
455
sprangb1ca0732017-02-01 08:38:12 -0800456class AdaptingFrameForwarder : public test::FrameForwarder {
457 public:
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200458 explicit AdaptingFrameForwarder(TimeController* time_controller)
459 : time_controller_(time_controller), adaptation_enabled_(false) {}
asaperssonfab67072017-04-04 05:51:49 -0700460 ~AdaptingFrameForwarder() override {}
sprangb1ca0732017-02-01 08:38:12 -0800461
462 void set_adaptation_enabled(bool enabled) {
Markus Handella3765182020-07-08 13:13:32 +0200463 MutexLock lock(&mutex_);
sprangb1ca0732017-02-01 08:38:12 -0800464 adaptation_enabled_ = enabled;
465 }
466
asaperssonfab67072017-04-04 05:51:49 -0700467 bool adaption_enabled() const {
Markus Handella3765182020-07-08 13:13:32 +0200468 MutexLock lock(&mutex_);
sprangb1ca0732017-02-01 08:38:12 -0800469 return adaptation_enabled_;
470 }
471
asapersson09f05612017-05-15 23:40:18 -0700472 rtc::VideoSinkWants last_wants() const {
Markus Handella3765182020-07-08 13:13:32 +0200473 MutexLock lock(&mutex_);
asapersson09f05612017-05-15 23:40:18 -0700474 return last_wants_;
475 }
476
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200477 absl::optional<int> last_sent_width() const { return last_width_; }
478 absl::optional<int> last_sent_height() const { return last_height_; }
Jonathan Yubc771b72017-12-08 17:04:29 -0800479
sprangb1ca0732017-02-01 08:38:12 -0800480 void IncomingCapturedFrame(const VideoFrame& video_frame) override {
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200481 RTC_DCHECK(time_controller_->GetMainThread()->IsCurrent());
482 time_controller_->AdvanceTime(TimeDelta::Millis(0));
483
sprangb1ca0732017-02-01 08:38:12 -0800484 int cropped_width = 0;
485 int cropped_height = 0;
486 int out_width = 0;
487 int out_height = 0;
sprangc5d62e22017-04-02 23:53:04 -0700488 if (adaption_enabled()) {
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200489 RTC_DLOG(INFO) << "IncomingCapturedFrame: AdaptFrameResolution()"
490 << "w=" << video_frame.width()
491 << "h=" << video_frame.height();
sprangc5d62e22017-04-02 23:53:04 -0700492 if (adapter_.AdaptFrameResolution(
493 video_frame.width(), video_frame.height(),
494 video_frame.timestamp_us() * 1000, &cropped_width,
495 &cropped_height, &out_width, &out_height)) {
Artem Titov1ebfb6a2019-01-03 23:49:37 +0100496 VideoFrame adapted_frame =
497 VideoFrame::Builder()
498 .set_video_frame_buffer(new rtc::RefCountedObject<TestBuffer>(
499 nullptr, out_width, out_height))
500 .set_timestamp_rtp(99)
501 .set_timestamp_ms(99)
502 .set_rotation(kVideoRotation_0)
503 .build();
sprangc5d62e22017-04-02 23:53:04 -0700504 adapted_frame.set_ntp_time_ms(video_frame.ntp_time_ms());
Ilya Nikolaevskiy648b9d72019-12-03 16:54:17 +0100505 if (video_frame.has_update_rect()) {
506 adapted_frame.set_update_rect(
507 video_frame.update_rect().ScaleWithFrame(
508 video_frame.width(), video_frame.height(), 0, 0,
509 video_frame.width(), video_frame.height(), out_width,
510 out_height));
511 }
sprangc5d62e22017-04-02 23:53:04 -0700512 test::FrameForwarder::IncomingCapturedFrame(adapted_frame);
Jonathan Yubc771b72017-12-08 17:04:29 -0800513 last_width_.emplace(adapted_frame.width());
514 last_height_.emplace(adapted_frame.height());
515 } else {
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200516 last_width_ = absl::nullopt;
517 last_height_ = absl::nullopt;
sprangc5d62e22017-04-02 23:53:04 -0700518 }
sprangb1ca0732017-02-01 08:38:12 -0800519 } else {
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200520 RTC_DLOG(INFO) << "IncomingCapturedFrame: adaptation not enabled";
sprangb1ca0732017-02-01 08:38:12 -0800521 test::FrameForwarder::IncomingCapturedFrame(video_frame);
Jonathan Yubc771b72017-12-08 17:04:29 -0800522 last_width_.emplace(video_frame.width());
523 last_height_.emplace(video_frame.height());
sprangb1ca0732017-02-01 08:38:12 -0800524 }
525 }
526
527 void AddOrUpdateSink(rtc::VideoSinkInterface<VideoFrame>* sink,
528 const rtc::VideoSinkWants& wants) override {
Markus Handella3765182020-07-08 13:13:32 +0200529 MutexLock lock(&mutex_);
Markus Handell16038ab2020-05-28 08:37:30 +0200530 last_wants_ = sink_wants_locked();
Rasmus Brandt287e4642019-11-15 16:56:01 +0100531 adapter_.OnSinkWants(wants);
Markus Handell16038ab2020-05-28 08:37:30 +0200532 test::FrameForwarder::AddOrUpdateSinkLocked(sink, wants);
sprangb1ca0732017-02-01 08:38:12 -0800533 }
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200534
535 TimeController* const time_controller_;
sprangb1ca0732017-02-01 08:38:12 -0800536 cricket::VideoAdapter adapter_;
Markus Handella3765182020-07-08 13:13:32 +0200537 bool adaptation_enabled_ RTC_GUARDED_BY(mutex_);
538 rtc::VideoSinkWants last_wants_ RTC_GUARDED_BY(mutex_);
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200539 absl::optional<int> last_width_;
540 absl::optional<int> last_height_;
sprangb1ca0732017-02-01 08:38:12 -0800541};
sprangc5d62e22017-04-02 23:53:04 -0700542
Niels Möller213618e2018-07-24 09:29:58 +0200543// TODO(nisse): Mock only VideoStreamEncoderObserver.
sprangc5d62e22017-04-02 23:53:04 -0700544class MockableSendStatisticsProxy : public SendStatisticsProxy {
545 public:
546 MockableSendStatisticsProxy(Clock* clock,
547 const VideoSendStream::Config& config,
548 VideoEncoderConfig::ContentType content_type)
549 : SendStatisticsProxy(clock, config, content_type) {}
550
551 VideoSendStream::Stats GetStats() override {
Markus Handella3765182020-07-08 13:13:32 +0200552 MutexLock lock(&lock_);
sprangc5d62e22017-04-02 23:53:04 -0700553 if (mock_stats_)
554 return *mock_stats_;
555 return SendStatisticsProxy::GetStats();
556 }
557
Niels Möller213618e2018-07-24 09:29:58 +0200558 int GetInputFrameRate() const override {
Markus Handella3765182020-07-08 13:13:32 +0200559 MutexLock lock(&lock_);
Niels Möller213618e2018-07-24 09:29:58 +0200560 if (mock_stats_)
561 return mock_stats_->input_frame_rate;
562 return SendStatisticsProxy::GetInputFrameRate();
563 }
sprangc5d62e22017-04-02 23:53:04 -0700564 void SetMockStats(const VideoSendStream::Stats& stats) {
Markus Handella3765182020-07-08 13:13:32 +0200565 MutexLock lock(&lock_);
sprangc5d62e22017-04-02 23:53:04 -0700566 mock_stats_.emplace(stats);
567 }
568
569 void ResetMockStats() {
Markus Handella3765182020-07-08 13:13:32 +0200570 MutexLock lock(&lock_);
sprangc5d62e22017-04-02 23:53:04 -0700571 mock_stats_.reset();
572 }
573
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200574 void SetDroppedFrameCallback(std::function<void(DropReason)> callback) {
575 on_frame_dropped_ = std::move(callback);
576 }
577
sprangc5d62e22017-04-02 23:53:04 -0700578 private:
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200579 void OnFrameDropped(DropReason reason) override {
580 SendStatisticsProxy::OnFrameDropped(reason);
581 if (on_frame_dropped_)
582 on_frame_dropped_(reason);
583 }
584
Markus Handella3765182020-07-08 13:13:32 +0200585 mutable Mutex lock_;
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200586 absl::optional<VideoSendStream::Stats> mock_stats_ RTC_GUARDED_BY(lock_);
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200587 std::function<void(DropReason)> on_frame_dropped_;
sprangc5d62e22017-04-02 23:53:04 -0700588};
589
philipel9b058032020-02-10 11:30:00 +0100590class MockEncoderSelector
591 : public VideoEncoderFactory::EncoderSelectorInterface {
592 public:
Danil Chapovalov91fdc602020-05-14 19:17:51 +0200593 MOCK_METHOD(void,
594 OnCurrentEncoder,
595 (const SdpVideoFormat& format),
596 (override));
597 MOCK_METHOD(absl::optional<SdpVideoFormat>,
598 OnAvailableBitrate,
599 (const DataRate& rate),
600 (override));
601 MOCK_METHOD(absl::optional<SdpVideoFormat>, OnEncoderBroken, (), (override));
philipel9b058032020-02-10 11:30:00 +0100602};
603
perkj803d97f2016-11-01 11:45:46 -0700604} // namespace
605
mflodmancc3d4422017-08-03 08:27:51 -0700606class VideoStreamEncoderTest : public ::testing::Test {
perkj26091b12016-09-01 01:17:40 -0700607 public:
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200608 static const int kDefaultTimeoutMs = 1000;
perkj26091b12016-09-01 01:17:40 -0700609
mflodmancc3d4422017-08-03 08:27:51 -0700610 VideoStreamEncoderTest()
perkj26091b12016-09-01 01:17:40 -0700611 : video_send_config_(VideoSendStream::Config(nullptr)),
perkjfa10b552016-10-02 23:45:26 -0700612 codec_width_(320),
613 codec_height_(240),
Åsa Persson8c1bf952018-09-13 10:42:19 +0200614 max_framerate_(kDefaultFramerate),
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200615 fake_encoder_(&time_controller_),
Niels Möller4db138e2018-04-19 09:04:13 +0200616 encoder_factory_(&fake_encoder_),
sprangc5d62e22017-04-02 23:53:04 -0700617 stats_proxy_(new MockableSendStatisticsProxy(
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200618 time_controller_.GetClock(),
perkj803d97f2016-11-01 11:45:46 -0700619 video_send_config_,
620 webrtc::VideoEncoderConfig::ContentType::kRealtimeVideo)),
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200621 sink_(&time_controller_, &fake_encoder_) {}
perkj26091b12016-09-01 01:17:40 -0700622
623 void SetUp() override {
perkj803d97f2016-11-01 11:45:46 -0700624 metrics::Reset();
perkj26091b12016-09-01 01:17:40 -0700625 video_send_config_ = VideoSendStream::Config(nullptr);
Niels Möller4db138e2018-04-19 09:04:13 +0200626 video_send_config_.encoder_settings.encoder_factory = &encoder_factory_;
Jiawei Ouc2ebe212018-11-08 10:02:56 -0800627 video_send_config_.encoder_settings.bitrate_allocator_factory =
Sergey Silkin5ee69672019-07-02 14:18:34 +0200628 &bitrate_allocator_factory_;
Niels Möller259a4972018-04-05 15:36:51 +0200629 video_send_config_.rtp.payload_name = "FAKE";
630 video_send_config_.rtp.payload_type = 125;
perkj26091b12016-09-01 01:17:40 -0700631
Per512ecb32016-09-23 15:52:06 +0200632 VideoEncoderConfig video_encoder_config;
Niels Möller259a4972018-04-05 15:36:51 +0200633 test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
Åsa Persson17107062020-10-08 08:57:51 +0200634 EXPECT_EQ(1u, video_encoder_config.simulcast_layers.size());
635 video_encoder_config.simulcast_layers[0].num_temporal_layers = 1;
636 video_encoder_config.simulcast_layers[0].max_framerate = max_framerate_;
Erik Språng08127a92016-11-16 16:41:30 +0100637 video_encoder_config_ = video_encoder_config.Copy();
sprang4847ae62017-06-27 07:06:52 -0700638
Niels Möllerf1338562018-04-26 09:51:47 +0200639 ConfigureEncoder(std::move(video_encoder_config));
asapersson5f7226f2016-11-25 04:37:00 -0800640 }
641
Niels Möllerf1338562018-04-26 09:51:47 +0200642 void ConfigureEncoder(VideoEncoderConfig video_encoder_config) {
mflodmancc3d4422017-08-03 08:27:51 -0700643 if (video_stream_encoder_)
644 video_stream_encoder_->Stop();
645 video_stream_encoder_.reset(new VideoStreamEncoderUnderTest(
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200646 &time_controller_, GetTaskQueueFactory(), stats_proxy_.get(),
647 video_send_config_.encoder_settings));
mflodmancc3d4422017-08-03 08:27:51 -0700648 video_stream_encoder_->SetSink(&sink_, false /* rotation_applied */);
649 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -0700650 &video_source_, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
mflodmancc3d4422017-08-03 08:27:51 -0700651 video_stream_encoder_->SetStartBitrate(kTargetBitrateBps);
652 video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config),
Niels Möllerf1338562018-04-26 09:51:47 +0200653 kMaxPayloadLength);
mflodmancc3d4422017-08-03 08:27:51 -0700654 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
asapersson5f7226f2016-11-25 04:37:00 -0800655 }
656
Per Kjellanderdcef6412020-10-07 15:09:05 +0200657 void ResetEncoder(
658 const std::string& payload_name,
659 size_t num_streams,
660 size_t num_temporal_layers,
661 unsigned char num_spatial_layers,
662 bool screenshare,
663 VideoStreamEncoderSettings::BitrateAllocationCallbackType
664 allocation_cb_type =
665 VideoStreamEncoderSettings::BitrateAllocationCallbackType::
666 kVideoBitrateAllocationWhenScreenSharing) {
Niels Möller259a4972018-04-05 15:36:51 +0200667 video_send_config_.rtp.payload_name = payload_name;
Per Kjellanderdcef6412020-10-07 15:09:05 +0200668 video_send_config_.encoder_settings.allocation_cb_type = allocation_cb_type;
asapersson5f7226f2016-11-25 04:37:00 -0800669
670 VideoEncoderConfig video_encoder_config;
Åsa Persson17107062020-10-08 08:57:51 +0200671 test::FillEncoderConfiguration(PayloadStringToCodecType(payload_name),
672 num_streams, &video_encoder_config);
673 for (auto& layer : video_encoder_config.simulcast_layers) {
674 layer.num_temporal_layers = num_temporal_layers;
675 layer.max_framerate = kDefaultFramerate;
676 }
Erik Språngd7329ca2019-02-21 21:19:53 +0100677 video_encoder_config.max_bitrate_bps =
678 num_streams == 1 ? kTargetBitrateBps : kSimulcastTargetBitrateBps;
sprang4847ae62017-06-27 07:06:52 -0700679 video_encoder_config.content_type =
680 screenshare ? VideoEncoderConfig::ContentType::kScreen
681 : VideoEncoderConfig::ContentType::kRealtimeVideo;
emircanbbcc3562017-08-18 00:28:40 -0700682 if (payload_name == "VP9") {
683 VideoCodecVP9 vp9_settings = VideoEncoder::GetDefaultVp9Settings();
684 vp9_settings.numberOfSpatialLayers = num_spatial_layers;
Mirta Dvornicic97910da2020-07-14 15:29:23 +0200685 vp9_settings.automaticResizeOn = num_spatial_layers <= 1;
emircanbbcc3562017-08-18 00:28:40 -0700686 video_encoder_config.encoder_specific_settings =
687 new rtc::RefCountedObject<
688 VideoEncoderConfig::Vp9EncoderSpecificSettings>(vp9_settings);
689 }
Niels Möllerf1338562018-04-26 09:51:47 +0200690 ConfigureEncoder(std::move(video_encoder_config));
perkj26091b12016-09-01 01:17:40 -0700691 }
692
sprang57c2fff2017-01-16 06:24:02 -0800693 VideoFrame CreateFrame(int64_t ntp_time_ms,
694 rtc::Event* destruction_event) const {
Artem Titov1ebfb6a2019-01-03 23:49:37 +0100695 VideoFrame frame =
696 VideoFrame::Builder()
697 .set_video_frame_buffer(new rtc::RefCountedObject<TestBuffer>(
698 destruction_event, codec_width_, codec_height_))
699 .set_timestamp_rtp(99)
700 .set_timestamp_ms(99)
701 .set_rotation(kVideoRotation_0)
702 .build();
sprang57c2fff2017-01-16 06:24:02 -0800703 frame.set_ntp_time_ms(ntp_time_ms);
perkj26091b12016-09-01 01:17:40 -0700704 return frame;
705 }
706
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +0100707 VideoFrame CreateFrameWithUpdatedPixel(int64_t ntp_time_ms,
708 rtc::Event* destruction_event,
709 int offset_x) const {
710 VideoFrame frame =
711 VideoFrame::Builder()
712 .set_video_frame_buffer(new rtc::RefCountedObject<TestBuffer>(
713 destruction_event, codec_width_, codec_height_))
714 .set_timestamp_rtp(99)
715 .set_timestamp_ms(99)
716 .set_rotation(kVideoRotation_0)
Artem Titov5256d8b2019-12-02 10:34:12 +0100717 .set_update_rect(VideoFrame::UpdateRect{offset_x, 0, 1, 1})
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +0100718 .build();
719 frame.set_ntp_time_ms(ntp_time_ms);
720 return frame;
721 }
722
sprang57c2fff2017-01-16 06:24:02 -0800723 VideoFrame CreateFrame(int64_t ntp_time_ms, int width, int height) const {
Artem Titov1ebfb6a2019-01-03 23:49:37 +0100724 VideoFrame frame =
725 VideoFrame::Builder()
726 .set_video_frame_buffer(
727 new rtc::RefCountedObject<TestBuffer>(nullptr, width, height))
728 .set_timestamp_rtp(99)
729 .set_timestamp_ms(99)
730 .set_rotation(kVideoRotation_0)
731 .build();
sprang57c2fff2017-01-16 06:24:02 -0800732 frame.set_ntp_time_ms(ntp_time_ms);
sprangc5d62e22017-04-02 23:53:04 -0700733 frame.set_timestamp_us(ntp_time_ms * 1000);
perkj803d97f2016-11-01 11:45:46 -0700734 return frame;
735 }
736
Evan Shrubsole895556e2020-10-05 09:15:13 +0200737 VideoFrame CreateNV12Frame(int64_t ntp_time_ms, int width, int height) const {
738 VideoFrame frame =
739 VideoFrame::Builder()
740 .set_video_frame_buffer(NV12Buffer::Create(width, height))
741 .set_timestamp_rtp(99)
742 .set_timestamp_ms(99)
743 .set_rotation(kVideoRotation_0)
744 .build();
745 frame.set_ntp_time_ms(ntp_time_ms);
746 frame.set_timestamp_us(ntp_time_ms * 1000);
747 return frame;
748 }
749
Noah Richards51db4212019-06-12 06:59:12 -0700750 VideoFrame CreateFakeNativeFrame(int64_t ntp_time_ms,
751 rtc::Event* destruction_event,
752 int width,
753 int height) const {
754 VideoFrame frame =
755 VideoFrame::Builder()
756 .set_video_frame_buffer(new rtc::RefCountedObject<FakeNativeBuffer>(
757 destruction_event, width, height))
758 .set_timestamp_rtp(99)
759 .set_timestamp_ms(99)
760 .set_rotation(kVideoRotation_0)
761 .build();
762 frame.set_ntp_time_ms(ntp_time_ms);
763 return frame;
764 }
765
Evan Shrubsole895556e2020-10-05 09:15:13 +0200766 VideoFrame CreateFakeNV12NativeFrame(int64_t ntp_time_ms,
767 rtc::Event* destruction_event,
768 int width,
769 int height) const {
770 VideoFrame frame = VideoFrame::Builder()
771 .set_video_frame_buffer(
772 new rtc::RefCountedObject<FakeNV12NativeBuffer>(
773 destruction_event, width, height))
774 .set_timestamp_rtp(99)
775 .set_timestamp_ms(99)
776 .set_rotation(kVideoRotation_0)
777 .build();
778 frame.set_ntp_time_ms(ntp_time_ms);
779 return frame;
780 }
781
Noah Richards51db4212019-06-12 06:59:12 -0700782 VideoFrame CreateFakeNativeFrame(int64_t ntp_time_ms,
783 rtc::Event* destruction_event) const {
784 return CreateFakeNativeFrame(ntp_time_ms, destruction_event, codec_width_,
785 codec_height_);
786 }
787
Åsa Perssonc29cb2c2019-03-25 12:06:59 +0100788 void VerifyAllocatedBitrate(const VideoBitrateAllocation& expected_bitrate) {
Henrik Boström381d1092020-05-12 18:49:07 +0200789 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +0100790 DataRate::BitsPerSec(kTargetBitrateBps),
791 DataRate::BitsPerSec(kTargetBitrateBps),
792 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Åsa Perssonc29cb2c2019-03-25 12:06:59 +0100793
794 video_source_.IncomingCapturedFrame(
795 CreateFrame(1, codec_width_, codec_height_));
796 WaitForEncodedFrame(1);
Per Kjellanderdcef6412020-10-07 15:09:05 +0200797 EXPECT_EQ(expected_bitrate, sink_.GetLastVideoBitrateAllocation());
Åsa Perssonc29cb2c2019-03-25 12:06:59 +0100798 }
799
sprang4847ae62017-06-27 07:06:52 -0700800 void WaitForEncodedFrame(int64_t expected_ntp_time) {
801 sink_.WaitForEncodedFrame(expected_ntp_time);
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200802 AdvanceTime(TimeDelta::Seconds(1) / max_framerate_);
sprang4847ae62017-06-27 07:06:52 -0700803 }
804
805 bool TimedWaitForEncodedFrame(int64_t expected_ntp_time, int64_t timeout_ms) {
806 bool ok = sink_.TimedWaitForEncodedFrame(expected_ntp_time, timeout_ms);
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200807 AdvanceTime(TimeDelta::Seconds(1) / max_framerate_);
sprang4847ae62017-06-27 07:06:52 -0700808 return ok;
809 }
810
811 void WaitForEncodedFrame(uint32_t expected_width, uint32_t expected_height) {
812 sink_.WaitForEncodedFrame(expected_width, expected_height);
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200813 AdvanceTime(TimeDelta::Seconds(1) / max_framerate_);
sprang4847ae62017-06-27 07:06:52 -0700814 }
815
816 void ExpectDroppedFrame() {
817 sink_.ExpectDroppedFrame();
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200818 AdvanceTime(TimeDelta::Seconds(1) / max_framerate_);
sprang4847ae62017-06-27 07:06:52 -0700819 }
820
821 bool WaitForFrame(int64_t timeout_ms) {
822 bool ok = sink_.WaitForFrame(timeout_ms);
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200823 AdvanceTime(TimeDelta::Seconds(1) / max_framerate_);
sprang4847ae62017-06-27 07:06:52 -0700824 return ok;
825 }
826
perkj26091b12016-09-01 01:17:40 -0700827 class TestEncoder : public test::FakeEncoder {
828 public:
Tomas Gunnarsson612445e2020-09-21 14:31:23 +0200829 explicit TestEncoder(TimeController* time_controller)
830 : FakeEncoder(time_controller->GetClock()),
831 time_controller_(time_controller) {
832 RTC_DCHECK(time_controller_);
833 }
perkj26091b12016-09-01 01:17:40 -0700834
asaperssonfab67072017-04-04 05:51:49 -0700835 VideoCodec codec_config() const {
Markus Handella3765182020-07-08 13:13:32 +0200836 MutexLock lock(&mutex_);
perkjfa10b552016-10-02 23:45:26 -0700837 return config_;
838 }
839
840 void BlockNextEncode() {
Markus Handella3765182020-07-08 13:13:32 +0200841 MutexLock lock(&local_mutex_);
perkjfa10b552016-10-02 23:45:26 -0700842 block_next_encode_ = true;
843 }
844
Erik Språngaed30702018-11-05 12:57:17 +0100845 VideoEncoder::EncoderInfo GetEncoderInfo() const override {
Markus Handella3765182020-07-08 13:13:32 +0200846 MutexLock lock(&local_mutex_);
Erik Språng9d69cbe2020-10-22 17:44:42 +0200847 EncoderInfo info = FakeEncoder::GetEncoderInfo();
Erik Språngb7cb7b52019-02-26 15:52:33 +0100848 if (initialized_ == EncoderState::kInitialized) {
Mirta Dvornicicccc1b572019-01-15 12:42:18 +0100849 if (quality_scaling_) {
Åsa Perssone644a032019-11-08 15:56:00 +0100850 info.scaling_settings = VideoEncoder::ScalingSettings(
851 kQpLow, kQpHigh, kMinPixelsPerFrame);
Mirta Dvornicicccc1b572019-01-15 12:42:18 +0100852 }
853 info.is_hardware_accelerated = is_hardware_accelerated_;
Åsa Perssonc29cb2c2019-03-25 12:06:59 +0100854 for (int i = 0; i < kMaxSpatialLayers; ++i) {
855 if (temporal_layers_supported_[i]) {
856 int num_layers = temporal_layers_supported_[i].value() ? 2 : 1;
857 info.fps_allocation[i].resize(num_layers);
858 }
859 }
Erik Språngaed30702018-11-05 12:57:17 +0100860 }
Sergey Silkin6456e352019-07-08 17:56:40 +0200861
862 info.resolution_bitrate_limits = resolution_bitrate_limits_;
Rasmus Brandt5cad55b2019-12-19 09:47:11 +0100863 info.requested_resolution_alignment = requested_resolution_alignment_;
Åsa Perssonc5a74ff2020-09-20 17:50:00 +0200864 info.apply_alignment_to_all_simulcast_layers =
865 apply_alignment_to_all_simulcast_layers_;
Evan Shrubsoleb556b082020-10-08 14:56:45 +0200866 info.preferred_pixel_formats = preferred_pixel_formats_;
Erik Språngaed30702018-11-05 12:57:17 +0100867 return info;
kthelgason876222f2016-11-29 01:44:11 -0800868 }
869
Erik Språngb7cb7b52019-02-26 15:52:33 +0100870 int32_t RegisterEncodeCompleteCallback(
871 EncodedImageCallback* callback) override {
Markus Handella3765182020-07-08 13:13:32 +0200872 MutexLock lock(&local_mutex_);
Erik Språngb7cb7b52019-02-26 15:52:33 +0100873 encoded_image_callback_ = callback;
874 return FakeEncoder::RegisterEncodeCompleteCallback(callback);
875 }
876
perkjfa10b552016-10-02 23:45:26 -0700877 void ContinueEncode() { continue_encode_event_.Set(); }
878
879 void CheckLastTimeStampsMatch(int64_t ntp_time_ms,
880 uint32_t timestamp) const {
Markus Handella3765182020-07-08 13:13:32 +0200881 MutexLock lock(&local_mutex_);
perkjfa10b552016-10-02 23:45:26 -0700882 EXPECT_EQ(timestamp_, timestamp);
883 EXPECT_EQ(ntp_time_ms_, ntp_time_ms);
884 }
885
kthelgason2fc52542017-03-03 00:24:41 -0800886 void SetQualityScaling(bool b) {
Markus Handella3765182020-07-08 13:13:32 +0200887 MutexLock lock(&local_mutex_);
kthelgason2fc52542017-03-03 00:24:41 -0800888 quality_scaling_ = b;
889 }
kthelgasonad9010c2017-02-14 00:46:51 -0800890
Rasmus Brandt5cad55b2019-12-19 09:47:11 +0100891 void SetRequestedResolutionAlignment(int requested_resolution_alignment) {
Markus Handella3765182020-07-08 13:13:32 +0200892 MutexLock lock(&local_mutex_);
Rasmus Brandt5cad55b2019-12-19 09:47:11 +0100893 requested_resolution_alignment_ = requested_resolution_alignment;
894 }
895
Åsa Perssonc5a74ff2020-09-20 17:50:00 +0200896 void SetApplyAlignmentToAllSimulcastLayers(bool b) {
897 MutexLock lock(&local_mutex_);
898 apply_alignment_to_all_simulcast_layers_ = b;
899 }
900
Mirta Dvornicicccc1b572019-01-15 12:42:18 +0100901 void SetIsHardwareAccelerated(bool is_hardware_accelerated) {
Markus Handella3765182020-07-08 13:13:32 +0200902 MutexLock lock(&local_mutex_);
Mirta Dvornicicccc1b572019-01-15 12:42:18 +0100903 is_hardware_accelerated_ = is_hardware_accelerated;
904 }
905
Åsa Perssonc29cb2c2019-03-25 12:06:59 +0100906 void SetTemporalLayersSupported(size_t spatial_idx, bool supported) {
907 RTC_DCHECK_LT(spatial_idx, kMaxSpatialLayers);
Markus Handella3765182020-07-08 13:13:32 +0200908 MutexLock lock(&local_mutex_);
Åsa Perssonc29cb2c2019-03-25 12:06:59 +0100909 temporal_layers_supported_[spatial_idx] = supported;
910 }
911
Sergey Silkin6456e352019-07-08 17:56:40 +0200912 void SetResolutionBitrateLimits(
913 std::vector<ResolutionBitrateLimits> thresholds) {
Markus Handella3765182020-07-08 13:13:32 +0200914 MutexLock lock(&local_mutex_);
Sergey Silkin6456e352019-07-08 17:56:40 +0200915 resolution_bitrate_limits_ = thresholds;
916 }
917
sprangfe627f32017-03-29 08:24:59 -0700918 void ForceInitEncodeFailure(bool force_failure) {
Markus Handella3765182020-07-08 13:13:32 +0200919 MutexLock lock(&local_mutex_);
sprangfe627f32017-03-29 08:24:59 -0700920 force_init_encode_failed_ = force_failure;
921 }
922
Niels Möller6bb5ab92019-01-11 11:11:10 +0100923 void SimulateOvershoot(double rate_factor) {
Markus Handella3765182020-07-08 13:13:32 +0200924 MutexLock lock(&local_mutex_);
Niels Möller6bb5ab92019-01-11 11:11:10 +0100925 rate_factor_ = rate_factor;
926 }
927
Erik Språngd7329ca2019-02-21 21:19:53 +0100928 uint32_t GetLastFramerate() const {
Markus Handella3765182020-07-08 13:13:32 +0200929 MutexLock lock(&local_mutex_);
Niels Möller6bb5ab92019-01-11 11:11:10 +0100930 return last_framerate_;
931 }
932
Erik Språngd7329ca2019-02-21 21:19:53 +0100933 VideoFrame::UpdateRect GetLastUpdateRect() const {
Markus Handella3765182020-07-08 13:13:32 +0200934 MutexLock lock(&local_mutex_);
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +0100935 return last_update_rect_;
936 }
937
Niels Möller87e2d782019-03-07 10:18:23 +0100938 const std::vector<VideoFrameType>& LastFrameTypes() const {
Markus Handella3765182020-07-08 13:13:32 +0200939 MutexLock lock(&local_mutex_);
Erik Språngd7329ca2019-02-21 21:19:53 +0100940 return last_frame_types_;
941 }
942
943 void InjectFrame(const VideoFrame& input_image, bool keyframe) {
Niels Möller87e2d782019-03-07 10:18:23 +0100944 const std::vector<VideoFrameType> frame_type = {
Niels Möller8f7ce222019-03-21 15:43:58 +0100945 keyframe ? VideoFrameType::kVideoFrameKey
946 : VideoFrameType::kVideoFrameDelta};
Erik Språngd7329ca2019-02-21 21:19:53 +0100947 {
Markus Handella3765182020-07-08 13:13:32 +0200948 MutexLock lock(&local_mutex_);
Erik Språngd7329ca2019-02-21 21:19:53 +0100949 last_frame_types_ = frame_type;
950 }
Niels Möllerb859b322019-03-07 12:40:01 +0100951 FakeEncoder::Encode(input_image, &frame_type);
Erik Språngd7329ca2019-02-21 21:19:53 +0100952 }
953
Erik Språngb7cb7b52019-02-26 15:52:33 +0100954 void InjectEncodedImage(const EncodedImage& image) {
Markus Handella3765182020-07-08 13:13:32 +0200955 MutexLock lock(&local_mutex_);
Danil Chapovalov2549f172020-08-12 17:30:36 +0200956 encoded_image_callback_->OnEncodedImage(image, nullptr);
Erik Språngb7cb7b52019-02-26 15:52:33 +0100957 }
958
Mirta Dvornicic97910da2020-07-14 15:29:23 +0200959 void SetEncodedImageData(
960 rtc::scoped_refptr<EncodedImageBufferInterface> encoded_image_data) {
Markus Handella3765182020-07-08 13:13:32 +0200961 MutexLock lock(&local_mutex_);
Mirta Dvornicic97910da2020-07-14 15:29:23 +0200962 encoded_image_data_ = encoded_image_data;
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +0200963 }
964
Erik Språngd7329ca2019-02-21 21:19:53 +0100965 void ExpectNullFrame() {
Markus Handella3765182020-07-08 13:13:32 +0200966 MutexLock lock(&local_mutex_);
Erik Språngd7329ca2019-02-21 21:19:53 +0100967 expect_null_frame_ = true;
968 }
969
Erik Språng5056af02019-09-02 15:53:11 +0200970 absl::optional<VideoEncoder::RateControlParameters>
971 GetAndResetLastRateControlSettings() {
972 auto settings = last_rate_control_settings_;
973 last_rate_control_settings_.reset();
974 return settings;
Erik Språngd7329ca2019-02-21 21:19:53 +0100975 }
976
Evan Shrubsole895556e2020-10-05 09:15:13 +0200977 absl::optional<VideoFrameBuffer::Type> GetLastInputPixelFormat() {
978 MutexLock lock(&local_mutex_);
979 return last_input_pixel_format_;
980 }
981
Sergey Silkin5ee69672019-07-02 14:18:34 +0200982 int GetNumEncoderInitializations() const {
Markus Handella3765182020-07-08 13:13:32 +0200983 MutexLock lock(&local_mutex_);
Sergey Silkin5ee69672019-07-02 14:18:34 +0200984 return num_encoder_initializations_;
985 }
986
Evan Shrubsole7c079f62019-09-26 09:55:03 +0200987 int GetNumSetRates() const {
Markus Handella3765182020-07-08 13:13:32 +0200988 MutexLock lock(&local_mutex_);
Evan Shrubsole7c079f62019-09-26 09:55:03 +0200989 return num_set_rates_;
990 }
991
Åsa Perssonc5a74ff2020-09-20 17:50:00 +0200992 VideoCodec video_codec() const {
993 MutexLock lock(&local_mutex_);
994 return video_codec_;
995 }
996
Evan Shrubsoleb556b082020-10-08 14:56:45 +0200997 void SetPreferredPixelFormats(
998 absl::InlinedVector<VideoFrameBuffer::Type, kMaxPreferredPixelFormats>
999 pixel_formats) {
1000 MutexLock lock(&local_mutex_);
1001 preferred_pixel_formats_ = std::move(pixel_formats);
1002 }
1003
perkjfa10b552016-10-02 23:45:26 -07001004 private:
perkj26091b12016-09-01 01:17:40 -07001005 int32_t Encode(const VideoFrame& input_image,
Niels Möller87e2d782019-03-07 10:18:23 +01001006 const std::vector<VideoFrameType>* frame_types) override {
perkj26091b12016-09-01 01:17:40 -07001007 bool block_encode;
1008 {
Markus Handella3765182020-07-08 13:13:32 +02001009 MutexLock lock(&local_mutex_);
Erik Språngd7329ca2019-02-21 21:19:53 +01001010 if (expect_null_frame_) {
1011 EXPECT_EQ(input_image.timestamp(), 0u);
1012 EXPECT_EQ(input_image.width(), 1);
1013 last_frame_types_ = *frame_types;
1014 expect_null_frame_ = false;
1015 } else {
1016 EXPECT_GT(input_image.timestamp(), timestamp_);
1017 EXPECT_GT(input_image.ntp_time_ms(), ntp_time_ms_);
1018 EXPECT_EQ(input_image.timestamp(), input_image.ntp_time_ms() * 90);
1019 }
perkj26091b12016-09-01 01:17:40 -07001020
1021 timestamp_ = input_image.timestamp();
1022 ntp_time_ms_ = input_image.ntp_time_ms();
perkj803d97f2016-11-01 11:45:46 -07001023 last_input_width_ = input_image.width();
1024 last_input_height_ = input_image.height();
perkj26091b12016-09-01 01:17:40 -07001025 block_encode = block_next_encode_;
1026 block_next_encode_ = false;
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01001027 last_update_rect_ = input_image.update_rect();
Erik Språngd7329ca2019-02-21 21:19:53 +01001028 last_frame_types_ = *frame_types;
Evan Shrubsole895556e2020-10-05 09:15:13 +02001029 last_input_pixel_format_ = input_image.video_frame_buffer()->type();
perkj26091b12016-09-01 01:17:40 -07001030 }
Niels Möllerb859b322019-03-07 12:40:01 +01001031 int32_t result = FakeEncoder::Encode(input_image, frame_types);
perkj26091b12016-09-01 01:17:40 -07001032 if (block_encode)
perkja49cbd32016-09-16 07:53:41 -07001033 EXPECT_TRUE(continue_encode_event_.Wait(kDefaultTimeoutMs));
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02001034
perkj26091b12016-09-01 01:17:40 -07001035 return result;
1036 }
1037
Niels Möller08ae7ce2020-09-23 15:58:12 +02001038 CodecSpecificInfo EncodeHook(
1039 EncodedImage& encoded_image,
1040 rtc::scoped_refptr<EncodedImageBuffer> buffer) override {
Danil Chapovalov2549f172020-08-12 17:30:36 +02001041 CodecSpecificInfo codec_specific;
Mirta Dvornicic97910da2020-07-14 15:29:23 +02001042 {
1043 MutexLock lock(&mutex_);
Danil Chapovalov2549f172020-08-12 17:30:36 +02001044 codec_specific.codecType = config_.codecType;
Mirta Dvornicic97910da2020-07-14 15:29:23 +02001045 }
1046 MutexLock lock(&local_mutex_);
1047 if (encoded_image_data_) {
Danil Chapovalov2549f172020-08-12 17:30:36 +02001048 encoded_image.SetEncodedData(encoded_image_data_);
Mirta Dvornicic97910da2020-07-14 15:29:23 +02001049 }
Danil Chapovalov2549f172020-08-12 17:30:36 +02001050 return codec_specific;
Mirta Dvornicic97910da2020-07-14 15:29:23 +02001051 }
1052
sprangfe627f32017-03-29 08:24:59 -07001053 int32_t InitEncode(const VideoCodec* config,
Elad Alon370f93a2019-06-11 14:57:57 +02001054 const Settings& settings) override {
1055 int res = FakeEncoder::InitEncode(config, settings);
Sergey Silkin5ee69672019-07-02 14:18:34 +02001056
Markus Handella3765182020-07-08 13:13:32 +02001057 MutexLock lock(&local_mutex_);
Erik Språngb7cb7b52019-02-26 15:52:33 +01001058 EXPECT_EQ(initialized_, EncoderState::kUninitialized);
Sergey Silkin5ee69672019-07-02 14:18:34 +02001059
1060 ++num_encoder_initializations_;
Åsa Perssonc5a74ff2020-09-20 17:50:00 +02001061 video_codec_ = *config;
Sergey Silkin5ee69672019-07-02 14:18:34 +02001062
Erik Språng82fad3d2018-03-21 09:57:23 +01001063 if (config->codecType == kVideoCodecVP8) {
sprangfe627f32017-03-29 08:24:59 -07001064 // Simulate setting up temporal layers, in order to validate the life
1065 // cycle of these objects.
Elad Aloncde8ab22019-03-20 11:56:20 +01001066 Vp8TemporalLayersFactory factory;
Elad Alon45befc52019-07-02 11:20:09 +02001067 frame_buffer_controller_ =
1068 factory.Create(*config, settings, &fec_controller_override_);
sprangfe627f32017-03-29 08:24:59 -07001069 }
Erik Språngb7cb7b52019-02-26 15:52:33 +01001070 if (force_init_encode_failed_) {
1071 initialized_ = EncoderState::kInitializationFailed;
sprangfe627f32017-03-29 08:24:59 -07001072 return -1;
Erik Språngb7cb7b52019-02-26 15:52:33 +01001073 }
Mirta Dvornicicccc1b572019-01-15 12:42:18 +01001074
Erik Språngb7cb7b52019-02-26 15:52:33 +01001075 initialized_ = EncoderState::kInitialized;
sprangfe627f32017-03-29 08:24:59 -07001076 return res;
1077 }
1078
Erik Språngb7cb7b52019-02-26 15:52:33 +01001079 int32_t Release() override {
Markus Handella3765182020-07-08 13:13:32 +02001080 MutexLock lock(&local_mutex_);
Erik Språngb7cb7b52019-02-26 15:52:33 +01001081 EXPECT_NE(initialized_, EncoderState::kUninitialized);
1082 initialized_ = EncoderState::kUninitialized;
1083 return FakeEncoder::Release();
1084 }
1085
Erik Språng16cb8f52019-04-12 13:59:09 +02001086 void SetRates(const RateControlParameters& parameters) {
Markus Handella3765182020-07-08 13:13:32 +02001087 MutexLock lock(&local_mutex_);
Evan Shrubsole7c079f62019-09-26 09:55:03 +02001088 num_set_rates_++;
Niels Möller6bb5ab92019-01-11 11:11:10 +01001089 VideoBitrateAllocation adjusted_rate_allocation;
1090 for (size_t si = 0; si < kMaxSpatialLayers; ++si) {
1091 for (size_t ti = 0; ti < kMaxTemporalStreams; ++ti) {
Erik Språng16cb8f52019-04-12 13:59:09 +02001092 if (parameters.bitrate.HasBitrate(si, ti)) {
Niels Möller6bb5ab92019-01-11 11:11:10 +01001093 adjusted_rate_allocation.SetBitrate(
1094 si, ti,
Erik Språng16cb8f52019-04-12 13:59:09 +02001095 static_cast<uint32_t>(parameters.bitrate.GetBitrate(si, ti) *
Niels Möller6bb5ab92019-01-11 11:11:10 +01001096 rate_factor_));
1097 }
1098 }
1099 }
Erik Språng16cb8f52019-04-12 13:59:09 +02001100 last_framerate_ = static_cast<uint32_t>(parameters.framerate_fps + 0.5);
Erik Språng5056af02019-09-02 15:53:11 +02001101 last_rate_control_settings_ = parameters;
Erik Språng16cb8f52019-04-12 13:59:09 +02001102 RateControlParameters adjusted_paramters = parameters;
1103 adjusted_paramters.bitrate = adjusted_rate_allocation;
1104 FakeEncoder::SetRates(adjusted_paramters);
Niels Möller6bb5ab92019-01-11 11:11:10 +01001105 }
1106
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02001107 TimeController* const time_controller_;
Markus Handella3765182020-07-08 13:13:32 +02001108 mutable Mutex local_mutex_;
Erik Språngb7cb7b52019-02-26 15:52:33 +01001109 enum class EncoderState {
1110 kUninitialized,
1111 kInitializationFailed,
1112 kInitialized
Markus Handella3765182020-07-08 13:13:32 +02001113 } initialized_ RTC_GUARDED_BY(local_mutex_) = EncoderState::kUninitialized;
1114 bool block_next_encode_ RTC_GUARDED_BY(local_mutex_) = false;
perkj26091b12016-09-01 01:17:40 -07001115 rtc::Event continue_encode_event_;
Markus Handella3765182020-07-08 13:13:32 +02001116 uint32_t timestamp_ RTC_GUARDED_BY(local_mutex_) = 0;
1117 int64_t ntp_time_ms_ RTC_GUARDED_BY(local_mutex_) = 0;
1118 int last_input_width_ RTC_GUARDED_BY(local_mutex_) = 0;
1119 int last_input_height_ RTC_GUARDED_BY(local_mutex_) = 0;
1120 bool quality_scaling_ RTC_GUARDED_BY(local_mutex_) = true;
1121 int requested_resolution_alignment_ RTC_GUARDED_BY(local_mutex_) = 1;
Åsa Perssonc5a74ff2020-09-20 17:50:00 +02001122 bool apply_alignment_to_all_simulcast_layers_ RTC_GUARDED_BY(local_mutex_) =
1123 false;
Markus Handella3765182020-07-08 13:13:32 +02001124 bool is_hardware_accelerated_ RTC_GUARDED_BY(local_mutex_) = false;
Mirta Dvornicic97910da2020-07-14 15:29:23 +02001125 rtc::scoped_refptr<EncodedImageBufferInterface> encoded_image_data_
1126 RTC_GUARDED_BY(local_mutex_);
Elad Aloncde8ab22019-03-20 11:56:20 +01001127 std::unique_ptr<Vp8FrameBufferController> frame_buffer_controller_
Markus Handella3765182020-07-08 13:13:32 +02001128 RTC_GUARDED_BY(local_mutex_);
Åsa Perssonc29cb2c2019-03-25 12:06:59 +01001129 absl::optional<bool>
1130 temporal_layers_supported_[kMaxSpatialLayers] RTC_GUARDED_BY(
Markus Handella3765182020-07-08 13:13:32 +02001131 local_mutex_);
1132 bool force_init_encode_failed_ RTC_GUARDED_BY(local_mutex_) = false;
1133 double rate_factor_ RTC_GUARDED_BY(local_mutex_) = 1.0;
1134 uint32_t last_framerate_ RTC_GUARDED_BY(local_mutex_) = 0;
Erik Språng5056af02019-09-02 15:53:11 +02001135 absl::optional<VideoEncoder::RateControlParameters>
1136 last_rate_control_settings_;
Markus Handella3765182020-07-08 13:13:32 +02001137 VideoFrame::UpdateRect last_update_rect_ RTC_GUARDED_BY(local_mutex_) = {
1138 0, 0, 0, 0};
Niels Möller87e2d782019-03-07 10:18:23 +01001139 std::vector<VideoFrameType> last_frame_types_;
Erik Språngd7329ca2019-02-21 21:19:53 +01001140 bool expect_null_frame_ = false;
Markus Handella3765182020-07-08 13:13:32 +02001141 EncodedImageCallback* encoded_image_callback_ RTC_GUARDED_BY(local_mutex_) =
1142 nullptr;
Evan Shrubsolefb862742020-03-16 16:18:36 +01001143 NiceMock<MockFecControllerOverride> fec_controller_override_;
Markus Handella3765182020-07-08 13:13:32 +02001144 int num_encoder_initializations_ RTC_GUARDED_BY(local_mutex_) = 0;
Sergey Silkin6456e352019-07-08 17:56:40 +02001145 std::vector<ResolutionBitrateLimits> resolution_bitrate_limits_
Markus Handella3765182020-07-08 13:13:32 +02001146 RTC_GUARDED_BY(local_mutex_);
1147 int num_set_rates_ RTC_GUARDED_BY(local_mutex_) = 0;
Åsa Perssonc5a74ff2020-09-20 17:50:00 +02001148 VideoCodec video_codec_ RTC_GUARDED_BY(local_mutex_);
Evan Shrubsole895556e2020-10-05 09:15:13 +02001149 absl::optional<VideoFrameBuffer::Type> last_input_pixel_format_
1150 RTC_GUARDED_BY(local_mutex_);
Evan Shrubsoleb556b082020-10-08 14:56:45 +02001151 absl::InlinedVector<VideoFrameBuffer::Type, kMaxPreferredPixelFormats>
1152 preferred_pixel_formats_ RTC_GUARDED_BY(local_mutex_);
perkj26091b12016-09-01 01:17:40 -07001153 };
1154
mflodmancc3d4422017-08-03 08:27:51 -07001155 class TestSink : public VideoStreamEncoder::EncoderSink {
perkj26091b12016-09-01 01:17:40 -07001156 public:
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02001157 TestSink(TimeController* time_controller, TestEncoder* test_encoder)
1158 : time_controller_(time_controller), test_encoder_(test_encoder) {
1159 RTC_DCHECK(time_controller_);
1160 }
perkj26091b12016-09-01 01:17:40 -07001161
perkj26091b12016-09-01 01:17:40 -07001162 void WaitForEncodedFrame(int64_t expected_ntp_time) {
sprang4847ae62017-06-27 07:06:52 -07001163 EXPECT_TRUE(
1164 TimedWaitForEncodedFrame(expected_ntp_time, kDefaultTimeoutMs));
1165 }
1166
1167 bool TimedWaitForEncodedFrame(int64_t expected_ntp_time,
1168 int64_t timeout_ms) {
perkj26091b12016-09-01 01:17:40 -07001169 uint32_t timestamp = 0;
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02001170 if (!WaitForFrame(timeout_ms))
sprang4847ae62017-06-27 07:06:52 -07001171 return false;
perkj26091b12016-09-01 01:17:40 -07001172 {
Markus Handella3765182020-07-08 13:13:32 +02001173 MutexLock lock(&mutex_);
sprangb1ca0732017-02-01 08:38:12 -08001174 timestamp = last_timestamp_;
perkj26091b12016-09-01 01:17:40 -07001175 }
1176 test_encoder_->CheckLastTimeStampsMatch(expected_ntp_time, timestamp);
sprang4847ae62017-06-27 07:06:52 -07001177 return true;
perkj26091b12016-09-01 01:17:40 -07001178 }
1179
sprangb1ca0732017-02-01 08:38:12 -08001180 void WaitForEncodedFrame(uint32_t expected_width,
1181 uint32_t expected_height) {
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02001182 EXPECT_TRUE(WaitForFrame(kDefaultTimeoutMs));
Åsa Perssonc74d8da2017-12-04 14:13:56 +01001183 CheckLastFrameSizeMatches(expected_width, expected_height);
sprangc5d62e22017-04-02 23:53:04 -07001184 }
1185
Åsa Perssonc74d8da2017-12-04 14:13:56 +01001186 void CheckLastFrameSizeMatches(uint32_t expected_width,
sprangc5d62e22017-04-02 23:53:04 -07001187 uint32_t expected_height) {
sprangb1ca0732017-02-01 08:38:12 -08001188 uint32_t width = 0;
1189 uint32_t height = 0;
sprangb1ca0732017-02-01 08:38:12 -08001190 {
Markus Handella3765182020-07-08 13:13:32 +02001191 MutexLock lock(&mutex_);
sprangb1ca0732017-02-01 08:38:12 -08001192 width = last_width_;
1193 height = last_height_;
1194 }
1195 EXPECT_EQ(expected_height, height);
1196 EXPECT_EQ(expected_width, width);
1197 }
1198
Ilya Nikolaevskiyba96e2f2019-06-04 15:15:14 +02001199 void CheckLastFrameRotationMatches(VideoRotation expected_rotation) {
1200 VideoRotation rotation;
1201 {
Markus Handella3765182020-07-08 13:13:32 +02001202 MutexLock lock(&mutex_);
Ilya Nikolaevskiyba96e2f2019-06-04 15:15:14 +02001203 rotation = last_rotation_;
1204 }
1205 EXPECT_EQ(expected_rotation, rotation);
1206 }
1207
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02001208 void ExpectDroppedFrame() { EXPECT_FALSE(WaitForFrame(100)); }
kthelgason2bc68642017-02-07 07:02:22 -08001209
sprangc5d62e22017-04-02 23:53:04 -07001210 bool WaitForFrame(int64_t timeout_ms) {
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02001211 RTC_DCHECK(time_controller_->GetMainThread()->IsCurrent());
1212 bool ret = encoded_frame_event_.Wait(timeout_ms);
1213 time_controller_->AdvanceTime(TimeDelta::Millis(0));
1214 return ret;
sprangc5d62e22017-04-02 23:53:04 -07001215 }
1216
perkj26091b12016-09-01 01:17:40 -07001217 void SetExpectNoFrames() {
Markus Handella3765182020-07-08 13:13:32 +02001218 MutexLock lock(&mutex_);
perkj26091b12016-09-01 01:17:40 -07001219 expect_frames_ = false;
1220 }
1221
asaperssonfab67072017-04-04 05:51:49 -07001222 int number_of_reconfigurations() const {
Markus Handella3765182020-07-08 13:13:32 +02001223 MutexLock lock(&mutex_);
Per512ecb32016-09-23 15:52:06 +02001224 return number_of_reconfigurations_;
1225 }
1226
asaperssonfab67072017-04-04 05:51:49 -07001227 int last_min_transmit_bitrate() const {
Markus Handella3765182020-07-08 13:13:32 +02001228 MutexLock lock(&mutex_);
Per512ecb32016-09-23 15:52:06 +02001229 return min_transmit_bitrate_bps_;
1230 }
1231
Erik Språngd7329ca2019-02-21 21:19:53 +01001232 void SetNumExpectedLayers(size_t num_layers) {
Markus Handella3765182020-07-08 13:13:32 +02001233 MutexLock lock(&mutex_);
Erik Språngd7329ca2019-02-21 21:19:53 +01001234 num_expected_layers_ = num_layers;
1235 }
1236
Erik Språngb7cb7b52019-02-26 15:52:33 +01001237 int64_t GetLastCaptureTimeMs() const {
Markus Handella3765182020-07-08 13:13:32 +02001238 MutexLock lock(&mutex_);
Erik Språngb7cb7b52019-02-26 15:52:33 +01001239 return last_capture_time_ms_;
1240 }
1241
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +02001242 std::vector<uint8_t> GetLastEncodedImageData() {
Markus Handella3765182020-07-08 13:13:32 +02001243 MutexLock lock(&mutex_);
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +02001244 return std::move(last_encoded_image_data_);
1245 }
1246
Per Kjellanderdcef6412020-10-07 15:09:05 +02001247 VideoBitrateAllocation GetLastVideoBitrateAllocation() {
1248 MutexLock lock(&mutex_);
1249 return last_bitrate_allocation_;
1250 }
1251
1252 int number_of_bitrate_allocations() const {
1253 MutexLock lock(&mutex_);
1254 return number_of_bitrate_allocations_;
1255 }
1256
Per Kjellandera9434842020-10-15 17:53:22 +02001257 VideoLayersAllocation GetLastVideoLayersAllocation() {
1258 MutexLock lock(&mutex_);
1259 return last_layers_allocation_;
1260 }
1261
1262 int number_of_layers_allocations() const {
1263 MutexLock lock(&mutex_);
1264 return number_of_layers_allocations_;
1265 }
1266
perkj26091b12016-09-01 01:17:40 -07001267 private:
sergeyu2cb155a2016-11-04 11:39:29 -07001268 Result OnEncodedImage(
1269 const EncodedImage& encoded_image,
Danil Chapovalov2549f172020-08-12 17:30:36 +02001270 const CodecSpecificInfo* codec_specific_info) override {
Markus Handella3765182020-07-08 13:13:32 +02001271 MutexLock lock(&mutex_);
Per512ecb32016-09-23 15:52:06 +02001272 EXPECT_TRUE(expect_frames_);
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +02001273 last_encoded_image_data_ = std::vector<uint8_t>(
1274 encoded_image.data(), encoded_image.data() + encoded_image.size());
Erik Språngd7329ca2019-02-21 21:19:53 +01001275 uint32_t timestamp = encoded_image.Timestamp();
1276 if (last_timestamp_ != timestamp) {
1277 num_received_layers_ = 1;
1278 } else {
1279 ++num_received_layers_;
1280 }
1281 last_timestamp_ = timestamp;
Erik Språngb7cb7b52019-02-26 15:52:33 +01001282 last_capture_time_ms_ = encoded_image.capture_time_ms_;
sprangb1ca0732017-02-01 08:38:12 -08001283 last_width_ = encoded_image._encodedWidth;
1284 last_height_ = encoded_image._encodedHeight;
Ilya Nikolaevskiyba96e2f2019-06-04 15:15:14 +02001285 last_rotation_ = encoded_image.rotation_;
Erik Språngd7329ca2019-02-21 21:19:53 +01001286 if (num_received_layers_ == num_expected_layers_) {
1287 encoded_frame_event_.Set();
1288 }
sprangb1ca0732017-02-01 08:38:12 -08001289 return Result(Result::OK, last_timestamp_);
Per512ecb32016-09-23 15:52:06 +02001290 }
1291
Rasmus Brandtc402dbe2019-02-04 11:09:46 +01001292 void OnEncoderConfigurationChanged(
1293 std::vector<VideoStream> streams,
Ilya Nikolaevskiy93be66c2020-04-02 14:10:27 +02001294 bool is_svc,
Rasmus Brandtc402dbe2019-02-04 11:09:46 +01001295 VideoEncoderConfig::ContentType content_type,
1296 int min_transmit_bitrate_bps) override {
Markus Handella3765182020-07-08 13:13:32 +02001297 MutexLock lock(&mutex_);
Per512ecb32016-09-23 15:52:06 +02001298 ++number_of_reconfigurations_;
1299 min_transmit_bitrate_bps_ = min_transmit_bitrate_bps;
1300 }
1301
Per Kjellanderdcef6412020-10-07 15:09:05 +02001302 void OnBitrateAllocationUpdated(
1303 const VideoBitrateAllocation& allocation) override {
1304 MutexLock lock(&mutex_);
1305 ++number_of_bitrate_allocations_;
1306 last_bitrate_allocation_ = allocation;
1307 }
1308
Per Kjellandera9434842020-10-15 17:53:22 +02001309 void OnVideoLayersAllocationUpdated(
1310 VideoLayersAllocation allocation) override {
1311 MutexLock lock(&mutex_);
1312 ++number_of_layers_allocations_;
1313 last_layers_allocation_ = allocation;
1314 rtc::StringBuilder log;
1315 for (const auto& layer : allocation.active_spatial_layers) {
1316 log << layer.width << "x" << layer.height << "@" << layer.frame_rate_fps
1317 << "[";
1318 for (const auto target_bitrate :
1319 layer.target_bitrate_per_temporal_layer) {
1320 log << target_bitrate.kbps() << ",";
1321 }
1322 log << "]";
1323 }
1324 RTC_DLOG(INFO) << "OnVideoLayersAllocationUpdated " << log.str();
1325 }
1326
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02001327 TimeController* const time_controller_;
Markus Handella3765182020-07-08 13:13:32 +02001328 mutable Mutex mutex_;
perkj26091b12016-09-01 01:17:40 -07001329 TestEncoder* test_encoder_;
1330 rtc::Event encoded_frame_event_;
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +02001331 std::vector<uint8_t> last_encoded_image_data_;
sprangb1ca0732017-02-01 08:38:12 -08001332 uint32_t last_timestamp_ = 0;
Erik Språngb7cb7b52019-02-26 15:52:33 +01001333 int64_t last_capture_time_ms_ = 0;
sprangb1ca0732017-02-01 08:38:12 -08001334 uint32_t last_height_ = 0;
1335 uint32_t last_width_ = 0;
Ilya Nikolaevskiyba96e2f2019-06-04 15:15:14 +02001336 VideoRotation last_rotation_ = kVideoRotation_0;
Erik Språngd7329ca2019-02-21 21:19:53 +01001337 size_t num_expected_layers_ = 1;
1338 size_t num_received_layers_ = 0;
perkj26091b12016-09-01 01:17:40 -07001339 bool expect_frames_ = true;
Per512ecb32016-09-23 15:52:06 +02001340 int number_of_reconfigurations_ = 0;
1341 int min_transmit_bitrate_bps_ = 0;
Per Kjellanderdcef6412020-10-07 15:09:05 +02001342 VideoBitrateAllocation last_bitrate_allocation_ RTC_GUARDED_BY(&mutex_);
1343 int number_of_bitrate_allocations_ RTC_GUARDED_BY(&mutex_) = 0;
Per Kjellandera9434842020-10-15 17:53:22 +02001344 VideoLayersAllocation last_layers_allocation_ RTC_GUARDED_BY(&mutex_);
1345 int number_of_layers_allocations_ RTC_GUARDED_BY(&mutex_) = 0;
perkj26091b12016-09-01 01:17:40 -07001346 };
1347
Sergey Silkin5ee69672019-07-02 14:18:34 +02001348 class VideoBitrateAllocatorProxyFactory
1349 : public VideoBitrateAllocatorFactory {
1350 public:
1351 VideoBitrateAllocatorProxyFactory()
1352 : bitrate_allocator_factory_(
1353 CreateBuiltinVideoBitrateAllocatorFactory()) {}
1354
1355 std::unique_ptr<VideoBitrateAllocator> CreateVideoBitrateAllocator(
1356 const VideoCodec& codec) override {
Markus Handella3765182020-07-08 13:13:32 +02001357 MutexLock lock(&mutex_);
Sergey Silkin5ee69672019-07-02 14:18:34 +02001358 codec_config_ = codec;
1359 return bitrate_allocator_factory_->CreateVideoBitrateAllocator(codec);
1360 }
1361
1362 VideoCodec codec_config() const {
Markus Handella3765182020-07-08 13:13:32 +02001363 MutexLock lock(&mutex_);
Sergey Silkin5ee69672019-07-02 14:18:34 +02001364 return codec_config_;
1365 }
1366
1367 private:
1368 std::unique_ptr<VideoBitrateAllocatorFactory> bitrate_allocator_factory_;
1369
Markus Handella3765182020-07-08 13:13:32 +02001370 mutable Mutex mutex_;
1371 VideoCodec codec_config_ RTC_GUARDED_BY(mutex_);
Sergey Silkin5ee69672019-07-02 14:18:34 +02001372 };
1373
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02001374 Clock* clock() { return time_controller_.GetClock(); }
1375 void AdvanceTime(TimeDelta duration) {
1376 time_controller_.AdvanceTime(duration);
1377 }
1378
1379 int64_t CurrentTimeMs() { return clock()->CurrentTime().ms(); }
1380
1381 protected:
1382 virtual TaskQueueFactory* GetTaskQueueFactory() {
1383 return time_controller_.GetTaskQueueFactory();
1384 }
1385
1386 GlobalSimulatedTimeController time_controller_{Timestamp::Micros(1234)};
perkj26091b12016-09-01 01:17:40 -07001387 VideoSendStream::Config video_send_config_;
Erik Språng08127a92016-11-16 16:41:30 +01001388 VideoEncoderConfig video_encoder_config_;
Per512ecb32016-09-23 15:52:06 +02001389 int codec_width_;
1390 int codec_height_;
sprang4847ae62017-06-27 07:06:52 -07001391 int max_framerate_;
perkj26091b12016-09-01 01:17:40 -07001392 TestEncoder fake_encoder_;
Niels Möllercbcbc222018-09-28 09:07:24 +02001393 test::VideoEncoderProxyFactory encoder_factory_;
Sergey Silkin5ee69672019-07-02 14:18:34 +02001394 VideoBitrateAllocatorProxyFactory bitrate_allocator_factory_;
sprangc5d62e22017-04-02 23:53:04 -07001395 std::unique_ptr<MockableSendStatisticsProxy> stats_proxy_;
perkj26091b12016-09-01 01:17:40 -07001396 TestSink sink_;
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02001397 AdaptingFrameForwarder video_source_{&time_controller_};
mflodmancc3d4422017-08-03 08:27:51 -07001398 std::unique_ptr<VideoStreamEncoderUnderTest> video_stream_encoder_;
perkj26091b12016-09-01 01:17:40 -07001399};
1400
mflodmancc3d4422017-08-03 08:27:51 -07001401TEST_F(VideoStreamEncoderTest, EncodeOneFrame) {
Henrik Boström381d1092020-05-12 18:49:07 +02001402 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001403 DataRate::BitsPerSec(kTargetBitrateBps),
1404 DataRate::BitsPerSec(kTargetBitrateBps),
1405 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Niels Möllerc572ff32018-11-07 08:43:50 +01001406 rtc::Event frame_destroyed_event;
perkja49cbd32016-09-16 07:53:41 -07001407 video_source_.IncomingCapturedFrame(CreateFrame(1, &frame_destroyed_event));
sprang4847ae62017-06-27 07:06:52 -07001408 WaitForEncodedFrame(1);
perkja49cbd32016-09-16 07:53:41 -07001409 EXPECT_TRUE(frame_destroyed_event.Wait(kDefaultTimeoutMs));
mflodmancc3d4422017-08-03 08:27:51 -07001410 video_stream_encoder_->Stop();
perkj26091b12016-09-01 01:17:40 -07001411}
1412
mflodmancc3d4422017-08-03 08:27:51 -07001413TEST_F(VideoStreamEncoderTest, DropsFramesBeforeFirstOnBitrateUpdated) {
perkj26091b12016-09-01 01:17:40 -07001414 // Dropped since no target bitrate has been set.
Niels Möllerc572ff32018-11-07 08:43:50 +01001415 rtc::Event frame_destroyed_event;
Sebastian Janssona3177052018-04-10 13:05:49 +02001416 // The encoder will cache up to one frame for a short duration. Adding two
1417 // frames means that the first frame will be dropped and the second frame will
1418 // be sent when the encoder is enabled.
perkja49cbd32016-09-16 07:53:41 -07001419 video_source_.IncomingCapturedFrame(CreateFrame(1, &frame_destroyed_event));
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02001420 AdvanceTime(TimeDelta::Millis(10));
Sebastian Janssona3177052018-04-10 13:05:49 +02001421 video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
perkja49cbd32016-09-16 07:53:41 -07001422 EXPECT_TRUE(frame_destroyed_event.Wait(kDefaultTimeoutMs));
perkj26091b12016-09-01 01:17:40 -07001423
Henrik Boström381d1092020-05-12 18:49:07 +02001424 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001425 DataRate::BitsPerSec(kTargetBitrateBps),
1426 DataRate::BitsPerSec(kTargetBitrateBps),
1427 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
perkj26091b12016-09-01 01:17:40 -07001428
Sebastian Janssona3177052018-04-10 13:05:49 +02001429 // The pending frame should be received.
sprang4847ae62017-06-27 07:06:52 -07001430 WaitForEncodedFrame(2);
Sebastian Janssona3177052018-04-10 13:05:49 +02001431 video_source_.IncomingCapturedFrame(CreateFrame(3, nullptr));
1432
1433 WaitForEncodedFrame(3);
mflodmancc3d4422017-08-03 08:27:51 -07001434 video_stream_encoder_->Stop();
perkj26091b12016-09-01 01:17:40 -07001435}
1436
mflodmancc3d4422017-08-03 08:27:51 -07001437TEST_F(VideoStreamEncoderTest, DropsFramesWhenRateSetToZero) {
Henrik Boström381d1092020-05-12 18:49:07 +02001438 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001439 DataRate::BitsPerSec(kTargetBitrateBps),
1440 DataRate::BitsPerSec(kTargetBitrateBps),
1441 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
perkja49cbd32016-09-16 07:53:41 -07001442 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
sprang4847ae62017-06-27 07:06:52 -07001443 WaitForEncodedFrame(1);
perkj26091b12016-09-01 01:17:40 -07001444
Henrik Boström381d1092020-05-12 18:49:07 +02001445 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
1446 DataRate::BitsPerSec(0), DataRate::BitsPerSec(0), DataRate::BitsPerSec(0),
1447 0, 0, 0);
Sebastian Janssona3177052018-04-10 13:05:49 +02001448 // The encoder will cache up to one frame for a short duration. Adding two
1449 // frames means that the first frame will be dropped and the second frame will
1450 // be sent when the encoder is resumed.
perkja49cbd32016-09-16 07:53:41 -07001451 video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
Sebastian Janssona3177052018-04-10 13:05:49 +02001452 video_source_.IncomingCapturedFrame(CreateFrame(3, nullptr));
perkj26091b12016-09-01 01:17:40 -07001453
Henrik Boström381d1092020-05-12 18:49:07 +02001454 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001455 DataRate::BitsPerSec(kTargetBitrateBps),
1456 DataRate::BitsPerSec(kTargetBitrateBps),
1457 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
sprang4847ae62017-06-27 07:06:52 -07001458 WaitForEncodedFrame(3);
Sebastian Janssona3177052018-04-10 13:05:49 +02001459 video_source_.IncomingCapturedFrame(CreateFrame(4, nullptr));
1460 WaitForEncodedFrame(4);
mflodmancc3d4422017-08-03 08:27:51 -07001461 video_stream_encoder_->Stop();
perkj26091b12016-09-01 01:17:40 -07001462}
1463
mflodmancc3d4422017-08-03 08:27:51 -07001464TEST_F(VideoStreamEncoderTest, DropsFramesWithSameOrOldNtpTimestamp) {
Henrik Boström381d1092020-05-12 18:49:07 +02001465 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001466 DataRate::BitsPerSec(kTargetBitrateBps),
1467 DataRate::BitsPerSec(kTargetBitrateBps),
1468 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
perkja49cbd32016-09-16 07:53:41 -07001469 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
sprang4847ae62017-06-27 07:06:52 -07001470 WaitForEncodedFrame(1);
perkj26091b12016-09-01 01:17:40 -07001471
1472 // This frame will be dropped since it has the same ntp timestamp.
perkja49cbd32016-09-16 07:53:41 -07001473 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
perkj26091b12016-09-01 01:17:40 -07001474
perkja49cbd32016-09-16 07:53:41 -07001475 video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
sprang4847ae62017-06-27 07:06:52 -07001476 WaitForEncodedFrame(2);
mflodmancc3d4422017-08-03 08:27:51 -07001477 video_stream_encoder_->Stop();
perkj26091b12016-09-01 01:17:40 -07001478}
1479
mflodmancc3d4422017-08-03 08:27:51 -07001480TEST_F(VideoStreamEncoderTest, DropsFrameAfterStop) {
Henrik Boström381d1092020-05-12 18:49:07 +02001481 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001482 DataRate::BitsPerSec(kTargetBitrateBps),
1483 DataRate::BitsPerSec(kTargetBitrateBps),
1484 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
perkj26091b12016-09-01 01:17:40 -07001485
perkja49cbd32016-09-16 07:53:41 -07001486 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
sprang4847ae62017-06-27 07:06:52 -07001487 WaitForEncodedFrame(1);
perkj26091b12016-09-01 01:17:40 -07001488
mflodmancc3d4422017-08-03 08:27:51 -07001489 video_stream_encoder_->Stop();
perkj26091b12016-09-01 01:17:40 -07001490 sink_.SetExpectNoFrames();
Niels Möllerc572ff32018-11-07 08:43:50 +01001491 rtc::Event frame_destroyed_event;
perkja49cbd32016-09-16 07:53:41 -07001492 video_source_.IncomingCapturedFrame(CreateFrame(2, &frame_destroyed_event));
1493 EXPECT_TRUE(frame_destroyed_event.Wait(kDefaultTimeoutMs));
perkj26091b12016-09-01 01:17:40 -07001494}
1495
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02001496class VideoStreamEncoderBlockedTest : public VideoStreamEncoderTest {
1497 public:
1498 VideoStreamEncoderBlockedTest() {}
1499
1500 TaskQueueFactory* GetTaskQueueFactory() override {
1501 return task_queue_factory_.get();
1502 }
1503
1504 private:
1505 std::unique_ptr<TaskQueueFactory> task_queue_factory_ =
1506 CreateDefaultTaskQueueFactory();
1507};
1508
1509TEST_F(VideoStreamEncoderBlockedTest, DropsPendingFramesOnSlowEncode) {
Henrik Boström381d1092020-05-12 18:49:07 +02001510 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001511 DataRate::BitsPerSec(kTargetBitrateBps),
1512 DataRate::BitsPerSec(kTargetBitrateBps),
1513 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
perkj26091b12016-09-01 01:17:40 -07001514
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02001515 int dropped_count = 0;
1516 stats_proxy_->SetDroppedFrameCallback(
1517 [&dropped_count](VideoStreamEncoderObserver::DropReason) {
1518 ++dropped_count;
1519 });
1520
perkj26091b12016-09-01 01:17:40 -07001521 fake_encoder_.BlockNextEncode();
perkja49cbd32016-09-16 07:53:41 -07001522 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
sprang4847ae62017-06-27 07:06:52 -07001523 WaitForEncodedFrame(1);
perkj26091b12016-09-01 01:17:40 -07001524 // Here, the encoder thread will be blocked in the TestEncoder waiting for a
1525 // call to ContinueEncode.
perkja49cbd32016-09-16 07:53:41 -07001526 video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
1527 video_source_.IncomingCapturedFrame(CreateFrame(3, nullptr));
perkj26091b12016-09-01 01:17:40 -07001528 fake_encoder_.ContinueEncode();
sprang4847ae62017-06-27 07:06:52 -07001529 WaitForEncodedFrame(3);
perkj26091b12016-09-01 01:17:40 -07001530
mflodmancc3d4422017-08-03 08:27:51 -07001531 video_stream_encoder_->Stop();
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02001532
1533 EXPECT_EQ(1, dropped_count);
perkj26091b12016-09-01 01:17:40 -07001534}
1535
Noah Richards51db4212019-06-12 06:59:12 -07001536TEST_F(VideoStreamEncoderTest, DropFrameWithFailedI420Conversion) {
Henrik Boström381d1092020-05-12 18:49:07 +02001537 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001538 DataRate::BitsPerSec(kTargetBitrateBps),
1539 DataRate::BitsPerSec(kTargetBitrateBps),
1540 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Noah Richards51db4212019-06-12 06:59:12 -07001541
1542 rtc::Event frame_destroyed_event;
1543 video_source_.IncomingCapturedFrame(
1544 CreateFakeNativeFrame(1, &frame_destroyed_event));
1545 ExpectDroppedFrame();
1546 EXPECT_TRUE(frame_destroyed_event.Wait(kDefaultTimeoutMs));
1547 video_stream_encoder_->Stop();
1548}
1549
1550TEST_F(VideoStreamEncoderTest, DropFrameWithFailedI420ConversionWithCrop) {
1551 // Use the cropping factory.
1552 video_encoder_config_.video_stream_factory =
1553 new rtc::RefCountedObject<CroppingVideoStreamFactory>(1, 30);
1554 video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config_),
1555 kMaxPayloadLength);
1556 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
1557
1558 // Capture a frame at codec_width_/codec_height_.
Henrik Boström381d1092020-05-12 18:49:07 +02001559 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001560 DataRate::BitsPerSec(kTargetBitrateBps),
1561 DataRate::BitsPerSec(kTargetBitrateBps),
1562 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Noah Richards51db4212019-06-12 06:59:12 -07001563 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
1564 WaitForEncodedFrame(1);
1565 // The encoder will have been configured once.
1566 EXPECT_EQ(1, sink_.number_of_reconfigurations());
1567 EXPECT_EQ(codec_width_, fake_encoder_.codec_config().width);
1568 EXPECT_EQ(codec_height_, fake_encoder_.codec_config().height);
1569
1570 // Now send in a fake frame that needs to be cropped as the width/height
1571 // aren't divisible by 4 (see CreateEncoderStreams above).
1572 rtc::Event frame_destroyed_event;
1573 video_source_.IncomingCapturedFrame(CreateFakeNativeFrame(
1574 2, &frame_destroyed_event, codec_width_ + 1, codec_height_ + 1));
1575 ExpectDroppedFrame();
1576 EXPECT_TRUE(frame_destroyed_event.Wait(kDefaultTimeoutMs));
1577 video_stream_encoder_->Stop();
1578}
1579
Evan Shrubsole895556e2020-10-05 09:15:13 +02001580TEST_F(VideoStreamEncoderTest, NonI420FramesShouldNotBeConvertedToI420) {
1581 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
1582 DataRate::BitsPerSec(kTargetBitrateBps),
1583 DataRate::BitsPerSec(kTargetBitrateBps),
1584 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
1585
1586 video_source_.IncomingCapturedFrame(
1587 CreateNV12Frame(1, codec_width_, codec_height_));
1588 WaitForEncodedFrame(1);
1589 EXPECT_EQ(VideoFrameBuffer::Type::kNV12,
1590 fake_encoder_.GetLastInputPixelFormat());
1591 video_stream_encoder_->Stop();
1592}
1593
Evan Shrubsoleb556b082020-10-08 14:56:45 +02001594TEST_F(VideoStreamEncoderTest,
1595 NativeFrameIsConvertedToI420IfNoFrameTypePreference) {
1596 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
1597 DataRate::BitsPerSec(kTargetBitrateBps),
1598 DataRate::BitsPerSec(kTargetBitrateBps),
1599 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
1600
1601 fake_encoder_.SetPreferredPixelFormats({});
1602
1603 rtc::Event frame_destroyed_event;
1604 video_source_.IncomingCapturedFrame(CreateFakeNV12NativeFrame(
1605 1, &frame_destroyed_event, codec_width_, codec_height_));
1606 WaitForEncodedFrame(1);
1607 EXPECT_EQ(VideoFrameBuffer::Type::kI420,
1608 fake_encoder_.GetLastInputPixelFormat());
1609 video_stream_encoder_->Stop();
1610}
1611
1612TEST_F(VideoStreamEncoderTest, NativeFrameMappedToPreferredPixelFormat) {
1613 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
1614 DataRate::BitsPerSec(kTargetBitrateBps),
1615 DataRate::BitsPerSec(kTargetBitrateBps),
1616 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
1617
1618 fake_encoder_.SetPreferredPixelFormats({VideoFrameBuffer::Type::kNV12});
1619
1620 rtc::Event frame_destroyed_event;
1621 video_source_.IncomingCapturedFrame(CreateFakeNV12NativeFrame(
1622 1, &frame_destroyed_event, codec_width_, codec_height_));
1623 WaitForEncodedFrame(1);
1624 EXPECT_EQ(VideoFrameBuffer::Type::kNV12,
1625 fake_encoder_.GetLastInputPixelFormat());
1626 video_stream_encoder_->Stop();
1627}
1628
1629TEST_F(VideoStreamEncoderTest, NativeFrameConvertedToI420IfMappingNotFeasible) {
1630 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
1631 DataRate::BitsPerSec(kTargetBitrateBps),
1632 DataRate::BitsPerSec(kTargetBitrateBps),
1633 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
1634
1635 // Fake NV12 native frame does not allow mapping to I444.
1636 fake_encoder_.SetPreferredPixelFormats({VideoFrameBuffer::Type::kI444});
1637
1638 rtc::Event frame_destroyed_event;
1639 video_source_.IncomingCapturedFrame(CreateFakeNV12NativeFrame(
1640 1, &frame_destroyed_event, codec_width_, codec_height_));
1641 WaitForEncodedFrame(1);
1642 EXPECT_EQ(VideoFrameBuffer::Type::kI420,
1643 fake_encoder_.GetLastInputPixelFormat());
1644 video_stream_encoder_->Stop();
1645}
1646
Evan Shrubsole895556e2020-10-05 09:15:13 +02001647TEST_F(VideoStreamEncoderTest, NativeFrameBackedByNV12FrameIsEncodedFromI420) {
1648 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
1649 DataRate::BitsPerSec(kTargetBitrateBps),
1650 DataRate::BitsPerSec(kTargetBitrateBps),
1651 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
1652
1653 rtc::Event frame_destroyed_event;
1654 video_source_.IncomingCapturedFrame(CreateFakeNV12NativeFrame(
1655 1, &frame_destroyed_event, codec_width_, codec_height_));
1656 WaitForEncodedFrame(1);
1657 EXPECT_EQ(VideoFrameBuffer::Type::kI420,
1658 fake_encoder_.GetLastInputPixelFormat());
1659 video_stream_encoder_->Stop();
1660}
1661
Ying Wang9b881ab2020-02-07 14:29:32 +01001662TEST_F(VideoStreamEncoderTest, DropsFramesWhenCongestionWindowPushbackSet) {
Henrik Boström381d1092020-05-12 18:49:07 +02001663 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001664 DataRate::BitsPerSec(kTargetBitrateBps),
1665 DataRate::BitsPerSec(kTargetBitrateBps),
1666 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Ying Wang9b881ab2020-02-07 14:29:32 +01001667 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
1668 WaitForEncodedFrame(1);
1669
Henrik Boström381d1092020-05-12 18:49:07 +02001670 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001671 DataRate::BitsPerSec(kTargetBitrateBps),
1672 DataRate::BitsPerSec(kTargetBitrateBps),
1673 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0.5);
Ying Wang9b881ab2020-02-07 14:29:32 +01001674 // The congestion window pushback is set to 0.5, which will drop 1/2 of
1675 // frames. Adding two frames means that the first frame will be dropped and
1676 // the second frame will be sent to the encoder.
1677 video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
1678 video_source_.IncomingCapturedFrame(CreateFrame(3, nullptr));
1679 WaitForEncodedFrame(3);
1680 video_source_.IncomingCapturedFrame(CreateFrame(4, nullptr));
1681 video_source_.IncomingCapturedFrame(CreateFrame(5, nullptr));
1682 WaitForEncodedFrame(5);
1683 EXPECT_EQ(2u, stats_proxy_->GetStats().frames_dropped_by_congestion_window);
1684 video_stream_encoder_->Stop();
1685}
1686
mflodmancc3d4422017-08-03 08:27:51 -07001687TEST_F(VideoStreamEncoderTest,
1688 ConfigureEncoderTriggersOnEncoderConfigurationChanged) {
Henrik Boström381d1092020-05-12 18:49:07 +02001689 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001690 DataRate::BitsPerSec(kTargetBitrateBps),
1691 DataRate::BitsPerSec(kTargetBitrateBps),
1692 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Per21d45d22016-10-30 21:37:57 +01001693 EXPECT_EQ(0, sink_.number_of_reconfigurations());
Per512ecb32016-09-23 15:52:06 +02001694
1695 // Capture a frame and wait for it to synchronize with the encoder thread.
Perf8c5f2b2016-09-23 16:24:55 +02001696 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
sprang4847ae62017-06-27 07:06:52 -07001697 WaitForEncodedFrame(1);
Per21d45d22016-10-30 21:37:57 +01001698 // The encoder will have been configured once when the first frame is
1699 // received.
1700 EXPECT_EQ(1, sink_.number_of_reconfigurations());
Per512ecb32016-09-23 15:52:06 +02001701
1702 VideoEncoderConfig video_encoder_config;
Niels Möller259a4972018-04-05 15:36:51 +02001703 test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
Per512ecb32016-09-23 15:52:06 +02001704 video_encoder_config.min_transmit_bitrate_bps = 9999;
mflodmancc3d4422017-08-03 08:27:51 -07001705 video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config),
Niels Möllerf1338562018-04-26 09:51:47 +02001706 kMaxPayloadLength);
Per512ecb32016-09-23 15:52:06 +02001707
1708 // Capture a frame and wait for it to synchronize with the encoder thread.
Perf8c5f2b2016-09-23 16:24:55 +02001709 video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
sprang4847ae62017-06-27 07:06:52 -07001710 WaitForEncodedFrame(2);
Per21d45d22016-10-30 21:37:57 +01001711 EXPECT_EQ(2, sink_.number_of_reconfigurations());
perkj3b703ed2016-09-29 23:25:40 -07001712 EXPECT_EQ(9999, sink_.last_min_transmit_bitrate());
perkj26105b42016-09-29 22:39:10 -07001713
mflodmancc3d4422017-08-03 08:27:51 -07001714 video_stream_encoder_->Stop();
perkj26105b42016-09-29 22:39:10 -07001715}
1716
mflodmancc3d4422017-08-03 08:27:51 -07001717TEST_F(VideoStreamEncoderTest, FrameResolutionChangeReconfigureEncoder) {
Henrik Boström381d1092020-05-12 18:49:07 +02001718 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001719 DataRate::BitsPerSec(kTargetBitrateBps),
1720 DataRate::BitsPerSec(kTargetBitrateBps),
1721 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
perkjfa10b552016-10-02 23:45:26 -07001722
1723 // Capture a frame and wait for it to synchronize with the encoder thread.
1724 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
sprang4847ae62017-06-27 07:06:52 -07001725 WaitForEncodedFrame(1);
Per21d45d22016-10-30 21:37:57 +01001726 // The encoder will have been configured once.
1727 EXPECT_EQ(1, sink_.number_of_reconfigurations());
perkjfa10b552016-10-02 23:45:26 -07001728 EXPECT_EQ(codec_width_, fake_encoder_.codec_config().width);
1729 EXPECT_EQ(codec_height_, fake_encoder_.codec_config().height);
1730
1731 codec_width_ *= 2;
1732 codec_height_ *= 2;
1733 // Capture a frame with a higher resolution and wait for it to synchronize
1734 // with the encoder thread.
1735 video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
sprang4847ae62017-06-27 07:06:52 -07001736 WaitForEncodedFrame(2);
perkjfa10b552016-10-02 23:45:26 -07001737 EXPECT_EQ(codec_width_, fake_encoder_.codec_config().width);
1738 EXPECT_EQ(codec_height_, fake_encoder_.codec_config().height);
Per21d45d22016-10-30 21:37:57 +01001739 EXPECT_EQ(2, sink_.number_of_reconfigurations());
perkjfa10b552016-10-02 23:45:26 -07001740
mflodmancc3d4422017-08-03 08:27:51 -07001741 video_stream_encoder_->Stop();
perkjfa10b552016-10-02 23:45:26 -07001742}
1743
Sergey Silkin443b7ee2019-06-28 12:53:07 +02001744TEST_F(VideoStreamEncoderTest,
1745 EncoderInstanceDestroyedBeforeAnotherInstanceCreated) {
Henrik Boström381d1092020-05-12 18:49:07 +02001746 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001747 DataRate::BitsPerSec(kTargetBitrateBps),
1748 DataRate::BitsPerSec(kTargetBitrateBps),
1749 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Sergey Silkin443b7ee2019-06-28 12:53:07 +02001750
1751 // Capture a frame and wait for it to synchronize with the encoder thread.
1752 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
1753 WaitForEncodedFrame(1);
1754
1755 VideoEncoderConfig video_encoder_config;
1756 test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
1757 // Changing the max payload data length recreates encoder.
1758 video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config),
1759 kMaxPayloadLength / 2);
1760
1761 // Capture a frame and wait for it to synchronize with the encoder thread.
1762 video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
1763 WaitForEncodedFrame(2);
1764 EXPECT_EQ(1, encoder_factory_.GetMaxNumberOfSimultaneousEncoderInstances());
1765
1766 video_stream_encoder_->Stop();
1767}
1768
Sergey Silkin5ee69672019-07-02 14:18:34 +02001769TEST_F(VideoStreamEncoderTest, BitrateLimitsChangeReconfigureRateAllocator) {
Henrik Boström381d1092020-05-12 18:49:07 +02001770 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001771 DataRate::BitsPerSec(kTargetBitrateBps),
1772 DataRate::BitsPerSec(kTargetBitrateBps),
1773 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Sergey Silkin5ee69672019-07-02 14:18:34 +02001774
1775 VideoEncoderConfig video_encoder_config;
1776 test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
1777 video_encoder_config.max_bitrate_bps = kTargetBitrateBps;
1778 video_stream_encoder_->SetStartBitrate(kStartBitrateBps);
1779 video_stream_encoder_->ConfigureEncoder(video_encoder_config.Copy(),
1780 kMaxPayloadLength);
1781
1782 // Capture a frame and wait for it to synchronize with the encoder thread.
1783 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
1784 WaitForEncodedFrame(1);
1785 // The encoder will have been configured once when the first frame is
1786 // received.
1787 EXPECT_EQ(1, sink_.number_of_reconfigurations());
1788 EXPECT_EQ(kTargetBitrateBps,
1789 bitrate_allocator_factory_.codec_config().maxBitrate * 1000);
1790 EXPECT_EQ(kStartBitrateBps,
1791 bitrate_allocator_factory_.codec_config().startBitrate * 1000);
1792
Sergey Silkin6456e352019-07-08 17:56:40 +02001793 test::FillEncoderConfiguration(kVideoCodecVP8, 1,
1794 &video_encoder_config); //???
Sergey Silkin5ee69672019-07-02 14:18:34 +02001795 video_encoder_config.max_bitrate_bps = kTargetBitrateBps * 2;
1796 video_stream_encoder_->SetStartBitrate(kStartBitrateBps * 2);
1797 video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config),
1798 kMaxPayloadLength);
1799
1800 // Capture a frame and wait for it to synchronize with the encoder thread.
1801 video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
1802 WaitForEncodedFrame(2);
1803 EXPECT_EQ(2, sink_.number_of_reconfigurations());
1804 // Bitrate limits have changed - rate allocator should be reconfigured,
1805 // encoder should not be reconfigured.
1806 EXPECT_EQ(kTargetBitrateBps * 2,
1807 bitrate_allocator_factory_.codec_config().maxBitrate * 1000);
1808 EXPECT_EQ(kStartBitrateBps * 2,
1809 bitrate_allocator_factory_.codec_config().startBitrate * 1000);
1810 EXPECT_EQ(1, fake_encoder_.GetNumEncoderInitializations());
1811
1812 video_stream_encoder_->Stop();
1813}
1814
Sergey Silkin6456e352019-07-08 17:56:40 +02001815TEST_F(VideoStreamEncoderTest,
Sergey Silkincd02eba2020-01-20 14:48:40 +01001816 IntersectionOfEncoderAndAppBitrateLimitsUsedWhenBothProvided) {
Henrik Boström381d1092020-05-12 18:49:07 +02001817 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001818 DataRate::BitsPerSec(kTargetBitrateBps),
1819 DataRate::BitsPerSec(kTargetBitrateBps),
1820 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Sergey Silkin6456e352019-07-08 17:56:40 +02001821
Sergey Silkincd02eba2020-01-20 14:48:40 +01001822 const uint32_t kMinEncBitrateKbps = 100;
1823 const uint32_t kMaxEncBitrateKbps = 1000;
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001824 const VideoEncoder::ResolutionBitrateLimits encoder_bitrate_limits(
Sergey Silkincd02eba2020-01-20 14:48:40 +01001825 /*frame_size_pixels=*/codec_width_ * codec_height_,
1826 /*min_start_bitrate_bps=*/0,
1827 /*min_bitrate_bps=*/kMinEncBitrateKbps * 1000,
1828 /*max_bitrate_bps=*/kMaxEncBitrateKbps * 1000);
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001829 fake_encoder_.SetResolutionBitrateLimits({encoder_bitrate_limits});
1830
Sergey Silkincd02eba2020-01-20 14:48:40 +01001831 VideoEncoderConfig video_encoder_config;
1832 test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
1833 video_encoder_config.max_bitrate_bps = (kMaxEncBitrateKbps + 1) * 1000;
1834 video_encoder_config.simulcast_layers[0].min_bitrate_bps =
1835 (kMinEncBitrateKbps + 1) * 1000;
1836 video_stream_encoder_->ConfigureEncoder(video_encoder_config.Copy(),
1837 kMaxPayloadLength);
1838
1839 // When both encoder and app provide bitrate limits, the intersection of
1840 // provided sets should be used.
1841 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
1842 WaitForEncodedFrame(1);
1843 EXPECT_EQ(kMaxEncBitrateKbps,
1844 bitrate_allocator_factory_.codec_config().maxBitrate);
1845 EXPECT_EQ(kMinEncBitrateKbps + 1,
1846 bitrate_allocator_factory_.codec_config().minBitrate);
1847
1848 video_encoder_config.max_bitrate_bps = (kMaxEncBitrateKbps - 1) * 1000;
1849 video_encoder_config.simulcast_layers[0].min_bitrate_bps =
1850 (kMinEncBitrateKbps - 1) * 1000;
1851 video_stream_encoder_->ConfigureEncoder(video_encoder_config.Copy(),
1852 kMaxPayloadLength);
1853 video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001854 WaitForEncodedFrame(2);
Sergey Silkincd02eba2020-01-20 14:48:40 +01001855 EXPECT_EQ(kMaxEncBitrateKbps - 1,
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001856 bitrate_allocator_factory_.codec_config().maxBitrate);
Sergey Silkincd02eba2020-01-20 14:48:40 +01001857 EXPECT_EQ(kMinEncBitrateKbps,
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001858 bitrate_allocator_factory_.codec_config().minBitrate);
1859
Sergey Silkincd02eba2020-01-20 14:48:40 +01001860 video_stream_encoder_->Stop();
1861}
1862
1863TEST_F(VideoStreamEncoderTest,
1864 EncoderAndAppLimitsDontIntersectEncoderLimitsIgnored) {
Henrik Boström381d1092020-05-12 18:49:07 +02001865 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001866 DataRate::BitsPerSec(kTargetBitrateBps),
1867 DataRate::BitsPerSec(kTargetBitrateBps),
1868 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Sergey Silkincd02eba2020-01-20 14:48:40 +01001869
1870 const uint32_t kMinAppBitrateKbps = 100;
1871 const uint32_t kMaxAppBitrateKbps = 200;
1872 const uint32_t kMinEncBitrateKbps = kMaxAppBitrateKbps + 1;
1873 const uint32_t kMaxEncBitrateKbps = kMaxAppBitrateKbps * 2;
1874 const VideoEncoder::ResolutionBitrateLimits encoder_bitrate_limits(
1875 /*frame_size_pixels=*/codec_width_ * codec_height_,
1876 /*min_start_bitrate_bps=*/0,
1877 /*min_bitrate_bps=*/kMinEncBitrateKbps * 1000,
1878 /*max_bitrate_bps=*/kMaxEncBitrateKbps * 1000);
1879 fake_encoder_.SetResolutionBitrateLimits({encoder_bitrate_limits});
1880
1881 VideoEncoderConfig video_encoder_config;
1882 test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
1883 video_encoder_config.max_bitrate_bps = kMaxAppBitrateKbps * 1000;
1884 video_encoder_config.simulcast_layers[0].min_bitrate_bps =
1885 kMinAppBitrateKbps * 1000;
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001886 video_stream_encoder_->ConfigureEncoder(video_encoder_config.Copy(),
1887 kMaxPayloadLength);
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001888
Sergey Silkincd02eba2020-01-20 14:48:40 +01001889 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
1890 WaitForEncodedFrame(1);
1891 EXPECT_EQ(kMaxAppBitrateKbps,
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001892 bitrate_allocator_factory_.codec_config().maxBitrate);
Sergey Silkincd02eba2020-01-20 14:48:40 +01001893 EXPECT_EQ(kMinAppBitrateKbps,
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001894 bitrate_allocator_factory_.codec_config().minBitrate);
Sergey Silkin6456e352019-07-08 17:56:40 +02001895
1896 video_stream_encoder_->Stop();
1897}
1898
1899TEST_F(VideoStreamEncoderTest,
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001900 EncoderRecommendedMaxAndMinBitratesUsedForGivenResolution) {
Henrik Boström381d1092020-05-12 18:49:07 +02001901 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001902 DataRate::BitsPerSec(kTargetBitrateBps),
1903 DataRate::BitsPerSec(kTargetBitrateBps),
1904 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Sergey Silkin6456e352019-07-08 17:56:40 +02001905
1906 const VideoEncoder::ResolutionBitrateLimits encoder_bitrate_limits_270p(
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001907 480 * 270, 34 * 1000, 12 * 1000, 1234 * 1000);
Sergey Silkin6456e352019-07-08 17:56:40 +02001908 const VideoEncoder::ResolutionBitrateLimits encoder_bitrate_limits_360p(
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001909 640 * 360, 43 * 1000, 21 * 1000, 2345 * 1000);
Sergey Silkin6456e352019-07-08 17:56:40 +02001910 fake_encoder_.SetResolutionBitrateLimits(
1911 {encoder_bitrate_limits_270p, encoder_bitrate_limits_360p});
1912
1913 VideoEncoderConfig video_encoder_config;
1914 test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
1915 video_encoder_config.max_bitrate_bps = 0;
1916 video_stream_encoder_->ConfigureEncoder(video_encoder_config.Copy(),
1917 kMaxPayloadLength);
1918
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001919 // 270p. The bitrate limits recommended by encoder for 270p should be used.
Sergey Silkin6456e352019-07-08 17:56:40 +02001920 video_source_.IncomingCapturedFrame(CreateFrame(1, 480, 270));
1921 WaitForEncodedFrame(1);
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001922 EXPECT_EQ(static_cast<uint32_t>(encoder_bitrate_limits_270p.min_bitrate_bps),
1923 bitrate_allocator_factory_.codec_config().minBitrate * 1000);
Sergey Silkin6456e352019-07-08 17:56:40 +02001924 EXPECT_EQ(static_cast<uint32_t>(encoder_bitrate_limits_270p.max_bitrate_bps),
1925 bitrate_allocator_factory_.codec_config().maxBitrate * 1000);
1926
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001927 // 360p. The bitrate limits recommended by encoder for 360p should be used.
Sergey Silkin6456e352019-07-08 17:56:40 +02001928 video_source_.IncomingCapturedFrame(CreateFrame(2, 640, 360));
1929 WaitForEncodedFrame(2);
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001930 EXPECT_EQ(static_cast<uint32_t>(encoder_bitrate_limits_360p.min_bitrate_bps),
1931 bitrate_allocator_factory_.codec_config().minBitrate * 1000);
Sergey Silkin6456e352019-07-08 17:56:40 +02001932 EXPECT_EQ(static_cast<uint32_t>(encoder_bitrate_limits_360p.max_bitrate_bps),
1933 bitrate_allocator_factory_.codec_config().maxBitrate * 1000);
1934
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001935 // Resolution between 270p and 360p. The bitrate limits recommended by
Sergey Silkin6456e352019-07-08 17:56:40 +02001936 // encoder for 360p should be used.
1937 video_source_.IncomingCapturedFrame(
1938 CreateFrame(3, (640 + 480) / 2, (360 + 270) / 2));
1939 WaitForEncodedFrame(3);
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001940 EXPECT_EQ(static_cast<uint32_t>(encoder_bitrate_limits_360p.min_bitrate_bps),
1941 bitrate_allocator_factory_.codec_config().minBitrate * 1000);
Sergey Silkin6456e352019-07-08 17:56:40 +02001942 EXPECT_EQ(static_cast<uint32_t>(encoder_bitrate_limits_360p.max_bitrate_bps),
1943 bitrate_allocator_factory_.codec_config().maxBitrate * 1000);
1944
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001945 // Resolution higher than 360p. The caps recommended by encoder should be
Sergey Silkin6456e352019-07-08 17:56:40 +02001946 // ignored.
1947 video_source_.IncomingCapturedFrame(CreateFrame(4, 960, 540));
1948 WaitForEncodedFrame(4);
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001949 EXPECT_NE(static_cast<uint32_t>(encoder_bitrate_limits_270p.min_bitrate_bps),
1950 bitrate_allocator_factory_.codec_config().minBitrate * 1000);
Sergey Silkin6456e352019-07-08 17:56:40 +02001951 EXPECT_NE(static_cast<uint32_t>(encoder_bitrate_limits_270p.max_bitrate_bps),
1952 bitrate_allocator_factory_.codec_config().maxBitrate * 1000);
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001953 EXPECT_NE(static_cast<uint32_t>(encoder_bitrate_limits_360p.min_bitrate_bps),
1954 bitrate_allocator_factory_.codec_config().minBitrate * 1000);
Sergey Silkin6456e352019-07-08 17:56:40 +02001955 EXPECT_NE(static_cast<uint32_t>(encoder_bitrate_limits_360p.max_bitrate_bps),
1956 bitrate_allocator_factory_.codec_config().maxBitrate * 1000);
1957
1958 // Resolution lower than 270p. The max bitrate limit recommended by encoder
1959 // for 270p should be used.
1960 video_source_.IncomingCapturedFrame(CreateFrame(5, 320, 180));
1961 WaitForEncodedFrame(5);
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001962 EXPECT_EQ(static_cast<uint32_t>(encoder_bitrate_limits_270p.min_bitrate_bps),
1963 bitrate_allocator_factory_.codec_config().minBitrate * 1000);
Sergey Silkin6456e352019-07-08 17:56:40 +02001964 EXPECT_EQ(static_cast<uint32_t>(encoder_bitrate_limits_270p.max_bitrate_bps),
1965 bitrate_allocator_factory_.codec_config().maxBitrate * 1000);
1966
1967 video_stream_encoder_->Stop();
1968}
1969
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001970TEST_F(VideoStreamEncoderTest, EncoderRecommendedMaxBitrateCapsTargetBitrate) {
Henrik Boström381d1092020-05-12 18:49:07 +02001971 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01001972 DataRate::BitsPerSec(kTargetBitrateBps),
1973 DataRate::BitsPerSec(kTargetBitrateBps),
1974 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Sergey Silkin6b2cec12019-08-09 16:04:05 +02001975
1976 VideoEncoderConfig video_encoder_config;
1977 test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
1978 video_encoder_config.max_bitrate_bps = 0;
1979 video_stream_encoder_->ConfigureEncoder(video_encoder_config.Copy(),
1980 kMaxPayloadLength);
1981
1982 // Encode 720p frame to get the default encoder target bitrate.
1983 video_source_.IncomingCapturedFrame(CreateFrame(1, 1280, 720));
1984 WaitForEncodedFrame(1);
1985 const uint32_t kDefaultTargetBitrateFor720pKbps =
1986 bitrate_allocator_factory_.codec_config()
1987 .simulcastStream[0]
1988 .targetBitrate;
1989
1990 // Set the max recommended encoder bitrate to something lower than the default
1991 // target bitrate.
1992 const VideoEncoder::ResolutionBitrateLimits encoder_bitrate_limits(
1993 1280 * 720, 10 * 1000, 10 * 1000,
1994 kDefaultTargetBitrateFor720pKbps / 2 * 1000);
1995 fake_encoder_.SetResolutionBitrateLimits({encoder_bitrate_limits});
1996
1997 // Change resolution to trigger encoder reinitialization.
1998 video_source_.IncomingCapturedFrame(CreateFrame(2, 640, 360));
1999 WaitForEncodedFrame(2);
2000 video_source_.IncomingCapturedFrame(CreateFrame(3, 1280, 720));
2001 WaitForEncodedFrame(3);
2002
2003 // Ensure the target bitrate is capped by the max bitrate.
2004 EXPECT_EQ(bitrate_allocator_factory_.codec_config().maxBitrate * 1000,
2005 static_cast<uint32_t>(encoder_bitrate_limits.max_bitrate_bps));
2006 EXPECT_EQ(bitrate_allocator_factory_.codec_config()
2007 .simulcastStream[0]
2008 .targetBitrate *
2009 1000,
2010 static_cast<uint32_t>(encoder_bitrate_limits.max_bitrate_bps));
2011
2012 video_stream_encoder_->Stop();
2013}
2014
mflodmancc3d4422017-08-03 08:27:51 -07002015TEST_F(VideoStreamEncoderTest, SwitchSourceDeregisterEncoderAsSink) {
perkj803d97f2016-11-01 11:45:46 -07002016 EXPECT_TRUE(video_source_.has_sinks());
2017 test::FrameForwarder new_video_source;
mflodmancc3d4422017-08-03 08:27:51 -07002018 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002019 &new_video_source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
perkj803d97f2016-11-01 11:45:46 -07002020 EXPECT_FALSE(video_source_.has_sinks());
2021 EXPECT_TRUE(new_video_source.has_sinks());
2022
mflodmancc3d4422017-08-03 08:27:51 -07002023 video_stream_encoder_->Stop();
perkj803d97f2016-11-01 11:45:46 -07002024}
2025
mflodmancc3d4422017-08-03 08:27:51 -07002026TEST_F(VideoStreamEncoderTest, SinkWantsRotationApplied) {
perkj803d97f2016-11-01 11:45:46 -07002027 EXPECT_FALSE(video_source_.sink_wants().rotation_applied);
mflodmancc3d4422017-08-03 08:27:51 -07002028 video_stream_encoder_->SetSink(&sink_, true /*rotation_applied*/);
perkj803d97f2016-11-01 11:45:46 -07002029 EXPECT_TRUE(video_source_.sink_wants().rotation_applied);
mflodmancc3d4422017-08-03 08:27:51 -07002030 video_stream_encoder_->Stop();
perkj803d97f2016-11-01 11:45:46 -07002031}
2032
Åsa Perssonc5a74ff2020-09-20 17:50:00 +02002033class ResolutionAlignmentTest
2034 : public VideoStreamEncoderTest,
2035 public ::testing::WithParamInterface<
2036 ::testing::tuple<int, std::vector<double>>> {
2037 public:
2038 ResolutionAlignmentTest()
2039 : requested_alignment_(::testing::get<0>(GetParam())),
2040 scale_factors_(::testing::get<1>(GetParam())) {}
2041
2042 protected:
2043 const int requested_alignment_;
2044 const std::vector<double> scale_factors_;
2045};
2046
2047INSTANTIATE_TEST_SUITE_P(
2048 AlignmentAndScaleFactors,
2049 ResolutionAlignmentTest,
2050 ::testing::Combine(
2051 ::testing::Values(1, 2, 3, 4, 5, 6, 16, 22), // requested_alignment_
2052 ::testing::Values(std::vector<double>{-1.0}, // scale_factors_
2053 std::vector<double>{-1.0, -1.0},
2054 std::vector<double>{-1.0, -1.0, -1.0},
2055 std::vector<double>{4.0, 2.0, 1.0},
2056 std::vector<double>{9999.0, -1.0, 1.0},
2057 std::vector<double>{3.99, 2.01, 1.0},
2058 std::vector<double>{4.9, 1.7, 1.25},
2059 std::vector<double>{10.0, 4.0, 3.0},
2060 std::vector<double>{1.75, 3.5},
2061 std::vector<double>{1.5, 2.5},
2062 std::vector<double>{1.3, 1.0})));
2063
2064TEST_P(ResolutionAlignmentTest, SinkWantsAlignmentApplied) {
2065 // Set requested resolution alignment.
Rasmus Brandt5cad55b2019-12-19 09:47:11 +01002066 video_source_.set_adaptation_enabled(true);
Åsa Perssonc5a74ff2020-09-20 17:50:00 +02002067 fake_encoder_.SetRequestedResolutionAlignment(requested_alignment_);
2068 fake_encoder_.SetApplyAlignmentToAllSimulcastLayers(true);
2069
2070 // Fill config with the scaling factor by which to reduce encoding size.
2071 const int num_streams = scale_factors_.size();
2072 VideoEncoderConfig config;
2073 test::FillEncoderConfiguration(kVideoCodecVP8, num_streams, &config);
2074 for (int i = 0; i < num_streams; ++i) {
2075 config.simulcast_layers[i].scale_resolution_down_by = scale_factors_[i];
2076 }
2077 config.video_stream_factory =
2078 new rtc::RefCountedObject<cricket::EncoderStreamFactory>(
2079 "VP8", /*max qp*/ 56, /*screencast*/ false,
2080 /*screenshare enabled*/ false);
2081 video_stream_encoder_->ConfigureEncoder(std::move(config), kMaxPayloadLength);
2082
Henrik Boström381d1092020-05-12 18:49:07 +02002083 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Åsa Perssonc5a74ff2020-09-20 17:50:00 +02002084 DataRate::BitsPerSec(kSimulcastTargetBitrateBps),
2085 DataRate::BitsPerSec(kSimulcastTargetBitrateBps),
2086 DataRate::BitsPerSec(kSimulcastTargetBitrateBps), 0, 0, 0);
2087 // Wait for all layers before triggering event.
2088 sink_.SetNumExpectedLayers(num_streams);
Rasmus Brandt5cad55b2019-12-19 09:47:11 +01002089
2090 // On the 1st frame, we should have initialized the encoder and
2091 // asked for its resolution requirements.
Åsa Perssonc5a74ff2020-09-20 17:50:00 +02002092 int64_t timestamp_ms = kFrameIntervalMs;
2093 video_source_.IncomingCapturedFrame(CreateFrame(timestamp_ms, 1280, 720));
2094 WaitForEncodedFrame(timestamp_ms);
2095 EXPECT_EQ(1, fake_encoder_.GetNumEncoderInitializations());
Rasmus Brandt5cad55b2019-12-19 09:47:11 +01002096
2097 // On the 2nd frame, we should be receiving a correctly aligned resolution.
2098 // (It's up the to the encoder to potentially drop the previous frame,
2099 // to avoid coding back-to-back keyframes.)
Åsa Perssonc5a74ff2020-09-20 17:50:00 +02002100 timestamp_ms += kFrameIntervalMs;
2101 video_source_.IncomingCapturedFrame(CreateFrame(timestamp_ms, 1280, 720));
2102 WaitForEncodedFrame(timestamp_ms);
2103 EXPECT_GE(fake_encoder_.GetNumEncoderInitializations(), 1);
2104
2105 VideoCodec codec = fake_encoder_.video_codec();
2106 EXPECT_EQ(codec.numberOfSimulcastStreams, num_streams);
2107 // Frame size should be a multiple of the requested alignment.
2108 for (int i = 0; i < codec.numberOfSimulcastStreams; ++i) {
2109 EXPECT_EQ(codec.simulcastStream[i].width % requested_alignment_, 0);
2110 EXPECT_EQ(codec.simulcastStream[i].height % requested_alignment_, 0);
2111 // Aspect ratio should match.
2112 EXPECT_EQ(codec.width * codec.simulcastStream[i].height,
2113 codec.height * codec.simulcastStream[i].width);
2114 }
Rasmus Brandt5cad55b2019-12-19 09:47:11 +01002115
2116 video_stream_encoder_->Stop();
2117}
2118
Jonathan Yubc771b72017-12-08 17:04:29 -08002119TEST_F(VideoStreamEncoderTest, TestCpuDowngrades_BalancedMode) {
2120 const int kFramerateFps = 30;
asaperssonf7e294d2017-06-13 23:25:22 -07002121 const int kWidth = 1280;
2122 const int kHeight = 720;
Jonathan Yubc771b72017-12-08 17:04:29 -08002123
2124 // We rely on the automatic resolution adaptation, but we handle framerate
2125 // adaptation manually by mocking the stats proxy.
2126 video_source_.set_adaptation_enabled(true);
asaperssonf7e294d2017-06-13 23:25:22 -07002127
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002128 // Enable BALANCED preference, no initial limitation.
Henrik Boström381d1092020-05-12 18:49:07 +02002129 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01002130 DataRate::BitsPerSec(kTargetBitrateBps),
2131 DataRate::BitsPerSec(kTargetBitrateBps),
2132 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002133 video_stream_encoder_->SetSource(&video_source_,
2134 webrtc::DegradationPreference::BALANCED);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02002135 EXPECT_THAT(video_source_.sink_wants(), UnlimitedSinkWants());
asaperssonf7e294d2017-06-13 23:25:22 -07002136 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
Jonathan Yubc771b72017-12-08 17:04:29 -08002137 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
asaperssonf7e294d2017-06-13 23:25:22 -07002138 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
2139
Jonathan Yubc771b72017-12-08 17:04:29 -08002140 // Adapt down as far as possible.
2141 rtc::VideoSinkWants last_wants;
2142 int64_t t = 1;
2143 int loop_count = 0;
2144 do {
2145 ++loop_count;
2146 last_wants = video_source_.sink_wants();
2147
2148 // Simulate the framerate we've been asked to adapt to.
2149 const int fps = std::min(kFramerateFps, last_wants.max_framerate_fps);
2150 const int frame_interval_ms = rtc::kNumMillisecsPerSec / fps;
2151 VideoSendStream::Stats mock_stats = stats_proxy_->GetStats();
2152 mock_stats.input_frame_rate = fps;
2153 stats_proxy_->SetMockStats(mock_stats);
2154
2155 video_source_.IncomingCapturedFrame(CreateFrame(t, kWidth, kHeight));
2156 sink_.WaitForEncodedFrame(t);
2157 t += frame_interval_ms;
2158
mflodmancc3d4422017-08-03 08:27:51 -07002159 video_stream_encoder_->TriggerCpuOveruse();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02002160 EXPECT_THAT(
Jonathan Yubc771b72017-12-08 17:04:29 -08002161 video_source_.sink_wants(),
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02002162 FpsInRangeForPixelsInBalanced(*video_source_.last_sent_width() *
2163 *video_source_.last_sent_height()));
Jonathan Yubc771b72017-12-08 17:04:29 -08002164 } while (video_source_.sink_wants().max_pixel_count <
2165 last_wants.max_pixel_count ||
2166 video_source_.sink_wants().max_framerate_fps <
2167 last_wants.max_framerate_fps);
asaperssonf7e294d2017-06-13 23:25:22 -07002168
Jonathan Yubc771b72017-12-08 17:04:29 -08002169 // Verify that we've adapted all the way down.
2170 stats_proxy_->ResetMockStats();
asaperssonf7e294d2017-06-13 23:25:22 -07002171 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
Jonathan Yubc771b72017-12-08 17:04:29 -08002172 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_framerate);
2173 EXPECT_EQ(loop_count - 1,
asaperssonf7e294d2017-06-13 23:25:22 -07002174 stats_proxy_->GetStats().number_of_cpu_adapt_changes);
Jonathan Yubc771b72017-12-08 17:04:29 -08002175 EXPECT_EQ(kMinPixelsPerFrame, *video_source_.last_sent_width() *
2176 *video_source_.last_sent_height());
2177 EXPECT_EQ(kMinBalancedFramerateFps,
2178 video_source_.sink_wants().max_framerate_fps);
asaperssonf7e294d2017-06-13 23:25:22 -07002179
Jonathan Yubc771b72017-12-08 17:04:29 -08002180 // Adapt back up the same number of times we adapted down.
2181 for (int i = 0; i < loop_count - 1; ++i) {
2182 last_wants = video_source_.sink_wants();
2183
2184 // Simulate the framerate we've been asked to adapt to.
2185 const int fps = std::min(kFramerateFps, last_wants.max_framerate_fps);
2186 const int frame_interval_ms = rtc::kNumMillisecsPerSec / fps;
2187 VideoSendStream::Stats mock_stats = stats_proxy_->GetStats();
2188 mock_stats.input_frame_rate = fps;
2189 stats_proxy_->SetMockStats(mock_stats);
2190
2191 video_source_.IncomingCapturedFrame(CreateFrame(t, kWidth, kHeight));
2192 sink_.WaitForEncodedFrame(t);
2193 t += frame_interval_ms;
2194
Henrik Boström91aa7322020-04-28 12:24:33 +02002195 video_stream_encoder_->TriggerCpuUnderuse();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02002196 EXPECT_THAT(
Jonathan Yubc771b72017-12-08 17:04:29 -08002197 video_source_.sink_wants(),
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02002198 FpsInRangeForPixelsInBalanced(*video_source_.last_sent_width() *
2199 *video_source_.last_sent_height()));
Jonathan Yubc771b72017-12-08 17:04:29 -08002200 EXPECT_TRUE(video_source_.sink_wants().max_pixel_count >
2201 last_wants.max_pixel_count ||
2202 video_source_.sink_wants().max_framerate_fps >
2203 last_wants.max_framerate_fps);
asaperssonf7e294d2017-06-13 23:25:22 -07002204 }
2205
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02002206 EXPECT_THAT(video_source_.sink_wants(), FpsMaxResolutionMax());
Jonathan Yubc771b72017-12-08 17:04:29 -08002207 stats_proxy_->ResetMockStats();
asaperssonf7e294d2017-06-13 23:25:22 -07002208 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
Jonathan Yubc771b72017-12-08 17:04:29 -08002209 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
2210 EXPECT_EQ((loop_count - 1) * 2,
2211 stats_proxy_->GetStats().number_of_cpu_adapt_changes);
asaperssonf7e294d2017-06-13 23:25:22 -07002212
mflodmancc3d4422017-08-03 08:27:51 -07002213 video_stream_encoder_->Stop();
asaperssonf7e294d2017-06-13 23:25:22 -07002214}
Rasmus Brandt5cad55b2019-12-19 09:47:11 +01002215
Evan Shrubsole2e2f6742020-05-14 10:41:15 +02002216TEST_F(VideoStreamEncoderTest,
2217 SinkWantsNotChangedByResourceLimitedBeforeDegradationPreferenceChange) {
2218 video_stream_encoder_->OnBitrateUpdated(
2219 DataRate::BitsPerSec(kTargetBitrateBps),
2220 DataRate::BitsPerSec(kTargetBitrateBps),
2221 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02002222 EXPECT_THAT(video_source_.sink_wants(), UnlimitedSinkWants());
Evan Shrubsole2e2f6742020-05-14 10:41:15 +02002223
2224 const int kFrameWidth = 1280;
2225 const int kFrameHeight = 720;
2226
2227 int64_t ntp_time = kFrameIntervalMs;
2228
2229 // Force an input frame rate to be available, or the adaptation call won't
2230 // know what framerate to adapt form.
2231 const int kInputFps = 30;
2232 VideoSendStream::Stats stats = stats_proxy_->GetStats();
2233 stats.input_frame_rate = kInputFps;
2234 stats_proxy_->SetMockStats(stats);
2235
2236 video_source_.set_adaptation_enabled(true);
2237 video_stream_encoder_->SetSource(
2238 &video_source_, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02002239 EXPECT_THAT(video_source_.sink_wants(), UnlimitedSinkWants());
Evan Shrubsole2e2f6742020-05-14 10:41:15 +02002240 video_source_.IncomingCapturedFrame(
2241 CreateFrame(ntp_time, kFrameWidth, kFrameHeight));
2242 sink_.WaitForEncodedFrame(ntp_time);
2243 ntp_time += kFrameIntervalMs;
2244
2245 // Trigger CPU overuse.
2246 video_stream_encoder_->TriggerCpuOveruse();
2247 video_source_.IncomingCapturedFrame(
2248 CreateFrame(ntp_time, kFrameWidth, kFrameHeight));
2249 sink_.WaitForEncodedFrame(ntp_time);
2250 ntp_time += kFrameIntervalMs;
2251
2252 EXPECT_FALSE(video_source_.sink_wants().target_pixel_count);
2253 EXPECT_EQ(std::numeric_limits<int>::max(),
2254 video_source_.sink_wants().max_pixel_count);
2255 // Some framerate constraint should be set.
2256 int restricted_fps = video_source_.sink_wants().max_framerate_fps;
2257 EXPECT_LT(restricted_fps, kInputFps);
2258 video_source_.IncomingCapturedFrame(
2259 CreateFrame(ntp_time, kFrameWidth, kFrameHeight));
2260 sink_.WaitForEncodedFrame(ntp_time);
2261 ntp_time += 100;
2262
Henrik Boström2671dac2020-05-19 16:29:09 +02002263 video_stream_encoder_->SetSourceAndWaitForRestrictionsUpdated(
Evan Shrubsole2e2f6742020-05-14 10:41:15 +02002264 &video_source_, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
2265 // Give the encoder queue time to process the change in degradation preference
2266 // by waiting for an encoded frame.
2267 video_source_.IncomingCapturedFrame(
2268 CreateFrame(ntp_time, kFrameWidth, kFrameHeight));
2269 sink_.WaitForEncodedFrame(ntp_time);
2270 ntp_time += kFrameIntervalMs;
2271
2272 video_stream_encoder_->TriggerQualityLow();
2273 video_source_.IncomingCapturedFrame(
2274 CreateFrame(ntp_time, kFrameWidth, kFrameHeight));
2275 sink_.WaitForEncodedFrame(ntp_time);
2276 ntp_time += kFrameIntervalMs;
2277
2278 // Some resolution constraint should be set.
2279 EXPECT_FALSE(video_source_.sink_wants().target_pixel_count);
2280 EXPECT_LT(video_source_.sink_wants().max_pixel_count,
2281 kFrameWidth * kFrameHeight);
2282 EXPECT_EQ(video_source_.sink_wants().max_framerate_fps, kInputFps);
2283
2284 int pixel_count = video_source_.sink_wants().max_pixel_count;
2285 // Triggering a CPU underuse should not change the sink wants since it has
2286 // not been overused for resolution since we changed degradation preference.
2287 video_stream_encoder_->TriggerCpuUnderuse();
2288 video_source_.IncomingCapturedFrame(
2289 CreateFrame(ntp_time, kFrameWidth, kFrameHeight));
2290 sink_.WaitForEncodedFrame(ntp_time);
2291 ntp_time += kFrameIntervalMs;
2292 EXPECT_EQ(video_source_.sink_wants().max_pixel_count, pixel_count);
2293 EXPECT_EQ(video_source_.sink_wants().max_framerate_fps, kInputFps);
2294
Evan Shrubsole64469032020-06-11 10:45:29 +02002295 // Change the degradation preference back. CPU underuse should not adapt since
2296 // QP is most limited.
Henrik Boström2671dac2020-05-19 16:29:09 +02002297 video_stream_encoder_->SetSourceAndWaitForRestrictionsUpdated(
Evan Shrubsole2e2f6742020-05-14 10:41:15 +02002298 &video_source_, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
2299 video_source_.IncomingCapturedFrame(
2300 CreateFrame(ntp_time, kFrameWidth, kFrameHeight));
2301 sink_.WaitForEncodedFrame(ntp_time);
2302 ntp_time += 100;
2303 // Resolution adaptations is gone after changing degradation preference.
2304 EXPECT_FALSE(video_source_.sink_wants().target_pixel_count);
2305 EXPECT_EQ(std::numeric_limits<int>::max(),
2306 video_source_.sink_wants().max_pixel_count);
2307 // The fps adaptation from above is now back.
2308 EXPECT_EQ(video_source_.sink_wants().max_framerate_fps, restricted_fps);
2309
2310 // Trigger CPU underuse.
2311 video_stream_encoder_->TriggerCpuUnderuse();
2312 video_source_.IncomingCapturedFrame(
2313 CreateFrame(ntp_time, kFrameWidth, kFrameHeight));
2314 sink_.WaitForEncodedFrame(ntp_time);
2315 ntp_time += kFrameIntervalMs;
Evan Shrubsole64469032020-06-11 10:45:29 +02002316 EXPECT_EQ(video_source_.sink_wants().max_framerate_fps, restricted_fps);
2317
2318 // Trigger QP underuse, fps should return to normal.
2319 video_stream_encoder_->TriggerQualityHigh();
2320 video_source_.IncomingCapturedFrame(
2321 CreateFrame(ntp_time, kFrameWidth, kFrameHeight));
2322 sink_.WaitForEncodedFrame(ntp_time);
2323 ntp_time += kFrameIntervalMs;
2324 EXPECT_THAT(video_source_.sink_wants(), FpsMax());
Evan Shrubsole2e2f6742020-05-14 10:41:15 +02002325
2326 video_stream_encoder_->Stop();
2327}
2328
mflodmancc3d4422017-08-03 08:27:51 -07002329TEST_F(VideoStreamEncoderTest, SinkWantsStoredByDegradationPreference) {
Henrik Boström381d1092020-05-12 18:49:07 +02002330 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01002331 DataRate::BitsPerSec(kTargetBitrateBps),
2332 DataRate::BitsPerSec(kTargetBitrateBps),
2333 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02002334 EXPECT_THAT(video_source_.sink_wants(), UnlimitedSinkWants());
perkj803d97f2016-11-01 11:45:46 -07002335
sprangc5d62e22017-04-02 23:53:04 -07002336 const int kFrameWidth = 1280;
2337 const int kFrameHeight = 720;
sprangc5d62e22017-04-02 23:53:04 -07002338
Åsa Persson8c1bf952018-09-13 10:42:19 +02002339 int64_t frame_timestamp = 1;
perkj803d97f2016-11-01 11:45:46 -07002340
kthelgason5e13d412016-12-01 03:59:51 -08002341 video_source_.IncomingCapturedFrame(
sprangc5d62e22017-04-02 23:53:04 -07002342 CreateFrame(frame_timestamp, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 07:06:52 -07002343 WaitForEncodedFrame(frame_timestamp);
sprangc5d62e22017-04-02 23:53:04 -07002344 frame_timestamp += kFrameIntervalMs;
2345
perkj803d97f2016-11-01 11:45:46 -07002346 // Trigger CPU overuse.
mflodmancc3d4422017-08-03 08:27:51 -07002347 video_stream_encoder_->TriggerCpuOveruse();
perkj803d97f2016-11-01 11:45:46 -07002348 video_source_.IncomingCapturedFrame(
sprangc5d62e22017-04-02 23:53:04 -07002349 CreateFrame(frame_timestamp, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 07:06:52 -07002350 WaitForEncodedFrame(frame_timestamp);
sprangc5d62e22017-04-02 23:53:04 -07002351 frame_timestamp += kFrameIntervalMs;
sprang3ea3c772017-03-30 07:23:48 -07002352
asapersson0944a802017-04-07 00:57:58 -07002353 // Default degradation preference is maintain-framerate, so will lower max
sprangc5d62e22017-04-02 23:53:04 -07002354 // wanted resolution.
2355 EXPECT_FALSE(video_source_.sink_wants().target_pixel_count);
2356 EXPECT_LT(video_source_.sink_wants().max_pixel_count,
2357 kFrameWidth * kFrameHeight);
Åsa Persson8c1bf952018-09-13 10:42:19 +02002358 EXPECT_EQ(kDefaultFramerate, video_source_.sink_wants().max_framerate_fps);
sprangc5d62e22017-04-02 23:53:04 -07002359
2360 // Set new source, switch to maintain-resolution.
perkj803d97f2016-11-01 11:45:46 -07002361 test::FrameForwarder new_video_source;
Henrik Boström381d1092020-05-12 18:49:07 +02002362 video_stream_encoder_->SetSourceAndWaitForRestrictionsUpdated(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002363 &new_video_source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
Henrik Boström07b17df2020-01-15 11:42:12 +01002364 // Give the encoder queue time to process the change in degradation preference
2365 // by waiting for an encoded frame.
2366 new_video_source.IncomingCapturedFrame(
2367 CreateFrame(frame_timestamp, kFrameWidth, kFrameWidth));
2368 sink_.WaitForEncodedFrame(frame_timestamp);
2369 frame_timestamp += kFrameIntervalMs;
sprangc5d62e22017-04-02 23:53:04 -07002370 // Initially no degradation registered.
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02002371 EXPECT_THAT(new_video_source.sink_wants(), FpsMaxResolutionMax());
perkj803d97f2016-11-01 11:45:46 -07002372
sprangc5d62e22017-04-02 23:53:04 -07002373 // Force an input frame rate to be available, or the adaptation call won't
2374 // know what framerate to adapt form.
asapersson02465b82017-04-10 01:12:52 -07002375 const int kInputFps = 30;
sprangc5d62e22017-04-02 23:53:04 -07002376 VideoSendStream::Stats stats = stats_proxy_->GetStats();
asapersson02465b82017-04-10 01:12:52 -07002377 stats.input_frame_rate = kInputFps;
sprangc5d62e22017-04-02 23:53:04 -07002378 stats_proxy_->SetMockStats(stats);
2379
mflodmancc3d4422017-08-03 08:27:51 -07002380 video_stream_encoder_->TriggerCpuOveruse();
perkj803d97f2016-11-01 11:45:46 -07002381 new_video_source.IncomingCapturedFrame(
sprangc5d62e22017-04-02 23:53:04 -07002382 CreateFrame(frame_timestamp, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 07:06:52 -07002383 WaitForEncodedFrame(frame_timestamp);
sprangc5d62e22017-04-02 23:53:04 -07002384 frame_timestamp += kFrameIntervalMs;
2385
2386 // Some framerate constraint should be set.
sprang84a37592017-02-10 07:04:27 -08002387 EXPECT_FALSE(new_video_source.sink_wants().target_pixel_count);
sprangc5d62e22017-04-02 23:53:04 -07002388 EXPECT_EQ(std::numeric_limits<int>::max(),
2389 new_video_source.sink_wants().max_pixel_count);
asapersson02465b82017-04-10 01:12:52 -07002390 EXPECT_LT(new_video_source.sink_wants().max_framerate_fps, kInputFps);
sprangc5d62e22017-04-02 23:53:04 -07002391
asapersson02465b82017-04-10 01:12:52 -07002392 // Turn off degradation completely.
Henrik Boström381d1092020-05-12 18:49:07 +02002393 video_stream_encoder_->SetSourceAndWaitForRestrictionsUpdated(
2394 &new_video_source, webrtc::DegradationPreference::DISABLED);
Henrik Boström07b17df2020-01-15 11:42:12 +01002395 // Give the encoder queue time to process the change in degradation preference
2396 // by waiting for an encoded frame.
2397 new_video_source.IncomingCapturedFrame(
2398 CreateFrame(frame_timestamp, kFrameWidth, kFrameWidth));
2399 sink_.WaitForEncodedFrame(frame_timestamp);
2400 frame_timestamp += kFrameIntervalMs;
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02002401 EXPECT_THAT(new_video_source.sink_wants(), FpsMaxResolutionMax());
sprangc5d62e22017-04-02 23:53:04 -07002402
mflodmancc3d4422017-08-03 08:27:51 -07002403 video_stream_encoder_->TriggerCpuOveruse();
sprangc5d62e22017-04-02 23:53:04 -07002404 new_video_source.IncomingCapturedFrame(
2405 CreateFrame(frame_timestamp, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 07:06:52 -07002406 WaitForEncodedFrame(frame_timestamp);
sprangc5d62e22017-04-02 23:53:04 -07002407 frame_timestamp += kFrameIntervalMs;
2408
2409 // Still no degradation.
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02002410 EXPECT_THAT(new_video_source.sink_wants(), FpsMaxResolutionMax());
perkj803d97f2016-11-01 11:45:46 -07002411
2412 // Calling SetSource with resolution scaling enabled apply the old SinkWants.
Henrik Boström381d1092020-05-12 18:49:07 +02002413 video_stream_encoder_->SetSourceAndWaitForRestrictionsUpdated(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002414 &new_video_source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
Henrik Boström07b17df2020-01-15 11:42:12 +01002415 // Give the encoder queue time to process the change in degradation preference
2416 // by waiting for an encoded frame.
2417 new_video_source.IncomingCapturedFrame(
2418 CreateFrame(frame_timestamp, kFrameWidth, kFrameWidth));
2419 sink_.WaitForEncodedFrame(frame_timestamp);
2420 frame_timestamp += kFrameIntervalMs;
sprangc5d62e22017-04-02 23:53:04 -07002421 EXPECT_LT(new_video_source.sink_wants().max_pixel_count,
2422 kFrameWidth * kFrameHeight);
sprang84a37592017-02-10 07:04:27 -08002423 EXPECT_FALSE(new_video_source.sink_wants().target_pixel_count);
Åsa Persson8c1bf952018-09-13 10:42:19 +02002424 EXPECT_EQ(kDefaultFramerate, new_video_source.sink_wants().max_framerate_fps);
sprangc5d62e22017-04-02 23:53:04 -07002425
2426 // Calling SetSource with framerate scaling enabled apply the old SinkWants.
Henrik Boström381d1092020-05-12 18:49:07 +02002427 video_stream_encoder_->SetSourceAndWaitForRestrictionsUpdated(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002428 &new_video_source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
Henrik Boström07b17df2020-01-15 11:42:12 +01002429 // Give the encoder queue time to process the change in degradation preference
2430 // by waiting for an encoded frame.
2431 new_video_source.IncomingCapturedFrame(
2432 CreateFrame(frame_timestamp, kFrameWidth, kFrameWidth));
2433 sink_.WaitForEncodedFrame(frame_timestamp);
2434 frame_timestamp += kFrameIntervalMs;
sprangc5d62e22017-04-02 23:53:04 -07002435 EXPECT_FALSE(new_video_source.sink_wants().target_pixel_count);
2436 EXPECT_EQ(std::numeric_limits<int>::max(),
2437 new_video_source.sink_wants().max_pixel_count);
asapersson02465b82017-04-10 01:12:52 -07002438 EXPECT_LT(new_video_source.sink_wants().max_framerate_fps, kInputFps);
perkj803d97f2016-11-01 11:45:46 -07002439
mflodmancc3d4422017-08-03 08:27:51 -07002440 video_stream_encoder_->Stop();
perkj803d97f2016-11-01 11:45:46 -07002441}
2442
mflodmancc3d4422017-08-03 08:27:51 -07002443TEST_F(VideoStreamEncoderTest, StatsTracksQualityAdaptationStats) {
Henrik Boström381d1092020-05-12 18:49:07 +02002444 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01002445 DataRate::BitsPerSec(kTargetBitrateBps),
2446 DataRate::BitsPerSec(kTargetBitrateBps),
2447 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
perkj803d97f2016-11-01 11:45:46 -07002448
asaperssonfab67072017-04-04 05:51:49 -07002449 const int kWidth = 1280;
2450 const int kHeight = 720;
asaperssonfab67072017-04-04 05:51:49 -07002451 video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002452 WaitForEncodedFrame(1);
asaperssonfab67072017-04-04 05:51:49 -07002453 VideoSendStream::Stats stats = stats_proxy_->GetStats();
2454 EXPECT_FALSE(stats.bw_limited_resolution);
2455 EXPECT_EQ(0, stats.number_of_quality_adapt_changes);
2456
2457 // Trigger adapt down.
mflodmancc3d4422017-08-03 08:27:51 -07002458 video_stream_encoder_->TriggerQualityLow();
asaperssonfab67072017-04-04 05:51:49 -07002459 video_source_.IncomingCapturedFrame(CreateFrame(2, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002460 WaitForEncodedFrame(2);
asaperssonfab67072017-04-04 05:51:49 -07002461
2462 stats = stats_proxy_->GetStats();
2463 EXPECT_TRUE(stats.bw_limited_resolution);
2464 EXPECT_EQ(1, stats.number_of_quality_adapt_changes);
2465
2466 // Trigger adapt up.
mflodmancc3d4422017-08-03 08:27:51 -07002467 video_stream_encoder_->TriggerQualityHigh();
asaperssonfab67072017-04-04 05:51:49 -07002468 video_source_.IncomingCapturedFrame(CreateFrame(3, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002469 WaitForEncodedFrame(3);
asaperssonfab67072017-04-04 05:51:49 -07002470
2471 stats = stats_proxy_->GetStats();
2472 EXPECT_FALSE(stats.bw_limited_resolution);
2473 EXPECT_EQ(2, stats.number_of_quality_adapt_changes);
2474 EXPECT_EQ(0, stats.number_of_cpu_adapt_changes);
2475
mflodmancc3d4422017-08-03 08:27:51 -07002476 video_stream_encoder_->Stop();
asaperssonfab67072017-04-04 05:51:49 -07002477}
2478
mflodmancc3d4422017-08-03 08:27:51 -07002479TEST_F(VideoStreamEncoderTest, StatsTracksCpuAdaptationStats) {
Henrik Boström381d1092020-05-12 18:49:07 +02002480 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01002481 DataRate::BitsPerSec(kTargetBitrateBps),
2482 DataRate::BitsPerSec(kTargetBitrateBps),
2483 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asaperssonfab67072017-04-04 05:51:49 -07002484
2485 const int kWidth = 1280;
2486 const int kHeight = 720;
asaperssonfab67072017-04-04 05:51:49 -07002487 video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002488 WaitForEncodedFrame(1);
perkj803d97f2016-11-01 11:45:46 -07002489 VideoSendStream::Stats stats = stats_proxy_->GetStats();
2490 EXPECT_FALSE(stats.cpu_limited_resolution);
2491 EXPECT_EQ(0, stats.number_of_cpu_adapt_changes);
2492
2493 // Trigger CPU overuse.
mflodmancc3d4422017-08-03 08:27:51 -07002494 video_stream_encoder_->TriggerCpuOveruse();
asaperssonfab67072017-04-04 05:51:49 -07002495 video_source_.IncomingCapturedFrame(CreateFrame(2, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002496 WaitForEncodedFrame(2);
perkj803d97f2016-11-01 11:45:46 -07002497
2498 stats = stats_proxy_->GetStats();
2499 EXPECT_TRUE(stats.cpu_limited_resolution);
2500 EXPECT_EQ(1, stats.number_of_cpu_adapt_changes);
2501
2502 // Trigger CPU normal use.
Henrik Boström91aa7322020-04-28 12:24:33 +02002503 video_stream_encoder_->TriggerCpuUnderuse();
asaperssonfab67072017-04-04 05:51:49 -07002504 video_source_.IncomingCapturedFrame(CreateFrame(3, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002505 WaitForEncodedFrame(3);
perkj803d97f2016-11-01 11:45:46 -07002506
2507 stats = stats_proxy_->GetStats();
2508 EXPECT_FALSE(stats.cpu_limited_resolution);
2509 EXPECT_EQ(2, stats.number_of_cpu_adapt_changes);
asaperssonfab67072017-04-04 05:51:49 -07002510 EXPECT_EQ(0, stats.number_of_quality_adapt_changes);
perkj803d97f2016-11-01 11:45:46 -07002511
mflodmancc3d4422017-08-03 08:27:51 -07002512 video_stream_encoder_->Stop();
perkj803d97f2016-11-01 11:45:46 -07002513}
2514
mflodmancc3d4422017-08-03 08:27:51 -07002515TEST_F(VideoStreamEncoderTest, SwitchingSourceKeepsCpuAdaptation) {
Henrik Boström381d1092020-05-12 18:49:07 +02002516 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01002517 DataRate::BitsPerSec(kTargetBitrateBps),
2518 DataRate::BitsPerSec(kTargetBitrateBps),
2519 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
kthelgason876222f2016-11-29 01:44:11 -08002520
asaperssonfab67072017-04-04 05:51:49 -07002521 const int kWidth = 1280;
2522 const int kHeight = 720;
2523 video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002524 WaitForEncodedFrame(1);
kthelgason876222f2016-11-29 01:44:11 -08002525 VideoSendStream::Stats stats = stats_proxy_->GetStats();
asapersson09f05612017-05-15 23:40:18 -07002526 EXPECT_FALSE(stats.bw_limited_resolution);
kthelgason876222f2016-11-29 01:44:11 -08002527 EXPECT_FALSE(stats.cpu_limited_resolution);
2528 EXPECT_EQ(0, stats.number_of_cpu_adapt_changes);
2529
asaperssonfab67072017-04-04 05:51:49 -07002530 // Trigger CPU overuse.
mflodmancc3d4422017-08-03 08:27:51 -07002531 video_stream_encoder_->TriggerCpuOveruse();
asaperssonfab67072017-04-04 05:51:49 -07002532 video_source_.IncomingCapturedFrame(CreateFrame(2, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002533 WaitForEncodedFrame(2);
kthelgason876222f2016-11-29 01:44:11 -08002534 stats = stats_proxy_->GetStats();
asapersson09f05612017-05-15 23:40:18 -07002535 EXPECT_FALSE(stats.bw_limited_resolution);
kthelgason876222f2016-11-29 01:44:11 -08002536 EXPECT_TRUE(stats.cpu_limited_resolution);
2537 EXPECT_EQ(1, stats.number_of_cpu_adapt_changes);
2538
2539 // Set new source with adaptation still enabled.
2540 test::FrameForwarder new_video_source;
mflodmancc3d4422017-08-03 08:27:51 -07002541 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002542 &new_video_source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
kthelgason876222f2016-11-29 01:44:11 -08002543
asaperssonfab67072017-04-04 05:51:49 -07002544 new_video_source.IncomingCapturedFrame(CreateFrame(3, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002545 WaitForEncodedFrame(3);
kthelgason876222f2016-11-29 01:44:11 -08002546 stats = stats_proxy_->GetStats();
asapersson09f05612017-05-15 23:40:18 -07002547 EXPECT_FALSE(stats.bw_limited_resolution);
kthelgason876222f2016-11-29 01:44:11 -08002548 EXPECT_TRUE(stats.cpu_limited_resolution);
2549 EXPECT_EQ(1, stats.number_of_cpu_adapt_changes);
2550
2551 // Set adaptation disabled.
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002552 video_stream_encoder_->SetSource(&new_video_source,
2553 webrtc::DegradationPreference::DISABLED);
kthelgason876222f2016-11-29 01:44:11 -08002554
asaperssonfab67072017-04-04 05:51:49 -07002555 new_video_source.IncomingCapturedFrame(CreateFrame(4, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002556 WaitForEncodedFrame(4);
kthelgason876222f2016-11-29 01:44:11 -08002557 stats = stats_proxy_->GetStats();
asapersson09f05612017-05-15 23:40:18 -07002558 EXPECT_FALSE(stats.bw_limited_resolution);
kthelgason876222f2016-11-29 01:44:11 -08002559 EXPECT_FALSE(stats.cpu_limited_resolution);
2560 EXPECT_EQ(1, stats.number_of_cpu_adapt_changes);
2561
2562 // Set adaptation back to enabled.
mflodmancc3d4422017-08-03 08:27:51 -07002563 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002564 &new_video_source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
kthelgason876222f2016-11-29 01:44:11 -08002565
asaperssonfab67072017-04-04 05:51:49 -07002566 new_video_source.IncomingCapturedFrame(CreateFrame(5, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002567 WaitForEncodedFrame(5);
kthelgason876222f2016-11-29 01:44:11 -08002568 stats = stats_proxy_->GetStats();
asapersson09f05612017-05-15 23:40:18 -07002569 EXPECT_FALSE(stats.bw_limited_resolution);
kthelgason876222f2016-11-29 01:44:11 -08002570 EXPECT_TRUE(stats.cpu_limited_resolution);
2571 EXPECT_EQ(1, stats.number_of_cpu_adapt_changes);
2572
asaperssonfab67072017-04-04 05:51:49 -07002573 // Trigger CPU normal use.
Henrik Boström91aa7322020-04-28 12:24:33 +02002574 video_stream_encoder_->TriggerCpuUnderuse();
asaperssonfab67072017-04-04 05:51:49 -07002575 new_video_source.IncomingCapturedFrame(CreateFrame(6, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002576 WaitForEncodedFrame(6);
kthelgason876222f2016-11-29 01:44:11 -08002577 stats = stats_proxy_->GetStats();
asapersson09f05612017-05-15 23:40:18 -07002578 EXPECT_FALSE(stats.bw_limited_resolution);
kthelgason876222f2016-11-29 01:44:11 -08002579 EXPECT_FALSE(stats.cpu_limited_resolution);
2580 EXPECT_EQ(2, stats.number_of_cpu_adapt_changes);
asapersson02465b82017-04-10 01:12:52 -07002581 EXPECT_EQ(0, stats.number_of_quality_adapt_changes);
kthelgason876222f2016-11-29 01:44:11 -08002582
mflodmancc3d4422017-08-03 08:27:51 -07002583 video_stream_encoder_->Stop();
kthelgason876222f2016-11-29 01:44:11 -08002584}
2585
mflodmancc3d4422017-08-03 08:27:51 -07002586TEST_F(VideoStreamEncoderTest, SwitchingSourceKeepsQualityAdaptation) {
Henrik Boström381d1092020-05-12 18:49:07 +02002587 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01002588 DataRate::BitsPerSec(kTargetBitrateBps),
2589 DataRate::BitsPerSec(kTargetBitrateBps),
2590 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
kthelgason876222f2016-11-29 01:44:11 -08002591
asaperssonfab67072017-04-04 05:51:49 -07002592 const int kWidth = 1280;
2593 const int kHeight = 720;
2594 video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002595 WaitForEncodedFrame(1);
kthelgason876222f2016-11-29 01:44:11 -08002596 VideoSendStream::Stats stats = stats_proxy_->GetStats();
kthelgason876222f2016-11-29 01:44:11 -08002597 EXPECT_FALSE(stats.bw_limited_resolution);
asapersson13874762017-06-07 00:01:02 -07002598 EXPECT_FALSE(stats.bw_limited_framerate);
asaperssonfab67072017-04-04 05:51:49 -07002599 EXPECT_EQ(0, stats.number_of_quality_adapt_changes);
kthelgason876222f2016-11-29 01:44:11 -08002600
2601 // Set new source with adaptation still enabled.
2602 test::FrameForwarder new_video_source;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002603 video_stream_encoder_->SetSource(&new_video_source,
2604 webrtc::DegradationPreference::BALANCED);
kthelgason876222f2016-11-29 01:44:11 -08002605
asaperssonfab67072017-04-04 05:51:49 -07002606 new_video_source.IncomingCapturedFrame(CreateFrame(2, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002607 WaitForEncodedFrame(2);
kthelgason876222f2016-11-29 01:44:11 -08002608 stats = stats_proxy_->GetStats();
kthelgason876222f2016-11-29 01:44:11 -08002609 EXPECT_FALSE(stats.bw_limited_resolution);
asapersson13874762017-06-07 00:01:02 -07002610 EXPECT_FALSE(stats.bw_limited_framerate);
asaperssonfab67072017-04-04 05:51:49 -07002611 EXPECT_EQ(0, stats.number_of_quality_adapt_changes);
kthelgason876222f2016-11-29 01:44:11 -08002612
asaperssonfab67072017-04-04 05:51:49 -07002613 // Trigger adapt down.
mflodmancc3d4422017-08-03 08:27:51 -07002614 video_stream_encoder_->TriggerQualityLow();
asaperssonfab67072017-04-04 05:51:49 -07002615 new_video_source.IncomingCapturedFrame(CreateFrame(3, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002616 WaitForEncodedFrame(3);
kthelgason876222f2016-11-29 01:44:11 -08002617 stats = stats_proxy_->GetStats();
kthelgason876222f2016-11-29 01:44:11 -08002618 EXPECT_TRUE(stats.bw_limited_resolution);
asapersson13874762017-06-07 00:01:02 -07002619 EXPECT_FALSE(stats.bw_limited_framerate);
asaperssonfab67072017-04-04 05:51:49 -07002620 EXPECT_EQ(1, stats.number_of_quality_adapt_changes);
kthelgason876222f2016-11-29 01:44:11 -08002621
asaperssonfab67072017-04-04 05:51:49 -07002622 // Set new source with adaptation still enabled.
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002623 video_stream_encoder_->SetSource(&new_video_source,
2624 webrtc::DegradationPreference::BALANCED);
kthelgason876222f2016-11-29 01:44:11 -08002625
asaperssonfab67072017-04-04 05:51:49 -07002626 new_video_source.IncomingCapturedFrame(CreateFrame(4, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002627 WaitForEncodedFrame(4);
kthelgason876222f2016-11-29 01:44:11 -08002628 stats = stats_proxy_->GetStats();
kthelgason876222f2016-11-29 01:44:11 -08002629 EXPECT_TRUE(stats.bw_limited_resolution);
asapersson13874762017-06-07 00:01:02 -07002630 EXPECT_FALSE(stats.bw_limited_framerate);
asaperssonfab67072017-04-04 05:51:49 -07002631 EXPECT_EQ(1, stats.number_of_quality_adapt_changes);
kthelgason876222f2016-11-29 01:44:11 -08002632
asapersson02465b82017-04-10 01:12:52 -07002633 // Disable resolution scaling.
mflodmancc3d4422017-08-03 08:27:51 -07002634 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002635 &new_video_source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
kthelgason876222f2016-11-29 01:44:11 -08002636
asaperssonfab67072017-04-04 05:51:49 -07002637 new_video_source.IncomingCapturedFrame(CreateFrame(5, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002638 WaitForEncodedFrame(5);
kthelgason876222f2016-11-29 01:44:11 -08002639 stats = stats_proxy_->GetStats();
kthelgason876222f2016-11-29 01:44:11 -08002640 EXPECT_FALSE(stats.bw_limited_resolution);
asapersson13874762017-06-07 00:01:02 -07002641 EXPECT_FALSE(stats.bw_limited_framerate);
asaperssonfab67072017-04-04 05:51:49 -07002642 EXPECT_EQ(1, stats.number_of_quality_adapt_changes);
2643 EXPECT_EQ(0, stats.number_of_cpu_adapt_changes);
kthelgason876222f2016-11-29 01:44:11 -08002644
mflodmancc3d4422017-08-03 08:27:51 -07002645 video_stream_encoder_->Stop();
kthelgason876222f2016-11-29 01:44:11 -08002646}
2647
mflodmancc3d4422017-08-03 08:27:51 -07002648TEST_F(VideoStreamEncoderTest,
2649 QualityAdaptationStatsAreResetWhenScalerIsDisabled) {
Henrik Boström381d1092020-05-12 18:49:07 +02002650 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01002651 DataRate::BitsPerSec(kTargetBitrateBps),
2652 DataRate::BitsPerSec(kTargetBitrateBps),
2653 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asapersson36e9eb42017-03-31 05:29:12 -07002654
2655 const int kWidth = 1280;
2656 const int kHeight = 720;
Åsa Persson8c1bf952018-09-13 10:42:19 +02002657 int64_t timestamp_ms = kFrameIntervalMs;
asapersson36e9eb42017-03-31 05:29:12 -07002658 video_source_.set_adaptation_enabled(true);
Åsa Persson8c1bf952018-09-13 10:42:19 +02002659 video_source_.IncomingCapturedFrame(
2660 CreateFrame(timestamp_ms, kWidth, kHeight));
2661 WaitForEncodedFrame(timestamp_ms);
asapersson36e9eb42017-03-31 05:29:12 -07002662 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
2663 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
2664 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
2665
2666 // Trigger adapt down.
mflodmancc3d4422017-08-03 08:27:51 -07002667 video_stream_encoder_->TriggerQualityLow();
Åsa Persson8c1bf952018-09-13 10:42:19 +02002668 timestamp_ms += kFrameIntervalMs;
2669 video_source_.IncomingCapturedFrame(
2670 CreateFrame(timestamp_ms, kWidth, kHeight));
2671 WaitForEncodedFrame(timestamp_ms);
asapersson36e9eb42017-03-31 05:29:12 -07002672 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
2673 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
2674 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
2675
2676 // Trigger overuse.
mflodmancc3d4422017-08-03 08:27:51 -07002677 video_stream_encoder_->TriggerCpuOveruse();
Åsa Persson8c1bf952018-09-13 10:42:19 +02002678 timestamp_ms += kFrameIntervalMs;
2679 video_source_.IncomingCapturedFrame(
2680 CreateFrame(timestamp_ms, kWidth, kHeight));
2681 WaitForEncodedFrame(timestamp_ms);
asapersson36e9eb42017-03-31 05:29:12 -07002682 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
2683 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
2684 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
2685
Niels Möller4db138e2018-04-19 09:04:13 +02002686 // Leave source unchanged, but disable quality scaler.
asapersson36e9eb42017-03-31 05:29:12 -07002687 fake_encoder_.SetQualityScaling(false);
Niels Möller4db138e2018-04-19 09:04:13 +02002688
2689 VideoEncoderConfig video_encoder_config;
2690 test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
2691 // Make format different, to force recreation of encoder.
2692 video_encoder_config.video_format.parameters["foo"] = "foo";
2693 video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config),
Niels Möllerf1338562018-04-26 09:51:47 +02002694 kMaxPayloadLength);
Åsa Persson8c1bf952018-09-13 10:42:19 +02002695 timestamp_ms += kFrameIntervalMs;
2696 video_source_.IncomingCapturedFrame(
2697 CreateFrame(timestamp_ms, kWidth, kHeight));
2698 WaitForEncodedFrame(timestamp_ms);
asapersson36e9eb42017-03-31 05:29:12 -07002699 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
2700 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
2701 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
2702
mflodmancc3d4422017-08-03 08:27:51 -07002703 video_stream_encoder_->Stop();
asapersson36e9eb42017-03-31 05:29:12 -07002704}
2705
mflodmancc3d4422017-08-03 08:27:51 -07002706TEST_F(VideoStreamEncoderTest,
Evan Shrubsole33be9df2020-03-05 18:39:32 +01002707 StatsTracksCpuAdaptationStatsWhenSwitchingSource_Balanced) {
Henrik Boström381d1092020-05-12 18:49:07 +02002708 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Evan Shrubsole33be9df2020-03-05 18:39:32 +01002709 DataRate::BitsPerSec(kTargetBitrateBps),
2710 DataRate::BitsPerSec(kTargetBitrateBps),
2711 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
2712
2713 const int kWidth = 1280;
2714 const int kHeight = 720;
2715 int sequence = 1;
2716
2717 // Enable BALANCED preference, no initial limitation.
2718 test::FrameForwarder source;
2719 video_stream_encoder_->SetSource(&source,
2720 webrtc::DegradationPreference::BALANCED);
2721 source.IncomingCapturedFrame(CreateFrame(sequence, kWidth, kHeight));
2722 WaitForEncodedFrame(sequence++);
2723 VideoSendStream::Stats stats = stats_proxy_->GetStats();
2724 EXPECT_FALSE(stats.cpu_limited_resolution);
2725 EXPECT_FALSE(stats.cpu_limited_framerate);
2726 EXPECT_EQ(0, stats.number_of_cpu_adapt_changes);
2727
2728 // Trigger CPU overuse, should now adapt down.
2729 video_stream_encoder_->TriggerCpuOveruse();
2730 source.IncomingCapturedFrame(CreateFrame(sequence, kWidth, kHeight));
2731 WaitForEncodedFrame(sequence++);
2732 stats = stats_proxy_->GetStats();
2733 EXPECT_EQ(1, stats.number_of_cpu_adapt_changes);
2734
2735 // Set new degradation preference should clear restrictions since we changed
2736 // from BALANCED.
Evan Shrubsolede2049e2020-05-25 16:54:21 +02002737 video_stream_encoder_->SetSourceAndWaitForRestrictionsUpdated(
Evan Shrubsole33be9df2020-03-05 18:39:32 +01002738 &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
2739 source.IncomingCapturedFrame(CreateFrame(sequence, kWidth, kHeight));
2740 WaitForEncodedFrame(sequence++);
2741 stats = stats_proxy_->GetStats();
2742 EXPECT_FALSE(stats.cpu_limited_resolution);
2743 EXPECT_FALSE(stats.cpu_limited_framerate);
2744 EXPECT_EQ(1, stats.number_of_cpu_adapt_changes);
2745
2746 // Force an input frame rate to be available, or the adaptation call won't
2747 // know what framerate to adapt from.
2748 VideoSendStream::Stats mock_stats = stats_proxy_->GetStats();
2749 mock_stats.input_frame_rate = 30;
2750 stats_proxy_->SetMockStats(mock_stats);
2751 video_stream_encoder_->TriggerCpuOveruse();
2752 stats_proxy_->ResetMockStats();
2753 source.IncomingCapturedFrame(CreateFrame(sequence, kWidth, kHeight));
2754 WaitForEncodedFrame(sequence++);
2755
2756 // We have now adapted once.
2757 stats = stats_proxy_->GetStats();
2758 EXPECT_EQ(2, stats.number_of_cpu_adapt_changes);
2759
2760 // Back to BALANCED, should clear the restrictions again.
Evan Shrubsolede2049e2020-05-25 16:54:21 +02002761 video_stream_encoder_->SetSourceAndWaitForRestrictionsUpdated(
2762 &source, webrtc::DegradationPreference::BALANCED);
Evan Shrubsole33be9df2020-03-05 18:39:32 +01002763 source.IncomingCapturedFrame(CreateFrame(sequence, kWidth, kHeight));
2764 WaitForEncodedFrame(sequence++);
2765 stats = stats_proxy_->GetStats();
2766 EXPECT_FALSE(stats.cpu_limited_resolution);
2767 EXPECT_FALSE(stats.cpu_limited_framerate);
2768 EXPECT_EQ(2, stats.number_of_cpu_adapt_changes);
2769
2770 video_stream_encoder_->Stop();
2771}
2772
2773TEST_F(VideoStreamEncoderTest,
mflodmancc3d4422017-08-03 08:27:51 -07002774 StatsTracksCpuAdaptationStatsWhenSwitchingSource) {
Henrik Boström381d1092020-05-12 18:49:07 +02002775 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01002776 DataRate::BitsPerSec(kTargetBitrateBps),
2777 DataRate::BitsPerSec(kTargetBitrateBps),
2778 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
perkj803d97f2016-11-01 11:45:46 -07002779
asapersson0944a802017-04-07 00:57:58 -07002780 const int kWidth = 1280;
2781 const int kHeight = 720;
sprang84a37592017-02-10 07:04:27 -08002782 int sequence = 1;
perkj803d97f2016-11-01 11:45:46 -07002783
asaperssonfab67072017-04-04 05:51:49 -07002784 video_source_.IncomingCapturedFrame(CreateFrame(sequence, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002785 WaitForEncodedFrame(sequence++);
perkj803d97f2016-11-01 11:45:46 -07002786 VideoSendStream::Stats stats = stats_proxy_->GetStats();
sprang84a37592017-02-10 07:04:27 -08002787 EXPECT_FALSE(stats.cpu_limited_resolution);
asapersson13874762017-06-07 00:01:02 -07002788 EXPECT_FALSE(stats.cpu_limited_framerate);
sprang84a37592017-02-10 07:04:27 -08002789 EXPECT_EQ(0, stats.number_of_cpu_adapt_changes);
2790
asapersson02465b82017-04-10 01:12:52 -07002791 // Trigger CPU overuse, should now adapt down.
mflodmancc3d4422017-08-03 08:27:51 -07002792 video_stream_encoder_->TriggerCpuOveruse();
asaperssonfab67072017-04-04 05:51:49 -07002793 video_source_.IncomingCapturedFrame(CreateFrame(sequence, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002794 WaitForEncodedFrame(sequence++);
sprang84a37592017-02-10 07:04:27 -08002795 stats = stats_proxy_->GetStats();
perkj803d97f2016-11-01 11:45:46 -07002796 EXPECT_TRUE(stats.cpu_limited_resolution);
asapersson13874762017-06-07 00:01:02 -07002797 EXPECT_FALSE(stats.cpu_limited_framerate);
perkj803d97f2016-11-01 11:45:46 -07002798 EXPECT_EQ(1, stats.number_of_cpu_adapt_changes);
2799
2800 // Set new source with adaptation still enabled.
2801 test::FrameForwarder new_video_source;
mflodmancc3d4422017-08-03 08:27:51 -07002802 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002803 &new_video_source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
perkj803d97f2016-11-01 11:45:46 -07002804
2805 new_video_source.IncomingCapturedFrame(
asaperssonfab67072017-04-04 05:51:49 -07002806 CreateFrame(sequence, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002807 WaitForEncodedFrame(sequence++);
perkj803d97f2016-11-01 11:45:46 -07002808 stats = stats_proxy_->GetStats();
2809 EXPECT_TRUE(stats.cpu_limited_resolution);
asapersson09f05612017-05-15 23:40:18 -07002810 EXPECT_FALSE(stats.cpu_limited_framerate);
perkj803d97f2016-11-01 11:45:46 -07002811 EXPECT_EQ(1, stats.number_of_cpu_adapt_changes);
2812
sprangc5d62e22017-04-02 23:53:04 -07002813 // Set cpu adaptation by frame dropping.
mflodmancc3d4422017-08-03 08:27:51 -07002814 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002815 &new_video_source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
perkj803d97f2016-11-01 11:45:46 -07002816 new_video_source.IncomingCapturedFrame(
asaperssonfab67072017-04-04 05:51:49 -07002817 CreateFrame(sequence, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002818 WaitForEncodedFrame(sequence++);
perkj803d97f2016-11-01 11:45:46 -07002819 stats = stats_proxy_->GetStats();
sprangc5d62e22017-04-02 23:53:04 -07002820 // Not adapted at first.
perkj803d97f2016-11-01 11:45:46 -07002821 EXPECT_FALSE(stats.cpu_limited_resolution);
asapersson09f05612017-05-15 23:40:18 -07002822 EXPECT_FALSE(stats.cpu_limited_framerate);
perkj803d97f2016-11-01 11:45:46 -07002823 EXPECT_EQ(1, stats.number_of_cpu_adapt_changes);
2824
sprangc5d62e22017-04-02 23:53:04 -07002825 // Force an input frame rate to be available, or the adaptation call won't
asapersson09f05612017-05-15 23:40:18 -07002826 // know what framerate to adapt from.
sprangc5d62e22017-04-02 23:53:04 -07002827 VideoSendStream::Stats mock_stats = stats_proxy_->GetStats();
2828 mock_stats.input_frame_rate = 30;
2829 stats_proxy_->SetMockStats(mock_stats);
mflodmancc3d4422017-08-03 08:27:51 -07002830 video_stream_encoder_->TriggerCpuOveruse();
sprangc5d62e22017-04-02 23:53:04 -07002831 stats_proxy_->ResetMockStats();
2832
2833 new_video_source.IncomingCapturedFrame(
asaperssonfab67072017-04-04 05:51:49 -07002834 CreateFrame(sequence, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002835 WaitForEncodedFrame(sequence++);
sprangc5d62e22017-04-02 23:53:04 -07002836
2837 // Framerate now adapted.
2838 stats = stats_proxy_->GetStats();
asapersson09f05612017-05-15 23:40:18 -07002839 EXPECT_FALSE(stats.cpu_limited_resolution);
2840 EXPECT_TRUE(stats.cpu_limited_framerate);
sprangc5d62e22017-04-02 23:53:04 -07002841 EXPECT_EQ(2, stats.number_of_cpu_adapt_changes);
2842
2843 // Disable CPU adaptation.
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002844 video_stream_encoder_->SetSource(&new_video_source,
2845 webrtc::DegradationPreference::DISABLED);
sprangc5d62e22017-04-02 23:53:04 -07002846 new_video_source.IncomingCapturedFrame(
asaperssonfab67072017-04-04 05:51:49 -07002847 CreateFrame(sequence, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002848 WaitForEncodedFrame(sequence++);
sprangc5d62e22017-04-02 23:53:04 -07002849
2850 stats = stats_proxy_->GetStats();
2851 EXPECT_FALSE(stats.cpu_limited_resolution);
asapersson13874762017-06-07 00:01:02 -07002852 EXPECT_FALSE(stats.cpu_limited_framerate);
sprangc5d62e22017-04-02 23:53:04 -07002853 EXPECT_EQ(2, stats.number_of_cpu_adapt_changes);
2854
2855 // Try to trigger overuse. Should not succeed.
2856 stats_proxy_->SetMockStats(mock_stats);
mflodmancc3d4422017-08-03 08:27:51 -07002857 video_stream_encoder_->TriggerCpuOveruse();
sprangc5d62e22017-04-02 23:53:04 -07002858 stats_proxy_->ResetMockStats();
2859
2860 stats = stats_proxy_->GetStats();
2861 EXPECT_FALSE(stats.cpu_limited_resolution);
asapersson13874762017-06-07 00:01:02 -07002862 EXPECT_FALSE(stats.cpu_limited_framerate);
sprangc5d62e22017-04-02 23:53:04 -07002863 EXPECT_EQ(2, stats.number_of_cpu_adapt_changes);
2864
2865 // Switch back the source with resolution adaptation enabled.
mflodmancc3d4422017-08-03 08:27:51 -07002866 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002867 &video_source_, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
asaperssonfab67072017-04-04 05:51:49 -07002868 video_source_.IncomingCapturedFrame(CreateFrame(sequence, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002869 WaitForEncodedFrame(sequence++);
perkj803d97f2016-11-01 11:45:46 -07002870 stats = stats_proxy_->GetStats();
2871 EXPECT_TRUE(stats.cpu_limited_resolution);
asapersson13874762017-06-07 00:01:02 -07002872 EXPECT_FALSE(stats.cpu_limited_framerate);
sprangc5d62e22017-04-02 23:53:04 -07002873 EXPECT_EQ(2, stats.number_of_cpu_adapt_changes);
perkj803d97f2016-11-01 11:45:46 -07002874
2875 // Trigger CPU normal usage.
Henrik Boström91aa7322020-04-28 12:24:33 +02002876 video_stream_encoder_->TriggerCpuUnderuse();
asaperssonfab67072017-04-04 05:51:49 -07002877 video_source_.IncomingCapturedFrame(CreateFrame(sequence, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002878 WaitForEncodedFrame(sequence++);
perkj803d97f2016-11-01 11:45:46 -07002879 stats = stats_proxy_->GetStats();
2880 EXPECT_FALSE(stats.cpu_limited_resolution);
asapersson13874762017-06-07 00:01:02 -07002881 EXPECT_FALSE(stats.cpu_limited_framerate);
sprangc5d62e22017-04-02 23:53:04 -07002882 EXPECT_EQ(3, stats.number_of_cpu_adapt_changes);
2883
2884 // Back to the source with adaptation off, set it back to maintain-resolution.
mflodmancc3d4422017-08-03 08:27:51 -07002885 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002886 &new_video_source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
sprangc5d62e22017-04-02 23:53:04 -07002887 new_video_source.IncomingCapturedFrame(
asaperssonfab67072017-04-04 05:51:49 -07002888 CreateFrame(sequence, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002889 WaitForEncodedFrame(sequence++);
sprangc5d62e22017-04-02 23:53:04 -07002890 stats = stats_proxy_->GetStats();
asapersson13874762017-06-07 00:01:02 -07002891 // Disabled, since we previously switched the source to disabled.
sprangc5d62e22017-04-02 23:53:04 -07002892 EXPECT_FALSE(stats.cpu_limited_resolution);
asapersson13874762017-06-07 00:01:02 -07002893 EXPECT_TRUE(stats.cpu_limited_framerate);
sprangc5d62e22017-04-02 23:53:04 -07002894 EXPECT_EQ(3, stats.number_of_cpu_adapt_changes);
2895
2896 // Trigger CPU normal usage.
Henrik Boström91aa7322020-04-28 12:24:33 +02002897 video_stream_encoder_->TriggerCpuUnderuse();
sprangc5d62e22017-04-02 23:53:04 -07002898 new_video_source.IncomingCapturedFrame(
asaperssonfab67072017-04-04 05:51:49 -07002899 CreateFrame(sequence, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002900 WaitForEncodedFrame(sequence++);
sprangc5d62e22017-04-02 23:53:04 -07002901 stats = stats_proxy_->GetStats();
2902 EXPECT_FALSE(stats.cpu_limited_resolution);
asapersson13874762017-06-07 00:01:02 -07002903 EXPECT_FALSE(stats.cpu_limited_framerate);
sprangc5d62e22017-04-02 23:53:04 -07002904 EXPECT_EQ(4, stats.number_of_cpu_adapt_changes);
asapersson02465b82017-04-10 01:12:52 -07002905 EXPECT_EQ(0, stats.number_of_quality_adapt_changes);
perkj803d97f2016-11-01 11:45:46 -07002906
mflodmancc3d4422017-08-03 08:27:51 -07002907 video_stream_encoder_->Stop();
perkj803d97f2016-11-01 11:45:46 -07002908}
2909
mflodmancc3d4422017-08-03 08:27:51 -07002910TEST_F(VideoStreamEncoderTest,
2911 ScalingUpAndDownDoesNothingWithMaintainResolution) {
asaperssonfab67072017-04-04 05:51:49 -07002912 const int kWidth = 1280;
2913 const int kHeight = 720;
Henrik Boström381d1092020-05-12 18:49:07 +02002914 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01002915 DataRate::BitsPerSec(kTargetBitrateBps),
2916 DataRate::BitsPerSec(kTargetBitrateBps),
2917 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
kthelgason876222f2016-11-29 01:44:11 -08002918
asaperssonfab67072017-04-04 05:51:49 -07002919 // Expect no scaling to begin with.
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02002920 EXPECT_THAT(video_source_.sink_wants(), UnlimitedSinkWants());
kthelgason876222f2016-11-29 01:44:11 -08002921
asaperssonfab67072017-04-04 05:51:49 -07002922 video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002923 WaitForEncodedFrame(1);
kthelgason876222f2016-11-29 01:44:11 -08002924
asaperssonfab67072017-04-04 05:51:49 -07002925 // Trigger scale down.
mflodmancc3d4422017-08-03 08:27:51 -07002926 video_stream_encoder_->TriggerQualityLow();
kthelgason5e13d412016-12-01 03:59:51 -08002927
asaperssonfab67072017-04-04 05:51:49 -07002928 video_source_.IncomingCapturedFrame(CreateFrame(2, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002929 WaitForEncodedFrame(2);
kthelgason5e13d412016-12-01 03:59:51 -08002930
kthelgason876222f2016-11-29 01:44:11 -08002931 // Expect a scale down.
2932 EXPECT_TRUE(video_source_.sink_wants().max_pixel_count);
asaperssonfab67072017-04-04 05:51:49 -07002933 EXPECT_LT(video_source_.sink_wants().max_pixel_count, kWidth * kHeight);
kthelgason876222f2016-11-29 01:44:11 -08002934
asapersson02465b82017-04-10 01:12:52 -07002935 // Set resolution scaling disabled.
kthelgason876222f2016-11-29 01:44:11 -08002936 test::FrameForwarder new_video_source;
mflodmancc3d4422017-08-03 08:27:51 -07002937 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002938 &new_video_source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
kthelgason876222f2016-11-29 01:44:11 -08002939
asaperssonfab67072017-04-04 05:51:49 -07002940 // Trigger scale down.
mflodmancc3d4422017-08-03 08:27:51 -07002941 video_stream_encoder_->TriggerQualityLow();
asaperssonfab67072017-04-04 05:51:49 -07002942 new_video_source.IncomingCapturedFrame(CreateFrame(3, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002943 WaitForEncodedFrame(3);
kthelgason876222f2016-11-29 01:44:11 -08002944
asaperssonfab67072017-04-04 05:51:49 -07002945 // Expect no scaling.
sprangc5d62e22017-04-02 23:53:04 -07002946 EXPECT_EQ(std::numeric_limits<int>::max(),
2947 new_video_source.sink_wants().max_pixel_count);
kthelgason876222f2016-11-29 01:44:11 -08002948
asaperssonfab67072017-04-04 05:51:49 -07002949 // Trigger scale up.
mflodmancc3d4422017-08-03 08:27:51 -07002950 video_stream_encoder_->TriggerQualityHigh();
asaperssonfab67072017-04-04 05:51:49 -07002951 new_video_source.IncomingCapturedFrame(CreateFrame(4, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002952 WaitForEncodedFrame(4);
kthelgason876222f2016-11-29 01:44:11 -08002953
asapersson02465b82017-04-10 01:12:52 -07002954 // Expect nothing to change, still no scaling.
sprangc5d62e22017-04-02 23:53:04 -07002955 EXPECT_EQ(std::numeric_limits<int>::max(),
2956 new_video_source.sink_wants().max_pixel_count);
kthelgason876222f2016-11-29 01:44:11 -08002957
mflodmancc3d4422017-08-03 08:27:51 -07002958 video_stream_encoder_->Stop();
kthelgason876222f2016-11-29 01:44:11 -08002959}
2960
mflodmancc3d4422017-08-03 08:27:51 -07002961TEST_F(VideoStreamEncoderTest,
2962 SkipsSameAdaptDownRequest_MaintainFramerateMode) {
asapersson02465b82017-04-10 01:12:52 -07002963 const int kWidth = 1280;
2964 const int kHeight = 720;
Henrik Boström381d1092020-05-12 18:49:07 +02002965 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01002966 DataRate::BitsPerSec(kTargetBitrateBps),
2967 DataRate::BitsPerSec(kTargetBitrateBps),
2968 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asapersson02465b82017-04-10 01:12:52 -07002969
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002970 // Enable MAINTAIN_FRAMERATE preference, no initial limitation.
asapersson02465b82017-04-10 01:12:52 -07002971 test::FrameForwarder source;
mflodmancc3d4422017-08-03 08:27:51 -07002972 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07002973 &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
asapersson02465b82017-04-10 01:12:52 -07002974
2975 source.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07002976 WaitForEncodedFrame(1);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02002977 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asapersson02465b82017-04-10 01:12:52 -07002978 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
2979 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
2980
2981 // Trigger adapt down, expect scaled down resolution.
mflodmancc3d4422017-08-03 08:27:51 -07002982 video_stream_encoder_->TriggerCpuOveruse();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02002983 EXPECT_THAT(source.sink_wants(),
2984 FpsMaxResolutionMatches(Lt(kWidth * kHeight)));
asapersson02465b82017-04-10 01:12:52 -07002985 const int kLastMaxPixelCount = source.sink_wants().max_pixel_count;
2986 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
2987 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
2988
2989 // Trigger adapt down for same input resolution, expect no change.
mflodmancc3d4422017-08-03 08:27:51 -07002990 video_stream_encoder_->TriggerCpuOveruse();
asapersson02465b82017-04-10 01:12:52 -07002991 EXPECT_EQ(kLastMaxPixelCount, source.sink_wants().max_pixel_count);
2992 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
2993 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
2994
mflodmancc3d4422017-08-03 08:27:51 -07002995 video_stream_encoder_->Stop();
asapersson02465b82017-04-10 01:12:52 -07002996}
2997
mflodmancc3d4422017-08-03 08:27:51 -07002998TEST_F(VideoStreamEncoderTest, SkipsSameOrLargerAdaptDownRequest_BalancedMode) {
asaperssonf7e294d2017-06-13 23:25:22 -07002999 const int kWidth = 1280;
3000 const int kHeight = 720;
Henrik Boström381d1092020-05-12 18:49:07 +02003001 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01003002 DataRate::BitsPerSec(kTargetBitrateBps),
3003 DataRate::BitsPerSec(kTargetBitrateBps),
3004 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asaperssonf7e294d2017-06-13 23:25:22 -07003005
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003006 // Enable BALANCED preference, no initial limitation.
asaperssonf7e294d2017-06-13 23:25:22 -07003007 test::FrameForwarder source;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003008 video_stream_encoder_->SetSource(&source,
3009 webrtc::DegradationPreference::BALANCED);
asaperssonf7e294d2017-06-13 23:25:22 -07003010 source.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
3011 sink_.WaitForEncodedFrame(1);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003012 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-13 23:25:22 -07003013
3014 // Trigger adapt down, expect scaled down resolution.
mflodmancc3d4422017-08-03 08:27:51 -07003015 video_stream_encoder_->TriggerQualityLow();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003016 EXPECT_THAT(source.sink_wants(),
3017 FpsMaxResolutionMatches(Lt(kWidth * kHeight)));
asaperssonf7e294d2017-06-13 23:25:22 -07003018 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
3019 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3020 const int kLastMaxPixelCount = source.sink_wants().max_pixel_count;
3021
3022 // Trigger adapt down for same input resolution, expect no change.
3023 source.IncomingCapturedFrame(CreateFrame(2, kWidth, kHeight));
3024 sink_.WaitForEncodedFrame(2);
mflodmancc3d4422017-08-03 08:27:51 -07003025 video_stream_encoder_->TriggerQualityLow();
asaperssonf7e294d2017-06-13 23:25:22 -07003026 EXPECT_EQ(kLastMaxPixelCount, source.sink_wants().max_pixel_count);
3027 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
3028 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3029
3030 // Trigger adapt down for larger input resolution, expect no change.
3031 source.IncomingCapturedFrame(CreateFrame(3, kWidth + 1, kHeight + 1));
3032 sink_.WaitForEncodedFrame(3);
mflodmancc3d4422017-08-03 08:27:51 -07003033 video_stream_encoder_->TriggerQualityLow();
asaperssonf7e294d2017-06-13 23:25:22 -07003034 EXPECT_EQ(kLastMaxPixelCount, source.sink_wants().max_pixel_count);
3035 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
3036 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3037
mflodmancc3d4422017-08-03 08:27:51 -07003038 video_stream_encoder_->Stop();
asaperssonf7e294d2017-06-13 23:25:22 -07003039}
3040
mflodmancc3d4422017-08-03 08:27:51 -07003041TEST_F(VideoStreamEncoderTest,
3042 NoChangeForInitialNormalUsage_MaintainFramerateMode) {
asapersson02465b82017-04-10 01:12:52 -07003043 const int kWidth = 1280;
3044 const int kHeight = 720;
Henrik Boström381d1092020-05-12 18:49:07 +02003045 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01003046 DataRate::BitsPerSec(kTargetBitrateBps),
3047 DataRate::BitsPerSec(kTargetBitrateBps),
3048 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asapersson02465b82017-04-10 01:12:52 -07003049
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003050 // Enable MAINTAIN_FRAMERATE preference, no initial limitation.
asapersson02465b82017-04-10 01:12:52 -07003051 test::FrameForwarder source;
mflodmancc3d4422017-08-03 08:27:51 -07003052 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003053 &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
asapersson02465b82017-04-10 01:12:52 -07003054
3055 source.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07003056 WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003057 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asapersson02465b82017-04-10 01:12:52 -07003058 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
3059 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3060
3061 // Trigger adapt up, expect no change.
Henrik Boström91aa7322020-04-28 12:24:33 +02003062 video_stream_encoder_->TriggerCpuUnderuse();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003063 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asapersson02465b82017-04-10 01:12:52 -07003064 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
3065 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3066
mflodmancc3d4422017-08-03 08:27:51 -07003067 video_stream_encoder_->Stop();
asapersson02465b82017-04-10 01:12:52 -07003068}
3069
mflodmancc3d4422017-08-03 08:27:51 -07003070TEST_F(VideoStreamEncoderTest,
3071 NoChangeForInitialNormalUsage_MaintainResolutionMode) {
asapersson02465b82017-04-10 01:12:52 -07003072 const int kWidth = 1280;
3073 const int kHeight = 720;
Henrik Boström381d1092020-05-12 18:49:07 +02003074 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01003075 DataRate::BitsPerSec(kTargetBitrateBps),
3076 DataRate::BitsPerSec(kTargetBitrateBps),
3077 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asapersson02465b82017-04-10 01:12:52 -07003078
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003079 // Enable MAINTAIN_RESOLUTION preference, no initial limitation.
asapersson02465b82017-04-10 01:12:52 -07003080 test::FrameForwarder source;
mflodmancc3d4422017-08-03 08:27:51 -07003081 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003082 &source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
asapersson02465b82017-04-10 01:12:52 -07003083
3084 source.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07003085 WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003086 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asapersson09f05612017-05-15 23:40:18 -07003087 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
asapersson02465b82017-04-10 01:12:52 -07003088 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3089
3090 // Trigger adapt up, expect no change.
Henrik Boström91aa7322020-04-28 12:24:33 +02003091 video_stream_encoder_->TriggerCpuUnderuse();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003092 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asapersson09f05612017-05-15 23:40:18 -07003093 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
asapersson02465b82017-04-10 01:12:52 -07003094 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3095
mflodmancc3d4422017-08-03 08:27:51 -07003096 video_stream_encoder_->Stop();
asapersson02465b82017-04-10 01:12:52 -07003097}
3098
mflodmancc3d4422017-08-03 08:27:51 -07003099TEST_F(VideoStreamEncoderTest, NoChangeForInitialNormalUsage_BalancedMode) {
asaperssonf7e294d2017-06-13 23:25:22 -07003100 const int kWidth = 1280;
3101 const int kHeight = 720;
Henrik Boström381d1092020-05-12 18:49:07 +02003102 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01003103 DataRate::BitsPerSec(kTargetBitrateBps),
3104 DataRate::BitsPerSec(kTargetBitrateBps),
3105 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asaperssonf7e294d2017-06-13 23:25:22 -07003106
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003107 // Enable BALANCED preference, no initial limitation.
asaperssonf7e294d2017-06-13 23:25:22 -07003108 test::FrameForwarder source;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003109 video_stream_encoder_->SetSource(&source,
3110 webrtc::DegradationPreference::BALANCED);
asaperssonf7e294d2017-06-13 23:25:22 -07003111
3112 source.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
3113 sink_.WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003114 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-13 23:25:22 -07003115 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
3116 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
3117 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3118
3119 // Trigger adapt up, expect no change.
mflodmancc3d4422017-08-03 08:27:51 -07003120 video_stream_encoder_->TriggerQualityHigh();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003121 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-13 23:25:22 -07003122 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
3123 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
3124 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3125
mflodmancc3d4422017-08-03 08:27:51 -07003126 video_stream_encoder_->Stop();
asaperssonf7e294d2017-06-13 23:25:22 -07003127}
3128
mflodmancc3d4422017-08-03 08:27:51 -07003129TEST_F(VideoStreamEncoderTest, NoChangeForInitialNormalUsage_DisabledMode) {
asapersson09f05612017-05-15 23:40:18 -07003130 const int kWidth = 1280;
3131 const int kHeight = 720;
Henrik Boström381d1092020-05-12 18:49:07 +02003132 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01003133 DataRate::BitsPerSec(kTargetBitrateBps),
3134 DataRate::BitsPerSec(kTargetBitrateBps),
3135 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asapersson09f05612017-05-15 23:40:18 -07003136
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003137 // Enable DISABLED preference, no initial limitation.
asapersson09f05612017-05-15 23:40:18 -07003138 test::FrameForwarder source;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003139 video_stream_encoder_->SetSource(&source,
3140 webrtc::DegradationPreference::DISABLED);
asapersson09f05612017-05-15 23:40:18 -07003141
3142 source.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
3143 sink_.WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003144 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asapersson09f05612017-05-15 23:40:18 -07003145 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
3146 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
3147 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3148
3149 // Trigger adapt up, expect no change.
mflodmancc3d4422017-08-03 08:27:51 -07003150 video_stream_encoder_->TriggerQualityHigh();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003151 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asapersson09f05612017-05-15 23:40:18 -07003152 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
3153 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
3154 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3155
mflodmancc3d4422017-08-03 08:27:51 -07003156 video_stream_encoder_->Stop();
asapersson09f05612017-05-15 23:40:18 -07003157}
3158
mflodmancc3d4422017-08-03 08:27:51 -07003159TEST_F(VideoStreamEncoderTest,
3160 AdaptsResolutionForLowQuality_MaintainFramerateMode) {
asapersson02465b82017-04-10 01:12:52 -07003161 const int kWidth = 1280;
3162 const int kHeight = 720;
Henrik Boström381d1092020-05-12 18:49:07 +02003163 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01003164 DataRate::BitsPerSec(kTargetBitrateBps),
3165 DataRate::BitsPerSec(kTargetBitrateBps),
3166 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asapersson02465b82017-04-10 01:12:52 -07003167
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003168 // Enable MAINTAIN_FRAMERATE preference, no initial limitation.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02003169 AdaptingFrameForwarder source(&time_controller_);
asapersson02465b82017-04-10 01:12:52 -07003170 source.set_adaptation_enabled(true);
mflodmancc3d4422017-08-03 08:27:51 -07003171 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003172 &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
asapersson02465b82017-04-10 01:12:52 -07003173
3174 source.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07003175 WaitForEncodedFrame(1);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003176 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asapersson02465b82017-04-10 01:12:52 -07003177 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
3178 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3179
3180 // Trigger adapt down, expect scaled down resolution.
mflodmancc3d4422017-08-03 08:27:51 -07003181 video_stream_encoder_->TriggerQualityLow();
asapersson02465b82017-04-10 01:12:52 -07003182 source.IncomingCapturedFrame(CreateFrame(2, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07003183 WaitForEncodedFrame(2);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003184 EXPECT_THAT(source.sink_wants(),
3185 FpsMaxResolutionMatches(Lt(kWidth * kHeight)));
asapersson02465b82017-04-10 01:12:52 -07003186 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
3187 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3188
3189 // Trigger adapt up, expect no restriction.
mflodmancc3d4422017-08-03 08:27:51 -07003190 video_stream_encoder_->TriggerQualityHigh();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003191 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asapersson02465b82017-04-10 01:12:52 -07003192 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
3193 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3194 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3195
mflodmancc3d4422017-08-03 08:27:51 -07003196 video_stream_encoder_->Stop();
asapersson02465b82017-04-10 01:12:52 -07003197}
3198
mflodmancc3d4422017-08-03 08:27:51 -07003199TEST_F(VideoStreamEncoderTest,
3200 AdaptsFramerateForLowQuality_MaintainResolutionMode) {
asapersson09f05612017-05-15 23:40:18 -07003201 const int kWidth = 1280;
3202 const int kHeight = 720;
3203 const int kInputFps = 30;
Henrik Boström381d1092020-05-12 18:49:07 +02003204 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01003205 DataRate::BitsPerSec(kTargetBitrateBps),
3206 DataRate::BitsPerSec(kTargetBitrateBps),
3207 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asapersson09f05612017-05-15 23:40:18 -07003208
3209 VideoSendStream::Stats stats = stats_proxy_->GetStats();
3210 stats.input_frame_rate = kInputFps;
3211 stats_proxy_->SetMockStats(stats);
3212
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003213 // Expect no scaling to begin with (preference: MAINTAIN_FRAMERATE).
asapersson09f05612017-05-15 23:40:18 -07003214 video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
3215 sink_.WaitForEncodedFrame(1);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003216 EXPECT_THAT(video_source_.sink_wants(), FpsMaxResolutionMax());
asapersson09f05612017-05-15 23:40:18 -07003217
3218 // Trigger adapt down, expect scaled down resolution.
mflodmancc3d4422017-08-03 08:27:51 -07003219 video_stream_encoder_->TriggerQualityLow();
asapersson09f05612017-05-15 23:40:18 -07003220 video_source_.IncomingCapturedFrame(CreateFrame(2, kWidth, kHeight));
3221 sink_.WaitForEncodedFrame(2);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003222 EXPECT_THAT(video_source_.sink_wants(),
3223 FpsMaxResolutionMatches(Lt(kWidth * kHeight)));
asapersson09f05612017-05-15 23:40:18 -07003224
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003225 // Enable MAINTAIN_RESOLUTION preference.
asapersson09f05612017-05-15 23:40:18 -07003226 test::FrameForwarder new_video_source;
Henrik Boström2671dac2020-05-19 16:29:09 +02003227 video_stream_encoder_->SetSourceAndWaitForRestrictionsUpdated(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003228 &new_video_source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
Henrik Boström07b17df2020-01-15 11:42:12 +01003229 // Give the encoder queue time to process the change in degradation preference
3230 // by waiting for an encoded frame.
3231 new_video_source.IncomingCapturedFrame(CreateFrame(3, kWidth, kHeight));
3232 sink_.WaitForEncodedFrame(3);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003233 EXPECT_THAT(new_video_source.sink_wants(), FpsMaxResolutionMax());
asapersson09f05612017-05-15 23:40:18 -07003234
3235 // Trigger adapt down, expect reduced framerate.
mflodmancc3d4422017-08-03 08:27:51 -07003236 video_stream_encoder_->TriggerQualityLow();
Henrik Boström07b17df2020-01-15 11:42:12 +01003237 new_video_source.IncomingCapturedFrame(CreateFrame(4, kWidth, kHeight));
3238 sink_.WaitForEncodedFrame(4);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003239 EXPECT_THAT(new_video_source.sink_wants(),
3240 FpsMatchesResolutionMax(Lt(kInputFps)));
asapersson09f05612017-05-15 23:40:18 -07003241
3242 // Trigger adapt up, expect no restriction.
mflodmancc3d4422017-08-03 08:27:51 -07003243 video_stream_encoder_->TriggerQualityHigh();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003244 EXPECT_THAT(new_video_source.sink_wants(), FpsMaxResolutionMax());
asapersson09f05612017-05-15 23:40:18 -07003245
mflodmancc3d4422017-08-03 08:27:51 -07003246 video_stream_encoder_->Stop();
asapersson09f05612017-05-15 23:40:18 -07003247}
3248
mflodmancc3d4422017-08-03 08:27:51 -07003249TEST_F(VideoStreamEncoderTest, DoesNotScaleBelowSetResolutionLimit) {
asaperssond0de2952017-04-21 01:47:31 -07003250 const int kWidth = 1280;
3251 const int kHeight = 720;
3252 const size_t kNumFrames = 10;
3253
Henrik Boström381d1092020-05-12 18:49:07 +02003254 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01003255 DataRate::BitsPerSec(kTargetBitrateBps),
3256 DataRate::BitsPerSec(kTargetBitrateBps),
3257 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
kthelgason5e13d412016-12-01 03:59:51 -08003258
asaperssond0de2952017-04-21 01:47:31 -07003259 // Enable adapter, expected input resolutions when downscaling:
asapersson142fcc92017-08-17 08:58:54 -07003260 // 1280x720 -> 960x540 -> 640x360 -> 480x270 -> 320x180 (kMinPixelsPerFrame)
asaperssond0de2952017-04-21 01:47:31 -07003261 video_source_.set_adaptation_enabled(true);
3262
3263 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
3264 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3265
3266 int downscales = 0;
3267 for (size_t i = 1; i <= kNumFrames; i++) {
Åsa Persson8c1bf952018-09-13 10:42:19 +02003268 video_source_.IncomingCapturedFrame(
3269 CreateFrame(i * kFrameIntervalMs, kWidth, kHeight));
3270 WaitForEncodedFrame(i * kFrameIntervalMs);
asaperssond0de2952017-04-21 01:47:31 -07003271
asaperssonfab67072017-04-04 05:51:49 -07003272 // Trigger scale down.
asaperssond0de2952017-04-21 01:47:31 -07003273 rtc::VideoSinkWants last_wants = video_source_.sink_wants();
mflodmancc3d4422017-08-03 08:27:51 -07003274 video_stream_encoder_->TriggerQualityLow();
sprangc5d62e22017-04-02 23:53:04 -07003275 EXPECT_GE(video_source_.sink_wants().max_pixel_count, kMinPixelsPerFrame);
asaperssond0de2952017-04-21 01:47:31 -07003276
3277 if (video_source_.sink_wants().max_pixel_count < last_wants.max_pixel_count)
3278 ++downscales;
3279
3280 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
3281 EXPECT_EQ(downscales,
3282 stats_proxy_->GetStats().number_of_quality_adapt_changes);
3283 EXPECT_GT(downscales, 0);
kthelgason5e13d412016-12-01 03:59:51 -08003284 }
mflodmancc3d4422017-08-03 08:27:51 -07003285 video_stream_encoder_->Stop();
asaperssond0de2952017-04-21 01:47:31 -07003286}
3287
mflodmancc3d4422017-08-03 08:27:51 -07003288TEST_F(VideoStreamEncoderTest,
asaperssond0de2952017-04-21 01:47:31 -07003289 AdaptsResolutionUpAndDownTwiceOnOveruse_MaintainFramerateMode) {
3290 const int kWidth = 1280;
3291 const int kHeight = 720;
Henrik Boström381d1092020-05-12 18:49:07 +02003292 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01003293 DataRate::BitsPerSec(kTargetBitrateBps),
3294 DataRate::BitsPerSec(kTargetBitrateBps),
3295 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asaperssond0de2952017-04-21 01:47:31 -07003296
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003297 // Enable MAINTAIN_FRAMERATE preference, no initial limitation.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02003298 AdaptingFrameForwarder source(&time_controller_);
asaperssond0de2952017-04-21 01:47:31 -07003299 source.set_adaptation_enabled(true);
mflodmancc3d4422017-08-03 08:27:51 -07003300 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003301 &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
asaperssond0de2952017-04-21 01:47:31 -07003302
Åsa Persson8c1bf952018-09-13 10:42:19 +02003303 int64_t timestamp_ms = kFrameIntervalMs;
3304 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07003305 WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003306 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssond0de2952017-04-21 01:47:31 -07003307 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
3308 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3309
3310 // Trigger adapt down, expect scaled down resolution.
mflodmancc3d4422017-08-03 08:27:51 -07003311 video_stream_encoder_->TriggerCpuOveruse();
Åsa Persson8c1bf952018-09-13 10:42:19 +02003312 timestamp_ms += kFrameIntervalMs;
3313 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
3314 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003315 EXPECT_THAT(source.sink_wants(),
3316 FpsMaxResolutionMatches(Lt(kWidth * kHeight)));
asaperssond0de2952017-04-21 01:47:31 -07003317 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
3318 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3319
3320 // Trigger adapt up, expect no restriction.
Henrik Boström91aa7322020-04-28 12:24:33 +02003321 video_stream_encoder_->TriggerCpuUnderuse();
Åsa Persson8c1bf952018-09-13 10:42:19 +02003322 timestamp_ms += kFrameIntervalMs;
3323 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07003324 WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003325 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssond0de2952017-04-21 01:47:31 -07003326 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
3327 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3328
3329 // Trigger adapt down, expect scaled down resolution.
mflodmancc3d4422017-08-03 08:27:51 -07003330 video_stream_encoder_->TriggerCpuOveruse();
Åsa Persson8c1bf952018-09-13 10:42:19 +02003331 timestamp_ms += kFrameIntervalMs;
3332 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
3333 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003334 EXPECT_THAT(source.sink_wants(),
3335 FpsMaxResolutionMatches(Lt(kWidth * kHeight)));
asaperssond0de2952017-04-21 01:47:31 -07003336 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
3337 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3338
3339 // Trigger adapt up, expect no restriction.
Henrik Boström91aa7322020-04-28 12:24:33 +02003340 video_stream_encoder_->TriggerCpuUnderuse();
Åsa Persson8c1bf952018-09-13 10:42:19 +02003341 timestamp_ms += kFrameIntervalMs;
3342 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
asapersson09f05612017-05-15 23:40:18 -07003343 sink_.WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003344 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssond0de2952017-04-21 01:47:31 -07003345 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
3346 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3347
mflodmancc3d4422017-08-03 08:27:51 -07003348 video_stream_encoder_->Stop();
asaperssond0de2952017-04-21 01:47:31 -07003349}
3350
mflodmancc3d4422017-08-03 08:27:51 -07003351TEST_F(VideoStreamEncoderTest,
asaperssonf7e294d2017-06-13 23:25:22 -07003352 AdaptsResolutionUpAndDownTwiceForLowQuality_BalancedMode_NoFpsLimit) {
3353 const int kWidth = 1280;
3354 const int kHeight = 720;
Henrik Boström381d1092020-05-12 18:49:07 +02003355 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01003356 DataRate::BitsPerSec(kTargetBitrateBps),
3357 DataRate::BitsPerSec(kTargetBitrateBps),
3358 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asaperssonf7e294d2017-06-13 23:25:22 -07003359
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003360 // Enable BALANCED preference, no initial limitation.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02003361 AdaptingFrameForwarder source(&time_controller_);
asaperssonf7e294d2017-06-13 23:25:22 -07003362 source.set_adaptation_enabled(true);
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003363 video_stream_encoder_->SetSource(&source,
3364 webrtc::DegradationPreference::BALANCED);
asaperssonf7e294d2017-06-13 23:25:22 -07003365
Åsa Persson8c1bf952018-09-13 10:42:19 +02003366 int64_t timestamp_ms = kFrameIntervalMs;
3367 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
asaperssonf7e294d2017-06-13 23:25:22 -07003368 sink_.WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003369 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-13 23:25:22 -07003370 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
3371 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3372
3373 // Trigger adapt down, expect scaled down resolution.
mflodmancc3d4422017-08-03 08:27:51 -07003374 video_stream_encoder_->TriggerQualityLow();
Åsa Persson8c1bf952018-09-13 10:42:19 +02003375 timestamp_ms += kFrameIntervalMs;
3376 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
3377 sink_.WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003378 EXPECT_THAT(source.sink_wants(),
3379 FpsMaxResolutionMatches(Lt(kWidth * kHeight)));
asaperssonf7e294d2017-06-13 23:25:22 -07003380 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
3381 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3382
3383 // Trigger adapt up, expect no restriction.
mflodmancc3d4422017-08-03 08:27:51 -07003384 video_stream_encoder_->TriggerQualityHigh();
Åsa Persson8c1bf952018-09-13 10:42:19 +02003385 timestamp_ms += kFrameIntervalMs;
3386 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
asaperssonf7e294d2017-06-13 23:25:22 -07003387 sink_.WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003388 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-13 23:25:22 -07003389 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
3390 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3391
3392 // Trigger adapt down, expect scaled down resolution.
mflodmancc3d4422017-08-03 08:27:51 -07003393 video_stream_encoder_->TriggerQualityLow();
Åsa Persson8c1bf952018-09-13 10:42:19 +02003394 timestamp_ms += kFrameIntervalMs;
3395 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
3396 sink_.WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003397 EXPECT_THAT(source.sink_wants(),
3398 FpsMaxResolutionMatches(Lt(kWidth * kHeight)));
asaperssonf7e294d2017-06-13 23:25:22 -07003399 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
3400 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3401
3402 // Trigger adapt up, expect no restriction.
mflodmancc3d4422017-08-03 08:27:51 -07003403 video_stream_encoder_->TriggerQualityHigh();
Åsa Persson8c1bf952018-09-13 10:42:19 +02003404 timestamp_ms += kFrameIntervalMs;
3405 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
asaperssonf7e294d2017-06-13 23:25:22 -07003406 sink_.WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003407 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-13 23:25:22 -07003408 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
3409 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3410
mflodmancc3d4422017-08-03 08:27:51 -07003411 video_stream_encoder_->Stop();
asaperssonf7e294d2017-06-13 23:25:22 -07003412}
3413
Sergey Silkin41c650b2019-10-14 13:12:19 +02003414TEST_F(VideoStreamEncoderTest, AdaptUpIfBwEstimateIsHigherThanMinBitrate) {
3415 fake_encoder_.SetResolutionBitrateLimits(
3416 {kEncoderBitrateLimits540p, kEncoderBitrateLimits720p});
3417
Henrik Boström381d1092020-05-12 18:49:07 +02003418 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01003419 DataRate::BitsPerSec(kEncoderBitrateLimits720p.min_start_bitrate_bps),
3420 DataRate::BitsPerSec(kEncoderBitrateLimits720p.min_start_bitrate_bps),
3421 DataRate::BitsPerSec(kEncoderBitrateLimits720p.min_start_bitrate_bps), 0,
3422 0, 0);
Sergey Silkin41c650b2019-10-14 13:12:19 +02003423
3424 // Enable MAINTAIN_FRAMERATE preference, no initial limitation.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02003425 AdaptingFrameForwarder source(&time_controller_);
Sergey Silkin41c650b2019-10-14 13:12:19 +02003426 source.set_adaptation_enabled(true);
3427 video_stream_encoder_->SetSource(
3428 &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
3429
3430 // Insert 720p frame.
3431 int64_t timestamp_ms = kFrameIntervalMs;
3432 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, 1280, 720));
3433 WaitForEncodedFrame(1280, 720);
3434
3435 // Reduce bitrate and trigger adapt down.
Henrik Boström381d1092020-05-12 18:49:07 +02003436 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01003437 DataRate::BitsPerSec(kEncoderBitrateLimits540p.min_start_bitrate_bps),
3438 DataRate::BitsPerSec(kEncoderBitrateLimits540p.min_start_bitrate_bps),
3439 DataRate::BitsPerSec(kEncoderBitrateLimits540p.min_start_bitrate_bps), 0,
3440 0, 0);
Sergey Silkin41c650b2019-10-14 13:12:19 +02003441 video_stream_encoder_->TriggerQualityLow();
3442
3443 // Insert 720p frame. It should be downscaled and encoded.
3444 timestamp_ms += kFrameIntervalMs;
3445 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, 1280, 720));
3446 WaitForEncodedFrame(960, 540);
3447
3448 // Trigger adapt up. Higher resolution should not be requested duo to lack
3449 // of bitrate.
3450 video_stream_encoder_->TriggerQualityHigh();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003451 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMatches(Lt(1280 * 720)));
Sergey Silkin41c650b2019-10-14 13:12:19 +02003452
3453 // Increase bitrate.
Henrik Boström381d1092020-05-12 18:49:07 +02003454 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01003455 DataRate::BitsPerSec(kEncoderBitrateLimits720p.min_start_bitrate_bps),
3456 DataRate::BitsPerSec(kEncoderBitrateLimits720p.min_start_bitrate_bps),
3457 DataRate::BitsPerSec(kEncoderBitrateLimits720p.min_start_bitrate_bps), 0,
3458 0, 0);
Sergey Silkin41c650b2019-10-14 13:12:19 +02003459
3460 // Trigger adapt up. Higher resolution should be requested.
3461 video_stream_encoder_->TriggerQualityHigh();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003462 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
Sergey Silkin41c650b2019-10-14 13:12:19 +02003463
3464 video_stream_encoder_->Stop();
3465}
3466
3467TEST_F(VideoStreamEncoderTest, DropFirstFramesIfBwEstimateIsTooLow) {
3468 fake_encoder_.SetResolutionBitrateLimits(
3469 {kEncoderBitrateLimits540p, kEncoderBitrateLimits720p});
3470
3471 // Set bitrate equal to min bitrate of 540p.
Henrik Boström381d1092020-05-12 18:49:07 +02003472 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01003473 DataRate::BitsPerSec(kEncoderBitrateLimits540p.min_start_bitrate_bps),
3474 DataRate::BitsPerSec(kEncoderBitrateLimits540p.min_start_bitrate_bps),
3475 DataRate::BitsPerSec(kEncoderBitrateLimits540p.min_start_bitrate_bps), 0,
3476 0, 0);
Sergey Silkin41c650b2019-10-14 13:12:19 +02003477
3478 // Enable MAINTAIN_FRAMERATE preference, no initial limitation.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02003479 AdaptingFrameForwarder source(&time_controller_);
Sergey Silkin41c650b2019-10-14 13:12:19 +02003480 source.set_adaptation_enabled(true);
3481 video_stream_encoder_->SetSource(
3482 &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
3483
3484 // Insert 720p frame. It should be dropped and lower resolution should be
3485 // requested.
3486 int64_t timestamp_ms = kFrameIntervalMs;
3487 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, 1280, 720));
3488 ExpectDroppedFrame();
Henrik Boström2671dac2020-05-19 16:29:09 +02003489 EXPECT_TRUE_WAIT(source.sink_wants().max_pixel_count < 1280 * 720, 5000);
Sergey Silkin41c650b2019-10-14 13:12:19 +02003490
3491 // Insert 720p frame. It should be downscaled and encoded.
3492 timestamp_ms += kFrameIntervalMs;
3493 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, 1280, 720));
3494 WaitForEncodedFrame(960, 540);
3495
3496 video_stream_encoder_->Stop();
3497}
3498
Åsa Perssonb67c44c2019-09-24 15:25:32 +02003499class BalancedDegradationTest : public VideoStreamEncoderTest {
3500 protected:
3501 void SetupTest() {
3502 // Reset encoder for field trials to take effect.
3503 ConfigureEncoder(video_encoder_config_.Copy());
Åsa Perssonccfb3402019-09-25 15:13:04 +02003504 OnBitrateUpdated(kTargetBitrateBps);
Åsa Perssonb67c44c2019-09-24 15:25:32 +02003505
3506 // Enable BALANCED preference.
3507 source_.set_adaptation_enabled(true);
Åsa Perssonccfb3402019-09-25 15:13:04 +02003508 video_stream_encoder_->SetSource(&source_, DegradationPreference::BALANCED);
3509 }
3510
3511 void OnBitrateUpdated(int bitrate_bps) {
Henrik Boström381d1092020-05-12 18:49:07 +02003512 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01003513 DataRate::BitsPerSec(bitrate_bps), DataRate::BitsPerSec(bitrate_bps),
3514 DataRate::BitsPerSec(bitrate_bps), 0, 0, 0);
Åsa Perssonb67c44c2019-09-24 15:25:32 +02003515 }
3516
Åsa Persson45b176f2019-09-30 11:19:05 +02003517 void InsertFrame() {
Åsa Perssonb67c44c2019-09-24 15:25:32 +02003518 timestamp_ms_ += kFrameIntervalMs;
3519 source_.IncomingCapturedFrame(CreateFrame(timestamp_ms_, kWidth, kHeight));
Åsa Persson45b176f2019-09-30 11:19:05 +02003520 }
3521
3522 void InsertFrameAndWaitForEncoded() {
3523 InsertFrame();
Åsa Perssonb67c44c2019-09-24 15:25:32 +02003524 sink_.WaitForEncodedFrame(timestamp_ms_);
3525 }
3526
3527 const int kWidth = 640; // pixels:640x360=230400
3528 const int kHeight = 360;
3529 const int64_t kFrameIntervalMs = 150; // Use low fps to not drop any frame.
3530 int64_t timestamp_ms_ = 0;
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02003531 AdaptingFrameForwarder source_{&time_controller_};
Åsa Perssonb67c44c2019-09-24 15:25:32 +02003532};
3533
Evan Shrubsolea1c77f62020-08-10 11:01:06 +02003534TEST_F(BalancedDegradationTest, AdaptDownTwiceIfMinFpsDiffLtThreshold) {
Åsa Perssonb67c44c2019-09-24 15:25:32 +02003535 test::ScopedFieldTrials field_trials(
3536 "WebRTC-Video-BalancedDegradationSettings/"
3537 "pixels:57600|129600|230400,fps:7|10|24,fps_diff:1|1|1/");
3538 SetupTest();
3539
3540 // Force input frame rate.
3541 const int kInputFps = 24;
3542 VideoSendStream::Stats stats = stats_proxy_->GetStats();
3543 stats.input_frame_rate = kInputFps;
3544 stats_proxy_->SetMockStats(stats);
3545
Åsa Persson45b176f2019-09-30 11:19:05 +02003546 InsertFrameAndWaitForEncoded();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003547 EXPECT_THAT(source_.sink_wants(), FpsMaxResolutionMax());
Åsa Perssonb67c44c2019-09-24 15:25:32 +02003548
Evan Shrubsolea1c77f62020-08-10 11:01:06 +02003549 // Trigger adapt down, expect scaled down framerate and resolution,
3550 // since Fps diff (input-requested:0) < threshold.
3551 video_stream_encoder_->TriggerQualityLow();
3552 EXPECT_THAT(source_.sink_wants(),
3553 AllOf(WantsFps(Eq(24)), WantsMaxPixels(Le(230400))));
Åsa Perssonb67c44c2019-09-24 15:25:32 +02003554
3555 video_stream_encoder_->Stop();
3556}
3557
Evan Shrubsolea1c77f62020-08-10 11:01:06 +02003558TEST_F(BalancedDegradationTest, AdaptDownOnceIfFpsDiffGeThreshold) {
Åsa Perssonb67c44c2019-09-24 15:25:32 +02003559 test::ScopedFieldTrials field_trials(
3560 "WebRTC-Video-BalancedDegradationSettings/"
3561 "pixels:57600|129600|230400,fps:7|10|24,fps_diff:1|1|1/");
3562 SetupTest();
3563
3564 // Force input frame rate.
3565 const int kInputFps = 25;
3566 VideoSendStream::Stats stats = stats_proxy_->GetStats();
3567 stats.input_frame_rate = kInputFps;
3568 stats_proxy_->SetMockStats(stats);
3569
Åsa Persson45b176f2019-09-30 11:19:05 +02003570 InsertFrameAndWaitForEncoded();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003571 EXPECT_THAT(source_.sink_wants(), FpsMaxResolutionMax());
Åsa Perssonb67c44c2019-09-24 15:25:32 +02003572
Evan Shrubsolea1c77f62020-08-10 11:01:06 +02003573 // Trigger adapt down, expect scaled down framerate only (640x360@24fps).
3574 // Fps diff (input-requested:1) == threshold.
3575 video_stream_encoder_->TriggerQualityLow();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003576 EXPECT_THAT(source_.sink_wants(), FpsMatchesResolutionMax(Eq(24)));
Åsa Perssonb67c44c2019-09-24 15:25:32 +02003577
3578 video_stream_encoder_->Stop();
3579}
3580
3581TEST_F(BalancedDegradationTest, AdaptDownUsesCodecSpecificFps) {
3582 test::ScopedFieldTrials field_trials(
3583 "WebRTC-Video-BalancedDegradationSettings/"
3584 "pixels:57600|129600|230400,fps:7|10|24,vp8_fps:8|11|22/");
3585 SetupTest();
3586
3587 EXPECT_EQ(kVideoCodecVP8, video_encoder_config_.codec_type);
3588
Åsa Persson45b176f2019-09-30 11:19:05 +02003589 InsertFrameAndWaitForEncoded();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003590 EXPECT_THAT(source_.sink_wants(), FpsMaxResolutionMax());
Åsa Perssonb67c44c2019-09-24 15:25:32 +02003591
3592 // Trigger adapt down, expect scaled down framerate (640x360@22fps).
3593 video_stream_encoder_->TriggerQualityLow();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003594 EXPECT_THAT(source_.sink_wants(), FpsMatchesResolutionMax(Eq(22)));
Åsa Perssonb67c44c2019-09-24 15:25:32 +02003595
3596 video_stream_encoder_->Stop();
3597}
3598
Åsa Perssonccfb3402019-09-25 15:13:04 +02003599TEST_F(BalancedDegradationTest, NoAdaptUpIfBwEstimateIsLessThanMinBitrate) {
Åsa Perssonb67c44c2019-09-24 15:25:32 +02003600 test::ScopedFieldTrials field_trials(
Åsa Persson1b247f12019-08-14 17:26:39 +02003601 "WebRTC-Video-BalancedDegradationSettings/"
3602 "pixels:57600|129600|230400,fps:7|10|14,kbps:0|0|425/");
Åsa Perssonccfb3402019-09-25 15:13:04 +02003603 SetupTest();
Åsa Persson1b247f12019-08-14 17:26:39 +02003604
Åsa Persson1b247f12019-08-14 17:26:39 +02003605 const int kMinBitrateBps = 425000;
3606 const int kTooLowMinBitrateBps = 424000;
Åsa Perssonccfb3402019-09-25 15:13:04 +02003607 OnBitrateUpdated(kTooLowMinBitrateBps);
Åsa Persson1b247f12019-08-14 17:26:39 +02003608
Åsa Persson45b176f2019-09-30 11:19:05 +02003609 InsertFrameAndWaitForEncoded();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003610 EXPECT_THAT(source_.sink_wants(), FpsMaxResolutionMax());
Åsa Persson1b247f12019-08-14 17:26:39 +02003611 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3612
3613 // Trigger adapt down, expect scaled down framerate (640x360@14fps).
3614 video_stream_encoder_->TriggerQualityLow();
Åsa Persson45b176f2019-09-30 11:19:05 +02003615 InsertFrameAndWaitForEncoded();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003616 EXPECT_THAT(source_.sink_wants(), FpsMatchesResolutionMax(Eq(14)));
Åsa Persson1b247f12019-08-14 17:26:39 +02003617 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3618
3619 // Trigger adapt down, expect scaled down resolution (480x270@14fps).
3620 video_stream_encoder_->TriggerQualityLow();
Åsa Persson45b176f2019-09-30 11:19:05 +02003621 InsertFrameAndWaitForEncoded();
Evan Shrubsole5fd40602020-05-25 16:19:54 +02003622 EXPECT_THAT(source_.sink_wants(), FpsEqResolutionLt(source_.last_wants()));
Åsa Persson1b247f12019-08-14 17:26:39 +02003623 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3624
Åsa Persson30ab0152019-08-27 12:22:33 +02003625 // Trigger adapt down, expect scaled down framerate (480x270@10fps).
3626 video_stream_encoder_->TriggerQualityLow();
Åsa Persson45b176f2019-09-30 11:19:05 +02003627 InsertFrameAndWaitForEncoded();
Evan Shrubsole5fd40602020-05-25 16:19:54 +02003628 EXPECT_THAT(source_.sink_wants(), FpsLtResolutionEq(source_.last_wants()));
Åsa Perssonccfb3402019-09-25 15:13:04 +02003629 EXPECT_EQ(source_.sink_wants().max_framerate_fps, 10);
Åsa Persson30ab0152019-08-27 12:22:33 +02003630 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3631
3632 // Trigger adapt up, expect no upscale in fps (target bitrate < min bitrate).
Åsa Persson1b247f12019-08-14 17:26:39 +02003633 video_stream_encoder_->TriggerQualityHigh();
Åsa Persson45b176f2019-09-30 11:19:05 +02003634 InsertFrameAndWaitForEncoded();
Åsa Persson30ab0152019-08-27 12:22:33 +02003635 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_quality_adapt_changes);
Åsa Persson1b247f12019-08-14 17:26:39 +02003636
Åsa Persson30ab0152019-08-27 12:22:33 +02003637 // Trigger adapt up, expect upscaled fps (target bitrate == min bitrate).
Åsa Perssonccfb3402019-09-25 15:13:04 +02003638 OnBitrateUpdated(kMinBitrateBps);
Åsa Persson1b247f12019-08-14 17:26:39 +02003639 video_stream_encoder_->TriggerQualityHigh();
Åsa Persson45b176f2019-09-30 11:19:05 +02003640 InsertFrameAndWaitForEncoded();
Åsa Perssonccfb3402019-09-25 15:13:04 +02003641 EXPECT_EQ(source_.sink_wants().max_framerate_fps, 14);
Åsa Persson30ab0152019-08-27 12:22:33 +02003642 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3643
3644 video_stream_encoder_->Stop();
3645}
3646
Åsa Perssonccfb3402019-09-25 15:13:04 +02003647TEST_F(BalancedDegradationTest,
Åsa Persson45b176f2019-09-30 11:19:05 +02003648 InitialFrameDropAdaptsFpsAndResolutionInOneStep) {
3649 test::ScopedFieldTrials field_trials(
3650 "WebRTC-Video-BalancedDegradationSettings/"
3651 "pixels:57600|129600|230400,fps:7|24|24/");
3652 SetupTest();
3653 OnBitrateUpdated(kLowTargetBitrateBps);
3654
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003655 EXPECT_THAT(source_.sink_wants(), UnlimitedSinkWants());
Åsa Persson45b176f2019-09-30 11:19:05 +02003656
3657 // Insert frame, expect scaled down:
3658 // framerate (640x360@24fps) -> resolution (480x270@24fps).
3659 InsertFrame();
3660 EXPECT_FALSE(WaitForFrame(1000));
3661 EXPECT_LT(source_.sink_wants().max_pixel_count, kWidth * kHeight);
3662 EXPECT_EQ(source_.sink_wants().max_framerate_fps, 24);
3663
3664 // Insert frame, expect scaled down:
3665 // resolution (320x180@24fps).
3666 InsertFrame();
3667 EXPECT_FALSE(WaitForFrame(1000));
3668 EXPECT_LT(source_.sink_wants().max_pixel_count,
3669 source_.last_wants().max_pixel_count);
3670 EXPECT_EQ(source_.sink_wants().max_framerate_fps, 24);
3671
3672 // Frame should not be dropped (min pixels per frame reached).
3673 InsertFrameAndWaitForEncoded();
3674
3675 video_stream_encoder_->Stop();
3676}
3677
3678TEST_F(BalancedDegradationTest,
Åsa Persson30ab0152019-08-27 12:22:33 +02003679 NoAdaptUpInResolutionIfBwEstimateIsLessThanMinBitrate) {
Åsa Perssonb67c44c2019-09-24 15:25:32 +02003680 test::ScopedFieldTrials field_trials(
Åsa Persson30ab0152019-08-27 12:22:33 +02003681 "WebRTC-Video-BalancedDegradationSettings/"
3682 "pixels:57600|129600|230400,fps:7|10|14,kbps_res:0|0|435/");
Åsa Perssonccfb3402019-09-25 15:13:04 +02003683 SetupTest();
Åsa Persson30ab0152019-08-27 12:22:33 +02003684
Åsa Persson30ab0152019-08-27 12:22:33 +02003685 const int kResolutionMinBitrateBps = 435000;
3686 const int kTooLowMinResolutionBitrateBps = 434000;
Åsa Perssonccfb3402019-09-25 15:13:04 +02003687 OnBitrateUpdated(kTooLowMinResolutionBitrateBps);
Åsa Persson30ab0152019-08-27 12:22:33 +02003688
Åsa Persson45b176f2019-09-30 11:19:05 +02003689 InsertFrameAndWaitForEncoded();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003690 EXPECT_THAT(source_.sink_wants(), FpsMaxResolutionMax());
Åsa Persson30ab0152019-08-27 12:22:33 +02003691 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3692
3693 // Trigger adapt down, expect scaled down framerate (640x360@14fps).
3694 video_stream_encoder_->TriggerQualityLow();
Åsa Persson45b176f2019-09-30 11:19:05 +02003695 InsertFrameAndWaitForEncoded();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003696 EXPECT_THAT(source_.sink_wants(), FpsMatchesResolutionMax(Eq(14)));
Åsa Persson30ab0152019-08-27 12:22:33 +02003697 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3698
3699 // Trigger adapt down, expect scaled down resolution (480x270@14fps).
3700 video_stream_encoder_->TriggerQualityLow();
Åsa Persson45b176f2019-09-30 11:19:05 +02003701 InsertFrameAndWaitForEncoded();
Evan Shrubsole5fd40602020-05-25 16:19:54 +02003702 EXPECT_THAT(source_.sink_wants(), FpsEqResolutionLt(source_.last_wants()));
Åsa Persson30ab0152019-08-27 12:22:33 +02003703 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3704
3705 // Trigger adapt down, expect scaled down framerate (480x270@10fps).
3706 video_stream_encoder_->TriggerQualityLow();
Åsa Persson45b176f2019-09-30 11:19:05 +02003707 InsertFrameAndWaitForEncoded();
Evan Shrubsole5fd40602020-05-25 16:19:54 +02003708 EXPECT_THAT(source_.sink_wants(), FpsLtResolutionEq(source_.last_wants()));
Åsa Persson1b247f12019-08-14 17:26:39 +02003709 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3710
Åsa Persson30ab0152019-08-27 12:22:33 +02003711 // Trigger adapt up, expect upscaled fps (no bitrate limit) (480x270@14fps).
3712 video_stream_encoder_->TriggerQualityHigh();
Åsa Persson45b176f2019-09-30 11:19:05 +02003713 InsertFrameAndWaitForEncoded();
Evan Shrubsole5fd40602020-05-25 16:19:54 +02003714 EXPECT_THAT(source_.sink_wants(), FpsGtResolutionEq(source_.last_wants()));
Åsa Persson30ab0152019-08-27 12:22:33 +02003715 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3716
3717 // Trigger adapt up, expect no upscale in res (target bitrate < min bitrate).
3718 video_stream_encoder_->TriggerQualityHigh();
Åsa Persson45b176f2019-09-30 11:19:05 +02003719 InsertFrameAndWaitForEncoded();
Åsa Persson30ab0152019-08-27 12:22:33 +02003720 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3721
3722 // Trigger adapt up, expect upscaled res (target bitrate == min bitrate).
Åsa Perssonccfb3402019-09-25 15:13:04 +02003723 OnBitrateUpdated(kResolutionMinBitrateBps);
Åsa Persson30ab0152019-08-27 12:22:33 +02003724 video_stream_encoder_->TriggerQualityHigh();
Åsa Persson45b176f2019-09-30 11:19:05 +02003725 InsertFrameAndWaitForEncoded();
Evan Shrubsole5fd40602020-05-25 16:19:54 +02003726 EXPECT_THAT(source_.sink_wants(), FpsEqResolutionGt(source_.last_wants()));
Åsa Persson30ab0152019-08-27 12:22:33 +02003727 EXPECT_EQ(5, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3728
3729 video_stream_encoder_->Stop();
3730}
3731
Åsa Perssonccfb3402019-09-25 15:13:04 +02003732TEST_F(BalancedDegradationTest,
Åsa Persson30ab0152019-08-27 12:22:33 +02003733 NoAdaptUpInFpsAndResolutionIfBwEstimateIsLessThanMinBitrate) {
Åsa Perssonb67c44c2019-09-24 15:25:32 +02003734 test::ScopedFieldTrials field_trials(
Åsa Persson30ab0152019-08-27 12:22:33 +02003735 "WebRTC-Video-BalancedDegradationSettings/"
3736 "pixels:57600|129600|230400,fps:7|10|14,kbps:0|0|425,kbps_res:0|0|435/");
Åsa Perssonccfb3402019-09-25 15:13:04 +02003737 SetupTest();
Åsa Persson30ab0152019-08-27 12:22:33 +02003738
Åsa Persson30ab0152019-08-27 12:22:33 +02003739 const int kMinBitrateBps = 425000;
3740 const int kTooLowMinBitrateBps = 424000;
3741 const int kResolutionMinBitrateBps = 435000;
3742 const int kTooLowMinResolutionBitrateBps = 434000;
Åsa Perssonccfb3402019-09-25 15:13:04 +02003743 OnBitrateUpdated(kTooLowMinBitrateBps);
Åsa Persson30ab0152019-08-27 12:22:33 +02003744
Åsa Persson45b176f2019-09-30 11:19:05 +02003745 InsertFrameAndWaitForEncoded();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003746 EXPECT_THAT(source_.sink_wants(), FpsMaxResolutionMax());
Åsa Persson30ab0152019-08-27 12:22:33 +02003747 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3748
3749 // Trigger adapt down, expect scaled down framerate (640x360@14fps).
3750 video_stream_encoder_->TriggerQualityLow();
Åsa Persson45b176f2019-09-30 11:19:05 +02003751 InsertFrameAndWaitForEncoded();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003752 EXPECT_THAT(source_.sink_wants(), FpsMatchesResolutionMax(Eq(14)));
Åsa Persson30ab0152019-08-27 12:22:33 +02003753 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3754
3755 // Trigger adapt down, expect scaled down resolution (480x270@14fps).
3756 video_stream_encoder_->TriggerQualityLow();
Åsa Persson45b176f2019-09-30 11:19:05 +02003757 InsertFrameAndWaitForEncoded();
Evan Shrubsole5fd40602020-05-25 16:19:54 +02003758 EXPECT_THAT(source_.sink_wants(), FpsEqResolutionLt(source_.last_wants()));
Åsa Persson30ab0152019-08-27 12:22:33 +02003759 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3760
3761 // Trigger adapt down, expect scaled down framerate (480x270@10fps).
3762 video_stream_encoder_->TriggerQualityLow();
Åsa Persson45b176f2019-09-30 11:19:05 +02003763 InsertFrameAndWaitForEncoded();
Evan Shrubsole5fd40602020-05-25 16:19:54 +02003764 EXPECT_THAT(source_.sink_wants(), FpsLtResolutionEq(source_.last_wants()));
Åsa Persson30ab0152019-08-27 12:22:33 +02003765 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3766
3767 // Trigger adapt up, expect no upscale (target bitrate < min bitrate).
3768 video_stream_encoder_->TriggerQualityHigh();
Åsa Persson45b176f2019-09-30 11:19:05 +02003769 InsertFrameAndWaitForEncoded();
Åsa Persson30ab0152019-08-27 12:22:33 +02003770 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3771
3772 // Trigger adapt up, expect upscaled fps (target bitrate == min bitrate).
Åsa Perssonccfb3402019-09-25 15:13:04 +02003773 OnBitrateUpdated(kMinBitrateBps);
Åsa Persson30ab0152019-08-27 12:22:33 +02003774 video_stream_encoder_->TriggerQualityHigh();
Åsa Persson45b176f2019-09-30 11:19:05 +02003775 InsertFrameAndWaitForEncoded();
Evan Shrubsole5fd40602020-05-25 16:19:54 +02003776 EXPECT_THAT(source_.sink_wants(), FpsGtResolutionEq(source_.last_wants()));
Åsa Persson30ab0152019-08-27 12:22:33 +02003777 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3778
3779 // Trigger adapt up, expect no upscale in res (target bitrate < min bitrate).
Åsa Perssonccfb3402019-09-25 15:13:04 +02003780 OnBitrateUpdated(kTooLowMinResolutionBitrateBps);
Åsa Persson30ab0152019-08-27 12:22:33 +02003781 video_stream_encoder_->TriggerQualityHigh();
Åsa Persson45b176f2019-09-30 11:19:05 +02003782 InsertFrameAndWaitForEncoded();
Åsa Persson30ab0152019-08-27 12:22:33 +02003783 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3784
3785 // Trigger adapt up, expect upscaled res (target bitrate == min bitrate).
Åsa Perssonccfb3402019-09-25 15:13:04 +02003786 OnBitrateUpdated(kResolutionMinBitrateBps);
Åsa Persson30ab0152019-08-27 12:22:33 +02003787 video_stream_encoder_->TriggerQualityHigh();
Åsa Persson45b176f2019-09-30 11:19:05 +02003788 InsertFrameAndWaitForEncoded();
Evan Shrubsole5fd40602020-05-25 16:19:54 +02003789 EXPECT_THAT(source_.sink_wants(), FpsEqResolutionGt(source_.last_wants()));
Åsa Persson30ab0152019-08-27 12:22:33 +02003790 EXPECT_EQ(5, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3791
Åsa Persson1b247f12019-08-14 17:26:39 +02003792 video_stream_encoder_->Stop();
3793}
3794
mflodmancc3d4422017-08-03 08:27:51 -07003795TEST_F(VideoStreamEncoderTest,
asaperssond0de2952017-04-21 01:47:31 -07003796 AdaptsResolutionOnOveruseAndLowQuality_MaintainFramerateMode) {
3797 const int kWidth = 1280;
3798 const int kHeight = 720;
Henrik Boström381d1092020-05-12 18:49:07 +02003799 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01003800 DataRate::BitsPerSec(kTargetBitrateBps),
3801 DataRate::BitsPerSec(kTargetBitrateBps),
3802 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asaperssond0de2952017-04-21 01:47:31 -07003803
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003804 // Enable MAINTAIN_FRAMERATE preference, no initial limitation.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02003805 AdaptingFrameForwarder source(&time_controller_);
asaperssond0de2952017-04-21 01:47:31 -07003806 source.set_adaptation_enabled(true);
mflodmancc3d4422017-08-03 08:27:51 -07003807 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003808 &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
asaperssond0de2952017-04-21 01:47:31 -07003809
Åsa Persson8c1bf952018-09-13 10:42:19 +02003810 int64_t timestamp_ms = kFrameIntervalMs;
3811 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07003812 WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003813 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssond0de2952017-04-21 01:47:31 -07003814 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
3815 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
3816 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3817 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3818
3819 // Trigger cpu adapt down, expect scaled down resolution (960x540).
mflodmancc3d4422017-08-03 08:27:51 -07003820 video_stream_encoder_->TriggerCpuOveruse();
Åsa Persson8c1bf952018-09-13 10:42:19 +02003821 timestamp_ms += kFrameIntervalMs;
3822 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
3823 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003824 EXPECT_THAT(source.sink_wants(),
3825 FpsMaxResolutionMatches(Lt(kWidth * kHeight)));
asaperssond0de2952017-04-21 01:47:31 -07003826 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
3827 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
3828 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3829 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3830
3831 // Trigger cpu adapt down, expect scaled down resolution (640x360).
mflodmancc3d4422017-08-03 08:27:51 -07003832 video_stream_encoder_->TriggerCpuOveruse();
Åsa Persson8c1bf952018-09-13 10:42:19 +02003833 timestamp_ms += kFrameIntervalMs;
3834 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
3835 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02003836 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionLt(source.last_wants()));
asaperssond0de2952017-04-21 01:47:31 -07003837 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
3838 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
3839 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3840 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3841
Jonathan Yubc771b72017-12-08 17:04:29 -08003842 // Trigger cpu adapt down, expect scaled down resolution (480x270).
mflodmancc3d4422017-08-03 08:27:51 -07003843 video_stream_encoder_->TriggerCpuOveruse();
Åsa Persson8c1bf952018-09-13 10:42:19 +02003844 timestamp_ms += kFrameIntervalMs;
3845 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
3846 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02003847 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionLt(source.last_wants()));
asaperssond0de2952017-04-21 01:47:31 -07003848 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
3849 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
Jonathan Yubc771b72017-12-08 17:04:29 -08003850 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
asaperssond0de2952017-04-21 01:47:31 -07003851 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3852
Jonathan Yubc771b72017-12-08 17:04:29 -08003853 // Trigger quality adapt down, expect scaled down resolution (320x180).
mflodmancc3d4422017-08-03 08:27:51 -07003854 video_stream_encoder_->TriggerQualityLow();
Åsa Persson8c1bf952018-09-13 10:42:19 +02003855 timestamp_ms += kFrameIntervalMs;
3856 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
3857 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02003858 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionLt(source.last_wants()));
Jonathan Yubc771b72017-12-08 17:04:29 -08003859 rtc::VideoSinkWants last_wants = source.sink_wants();
asaperssond0de2952017-04-21 01:47:31 -07003860 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
3861 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
3862 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3863 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3864
Jonathan Yubc771b72017-12-08 17:04:29 -08003865 // Trigger quality adapt down, expect no change (min resolution reached).
3866 video_stream_encoder_->TriggerQualityLow();
Åsa Persson8c1bf952018-09-13 10:42:19 +02003867 timestamp_ms += kFrameIntervalMs;
3868 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
3869 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02003870 EXPECT_THAT(source.sink_wants(), FpsMax());
3871 EXPECT_EQ(source.sink_wants().max_pixel_count, last_wants.max_pixel_count);
Jonathan Yubc771b72017-12-08 17:04:29 -08003872 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
3873 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
3874 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3875 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3876
Evan Shrubsole64469032020-06-11 10:45:29 +02003877 // Trigger quality adapt up, expect upscaled resolution (480x270).
3878 video_stream_encoder_->TriggerQualityHigh();
3879 timestamp_ms += kFrameIntervalMs;
3880 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
3881 WaitForEncodedFrame(timestamp_ms);
3882 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionGt(source.last_wants()));
3883 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
3884 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
3885 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3886 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_quality_adapt_changes);
3887
3888 // Trigger quality and cpu adapt up since both are most limited, expect
3889 // upscaled resolution (640x360).
Henrik Boström91aa7322020-04-28 12:24:33 +02003890 video_stream_encoder_->TriggerCpuUnderuse();
Evan Shrubsole64469032020-06-11 10:45:29 +02003891 video_stream_encoder_->TriggerQualityHigh();
Åsa Persson8c1bf952018-09-13 10:42:19 +02003892 timestamp_ms += kFrameIntervalMs;
3893 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
3894 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02003895 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionGt(source.last_wants()));
Jonathan Yubc771b72017-12-08 17:04:29 -08003896 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
3897 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
3898 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
Evan Shrubsole64469032020-06-11 10:45:29 +02003899 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_quality_adapt_changes);
Jonathan Yubc771b72017-12-08 17:04:29 -08003900
Evan Shrubsole64469032020-06-11 10:45:29 +02003901 // Trigger quality and cpu adapt up since both are most limited, expect
3902 // upscaled resolution (960x540).
Henrik Boström91aa7322020-04-28 12:24:33 +02003903 video_stream_encoder_->TriggerCpuUnderuse();
Evan Shrubsole64469032020-06-11 10:45:29 +02003904 video_stream_encoder_->TriggerQualityHigh();
Åsa Persson8c1bf952018-09-13 10:42:19 +02003905 timestamp_ms += kFrameIntervalMs;
3906 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
3907 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02003908 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionGt(source.last_wants()));
asaperssond0de2952017-04-21 01:47:31 -07003909 last_wants = source.sink_wants();
Evan Shrubsole64469032020-06-11 10:45:29 +02003910 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
asaperssond0de2952017-04-21 01:47:31 -07003911 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
Evan Shrubsole64469032020-06-11 10:45:29 +02003912 EXPECT_EQ(5, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
3913 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_quality_adapt_changes);
asaperssond0de2952017-04-21 01:47:31 -07003914
Evan Shrubsole64469032020-06-11 10:45:29 +02003915 // Trigger cpu adapt up, expect no change since not most limited (960x540).
3916 // However the stats will change since the CPU resource is no longer limited.
Henrik Boström91aa7322020-04-28 12:24:33 +02003917 video_stream_encoder_->TriggerCpuUnderuse();
Åsa Persson8c1bf952018-09-13 10:42:19 +02003918 timestamp_ms += kFrameIntervalMs;
3919 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
3920 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02003921 EXPECT_THAT(source.sink_wants(), FpsEqResolutionEqTo(last_wants));
asaperssond0de2952017-04-21 01:47:31 -07003922 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
3923 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
Jonathan Yubc771b72017-12-08 17:04:29 -08003924 EXPECT_EQ(6, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
Evan Shrubsole64469032020-06-11 10:45:29 +02003925 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_quality_adapt_changes);
asaperssond0de2952017-04-21 01:47:31 -07003926
3927 // Trigger quality adapt up, expect no restriction (1280x720).
mflodmancc3d4422017-08-03 08:27:51 -07003928 video_stream_encoder_->TriggerQualityHigh();
Åsa Persson8c1bf952018-09-13 10:42:19 +02003929 timestamp_ms += kFrameIntervalMs;
3930 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07003931 WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02003932 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionGt(source.last_wants()));
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02003933 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssond0de2952017-04-21 01:47:31 -07003934 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
3935 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
Jonathan Yubc771b72017-12-08 17:04:29 -08003936 EXPECT_EQ(6, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
Evan Shrubsole64469032020-06-11 10:45:29 +02003937 EXPECT_EQ(5, stats_proxy_->GetStats().number_of_quality_adapt_changes);
kthelgason5e13d412016-12-01 03:59:51 -08003938
mflodmancc3d4422017-08-03 08:27:51 -07003939 video_stream_encoder_->Stop();
kthelgason5e13d412016-12-01 03:59:51 -08003940}
3941
mflodmancc3d4422017-08-03 08:27:51 -07003942TEST_F(VideoStreamEncoderTest, CpuLimitedHistogramIsReported) {
asaperssonfab67072017-04-04 05:51:49 -07003943 const int kWidth = 640;
3944 const int kHeight = 360;
perkj803d97f2016-11-01 11:45:46 -07003945
Henrik Boström381d1092020-05-12 18:49:07 +02003946 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01003947 DataRate::BitsPerSec(kTargetBitrateBps),
3948 DataRate::BitsPerSec(kTargetBitrateBps),
3949 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
sprang4847ae62017-06-27 07:06:52 -07003950
perkj803d97f2016-11-01 11:45:46 -07003951 for (int i = 1; i <= SendStatisticsProxy::kMinRequiredMetricsSamples; ++i) {
asaperssonfab67072017-04-04 05:51:49 -07003952 video_source_.IncomingCapturedFrame(CreateFrame(i, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07003953 WaitForEncodedFrame(i);
perkj803d97f2016-11-01 11:45:46 -07003954 }
3955
mflodmancc3d4422017-08-03 08:27:51 -07003956 video_stream_encoder_->TriggerCpuOveruse();
perkj803d97f2016-11-01 11:45:46 -07003957 for (int i = 1; i <= SendStatisticsProxy::kMinRequiredMetricsSamples; ++i) {
asaperssonfab67072017-04-04 05:51:49 -07003958 video_source_.IncomingCapturedFrame(CreateFrame(
3959 SendStatisticsProxy::kMinRequiredMetricsSamples + i, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07003960 WaitForEncodedFrame(SendStatisticsProxy::kMinRequiredMetricsSamples + i);
perkj803d97f2016-11-01 11:45:46 -07003961 }
3962
mflodmancc3d4422017-08-03 08:27:51 -07003963 video_stream_encoder_->Stop();
3964 video_stream_encoder_.reset();
perkj803d97f2016-11-01 11:45:46 -07003965 stats_proxy_.reset();
sprangf8ee65e2017-02-28 08:49:33 -08003966
Ying Wangef3998f2019-12-09 13:06:53 +01003967 EXPECT_METRIC_EQ(
3968 1, metrics::NumSamples("WebRTC.Video.CpuLimitedResolutionInPercent"));
3969 EXPECT_METRIC_EQ(
perkj803d97f2016-11-01 11:45:46 -07003970 1, metrics::NumEvents("WebRTC.Video.CpuLimitedResolutionInPercent", 50));
3971}
3972
mflodmancc3d4422017-08-03 08:27:51 -07003973TEST_F(VideoStreamEncoderTest,
3974 CpuLimitedHistogramIsNotReportedForDisabledDegradation) {
Henrik Boström381d1092020-05-12 18:49:07 +02003975 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01003976 DataRate::BitsPerSec(kTargetBitrateBps),
3977 DataRate::BitsPerSec(kTargetBitrateBps),
3978 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asaperssonf4e44af2017-04-19 02:01:06 -07003979 const int kWidth = 640;
3980 const int kHeight = 360;
3981
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07003982 video_stream_encoder_->SetSource(&video_source_,
3983 webrtc::DegradationPreference::DISABLED);
asaperssonf4e44af2017-04-19 02:01:06 -07003984
3985 for (int i = 1; i <= SendStatisticsProxy::kMinRequiredMetricsSamples; ++i) {
3986 video_source_.IncomingCapturedFrame(CreateFrame(i, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07003987 WaitForEncodedFrame(i);
asaperssonf4e44af2017-04-19 02:01:06 -07003988 }
3989
mflodmancc3d4422017-08-03 08:27:51 -07003990 video_stream_encoder_->Stop();
3991 video_stream_encoder_.reset();
asaperssonf4e44af2017-04-19 02:01:06 -07003992 stats_proxy_.reset();
3993
3994 EXPECT_EQ(0,
3995 metrics::NumSamples("WebRTC.Video.CpuLimitedResolutionInPercent"));
3996}
3997
Per Kjellanderdcef6412020-10-07 15:09:05 +02003998TEST_F(VideoStreamEncoderTest, ReportsVideoBitrateAllocation) {
3999 ResetEncoder("FAKE", 1, 1, 1, /*screenshare*/ false,
4000 VideoStreamEncoderSettings::BitrateAllocationCallbackType::
4001 kVideoBitrateAllocation);
sprang57c2fff2017-01-16 06:24:02 -08004002
4003 const int kDefaultFps = 30;
Erik Språng566124a2018-04-23 12:32:22 +02004004 const VideoBitrateAllocation expected_bitrate =
Mirta Dvornicic6799d732020-02-12 15:36:49 +01004005 SimulcastRateAllocator(fake_encoder_.codec_config())
Florent Castelli8bbdb5b2019-08-02 15:16:28 +02004006 .Allocate(VideoBitrateAllocationParameters(kLowTargetBitrateBps,
4007 kDefaultFps));
sprang57c2fff2017-01-16 06:24:02 -08004008
Henrik Boström381d1092020-05-12 18:49:07 +02004009 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01004010 DataRate::BitsPerSec(kLowTargetBitrateBps),
4011 DataRate::BitsPerSec(kLowTargetBitrateBps),
4012 DataRate::BitsPerSec(kLowTargetBitrateBps), 0, 0, 0);
sprang57c2fff2017-01-16 06:24:02 -08004013
sprang57c2fff2017-01-16 06:24:02 -08004014 video_source_.IncomingCapturedFrame(
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02004015 CreateFrame(CurrentTimeMs(), codec_width_, codec_height_));
4016 WaitForEncodedFrame(CurrentTimeMs());
Per Kjellanderdcef6412020-10-07 15:09:05 +02004017 EXPECT_EQ(sink_.GetLastVideoBitrateAllocation(), expected_bitrate);
4018 EXPECT_EQ(sink_.number_of_bitrate_allocations(), 1);
4019
Erik Språngd7329ca2019-02-21 21:19:53 +01004020 // Check that encoder has been updated too, not just allocation observer.
Erik Språng9d69cbe2020-10-22 17:44:42 +02004021 EXPECT_TRUE(fake_encoder_.GetAndResetLastRateControlSettings().has_value());
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02004022 AdvanceTime(TimeDelta::Seconds(1) / kDefaultFps);
sprang57c2fff2017-01-16 06:24:02 -08004023
Per Kjellanderdcef6412020-10-07 15:09:05 +02004024 // VideoBitrateAllocation not updated on second frame.
sprang57c2fff2017-01-16 06:24:02 -08004025 video_source_.IncomingCapturedFrame(
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02004026 CreateFrame(CurrentTimeMs(), codec_width_, codec_height_));
4027 WaitForEncodedFrame(CurrentTimeMs());
Per Kjellanderdcef6412020-10-07 15:09:05 +02004028 EXPECT_EQ(sink_.number_of_bitrate_allocations(), 1);
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02004029 AdvanceTime(TimeDelta::Millis(1) / kDefaultFps);
sprang57c2fff2017-01-16 06:24:02 -08004030
Per Kjellanderdcef6412020-10-07 15:09:05 +02004031 // VideoBitrateAllocation updated after a process interval.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02004032 const int64_t start_time_ms = CurrentTimeMs();
Per Kjellanderd0a8f512020-10-07 11:28:41 +02004033 while (CurrentTimeMs() - start_time_ms < 5 * kProcessIntervalMs) {
Erik Språngd7329ca2019-02-21 21:19:53 +01004034 video_source_.IncomingCapturedFrame(
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02004035 CreateFrame(CurrentTimeMs(), codec_width_, codec_height_));
4036 WaitForEncodedFrame(CurrentTimeMs());
4037 AdvanceTime(TimeDelta::Millis(1) / kDefaultFps);
Erik Språngd7329ca2019-02-21 21:19:53 +01004038 }
Per Kjellanderdcef6412020-10-07 15:09:05 +02004039 EXPECT_GT(sink_.number_of_bitrate_allocations(), 3);
Erik Språngd7329ca2019-02-21 21:19:53 +01004040
mflodmancc3d4422017-08-03 08:27:51 -07004041 video_stream_encoder_->Stop();
sprang57c2fff2017-01-16 06:24:02 -08004042}
4043
Per Kjellandera9434842020-10-15 17:53:22 +02004044TEST_F(VideoStreamEncoderTest, ReportsVideoLayersAllocationForV8Simulcast) {
4045 ResetEncoder("VP8", /*num_streams*/ 2, 1, 1, /*screenshare*/ false,
4046 VideoStreamEncoderSettings::BitrateAllocationCallbackType::
4047 kVideoLayersAllocation);
4048
4049 const int kDefaultFps = 30;
4050
4051 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
4052 DataRate::BitsPerSec(kLowTargetBitrateBps),
4053 DataRate::BitsPerSec(kLowTargetBitrateBps),
4054 DataRate::BitsPerSec(kLowTargetBitrateBps), 0, 0, 0);
4055
4056 video_source_.IncomingCapturedFrame(
4057 CreateFrame(CurrentTimeMs(), codec_width_, codec_height_));
4058 WaitForEncodedFrame(CurrentTimeMs());
4059 EXPECT_EQ(sink_.number_of_layers_allocations(), 1);
4060 VideoLayersAllocation last_layer_allocation =
4061 sink_.GetLastVideoLayersAllocation();
4062 // kLowTargetBitrateBps is only enough for one spatial layer.
4063 ASSERT_EQ(last_layer_allocation.active_spatial_layers.size(), 1u);
4064
4065 VideoBitrateAllocation bitrate_allocation =
Erik Språng9d69cbe2020-10-22 17:44:42 +02004066 fake_encoder_.GetAndResetLastRateControlSettings()->target_bitrate;
Per Kjellandera9434842020-10-15 17:53:22 +02004067 // Check that encoder has been updated too, not just allocation observer.
4068 EXPECT_EQ(bitrate_allocation.get_sum_bps(), kLowTargetBitrateBps);
4069 AdvanceTime(TimeDelta::Seconds(1) / kDefaultFps);
4070
Erik Språng9d69cbe2020-10-22 17:44:42 +02004071 // VideoLayersAllocation might be updated if frame rate changes.
Per Kjellandera9434842020-10-15 17:53:22 +02004072 int number_of_layers_allocation = 1;
4073 const int64_t start_time_ms = CurrentTimeMs();
4074 while (CurrentTimeMs() - start_time_ms < 10 * kProcessIntervalMs) {
4075 video_source_.IncomingCapturedFrame(
4076 CreateFrame(CurrentTimeMs(), codec_width_, codec_height_));
4077 WaitForEncodedFrame(CurrentTimeMs());
Per Kjellandera9434842020-10-15 17:53:22 +02004078 if (number_of_layers_allocation != sink_.number_of_layers_allocations()) {
4079 number_of_layers_allocation = sink_.number_of_layers_allocations();
4080 VideoLayersAllocation new_allocation =
4081 sink_.GetLastVideoLayersAllocation();
4082 ASSERT_EQ(new_allocation.active_spatial_layers.size(), 1u);
4083 EXPECT_NE(new_allocation.active_spatial_layers[0].frame_rate_fps,
4084 last_layer_allocation.active_spatial_layers[0].frame_rate_fps);
4085 EXPECT_EQ(new_allocation.active_spatial_layers[0]
4086 .target_bitrate_per_temporal_layer,
4087 last_layer_allocation.active_spatial_layers[0]
4088 .target_bitrate_per_temporal_layer);
4089 last_layer_allocation = new_allocation;
4090 }
4091 }
4092 EXPECT_LE(sink_.number_of_layers_allocations(), 3);
4093 video_stream_encoder_->Stop();
4094}
4095
4096TEST_F(VideoStreamEncoderTest,
4097 ReportsUpdatedVideoLayersAllocationWhenBweChanges) {
4098 ResetEncoder("VP8", /*num_streams*/ 2, 1, 1, /*screenshare*/ false,
4099 VideoStreamEncoderSettings::BitrateAllocationCallbackType::
4100 kVideoLayersAllocation);
4101
4102 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
4103 DataRate::BitsPerSec(kLowTargetBitrateBps),
4104 DataRate::BitsPerSec(kLowTargetBitrateBps),
4105 DataRate::BitsPerSec(kLowTargetBitrateBps), 0, 0, 0);
4106
4107 video_source_.IncomingCapturedFrame(
4108 CreateFrame(CurrentTimeMs(), codec_width_, codec_height_));
4109 WaitForEncodedFrame(CurrentTimeMs());
4110 EXPECT_EQ(sink_.number_of_layers_allocations(), 1);
4111 VideoLayersAllocation last_layer_allocation =
4112 sink_.GetLastVideoLayersAllocation();
4113 // kLowTargetBitrateBps is only enough for one spatial layer.
4114 ASSERT_EQ(last_layer_allocation.active_spatial_layers.size(), 1u);
4115 EXPECT_EQ(last_layer_allocation.active_spatial_layers[0]
4116 .target_bitrate_per_temporal_layer[0],
4117 DataRate::BitsPerSec(kLowTargetBitrateBps));
4118
4119 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
4120 DataRate::BitsPerSec(kSimulcastTargetBitrateBps),
4121 DataRate::BitsPerSec(kSimulcastTargetBitrateBps),
4122 DataRate::BitsPerSec(kSimulcastTargetBitrateBps), 0, 0, 0);
4123 video_source_.IncomingCapturedFrame(
4124 CreateFrame(CurrentTimeMs(), codec_width_, codec_height_));
4125 WaitForEncodedFrame(CurrentTimeMs());
4126
4127 EXPECT_EQ(sink_.number_of_layers_allocations(), 2);
4128 last_layer_allocation = sink_.GetLastVideoLayersAllocation();
4129 ASSERT_EQ(last_layer_allocation.active_spatial_layers.size(), 2u);
4130 EXPECT_GT(last_layer_allocation.active_spatial_layers[1]
4131 .target_bitrate_per_temporal_layer[0],
4132 DataRate::Zero());
4133
4134 video_stream_encoder_->Stop();
4135}
4136
Åsa Perssonc29cb2c2019-03-25 12:06:59 +01004137TEST_F(VideoStreamEncoderTest, TemporalLayersNotDisabledIfSupported) {
4138 // 2 TLs configured, temporal layers supported by encoder.
4139 const int kNumTemporalLayers = 2;
Per Kjellanderdcef6412020-10-07 15:09:05 +02004140 ResetEncoder("VP8", 1, kNumTemporalLayers, 1, /*screenshare*/ false,
4141 VideoStreamEncoderSettings::BitrateAllocationCallbackType::
4142 kVideoBitrateAllocation);
Åsa Perssonc29cb2c2019-03-25 12:06:59 +01004143 fake_encoder_.SetTemporalLayersSupported(0, true);
4144
4145 // Bitrate allocated across temporal layers.
4146 const int kTl0Bps = kTargetBitrateBps *
4147 webrtc::SimulcastRateAllocator::GetTemporalRateAllocation(
Rasmus Brandt2b9317a2019-10-30 13:01:46 +01004148 kNumTemporalLayers, /*temporal_id*/ 0,
4149 /*base_heavy_tl3_alloc*/ false);
Åsa Perssonc29cb2c2019-03-25 12:06:59 +01004150 const int kTl1Bps = kTargetBitrateBps *
4151 webrtc::SimulcastRateAllocator::GetTemporalRateAllocation(
Rasmus Brandt2b9317a2019-10-30 13:01:46 +01004152 kNumTemporalLayers, /*temporal_id*/ 1,
4153 /*base_heavy_tl3_alloc*/ false);
Åsa Perssonc29cb2c2019-03-25 12:06:59 +01004154 VideoBitrateAllocation expected_bitrate;
4155 expected_bitrate.SetBitrate(/*si*/ 0, /*ti*/ 0, kTl0Bps);
4156 expected_bitrate.SetBitrate(/*si*/ 0, /*ti*/ 1, kTl1Bps - kTl0Bps);
4157
4158 VerifyAllocatedBitrate(expected_bitrate);
4159 video_stream_encoder_->Stop();
4160}
4161
4162TEST_F(VideoStreamEncoderTest, TemporalLayersDisabledIfNotSupported) {
4163 // 2 TLs configured, temporal layers not supported by encoder.
Per Kjellanderdcef6412020-10-07 15:09:05 +02004164 ResetEncoder("VP8", 1, /*num_temporal_layers*/ 2, 1, /*screenshare*/ false,
4165 VideoStreamEncoderSettings::BitrateAllocationCallbackType::
4166 kVideoBitrateAllocation);
Åsa Perssonc29cb2c2019-03-25 12:06:59 +01004167 fake_encoder_.SetTemporalLayersSupported(0, false);
4168
4169 // Temporal layers not supported by the encoder.
4170 // Total bitrate should be at ti:0.
4171 VideoBitrateAllocation expected_bitrate;
4172 expected_bitrate.SetBitrate(/*si*/ 0, /*ti*/ 0, kTargetBitrateBps);
4173
4174 VerifyAllocatedBitrate(expected_bitrate);
4175 video_stream_encoder_->Stop();
4176}
4177
4178TEST_F(VideoStreamEncoderTest, VerifyBitrateAllocationForTwoStreams) {
Per Kjellanderdcef6412020-10-07 15:09:05 +02004179 webrtc::test::ScopedFieldTrials field_trials(
4180 "WebRTC-Video-QualityScalerSettings/"
4181 "initial_bitrate_interval_ms:1000,initial_bitrate_factor:0.2/");
4182 // Reset encoder for field trials to take effect.
4183 ConfigureEncoder(video_encoder_config_.Copy());
4184
Åsa Perssonc29cb2c2019-03-25 12:06:59 +01004185 // 2 TLs configured, temporal layers only supported for first stream.
Per Kjellanderdcef6412020-10-07 15:09:05 +02004186 ResetEncoder("VP8", 2, /*num_temporal_layers*/ 2, 1, /*screenshare*/ false,
4187 VideoStreamEncoderSettings::BitrateAllocationCallbackType::
4188 kVideoBitrateAllocation);
Åsa Perssonc29cb2c2019-03-25 12:06:59 +01004189 fake_encoder_.SetTemporalLayersSupported(0, true);
4190 fake_encoder_.SetTemporalLayersSupported(1, false);
4191
4192 const int kS0Bps = 150000;
4193 const int kS0Tl0Bps =
Rasmus Brandt2b9317a2019-10-30 13:01:46 +01004194 kS0Bps *
4195 webrtc::SimulcastRateAllocator::GetTemporalRateAllocation(
4196 /*num_layers*/ 2, /*temporal_id*/ 0, /*base_heavy_tl3_alloc*/ false);
Åsa Perssonc29cb2c2019-03-25 12:06:59 +01004197 const int kS0Tl1Bps =
Rasmus Brandt2b9317a2019-10-30 13:01:46 +01004198 kS0Bps *
4199 webrtc::SimulcastRateAllocator::GetTemporalRateAllocation(
4200 /*num_layers*/ 2, /*temporal_id*/ 1, /*base_heavy_tl3_alloc*/ false);
Åsa Perssonc29cb2c2019-03-25 12:06:59 +01004201 const int kS1Bps = kTargetBitrateBps - kS0Tl1Bps;
4202 // Temporal layers not supported by si:1.
4203 VideoBitrateAllocation expected_bitrate;
4204 expected_bitrate.SetBitrate(/*si*/ 0, /*ti*/ 0, kS0Tl0Bps);
4205 expected_bitrate.SetBitrate(/*si*/ 0, /*ti*/ 1, kS0Tl1Bps - kS0Tl0Bps);
4206 expected_bitrate.SetBitrate(/*si*/ 1, /*ti*/ 0, kS1Bps);
4207
4208 VerifyAllocatedBitrate(expected_bitrate);
4209 video_stream_encoder_->Stop();
4210}
4211
Niels Möller7dc26b72017-12-06 10:27:48 +01004212TEST_F(VideoStreamEncoderTest, OveruseDetectorUpdatedOnReconfigureAndAdaption) {
4213 const int kFrameWidth = 1280;
4214 const int kFrameHeight = 720;
4215 const int kFramerate = 24;
4216
Henrik Boström381d1092020-05-12 18:49:07 +02004217 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01004218 DataRate::BitsPerSec(kTargetBitrateBps),
4219 DataRate::BitsPerSec(kTargetBitrateBps),
4220 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Niels Möller7dc26b72017-12-06 10:27:48 +01004221 test::FrameForwarder source;
4222 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07004223 &source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
Niels Möller7dc26b72017-12-06 10:27:48 +01004224
4225 // Insert a single frame, triggering initial configuration.
4226 source.IncomingCapturedFrame(CreateFrame(1, kFrameWidth, kFrameHeight));
4227 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
4228
4229 EXPECT_EQ(
4230 video_stream_encoder_->overuse_detector_proxy_->GetLastTargetFramerate(),
4231 kDefaultFramerate);
4232
4233 // Trigger reconfigure encoder (without resetting the entire instance).
4234 VideoEncoderConfig video_encoder_config;
Åsa Persson17107062020-10-08 08:57:51 +02004235 test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
4236 video_encoder_config.simulcast_layers[0].max_framerate = kFramerate;
Niels Möller7dc26b72017-12-06 10:27:48 +01004237 video_encoder_config.max_bitrate_bps = kTargetBitrateBps;
Niels Möller7dc26b72017-12-06 10:27:48 +01004238 video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config),
Niels Möllerf1338562018-04-26 09:51:47 +02004239 kMaxPayloadLength);
Niels Möller7dc26b72017-12-06 10:27:48 +01004240 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
4241
4242 // Detector should be updated with fps limit from codec config.
4243 EXPECT_EQ(
4244 video_stream_encoder_->overuse_detector_proxy_->GetLastTargetFramerate(),
4245 kFramerate);
4246
4247 // Trigger overuse, max framerate should be reduced.
4248 VideoSendStream::Stats stats = stats_proxy_->GetStats();
4249 stats.input_frame_rate = kFramerate;
4250 stats_proxy_->SetMockStats(stats);
4251 video_stream_encoder_->TriggerCpuOveruse();
4252 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
4253 int adapted_framerate =
4254 video_stream_encoder_->overuse_detector_proxy_->GetLastTargetFramerate();
4255 EXPECT_LT(adapted_framerate, kFramerate);
4256
4257 // Trigger underuse, max framerate should go back to codec configured fps.
4258 // Set extra low fps, to make sure it's actually reset, not just incremented.
4259 stats = stats_proxy_->GetStats();
4260 stats.input_frame_rate = adapted_framerate / 2;
4261 stats_proxy_->SetMockStats(stats);
Henrik Boström91aa7322020-04-28 12:24:33 +02004262 video_stream_encoder_->TriggerCpuUnderuse();
Niels Möller7dc26b72017-12-06 10:27:48 +01004263 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
4264 EXPECT_EQ(
4265 video_stream_encoder_->overuse_detector_proxy_->GetLastTargetFramerate(),
4266 kFramerate);
4267
4268 video_stream_encoder_->Stop();
4269}
4270
4271TEST_F(VideoStreamEncoderTest,
4272 OveruseDetectorUpdatedRespectsFramerateAfterUnderuse) {
4273 const int kFrameWidth = 1280;
4274 const int kFrameHeight = 720;
4275 const int kLowFramerate = 15;
4276 const int kHighFramerate = 25;
4277
Henrik Boström381d1092020-05-12 18:49:07 +02004278 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01004279 DataRate::BitsPerSec(kTargetBitrateBps),
4280 DataRate::BitsPerSec(kTargetBitrateBps),
4281 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Niels Möller7dc26b72017-12-06 10:27:48 +01004282 test::FrameForwarder source;
4283 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07004284 &source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
Niels Möller7dc26b72017-12-06 10:27:48 +01004285
4286 // Trigger initial configuration.
4287 VideoEncoderConfig video_encoder_config;
Åsa Persson17107062020-10-08 08:57:51 +02004288 test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
4289 video_encoder_config.simulcast_layers[0].max_framerate = kLowFramerate;
Niels Möller7dc26b72017-12-06 10:27:48 +01004290 video_encoder_config.max_bitrate_bps = kTargetBitrateBps;
Niels Möller7dc26b72017-12-06 10:27:48 +01004291 source.IncomingCapturedFrame(CreateFrame(1, kFrameWidth, kFrameHeight));
Åsa Persson17107062020-10-08 08:57:51 +02004292 video_stream_encoder_->ConfigureEncoder(video_encoder_config.Copy(),
Niels Möllerf1338562018-04-26 09:51:47 +02004293 kMaxPayloadLength);
Niels Möller7dc26b72017-12-06 10:27:48 +01004294 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
4295
4296 EXPECT_EQ(
4297 video_stream_encoder_->overuse_detector_proxy_->GetLastTargetFramerate(),
4298 kLowFramerate);
4299
4300 // Trigger overuse, max framerate should be reduced.
4301 VideoSendStream::Stats stats = stats_proxy_->GetStats();
4302 stats.input_frame_rate = kLowFramerate;
4303 stats_proxy_->SetMockStats(stats);
4304 video_stream_encoder_->TriggerCpuOveruse();
4305 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
4306 int adapted_framerate =
4307 video_stream_encoder_->overuse_detector_proxy_->GetLastTargetFramerate();
4308 EXPECT_LT(adapted_framerate, kLowFramerate);
4309
4310 // Reconfigure the encoder with a new (higher max framerate), max fps should
4311 // still respect the adaptation.
Åsa Persson17107062020-10-08 08:57:51 +02004312 video_encoder_config.simulcast_layers[0].max_framerate = kHighFramerate;
Niels Möller7dc26b72017-12-06 10:27:48 +01004313 source.IncomingCapturedFrame(CreateFrame(1, kFrameWidth, kFrameHeight));
4314 video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config),
Niels Möllerf1338562018-04-26 09:51:47 +02004315 kMaxPayloadLength);
Niels Möller7dc26b72017-12-06 10:27:48 +01004316 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
4317
4318 EXPECT_EQ(
4319 video_stream_encoder_->overuse_detector_proxy_->GetLastTargetFramerate(),
4320 adapted_framerate);
4321
4322 // Trigger underuse, max framerate should go back to codec configured fps.
4323 stats = stats_proxy_->GetStats();
4324 stats.input_frame_rate = adapted_framerate;
4325 stats_proxy_->SetMockStats(stats);
Henrik Boström91aa7322020-04-28 12:24:33 +02004326 video_stream_encoder_->TriggerCpuUnderuse();
Niels Möller7dc26b72017-12-06 10:27:48 +01004327 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
4328 EXPECT_EQ(
4329 video_stream_encoder_->overuse_detector_proxy_->GetLastTargetFramerate(),
4330 kHighFramerate);
4331
4332 video_stream_encoder_->Stop();
4333}
4334
mflodmancc3d4422017-08-03 08:27:51 -07004335TEST_F(VideoStreamEncoderTest,
4336 OveruseDetectorUpdatedOnDegradationPreferenceChange) {
sprangfda496a2017-06-15 04:21:07 -07004337 const int kFrameWidth = 1280;
4338 const int kFrameHeight = 720;
4339 const int kFramerate = 24;
4340
Henrik Boström381d1092020-05-12 18:49:07 +02004341 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01004342 DataRate::BitsPerSec(kTargetBitrateBps),
4343 DataRate::BitsPerSec(kTargetBitrateBps),
4344 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
sprangfda496a2017-06-15 04:21:07 -07004345 test::FrameForwarder source;
mflodmancc3d4422017-08-03 08:27:51 -07004346 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07004347 &source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
sprangfda496a2017-06-15 04:21:07 -07004348
4349 // Trigger initial configuration.
4350 VideoEncoderConfig video_encoder_config;
Åsa Persson17107062020-10-08 08:57:51 +02004351 test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
4352 video_encoder_config.simulcast_layers[0].max_framerate = kFramerate;
sprangfda496a2017-06-15 04:21:07 -07004353 video_encoder_config.max_bitrate_bps = kTargetBitrateBps;
sprangfda496a2017-06-15 04:21:07 -07004354 source.IncomingCapturedFrame(CreateFrame(1, kFrameWidth, kFrameHeight));
mflodmancc3d4422017-08-03 08:27:51 -07004355 video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config),
Niels Möllerf1338562018-04-26 09:51:47 +02004356 kMaxPayloadLength);
mflodmancc3d4422017-08-03 08:27:51 -07004357 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
sprangfda496a2017-06-15 04:21:07 -07004358
Niels Möller7dc26b72017-12-06 10:27:48 +01004359 EXPECT_EQ(
4360 video_stream_encoder_->overuse_detector_proxy_->GetLastTargetFramerate(),
4361 kFramerate);
sprangfda496a2017-06-15 04:21:07 -07004362
4363 // Trigger overuse, max framerate should be reduced.
4364 VideoSendStream::Stats stats = stats_proxy_->GetStats();
4365 stats.input_frame_rate = kFramerate;
4366 stats_proxy_->SetMockStats(stats);
mflodmancc3d4422017-08-03 08:27:51 -07004367 video_stream_encoder_->TriggerCpuOveruse();
4368 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
Niels Möller7dc26b72017-12-06 10:27:48 +01004369 int adapted_framerate =
4370 video_stream_encoder_->overuse_detector_proxy_->GetLastTargetFramerate();
sprangfda496a2017-06-15 04:21:07 -07004371 EXPECT_LT(adapted_framerate, kFramerate);
4372
4373 // Change degradation preference to not enable framerate scaling. Target
4374 // framerate should be changed to codec defined limit.
Henrik Boström381d1092020-05-12 18:49:07 +02004375 video_stream_encoder_->SetSourceAndWaitForFramerateUpdated(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07004376 &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
Niels Möller7dc26b72017-12-06 10:27:48 +01004377 EXPECT_EQ(
4378 video_stream_encoder_->overuse_detector_proxy_->GetLastTargetFramerate(),
4379 kFramerate);
sprangfda496a2017-06-15 04:21:07 -07004380
mflodmancc3d4422017-08-03 08:27:51 -07004381 video_stream_encoder_->Stop();
sprangfda496a2017-06-15 04:21:07 -07004382}
4383
mflodmancc3d4422017-08-03 08:27:51 -07004384TEST_F(VideoStreamEncoderTest, DropsFramesAndScalesWhenBitrateIsTooLow) {
asaperssonfab67072017-04-04 05:51:49 -07004385 const int kTooLowBitrateForFrameSizeBps = 10000;
Henrik Boström381d1092020-05-12 18:49:07 +02004386 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01004387 DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps),
4388 DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps),
4389 DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps), 0, 0, 0);
asaperssonfab67072017-04-04 05:51:49 -07004390 const int kWidth = 640;
4391 const int kHeight = 360;
kthelgason2bc68642017-02-07 07:02:22 -08004392
asaperssonfab67072017-04-04 05:51:49 -07004393 video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
kthelgason2bc68642017-02-07 07:02:22 -08004394
4395 // Expect to drop this frame, the wait should time out.
sprang4847ae62017-06-27 07:06:52 -07004396 ExpectDroppedFrame();
kthelgason2bc68642017-02-07 07:02:22 -08004397
4398 // Expect the sink_wants to specify a scaled frame.
Henrik Boström2671dac2020-05-19 16:29:09 +02004399 EXPECT_TRUE_WAIT(
4400 video_source_.sink_wants().max_pixel_count < kWidth * kHeight, 5000);
kthelgason2bc68642017-02-07 07:02:22 -08004401
sprangc5d62e22017-04-02 23:53:04 -07004402 int last_pixel_count = video_source_.sink_wants().max_pixel_count;
kthelgason2bc68642017-02-07 07:02:22 -08004403
asaperssonfab67072017-04-04 05:51:49 -07004404 // Next frame is scaled.
kthelgason2bc68642017-02-07 07:02:22 -08004405 video_source_.IncomingCapturedFrame(
asaperssonfab67072017-04-04 05:51:49 -07004406 CreateFrame(2, kWidth * 3 / 4, kHeight * 3 / 4));
kthelgason2bc68642017-02-07 07:02:22 -08004407
4408 // Expect to drop this frame, the wait should time out.
sprang4847ae62017-06-27 07:06:52 -07004409 ExpectDroppedFrame();
kthelgason2bc68642017-02-07 07:02:22 -08004410
Henrik Boström2671dac2020-05-19 16:29:09 +02004411 EXPECT_TRUE_WAIT(
4412 video_source_.sink_wants().max_pixel_count < last_pixel_count, 5000);
kthelgason2bc68642017-02-07 07:02:22 -08004413
mflodmancc3d4422017-08-03 08:27:51 -07004414 video_stream_encoder_->Stop();
kthelgason2bc68642017-02-07 07:02:22 -08004415}
4416
mflodmancc3d4422017-08-03 08:27:51 -07004417TEST_F(VideoStreamEncoderTest,
4418 NumberOfDroppedFramesLimitedWhenBitrateIsTooLow) {
asaperssonfab67072017-04-04 05:51:49 -07004419 const int kTooLowBitrateForFrameSizeBps = 10000;
Henrik Boström381d1092020-05-12 18:49:07 +02004420 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01004421 DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps),
4422 DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps),
4423 DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps), 0, 0, 0);
asaperssonfab67072017-04-04 05:51:49 -07004424 const int kWidth = 640;
4425 const int kHeight = 360;
kthelgason2bc68642017-02-07 07:02:22 -08004426
4427 // We expect the n initial frames to get dropped.
4428 int i;
4429 for (i = 1; i <= kMaxInitialFramedrop; ++i) {
asaperssonfab67072017-04-04 05:51:49 -07004430 video_source_.IncomingCapturedFrame(CreateFrame(i, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07004431 ExpectDroppedFrame();
kthelgason2bc68642017-02-07 07:02:22 -08004432 }
4433 // The n+1th frame should not be dropped, even though it's size is too large.
asaperssonfab67072017-04-04 05:51:49 -07004434 video_source_.IncomingCapturedFrame(CreateFrame(i, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07004435 WaitForEncodedFrame(i);
kthelgason2bc68642017-02-07 07:02:22 -08004436
4437 // Expect the sink_wants to specify a scaled frame.
asaperssonfab67072017-04-04 05:51:49 -07004438 EXPECT_LT(video_source_.sink_wants().max_pixel_count, kWidth * kHeight);
kthelgason2bc68642017-02-07 07:02:22 -08004439
mflodmancc3d4422017-08-03 08:27:51 -07004440 video_stream_encoder_->Stop();
kthelgason2bc68642017-02-07 07:02:22 -08004441}
4442
mflodmancc3d4422017-08-03 08:27:51 -07004443TEST_F(VideoStreamEncoderTest,
4444 InitialFrameDropOffWithMaintainResolutionPreference) {
asaperssonfab67072017-04-04 05:51:49 -07004445 const int kWidth = 640;
4446 const int kHeight = 360;
Henrik Boström381d1092020-05-12 18:49:07 +02004447 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01004448 DataRate::BitsPerSec(kLowTargetBitrateBps),
4449 DataRate::BitsPerSec(kLowTargetBitrateBps),
4450 DataRate::BitsPerSec(kLowTargetBitrateBps), 0, 0, 0);
kthelgason2bc68642017-02-07 07:02:22 -08004451
4452 // Set degradation preference.
mflodmancc3d4422017-08-03 08:27:51 -07004453 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07004454 &video_source_, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
kthelgason2bc68642017-02-07 07:02:22 -08004455
asaperssonfab67072017-04-04 05:51:49 -07004456 video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
kthelgason2bc68642017-02-07 07:02:22 -08004457 // Frame should not be dropped, even if it's too large.
sprang4847ae62017-06-27 07:06:52 -07004458 WaitForEncodedFrame(1);
kthelgason2bc68642017-02-07 07:02:22 -08004459
mflodmancc3d4422017-08-03 08:27:51 -07004460 video_stream_encoder_->Stop();
kthelgason2bc68642017-02-07 07:02:22 -08004461}
4462
mflodmancc3d4422017-08-03 08:27:51 -07004463TEST_F(VideoStreamEncoderTest, InitialFrameDropOffWhenEncoderDisabledScaling) {
asaperssonfab67072017-04-04 05:51:49 -07004464 const int kWidth = 640;
4465 const int kHeight = 360;
kthelgasonad9010c2017-02-14 00:46:51 -08004466 fake_encoder_.SetQualityScaling(false);
Niels Möller4db138e2018-04-19 09:04:13 +02004467
4468 VideoEncoderConfig video_encoder_config;
4469 test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
4470 // Make format different, to force recreation of encoder.
4471 video_encoder_config.video_format.parameters["foo"] = "foo";
4472 video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config),
Niels Möllerf1338562018-04-26 09:51:47 +02004473 kMaxPayloadLength);
Henrik Boström381d1092020-05-12 18:49:07 +02004474 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01004475 DataRate::BitsPerSec(kLowTargetBitrateBps),
4476 DataRate::BitsPerSec(kLowTargetBitrateBps),
4477 DataRate::BitsPerSec(kLowTargetBitrateBps), 0, 0, 0);
asapersson09f05612017-05-15 23:40:18 -07004478
kthelgasonb83797b2017-02-14 11:57:25 -08004479 // Force quality scaler reconfiguration by resetting the source.
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07004480 video_stream_encoder_->SetSource(&video_source_,
4481 webrtc::DegradationPreference::BALANCED);
kthelgasonad9010c2017-02-14 00:46:51 -08004482
asaperssonfab67072017-04-04 05:51:49 -07004483 video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
kthelgasonad9010c2017-02-14 00:46:51 -08004484 // Frame should not be dropped, even if it's too large.
sprang4847ae62017-06-27 07:06:52 -07004485 WaitForEncodedFrame(1);
kthelgasonad9010c2017-02-14 00:46:51 -08004486
mflodmancc3d4422017-08-03 08:27:51 -07004487 video_stream_encoder_->Stop();
kthelgasonad9010c2017-02-14 00:46:51 -08004488 fake_encoder_.SetQualityScaling(true);
4489}
4490
Åsa Persson139f4dc2019-08-02 09:29:58 +02004491TEST_F(VideoStreamEncoderTest, InitialFrameDropActivatesWhenBweDrops) {
4492 webrtc::test::ScopedFieldTrials field_trials(
4493 "WebRTC-Video-QualityScalerSettings/"
4494 "initial_bitrate_interval_ms:1000,initial_bitrate_factor:0.2/");
4495 // Reset encoder for field trials to take effect.
4496 ConfigureEncoder(video_encoder_config_.Copy());
4497 const int kNotTooLowBitrateForFrameSizeBps = kTargetBitrateBps * 0.2;
4498 const int kTooLowBitrateForFrameSizeBps = kTargetBitrateBps * 0.19;
4499 const int kWidth = 640;
4500 const int kHeight = 360;
4501
Henrik Boström381d1092020-05-12 18:49:07 +02004502 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01004503 DataRate::BitsPerSec(kTargetBitrateBps),
4504 DataRate::BitsPerSec(kTargetBitrateBps),
4505 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Åsa Persson139f4dc2019-08-02 09:29:58 +02004506 video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
4507 // Frame should not be dropped.
4508 WaitForEncodedFrame(1);
4509
Henrik Boström381d1092020-05-12 18:49:07 +02004510 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01004511 DataRate::BitsPerSec(kNotTooLowBitrateForFrameSizeBps),
4512 DataRate::BitsPerSec(kNotTooLowBitrateForFrameSizeBps),
4513 DataRate::BitsPerSec(kNotTooLowBitrateForFrameSizeBps), 0, 0, 0);
Åsa Persson139f4dc2019-08-02 09:29:58 +02004514 video_source_.IncomingCapturedFrame(CreateFrame(2, kWidth, kHeight));
4515 // Frame should not be dropped.
4516 WaitForEncodedFrame(2);
4517
Henrik Boström381d1092020-05-12 18:49:07 +02004518 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01004519 DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps),
4520 DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps),
4521 DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps), 0, 0, 0);
Åsa Persson139f4dc2019-08-02 09:29:58 +02004522 video_source_.IncomingCapturedFrame(CreateFrame(3, kWidth, kHeight));
4523 // Expect to drop this frame, the wait should time out.
4524 ExpectDroppedFrame();
4525
4526 // Expect the sink_wants to specify a scaled frame.
Henrik Boström2671dac2020-05-19 16:29:09 +02004527 EXPECT_TRUE_WAIT(
4528 video_source_.sink_wants().max_pixel_count < kWidth * kHeight, 5000);
Åsa Persson139f4dc2019-08-02 09:29:58 +02004529 video_stream_encoder_->Stop();
4530}
4531
Evan Shrubsolee3da1d32020-08-14 15:58:33 +02004532TEST_F(VideoStreamEncoderTest,
4533 InitialFrameDropNotReactivatedWhenBweDropsWhenScalingDisabled) {
4534 webrtc::test::ScopedFieldTrials field_trials(
4535 "WebRTC-Video-QualityScalerSettings/"
4536 "initial_bitrate_interval_ms:1000,initial_bitrate_factor:0.2/");
4537 fake_encoder_.SetQualityScaling(false);
4538 ConfigureEncoder(video_encoder_config_.Copy());
4539 const int kNotTooLowBitrateForFrameSizeBps = kTargetBitrateBps * 0.2;
4540 const int kTooLowBitrateForFrameSizeBps = kTargetBitrateBps * 0.19;
4541 const int kWidth = 640;
4542 const int kHeight = 360;
4543
4544 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
4545 DataRate::BitsPerSec(kTargetBitrateBps),
4546 DataRate::BitsPerSec(kTargetBitrateBps),
4547 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
4548 video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
4549 // Frame should not be dropped.
4550 WaitForEncodedFrame(1);
4551
4552 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
4553 DataRate::BitsPerSec(kNotTooLowBitrateForFrameSizeBps),
4554 DataRate::BitsPerSec(kNotTooLowBitrateForFrameSizeBps),
4555 DataRate::BitsPerSec(kNotTooLowBitrateForFrameSizeBps), 0, 0, 0);
4556 video_source_.IncomingCapturedFrame(CreateFrame(2, kWidth, kHeight));
4557 // Frame should not be dropped.
4558 WaitForEncodedFrame(2);
4559
4560 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
4561 DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps),
4562 DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps),
4563 DataRate::BitsPerSec(kTooLowBitrateForFrameSizeBps), 0, 0, 0);
4564 video_source_.IncomingCapturedFrame(CreateFrame(3, kWidth, kHeight));
4565 // Not dropped since quality scaling is disabled.
4566 WaitForEncodedFrame(3);
4567
4568 // Expect the sink_wants to specify a scaled frame.
Evan Shrubsole85728412020-08-25 13:12:12 +02004569 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
Evan Shrubsolee3da1d32020-08-14 15:58:33 +02004570 EXPECT_THAT(video_source_.sink_wants(), ResolutionMax());
4571
4572 video_stream_encoder_->Stop();
4573}
4574
Åsa Perssone644a032019-11-08 15:56:00 +01004575TEST_F(VideoStreamEncoderTest, RampsUpInQualityWhenBwIsHigh) {
4576 webrtc::test::ScopedFieldTrials field_trials(
4577 "WebRTC-Video-QualityRampupSettings/min_pixels:1,min_duration_ms:2000/");
4578
4579 // Reset encoder for field trials to take effect.
4580 VideoEncoderConfig config = video_encoder_config_.Copy();
4581 config.max_bitrate_bps = kTargetBitrateBps;
Evan Shrubsoledff79252020-04-16 11:34:32 +02004582 DataRate max_bitrate = DataRate::BitsPerSec(config.max_bitrate_bps);
Åsa Perssone644a032019-11-08 15:56:00 +01004583 ConfigureEncoder(std::move(config));
4584 fake_encoder_.SetQp(kQpLow);
4585
4586 // Enable MAINTAIN_FRAMERATE preference.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02004587 AdaptingFrameForwarder source(&time_controller_);
Åsa Perssone644a032019-11-08 15:56:00 +01004588 source.set_adaptation_enabled(true);
4589 video_stream_encoder_->SetSource(&source,
4590 DegradationPreference::MAINTAIN_FRAMERATE);
4591
4592 // Start at low bitrate.
4593 const int kLowBitrateBps = 200000;
Henrik Boström381d1092020-05-12 18:49:07 +02004594 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
4595 DataRate::BitsPerSec(kLowBitrateBps),
4596 DataRate::BitsPerSec(kLowBitrateBps),
4597 DataRate::BitsPerSec(kLowBitrateBps), 0, 0, 0);
Åsa Perssone644a032019-11-08 15:56:00 +01004598
4599 // Expect first frame to be dropped and resolution to be limited.
4600 const int kWidth = 1280;
4601 const int kHeight = 720;
4602 const int64_t kFrameIntervalMs = 100;
4603 int64_t timestamp_ms = kFrameIntervalMs;
4604 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
4605 ExpectDroppedFrame();
Henrik Boström2671dac2020-05-19 16:29:09 +02004606 EXPECT_TRUE_WAIT(source.sink_wants().max_pixel_count < kWidth * kHeight,
4607 5000);
Åsa Perssone644a032019-11-08 15:56:00 +01004608
4609 // Increase bitrate to encoder max.
Henrik Boström381d1092020-05-12 18:49:07 +02004610 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
4611 max_bitrate, max_bitrate, max_bitrate, 0, 0, 0);
Åsa Perssone644a032019-11-08 15:56:00 +01004612
4613 // Insert frames and advance |min_duration_ms|.
4614 for (size_t i = 1; i <= 10; i++) {
4615 timestamp_ms += kFrameIntervalMs;
4616 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
4617 WaitForEncodedFrame(timestamp_ms);
4618 }
4619 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
4620 EXPECT_LT(source.sink_wants().max_pixel_count, kWidth * kHeight);
4621
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02004622 AdvanceTime(TimeDelta::Millis(2000));
Åsa Perssone644a032019-11-08 15:56:00 +01004623
4624 // Insert frame should trigger high BW and release quality limitation.
4625 timestamp_ms += kFrameIntervalMs;
4626 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
4627 WaitForEncodedFrame(timestamp_ms);
Henrik Boström381d1092020-05-12 18:49:07 +02004628 // The ramp-up code involves the adaptation queue, give it time to execute.
4629 // TODO(hbos): Can we await an appropriate event instead?
Evan Shrubsole85728412020-08-25 13:12:12 +02004630 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02004631 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
Åsa Perssone644a032019-11-08 15:56:00 +01004632
4633 // Frame should not be adapted.
4634 timestamp_ms += kFrameIntervalMs;
4635 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
4636 WaitForEncodedFrame(kWidth, kHeight);
4637 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
4638
4639 video_stream_encoder_->Stop();
4640}
4641
mflodmancc3d4422017-08-03 08:27:51 -07004642TEST_F(VideoStreamEncoderTest,
Evan Shrubsole99b0f8d2020-08-25 13:12:28 +02004643 QualityScalerAdaptationsRemovedWhenQualityScalingDisabled) {
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02004644 AdaptingFrameForwarder source(&time_controller_);
Evan Shrubsole99b0f8d2020-08-25 13:12:28 +02004645 source.set_adaptation_enabled(true);
4646 video_stream_encoder_->SetSource(&source,
4647 DegradationPreference::MAINTAIN_FRAMERATE);
4648 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
4649 DataRate::BitsPerSec(kTargetBitrateBps),
4650 DataRate::BitsPerSec(kTargetBitrateBps),
4651 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
4652 fake_encoder_.SetQp(kQpHigh + 1);
4653 const int kWidth = 1280;
4654 const int kHeight = 720;
4655 const int64_t kFrameIntervalMs = 100;
4656 int64_t timestamp_ms = kFrameIntervalMs;
4657 for (size_t i = 1; i <= 100; i++) {
4658 timestamp_ms += kFrameIntervalMs;
4659 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
4660 WaitForEncodedFrame(timestamp_ms);
4661 }
4662 // Wait for QualityScaler, which will wait for 2000*2.5 ms until checking QP
4663 // for the first time.
4664 // TODO(eshr): We should avoid these waits by using threads with simulated
4665 // time.
4666 EXPECT_TRUE_WAIT(stats_proxy_->GetStats().bw_limited_resolution,
4667 2000 * 2.5 * 2);
4668 timestamp_ms += kFrameIntervalMs;
4669 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
4670 WaitForEncodedFrame(timestamp_ms);
4671 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
4672 EXPECT_THAT(source.sink_wants(), WantsMaxPixels(Lt(kWidth * kHeight)));
4673 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
4674
4675 // Disable Quality scaling by turning off scaler on the encoder and
4676 // reconfiguring.
4677 fake_encoder_.SetQualityScaling(false);
4678 video_stream_encoder_->ConfigureEncoder(video_encoder_config_.Copy(),
4679 kMaxPayloadLength);
4680 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02004681 AdvanceTime(TimeDelta::Millis(0));
Evan Shrubsole99b0f8d2020-08-25 13:12:28 +02004682 // Since we turned off the quality scaler, the adaptations made by it are
4683 // removed.
4684 EXPECT_THAT(source.sink_wants(), ResolutionMax());
4685 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
4686
4687 video_stream_encoder_->Stop();
4688}
4689
4690TEST_F(VideoStreamEncoderTest,
asaperssond0de2952017-04-21 01:47:31 -07004691 ResolutionNotAdaptedForTooSmallFrame_MaintainFramerateMode) {
4692 const int kTooSmallWidth = 10;
4693 const int kTooSmallHeight = 10;
Henrik Boström381d1092020-05-12 18:49:07 +02004694 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01004695 DataRate::BitsPerSec(kTargetBitrateBps),
4696 DataRate::BitsPerSec(kTargetBitrateBps),
4697 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asaperssond0de2952017-04-21 01:47:31 -07004698
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07004699 // Enable MAINTAIN_FRAMERATE preference, no initial limitation.
asaperssond0de2952017-04-21 01:47:31 -07004700 test::FrameForwarder source;
mflodmancc3d4422017-08-03 08:27:51 -07004701 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07004702 &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02004703 EXPECT_THAT(source.sink_wants(), UnlimitedSinkWants());
asaperssond0de2952017-04-21 01:47:31 -07004704 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
4705
4706 // Trigger adapt down, too small frame, expect no change.
4707 source.IncomingCapturedFrame(CreateFrame(1, kTooSmallWidth, kTooSmallHeight));
sprang4847ae62017-06-27 07:06:52 -07004708 WaitForEncodedFrame(1);
mflodmancc3d4422017-08-03 08:27:51 -07004709 video_stream_encoder_->TriggerCpuOveruse();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02004710 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssond0de2952017-04-21 01:47:31 -07004711 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
4712 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
4713
mflodmancc3d4422017-08-03 08:27:51 -07004714 video_stream_encoder_->Stop();
asaperssond0de2952017-04-21 01:47:31 -07004715}
4716
mflodmancc3d4422017-08-03 08:27:51 -07004717TEST_F(VideoStreamEncoderTest,
4718 ResolutionNotAdaptedForTooSmallFrame_BalancedMode) {
asaperssonf7e294d2017-06-13 23:25:22 -07004719 const int kTooSmallWidth = 10;
4720 const int kTooSmallHeight = 10;
4721 const int kFpsLimit = 7;
Henrik Boström381d1092020-05-12 18:49:07 +02004722 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01004723 DataRate::BitsPerSec(kTargetBitrateBps),
4724 DataRate::BitsPerSec(kTargetBitrateBps),
4725 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asaperssonf7e294d2017-06-13 23:25:22 -07004726
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07004727 // Enable BALANCED preference, no initial limitation.
asaperssonf7e294d2017-06-13 23:25:22 -07004728 test::FrameForwarder source;
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07004729 video_stream_encoder_->SetSource(&source,
4730 webrtc::DegradationPreference::BALANCED);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02004731 EXPECT_THAT(source.sink_wants(), UnlimitedSinkWants());
asaperssonf7e294d2017-06-13 23:25:22 -07004732 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
4733 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
4734
4735 // Trigger adapt down, expect limited framerate.
4736 source.IncomingCapturedFrame(CreateFrame(1, kTooSmallWidth, kTooSmallHeight));
sprang4847ae62017-06-27 07:06:52 -07004737 WaitForEncodedFrame(1);
mflodmancc3d4422017-08-03 08:27:51 -07004738 video_stream_encoder_->TriggerQualityLow();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02004739 EXPECT_THAT(source.sink_wants(), FpsMatchesResolutionMax(Eq(kFpsLimit)));
asaperssonf7e294d2017-06-13 23:25:22 -07004740 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
4741 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
4742 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
4743
4744 // Trigger adapt down, too small frame, expect no change.
4745 source.IncomingCapturedFrame(CreateFrame(2, kTooSmallWidth, kTooSmallHeight));
sprang4847ae62017-06-27 07:06:52 -07004746 WaitForEncodedFrame(2);
mflodmancc3d4422017-08-03 08:27:51 -07004747 video_stream_encoder_->TriggerQualityLow();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02004748 EXPECT_THAT(source.sink_wants(), FpsMatchesResolutionMax(Eq(kFpsLimit)));
asaperssonf7e294d2017-06-13 23:25:22 -07004749 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
4750 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
4751 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
4752
mflodmancc3d4422017-08-03 08:27:51 -07004753 video_stream_encoder_->Stop();
asaperssonf7e294d2017-06-13 23:25:22 -07004754}
4755
mflodmancc3d4422017-08-03 08:27:51 -07004756TEST_F(VideoStreamEncoderTest, FailingInitEncodeDoesntCauseCrash) {
asapersson02465b82017-04-10 01:12:52 -07004757 fake_encoder_.ForceInitEncodeFailure(true);
Henrik Boström381d1092020-05-12 18:49:07 +02004758 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01004759 DataRate::BitsPerSec(kTargetBitrateBps),
4760 DataRate::BitsPerSec(kTargetBitrateBps),
4761 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Niels Möllerf1338562018-04-26 09:51:47 +02004762 ResetEncoder("VP8", 2, 1, 1, false);
asapersson02465b82017-04-10 01:12:52 -07004763 const int kFrameWidth = 1280;
4764 const int kFrameHeight = 720;
4765 video_source_.IncomingCapturedFrame(
4766 CreateFrame(1, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 07:06:52 -07004767 ExpectDroppedFrame();
mflodmancc3d4422017-08-03 08:27:51 -07004768 video_stream_encoder_->Stop();
asapersson02465b82017-04-10 01:12:52 -07004769}
4770
sprangb1ca0732017-02-01 08:38:12 -08004771// TODO(sprang): Extend this with fps throttling and any "balanced" extensions.
mflodmancc3d4422017-08-03 08:27:51 -07004772TEST_F(VideoStreamEncoderTest,
4773 AdaptsResolutionOnOveruse_MaintainFramerateMode) {
Henrik Boström381d1092020-05-12 18:49:07 +02004774 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01004775 DataRate::BitsPerSec(kTargetBitrateBps),
4776 DataRate::BitsPerSec(kTargetBitrateBps),
4777 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
sprangb1ca0732017-02-01 08:38:12 -08004778
4779 const int kFrameWidth = 1280;
4780 const int kFrameHeight = 720;
4781 // Enabled default VideoAdapter downscaling. First step is 3/4, not 3/5 as
mflodmancc3d4422017-08-03 08:27:51 -07004782 // requested by
4783 // VideoStreamEncoder::VideoSourceProxy::RequestResolutionLowerThan().
sprangb1ca0732017-02-01 08:38:12 -08004784 video_source_.set_adaptation_enabled(true);
4785
4786 video_source_.IncomingCapturedFrame(
Åsa Persson8c1bf952018-09-13 10:42:19 +02004787 CreateFrame(1 * kFrameIntervalMs, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 07:06:52 -07004788 WaitForEncodedFrame(kFrameWidth, kFrameHeight);
sprangb1ca0732017-02-01 08:38:12 -08004789
4790 // Trigger CPU overuse, downscale by 3/4.
mflodmancc3d4422017-08-03 08:27:51 -07004791 video_stream_encoder_->TriggerCpuOveruse();
sprangb1ca0732017-02-01 08:38:12 -08004792 video_source_.IncomingCapturedFrame(
Åsa Persson8c1bf952018-09-13 10:42:19 +02004793 CreateFrame(2 * kFrameIntervalMs, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 07:06:52 -07004794 WaitForEncodedFrame((kFrameWidth * 3) / 4, (kFrameHeight * 3) / 4);
sprangb1ca0732017-02-01 08:38:12 -08004795
asaperssonfab67072017-04-04 05:51:49 -07004796 // Trigger CPU normal use, return to original resolution.
Henrik Boström91aa7322020-04-28 12:24:33 +02004797 video_stream_encoder_->TriggerCpuUnderuse();
sprangb1ca0732017-02-01 08:38:12 -08004798 video_source_.IncomingCapturedFrame(
Åsa Persson8c1bf952018-09-13 10:42:19 +02004799 CreateFrame(3 * kFrameIntervalMs, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 07:06:52 -07004800 WaitForEncodedFrame(kFrameWidth, kFrameHeight);
sprangb1ca0732017-02-01 08:38:12 -08004801
mflodmancc3d4422017-08-03 08:27:51 -07004802 video_stream_encoder_->Stop();
sprangb1ca0732017-02-01 08:38:12 -08004803}
sprangfe627f32017-03-29 08:24:59 -07004804
mflodmancc3d4422017-08-03 08:27:51 -07004805TEST_F(VideoStreamEncoderTest,
4806 AdaptsFramerateOnOveruse_MaintainResolutionMode) {
sprangc5d62e22017-04-02 23:53:04 -07004807 const int kFrameWidth = 1280;
4808 const int kFrameHeight = 720;
sprangc5d62e22017-04-02 23:53:04 -07004809
Henrik Boström381d1092020-05-12 18:49:07 +02004810 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01004811 DataRate::BitsPerSec(kTargetBitrateBps),
4812 DataRate::BitsPerSec(kTargetBitrateBps),
4813 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
mflodmancc3d4422017-08-03 08:27:51 -07004814 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07004815 &video_source_, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
sprangc5d62e22017-04-02 23:53:04 -07004816 video_source_.set_adaptation_enabled(true);
4817
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02004818 int64_t timestamp_ms = CurrentTimeMs();
sprangc5d62e22017-04-02 23:53:04 -07004819
4820 video_source_.IncomingCapturedFrame(
4821 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 07:06:52 -07004822 WaitForEncodedFrame(timestamp_ms);
sprangc5d62e22017-04-02 23:53:04 -07004823
4824 // Try to trigger overuse. No fps estimate available => no effect.
mflodmancc3d4422017-08-03 08:27:51 -07004825 video_stream_encoder_->TriggerCpuOveruse();
sprangc5d62e22017-04-02 23:53:04 -07004826
4827 // Insert frames for one second to get a stable estimate.
sprang4847ae62017-06-27 07:06:52 -07004828 for (int i = 0; i < max_framerate_; ++i) {
sprangc5d62e22017-04-02 23:53:04 -07004829 timestamp_ms += kFrameIntervalMs;
sprangc5d62e22017-04-02 23:53:04 -07004830 video_source_.IncomingCapturedFrame(
4831 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 07:06:52 -07004832 WaitForEncodedFrame(timestamp_ms);
sprangc5d62e22017-04-02 23:53:04 -07004833 }
4834
4835 // Trigger CPU overuse, reduce framerate by 2/3.
mflodmancc3d4422017-08-03 08:27:51 -07004836 video_stream_encoder_->TriggerCpuOveruse();
sprangc5d62e22017-04-02 23:53:04 -07004837 int num_frames_dropped = 0;
sprang4847ae62017-06-27 07:06:52 -07004838 for (int i = 0; i < max_framerate_; ++i) {
sprangc5d62e22017-04-02 23:53:04 -07004839 timestamp_ms += kFrameIntervalMs;
sprangc5d62e22017-04-02 23:53:04 -07004840 video_source_.IncomingCapturedFrame(
4841 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 07:06:52 -07004842 if (!WaitForFrame(kFrameTimeoutMs)) {
sprangc5d62e22017-04-02 23:53:04 -07004843 ++num_frames_dropped;
4844 } else {
Åsa Perssonc74d8da2017-12-04 14:13:56 +01004845 sink_.CheckLastFrameSizeMatches(kFrameWidth, kFrameHeight);
sprangc5d62e22017-04-02 23:53:04 -07004846 }
4847 }
4848
sprang4847ae62017-06-27 07:06:52 -07004849 // Add some slack to account for frames dropped by the frame dropper.
4850 const int kErrorMargin = 1;
4851 EXPECT_NEAR(num_frames_dropped, max_framerate_ - (max_framerate_ * 2 / 3),
sprangc5d62e22017-04-02 23:53:04 -07004852 kErrorMargin);
4853
4854 // Trigger CPU overuse, reduce framerate by 2/3 again.
mflodmancc3d4422017-08-03 08:27:51 -07004855 video_stream_encoder_->TriggerCpuOveruse();
sprangc5d62e22017-04-02 23:53:04 -07004856 num_frames_dropped = 0;
Åsa Persson8c1bf952018-09-13 10:42:19 +02004857 for (int i = 0; i <= max_framerate_; ++i) {
sprangc5d62e22017-04-02 23:53:04 -07004858 timestamp_ms += kFrameIntervalMs;
sprangc5d62e22017-04-02 23:53:04 -07004859 video_source_.IncomingCapturedFrame(
4860 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 07:06:52 -07004861 if (!WaitForFrame(kFrameTimeoutMs)) {
sprangc5d62e22017-04-02 23:53:04 -07004862 ++num_frames_dropped;
4863 } else {
Åsa Perssonc74d8da2017-12-04 14:13:56 +01004864 sink_.CheckLastFrameSizeMatches(kFrameWidth, kFrameHeight);
sprangc5d62e22017-04-02 23:53:04 -07004865 }
4866 }
sprang4847ae62017-06-27 07:06:52 -07004867 EXPECT_NEAR(num_frames_dropped, max_framerate_ - (max_framerate_ * 4 / 9),
sprangc5d62e22017-04-02 23:53:04 -07004868 kErrorMargin);
4869
4870 // Go back up one step.
Henrik Boström91aa7322020-04-28 12:24:33 +02004871 video_stream_encoder_->TriggerCpuUnderuse();
sprangc5d62e22017-04-02 23:53:04 -07004872 num_frames_dropped = 0;
sprang4847ae62017-06-27 07:06:52 -07004873 for (int i = 0; i < max_framerate_; ++i) {
sprangc5d62e22017-04-02 23:53:04 -07004874 timestamp_ms += kFrameIntervalMs;
sprangc5d62e22017-04-02 23:53:04 -07004875 video_source_.IncomingCapturedFrame(
4876 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 07:06:52 -07004877 if (!WaitForFrame(kFrameTimeoutMs)) {
sprangc5d62e22017-04-02 23:53:04 -07004878 ++num_frames_dropped;
4879 } else {
Åsa Perssonc74d8da2017-12-04 14:13:56 +01004880 sink_.CheckLastFrameSizeMatches(kFrameWidth, kFrameHeight);
sprangc5d62e22017-04-02 23:53:04 -07004881 }
4882 }
sprang4847ae62017-06-27 07:06:52 -07004883 EXPECT_NEAR(num_frames_dropped, max_framerate_ - (max_framerate_ * 2 / 3),
sprangc5d62e22017-04-02 23:53:04 -07004884 kErrorMargin);
4885
4886 // Go back up to original mode.
Henrik Boström91aa7322020-04-28 12:24:33 +02004887 video_stream_encoder_->TriggerCpuUnderuse();
sprangc5d62e22017-04-02 23:53:04 -07004888 num_frames_dropped = 0;
sprang4847ae62017-06-27 07:06:52 -07004889 for (int i = 0; i < max_framerate_; ++i) {
sprangc5d62e22017-04-02 23:53:04 -07004890 timestamp_ms += kFrameIntervalMs;
sprangc5d62e22017-04-02 23:53:04 -07004891 video_source_.IncomingCapturedFrame(
4892 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 07:06:52 -07004893 if (!WaitForFrame(kFrameTimeoutMs)) {
sprangc5d62e22017-04-02 23:53:04 -07004894 ++num_frames_dropped;
4895 } else {
Åsa Perssonc74d8da2017-12-04 14:13:56 +01004896 sink_.CheckLastFrameSizeMatches(kFrameWidth, kFrameHeight);
sprangc5d62e22017-04-02 23:53:04 -07004897 }
4898 }
4899 EXPECT_NEAR(num_frames_dropped, 0, kErrorMargin);
4900
mflodmancc3d4422017-08-03 08:27:51 -07004901 video_stream_encoder_->Stop();
sprangc5d62e22017-04-02 23:53:04 -07004902}
4903
mflodmancc3d4422017-08-03 08:27:51 -07004904TEST_F(VideoStreamEncoderTest, DoesntAdaptDownPastMinFramerate) {
sprangc5d62e22017-04-02 23:53:04 -07004905 const int kFramerateFps = 5;
4906 const int kFrameIntervalMs = rtc::kNumMillisecsPerSec / kFramerateFps;
sprangc5d62e22017-04-02 23:53:04 -07004907 const int kFrameWidth = 1280;
4908 const int kFrameHeight = 720;
4909
sprang4847ae62017-06-27 07:06:52 -07004910 // Reconfigure encoder with two temporal layers and screensharing, which will
4911 // disable frame dropping and make testing easier.
Niels Möllerf1338562018-04-26 09:51:47 +02004912 ResetEncoder("VP8", 1, 2, 1, true);
sprang4847ae62017-06-27 07:06:52 -07004913
Henrik Boström381d1092020-05-12 18:49:07 +02004914 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01004915 DataRate::BitsPerSec(kTargetBitrateBps),
4916 DataRate::BitsPerSec(kTargetBitrateBps),
4917 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
mflodmancc3d4422017-08-03 08:27:51 -07004918 video_stream_encoder_->SetSource(
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07004919 &video_source_, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
sprangc5d62e22017-04-02 23:53:04 -07004920 video_source_.set_adaptation_enabled(true);
4921
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02004922 int64_t timestamp_ms = CurrentTimeMs();
sprangc5d62e22017-04-02 23:53:04 -07004923
4924 // Trigger overuse as much as we can.
Jonathan Yubc771b72017-12-08 17:04:29 -08004925 rtc::VideoSinkWants last_wants;
4926 do {
4927 last_wants = video_source_.sink_wants();
4928
sprangc5d62e22017-04-02 23:53:04 -07004929 // Insert frames to get a new fps estimate...
4930 for (int j = 0; j < kFramerateFps; ++j) {
4931 video_source_.IncomingCapturedFrame(
4932 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
Jonathan Yubc771b72017-12-08 17:04:29 -08004933 if (video_source_.last_sent_width()) {
4934 sink_.WaitForEncodedFrame(timestamp_ms);
4935 }
sprangc5d62e22017-04-02 23:53:04 -07004936 timestamp_ms += kFrameIntervalMs;
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02004937 AdvanceTime(TimeDelta::Millis(kFrameIntervalMs));
sprangc5d62e22017-04-02 23:53:04 -07004938 }
4939 // ...and then try to adapt again.
mflodmancc3d4422017-08-03 08:27:51 -07004940 video_stream_encoder_->TriggerCpuOveruse();
Jonathan Yubc771b72017-12-08 17:04:29 -08004941 } while (video_source_.sink_wants().max_framerate_fps <
4942 last_wants.max_framerate_fps);
sprangc5d62e22017-04-02 23:53:04 -07004943
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02004944 EXPECT_THAT(video_source_.sink_wants(),
4945 FpsMatchesResolutionMax(Eq(kMinFramerateFps)));
asaperssonf7e294d2017-06-13 23:25:22 -07004946
mflodmancc3d4422017-08-03 08:27:51 -07004947 video_stream_encoder_->Stop();
sprangc5d62e22017-04-02 23:53:04 -07004948}
asaperssonf7e294d2017-06-13 23:25:22 -07004949
mflodmancc3d4422017-08-03 08:27:51 -07004950TEST_F(VideoStreamEncoderTest,
4951 AdaptsResolutionAndFramerateForLowQuality_BalancedMode) {
asaperssonf7e294d2017-06-13 23:25:22 -07004952 const int kWidth = 1280;
4953 const int kHeight = 720;
4954 const int64_t kFrameIntervalMs = 150;
4955 int64_t timestamp_ms = kFrameIntervalMs;
Henrik Boström381d1092020-05-12 18:49:07 +02004956 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01004957 DataRate::BitsPerSec(kTargetBitrateBps),
4958 DataRate::BitsPerSec(kTargetBitrateBps),
4959 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asaperssonf7e294d2017-06-13 23:25:22 -07004960
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07004961 // Enable BALANCED preference, no initial limitation.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02004962 AdaptingFrameForwarder source(&time_controller_);
asaperssonf7e294d2017-06-13 23:25:22 -07004963 source.set_adaptation_enabled(true);
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07004964 video_stream_encoder_->SetSource(&source,
4965 webrtc::DegradationPreference::BALANCED);
asaperssonf7e294d2017-06-13 23:25:22 -07004966 timestamp_ms += kFrameIntervalMs;
4967 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07004968 WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02004969 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-13 23:25:22 -07004970 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
4971 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
4972 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
4973
4974 // Trigger adapt down, expect scaled down resolution (960x540@30fps).
mflodmancc3d4422017-08-03 08:27:51 -07004975 video_stream_encoder_->TriggerQualityLow();
asaperssonf7e294d2017-06-13 23:25:22 -07004976 timestamp_ms += kFrameIntervalMs;
4977 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07004978 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02004979 EXPECT_THAT(source.sink_wants(),
4980 FpsMaxResolutionMatches(Lt(kWidth * kHeight)));
asaperssonf7e294d2017-06-13 23:25:22 -07004981 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
4982 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
4983 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
4984
4985 // Trigger adapt down, expect scaled down resolution (640x360@30fps).
mflodmancc3d4422017-08-03 08:27:51 -07004986 video_stream_encoder_->TriggerQualityLow();
asaperssonf7e294d2017-06-13 23:25:22 -07004987 timestamp_ms += kFrameIntervalMs;
4988 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07004989 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02004990 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionLt(source.last_wants()));
asaperssonf7e294d2017-06-13 23:25:22 -07004991 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
4992 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
4993 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_quality_adapt_changes);
4994
4995 // Trigger adapt down, expect reduced fps (640x360@15fps).
mflodmancc3d4422017-08-03 08:27:51 -07004996 video_stream_encoder_->TriggerQualityLow();
asaperssonf7e294d2017-06-13 23:25:22 -07004997 timestamp_ms += kFrameIntervalMs;
4998 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07004999 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02005000 EXPECT_THAT(source.sink_wants(), FpsLtResolutionEq(source.last_wants()));
asaperssonf7e294d2017-06-13 23:25:22 -07005001 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5002 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
5003 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5004
5005 // Trigger adapt down, expect scaled down resolution (480x270@15fps).
mflodmancc3d4422017-08-03 08:27:51 -07005006 video_stream_encoder_->TriggerQualityLow();
asaperssonf7e294d2017-06-13 23:25:22 -07005007 timestamp_ms += kFrameIntervalMs;
5008 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005009 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02005010 EXPECT_THAT(source.sink_wants(), FpsEqResolutionLt(source.last_wants()));
asaperssonf7e294d2017-06-13 23:25:22 -07005011 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5012 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
5013 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5014
5015 // Restrict bitrate, trigger adapt down, expect reduced fps (480x270@10fps).
mflodmancc3d4422017-08-03 08:27:51 -07005016 video_stream_encoder_->TriggerQualityLow();
asaperssonf7e294d2017-06-13 23:25:22 -07005017 timestamp_ms += kFrameIntervalMs;
5018 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005019 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02005020 EXPECT_THAT(source.sink_wants(), FpsLtResolutionEq(source.last_wants()));
asaperssonf7e294d2017-06-13 23:25:22 -07005021 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5022 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
5023 EXPECT_EQ(5, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5024
5025 // Trigger adapt down, expect scaled down resolution (320x180@10fps).
mflodmancc3d4422017-08-03 08:27:51 -07005026 video_stream_encoder_->TriggerQualityLow();
asaperssonf7e294d2017-06-13 23:25:22 -07005027 timestamp_ms += kFrameIntervalMs;
5028 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005029 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02005030 EXPECT_THAT(source.sink_wants(), FpsEqResolutionLt(source.last_wants()));
asaperssonf7e294d2017-06-13 23:25:22 -07005031 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5032 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
5033 EXPECT_EQ(6, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5034
5035 // Trigger adapt down, expect reduced fps (320x180@7fps).
mflodmancc3d4422017-08-03 08:27:51 -07005036 video_stream_encoder_->TriggerQualityLow();
asaperssonf7e294d2017-06-13 23:25:22 -07005037 timestamp_ms += kFrameIntervalMs;
5038 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005039 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02005040 EXPECT_THAT(source.sink_wants(), FpsLtResolutionEq(source.last_wants()));
asaperssonf7e294d2017-06-13 23:25:22 -07005041 rtc::VideoSinkWants last_wants = source.sink_wants();
5042 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5043 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
5044 EXPECT_EQ(7, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5045
5046 // Trigger adapt down, min resolution reached, expect no change.
mflodmancc3d4422017-08-03 08:27:51 -07005047 video_stream_encoder_->TriggerQualityLow();
asaperssonf7e294d2017-06-13 23:25:22 -07005048 timestamp_ms += kFrameIntervalMs;
5049 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005050 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02005051 EXPECT_THAT(source.sink_wants(), FpsEqResolutionEqTo(last_wants));
asaperssonf7e294d2017-06-13 23:25:22 -07005052 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5053 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
5054 EXPECT_EQ(7, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5055
Evan Shrubsole64469032020-06-11 10:45:29 +02005056 // Trigger adapt up, expect expect increased fps (320x180@10fps).
mflodmancc3d4422017-08-03 08:27:51 -07005057 video_stream_encoder_->TriggerQualityHigh();
asaperssonf7e294d2017-06-13 23:25:22 -07005058 timestamp_ms += kFrameIntervalMs;
5059 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005060 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02005061 EXPECT_THAT(source.sink_wants(), FpsGtResolutionEq(source.last_wants()));
asaperssonf7e294d2017-06-13 23:25:22 -07005062 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5063 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
5064 EXPECT_EQ(8, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5065
5066 // Trigger adapt up, expect upscaled resolution (480x270@10fps).
mflodmancc3d4422017-08-03 08:27:51 -07005067 video_stream_encoder_->TriggerQualityHigh();
asaperssonf7e294d2017-06-13 23:25:22 -07005068 timestamp_ms += kFrameIntervalMs;
5069 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005070 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02005071 EXPECT_THAT(source.sink_wants(), FpsEqResolutionGt(source.last_wants()));
asaperssonf7e294d2017-06-13 23:25:22 -07005072 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5073 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
5074 EXPECT_EQ(9, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5075
5076 // Increase bitrate, trigger adapt up, expect increased fps (480x270@15fps).
mflodmancc3d4422017-08-03 08:27:51 -07005077 video_stream_encoder_->TriggerQualityHigh();
asaperssonf7e294d2017-06-13 23:25:22 -07005078 timestamp_ms += kFrameIntervalMs;
5079 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005080 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02005081 EXPECT_THAT(source.sink_wants(), FpsGtResolutionEq(source.last_wants()));
asaperssonf7e294d2017-06-13 23:25:22 -07005082 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5083 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
5084 EXPECT_EQ(10, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5085
5086 // Trigger adapt up, expect upscaled resolution (640x360@15fps).
mflodmancc3d4422017-08-03 08:27:51 -07005087 video_stream_encoder_->TriggerQualityHigh();
asaperssonf7e294d2017-06-13 23:25:22 -07005088 timestamp_ms += kFrameIntervalMs;
5089 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005090 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02005091 EXPECT_THAT(source.sink_wants(), FpsEqResolutionGt(source.last_wants()));
asaperssonf7e294d2017-06-13 23:25:22 -07005092 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5093 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
5094 EXPECT_EQ(11, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5095
5096 // Trigger adapt up, expect increased fps (640x360@30fps).
mflodmancc3d4422017-08-03 08:27:51 -07005097 video_stream_encoder_->TriggerQualityHigh();
asaperssonf7e294d2017-06-13 23:25:22 -07005098 timestamp_ms += kFrameIntervalMs;
5099 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005100 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02005101 EXPECT_THAT(source.sink_wants(), FpsMax());
5102 EXPECT_EQ(source.sink_wants().max_pixel_count,
5103 source.last_wants().max_pixel_count);
asaperssonf7e294d2017-06-13 23:25:22 -07005104 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5105 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
5106 EXPECT_EQ(12, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5107
5108 // Trigger adapt up, expect upscaled resolution (960x540@30fps).
mflodmancc3d4422017-08-03 08:27:51 -07005109 video_stream_encoder_->TriggerQualityHigh();
asaperssonf7e294d2017-06-13 23:25:22 -07005110 timestamp_ms += kFrameIntervalMs;
5111 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005112 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02005113 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionGt(source.last_wants()));
asaperssonf7e294d2017-06-13 23:25:22 -07005114 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5115 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
5116 EXPECT_EQ(13, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5117
Åsa Persson30ab0152019-08-27 12:22:33 +02005118 // Trigger adapt up, expect no restriction (1280x720fps@30fps).
mflodmancc3d4422017-08-03 08:27:51 -07005119 video_stream_encoder_->TriggerQualityHigh();
asaperssonf7e294d2017-06-13 23:25:22 -07005120 timestamp_ms += kFrameIntervalMs;
5121 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005122 WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02005123 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionGt(source.last_wants()));
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02005124 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-13 23:25:22 -07005125 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
5126 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
5127 EXPECT_EQ(14, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5128
5129 // Trigger adapt up, expect no change.
mflodmancc3d4422017-08-03 08:27:51 -07005130 video_stream_encoder_->TriggerQualityHigh();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02005131 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-13 23:25:22 -07005132 EXPECT_EQ(14, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5133
mflodmancc3d4422017-08-03 08:27:51 -07005134 video_stream_encoder_->Stop();
asaperssonf7e294d2017-06-13 23:25:22 -07005135}
5136
mflodmancc3d4422017-08-03 08:27:51 -07005137TEST_F(VideoStreamEncoderTest, AdaptWithTwoReasonsAndDifferentOrder_Framerate) {
asaperssonf7e294d2017-06-13 23:25:22 -07005138 const int kWidth = 1280;
5139 const int kHeight = 720;
5140 const int64_t kFrameIntervalMs = 150;
5141 int64_t timestamp_ms = kFrameIntervalMs;
Henrik Boström381d1092020-05-12 18:49:07 +02005142 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005143 DataRate::BitsPerSec(kTargetBitrateBps),
5144 DataRate::BitsPerSec(kTargetBitrateBps),
5145 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asaperssonf7e294d2017-06-13 23:25:22 -07005146
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07005147 // Enable BALANCED preference, no initial limitation.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02005148 AdaptingFrameForwarder source(&time_controller_);
asaperssonf7e294d2017-06-13 23:25:22 -07005149 source.set_adaptation_enabled(true);
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07005150 video_stream_encoder_->SetSource(&source,
5151 webrtc::DegradationPreference::BALANCED);
asaperssonf7e294d2017-06-13 23:25:22 -07005152 timestamp_ms += kFrameIntervalMs;
5153 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005154 WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02005155 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-13 23:25:22 -07005156 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
5157 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
5158 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
5159 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
5160 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
5161 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5162
5163 // Trigger cpu adapt down, expect scaled down resolution (960x540@30fps).
mflodmancc3d4422017-08-03 08:27:51 -07005164 video_stream_encoder_->TriggerCpuOveruse();
asaperssonf7e294d2017-06-13 23:25:22 -07005165 timestamp_ms += kFrameIntervalMs;
5166 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005167 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02005168 EXPECT_THAT(source.sink_wants(),
5169 FpsMaxResolutionMatches(Lt(kWidth * kHeight)));
asaperssonf7e294d2017-06-13 23:25:22 -07005170 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
5171 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
5172 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
5173 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
5174 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
5175 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5176
5177 // Trigger cpu adapt down, expect scaled down resolution (640x360@30fps).
mflodmancc3d4422017-08-03 08:27:51 -07005178 video_stream_encoder_->TriggerCpuOveruse();
asaperssonf7e294d2017-06-13 23:25:22 -07005179 timestamp_ms += kFrameIntervalMs;
5180 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005181 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02005182 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionLt(source.last_wants()));
asaperssonf7e294d2017-06-13 23:25:22 -07005183 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
5184 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
5185 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
5186 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
5187 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
5188 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5189
5190 // Trigger quality adapt down, expect reduced fps (640x360@15fps).
mflodmancc3d4422017-08-03 08:27:51 -07005191 video_stream_encoder_->TriggerQualityLow();
asaperssonf7e294d2017-06-13 23:25:22 -07005192 timestamp_ms += kFrameIntervalMs;
5193 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005194 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02005195 EXPECT_THAT(source.sink_wants(), FpsLtResolutionEq(source.last_wants()));
Evan Shrubsole64469032020-06-11 10:45:29 +02005196 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
asaperssonf7e294d2017-06-13 23:25:22 -07005197 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
5198 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
5199 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
5200 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
5201 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5202
Evan Shrubsole64469032020-06-11 10:45:29 +02005203 // Trigger cpu adapt up, expect no change since QP is most limited.
5204 {
5205 // Store current sink wants since we expect no change and if there is no
5206 // change then last_wants() is not updated.
5207 auto previous_sink_wants = source.sink_wants();
5208 video_stream_encoder_->TriggerCpuUnderuse();
5209 timestamp_ms += kFrameIntervalMs;
5210 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
5211 WaitForEncodedFrame(timestamp_ms);
5212 EXPECT_THAT(source.sink_wants(), FpsEqResolutionEqTo(previous_sink_wants));
5213 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
5214 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5215 }
5216
5217 // Trigger quality adapt up, expect increased fps (640x360@30fps).
5218 video_stream_encoder_->TriggerQualityHigh();
5219 timestamp_ms += kFrameIntervalMs;
5220 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
5221 WaitForEncodedFrame(timestamp_ms);
5222 EXPECT_THAT(source.sink_wants(), FpsGtResolutionEq(source.last_wants()));
5223 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5224 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
5225 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
5226 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
5227 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
5228 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5229
5230 // Trigger quality adapt up and Cpu adapt up since both are most limited,
5231 // expect increased resolution (960x540@30fps).
5232 video_stream_encoder_->TriggerQualityHigh();
Henrik Boström91aa7322020-04-28 12:24:33 +02005233 video_stream_encoder_->TriggerCpuUnderuse();
asaperssonf7e294d2017-06-13 23:25:22 -07005234 timestamp_ms += kFrameIntervalMs;
5235 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005236 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole64469032020-06-11 10:45:29 +02005237 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionGt(source.last_wants()));
asaperssonf7e294d2017-06-13 23:25:22 -07005238 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
5239 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
5240 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
5241 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
5242 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
Evan Shrubsole64469032020-06-11 10:45:29 +02005243 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_quality_adapt_changes);
asaperssonf7e294d2017-06-13 23:25:22 -07005244
Evan Shrubsole64469032020-06-11 10:45:29 +02005245 // Trigger quality adapt up and Cpu adapt up since both are most limited,
5246 // expect no restriction (1280x720fps@30fps).
mflodmancc3d4422017-08-03 08:27:51 -07005247 video_stream_encoder_->TriggerQualityHigh();
Henrik Boström91aa7322020-04-28 12:24:33 +02005248 video_stream_encoder_->TriggerCpuUnderuse();
asaperssonf7e294d2017-06-13 23:25:22 -07005249 timestamp_ms += kFrameIntervalMs;
5250 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005251 WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02005252 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionGt(source.last_wants()));
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02005253 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-13 23:25:22 -07005254 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
5255 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
5256 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
5257 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
5258 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
Evan Shrubsole64469032020-06-11 10:45:29 +02005259 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_quality_adapt_changes);
asaperssonf7e294d2017-06-13 23:25:22 -07005260
5261 // Trigger adapt up, expect no change.
mflodmancc3d4422017-08-03 08:27:51 -07005262 video_stream_encoder_->TriggerQualityHigh();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02005263 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-13 23:25:22 -07005264 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
Evan Shrubsole64469032020-06-11 10:45:29 +02005265 EXPECT_EQ(4, stats_proxy_->GetStats().number_of_quality_adapt_changes);
asaperssonf7e294d2017-06-13 23:25:22 -07005266
mflodmancc3d4422017-08-03 08:27:51 -07005267 video_stream_encoder_->Stop();
asaperssonf7e294d2017-06-13 23:25:22 -07005268}
5269
mflodmancc3d4422017-08-03 08:27:51 -07005270TEST_F(VideoStreamEncoderTest,
5271 AdaptWithTwoReasonsAndDifferentOrder_Resolution) {
asaperssonf7e294d2017-06-13 23:25:22 -07005272 const int kWidth = 640;
5273 const int kHeight = 360;
5274 const int kFpsLimit = 15;
5275 const int64_t kFrameIntervalMs = 150;
5276 int64_t timestamp_ms = kFrameIntervalMs;
Henrik Boström381d1092020-05-12 18:49:07 +02005277 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005278 DataRate::BitsPerSec(kTargetBitrateBps),
5279 DataRate::BitsPerSec(kTargetBitrateBps),
5280 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
asaperssonf7e294d2017-06-13 23:25:22 -07005281
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07005282 // Enable BALANCED preference, no initial limitation.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02005283 AdaptingFrameForwarder source(&time_controller_);
asaperssonf7e294d2017-06-13 23:25:22 -07005284 source.set_adaptation_enabled(true);
Taylor Brandstetter49fcc102018-05-16 14:20:41 -07005285 video_stream_encoder_->SetSource(&source,
5286 webrtc::DegradationPreference::BALANCED);
asaperssonf7e294d2017-06-13 23:25:22 -07005287 timestamp_ms += kFrameIntervalMs;
5288 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005289 WaitForEncodedFrame(kWidth, kHeight);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02005290 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-13 23:25:22 -07005291 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
5292 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
5293 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
5294 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
5295 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
5296 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5297
5298 // Trigger cpu adapt down, expect scaled down framerate (640x360@15fps).
mflodmancc3d4422017-08-03 08:27:51 -07005299 video_stream_encoder_->TriggerCpuOveruse();
asaperssonf7e294d2017-06-13 23:25:22 -07005300 timestamp_ms += kFrameIntervalMs;
5301 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005302 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02005303 EXPECT_THAT(source.sink_wants(), FpsMatchesResolutionMax(Eq(kFpsLimit)));
asaperssonf7e294d2017-06-13 23:25:22 -07005304 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
5305 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
5306 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
5307 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_framerate);
5308 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
5309 EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5310
5311 // Trigger quality adapt down, expect scaled down resolution (480x270@15fps).
mflodmancc3d4422017-08-03 08:27:51 -07005312 video_stream_encoder_->TriggerQualityLow();
asaperssonf7e294d2017-06-13 23:25:22 -07005313 timestamp_ms += kFrameIntervalMs;
5314 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005315 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02005316 EXPECT_THAT(source.sink_wants(), FpsEqResolutionLt(source.last_wants()));
asaperssonf7e294d2017-06-13 23:25:22 -07005317 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
Evan Shrubsole64469032020-06-11 10:45:29 +02005318 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
asaperssonf7e294d2017-06-13 23:25:22 -07005319 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
5320 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_framerate);
5321 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
5322 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5323
Evan Shrubsole64469032020-06-11 10:45:29 +02005324 // Trigger cpu adapt up, expect no change because quality is most limited.
5325 {
5326 auto previous_sink_wants = source.sink_wants();
5327 // Store current sink wants since we expect no change ind if there is no
5328 // change then last__wants() is not updated.
5329 video_stream_encoder_->TriggerCpuUnderuse();
5330 timestamp_ms += kFrameIntervalMs;
5331 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
5332 WaitForEncodedFrame(timestamp_ms);
5333 EXPECT_THAT(source.sink_wants(), FpsEqResolutionEqTo(previous_sink_wants));
5334 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
5335 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
5336 }
5337
5338 // Trigger quality adapt up, expect upscaled resolution (640x360@15fps).
5339 video_stream_encoder_->TriggerQualityHigh();
asaperssonf7e294d2017-06-13 23:25:22 -07005340 timestamp_ms += kFrameIntervalMs;
5341 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005342 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5fd40602020-05-25 16:19:54 +02005343 EXPECT_THAT(source.sink_wants(), FpsEqResolutionGt(source.last_wants()));
asaperssonf7e294d2017-06-13 23:25:22 -07005344 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
5345 EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
5346 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
Evan Shrubsole64469032020-06-11 10:45:29 +02005347 EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_framerate);
5348 EXPECT_EQ(1, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
5349 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_quality_adapt_changes);
asaperssonf7e294d2017-06-13 23:25:22 -07005350
Evan Shrubsole64469032020-06-11 10:45:29 +02005351 // Trigger quality and cpu adapt up, expect increased fps (640x360@30fps).
mflodmancc3d4422017-08-03 08:27:51 -07005352 video_stream_encoder_->TriggerQualityHigh();
Evan Shrubsole64469032020-06-11 10:45:29 +02005353 video_stream_encoder_->TriggerCpuUnderuse();
asaperssonf7e294d2017-06-13 23:25:22 -07005354 timestamp_ms += kFrameIntervalMs;
5355 source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
sprang4847ae62017-06-27 07:06:52 -07005356 WaitForEncodedFrame(timestamp_ms);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02005357 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-13 23:25:22 -07005358 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
5359 EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
5360 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
5361 EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
5362 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
Evan Shrubsole64469032020-06-11 10:45:29 +02005363 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_quality_adapt_changes);
asaperssonf7e294d2017-06-13 23:25:22 -07005364
5365 // Trigger adapt up, expect no change.
mflodmancc3d4422017-08-03 08:27:51 -07005366 video_stream_encoder_->TriggerQualityHigh();
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02005367 EXPECT_THAT(source.sink_wants(), FpsMaxResolutionMax());
asaperssonf7e294d2017-06-13 23:25:22 -07005368 EXPECT_EQ(2, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
Evan Shrubsole64469032020-06-11 10:45:29 +02005369 EXPECT_EQ(3, stats_proxy_->GetStats().number_of_quality_adapt_changes);
asaperssonf7e294d2017-06-13 23:25:22 -07005370
mflodmancc3d4422017-08-03 08:27:51 -07005371 video_stream_encoder_->Stop();
asaperssonf7e294d2017-06-13 23:25:22 -07005372}
5373
mflodmancc3d4422017-08-03 08:27:51 -07005374TEST_F(VideoStreamEncoderTest, AcceptsFullHdAdaptedDownSimulcastFrames) {
ilnik6b826ef2017-06-16 06:53:48 -07005375 const int kFrameWidth = 1920;
5376 const int kFrameHeight = 1080;
5377 // 3/4 of 1920.
5378 const int kAdaptedFrameWidth = 1440;
5379 // 3/4 of 1080 rounded down to multiple of 4.
5380 const int kAdaptedFrameHeight = 808;
5381 const int kFramerate = 24;
5382
Henrik Boström381d1092020-05-12 18:49:07 +02005383 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005384 DataRate::BitsPerSec(kTargetBitrateBps),
5385 DataRate::BitsPerSec(kTargetBitrateBps),
5386 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
ilnik6b826ef2017-06-16 06:53:48 -07005387 // Trigger reconfigure encoder (without resetting the entire instance).
5388 VideoEncoderConfig video_encoder_config;
Niels Möller259a4972018-04-05 15:36:51 +02005389 video_encoder_config.codec_type = kVideoCodecVP8;
ilnik6b826ef2017-06-16 06:53:48 -07005390 video_encoder_config.max_bitrate_bps = kTargetBitrateBps;
5391 video_encoder_config.number_of_streams = 1;
5392 video_encoder_config.video_stream_factory =
5393 new rtc::RefCountedObject<CroppingVideoStreamFactory>(1, kFramerate);
mflodmancc3d4422017-08-03 08:27:51 -07005394 video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config),
Niels Möllerf1338562018-04-26 09:51:47 +02005395 kMaxPayloadLength);
mflodmancc3d4422017-08-03 08:27:51 -07005396 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
ilnik6b826ef2017-06-16 06:53:48 -07005397
5398 video_source_.set_adaptation_enabled(true);
5399
5400 video_source_.IncomingCapturedFrame(
5401 CreateFrame(1, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 07:06:52 -07005402 WaitForEncodedFrame(kFrameWidth, kFrameHeight);
ilnik6b826ef2017-06-16 06:53:48 -07005403
5404 // Trigger CPU overuse, downscale by 3/4.
mflodmancc3d4422017-08-03 08:27:51 -07005405 video_stream_encoder_->TriggerCpuOveruse();
ilnik6b826ef2017-06-16 06:53:48 -07005406 video_source_.IncomingCapturedFrame(
5407 CreateFrame(2, kFrameWidth, kFrameHeight));
sprang4847ae62017-06-27 07:06:52 -07005408 WaitForEncodedFrame(kAdaptedFrameWidth, kAdaptedFrameHeight);
ilnik6b826ef2017-06-16 06:53:48 -07005409
mflodmancc3d4422017-08-03 08:27:51 -07005410 video_stream_encoder_->Stop();
ilnik6b826ef2017-06-16 06:53:48 -07005411}
5412
mflodmancc3d4422017-08-03 08:27:51 -07005413TEST_F(VideoStreamEncoderTest, PeriodicallyUpdatesChannelParameters) {
sprang4847ae62017-06-27 07:06:52 -07005414 const int kFrameWidth = 1280;
5415 const int kFrameHeight = 720;
5416 const int kLowFps = 2;
5417 const int kHighFps = 30;
5418
Henrik Boström381d1092020-05-12 18:49:07 +02005419 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005420 DataRate::BitsPerSec(kTargetBitrateBps),
5421 DataRate::BitsPerSec(kTargetBitrateBps),
5422 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
sprang4847ae62017-06-27 07:06:52 -07005423
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02005424 int64_t timestamp_ms = CurrentTimeMs();
sprang4847ae62017-06-27 07:06:52 -07005425 max_framerate_ = kLowFps;
5426
5427 // Insert 2 seconds of 2fps video.
5428 for (int i = 0; i < kLowFps * 2; ++i) {
5429 video_source_.IncomingCapturedFrame(
5430 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
5431 WaitForEncodedFrame(timestamp_ms);
5432 timestamp_ms += 1000 / kLowFps;
5433 }
5434
5435 // Make sure encoder is updated with new target.
Henrik Boström381d1092020-05-12 18:49:07 +02005436 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005437 DataRate::BitsPerSec(kTargetBitrateBps),
5438 DataRate::BitsPerSec(kTargetBitrateBps),
5439 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
sprang4847ae62017-06-27 07:06:52 -07005440 video_source_.IncomingCapturedFrame(
5441 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
5442 WaitForEncodedFrame(timestamp_ms);
5443 timestamp_ms += 1000 / kLowFps;
5444
5445 EXPECT_EQ(kLowFps, fake_encoder_.GetConfiguredInputFramerate());
5446
5447 // Insert 30fps frames for just a little more than the forced update period.
Niels Möllerfe407b72019-09-10 10:48:48 +02005448 const int kVcmTimerIntervalFrames = (kProcessIntervalMs * kHighFps) / 1000;
sprang4847ae62017-06-27 07:06:52 -07005449 const int kFrameIntervalMs = 1000 / kHighFps;
5450 max_framerate_ = kHighFps;
5451 for (int i = 0; i < kVcmTimerIntervalFrames + 2; ++i) {
5452 video_source_.IncomingCapturedFrame(
5453 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
5454 // Wait for encoded frame, but skip ahead if it doesn't arrive as it might
5455 // be dropped if the encoder hans't been updated with the new higher target
5456 // framerate yet, causing it to overshoot the target bitrate and then
5457 // suffering the wrath of the media optimizer.
5458 TimedWaitForEncodedFrame(timestamp_ms, 2 * kFrameIntervalMs);
5459 timestamp_ms += kFrameIntervalMs;
5460 }
5461
5462 // Don expect correct measurement just yet, but it should be higher than
5463 // before.
5464 EXPECT_GT(fake_encoder_.GetConfiguredInputFramerate(), kLowFps);
5465
mflodmancc3d4422017-08-03 08:27:51 -07005466 video_stream_encoder_->Stop();
sprang4847ae62017-06-27 07:06:52 -07005467}
5468
mflodmancc3d4422017-08-03 08:27:51 -07005469TEST_F(VideoStreamEncoderTest, DoesNotUpdateBitrateAllocationWhenSuspended) {
sprang4847ae62017-06-27 07:06:52 -07005470 const int kFrameWidth = 1280;
5471 const int kFrameHeight = 720;
5472 const int kTargetBitrateBps = 1000000;
Per Kjellanderdcef6412020-10-07 15:09:05 +02005473 ResetEncoder("FAKE", 1, 1, 1, false,
5474 VideoStreamEncoderSettings::BitrateAllocationCallbackType::
5475 kVideoBitrateAllocation);
sprang4847ae62017-06-27 07:06:52 -07005476
Henrik Boström381d1092020-05-12 18:49:07 +02005477 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005478 DataRate::BitsPerSec(kTargetBitrateBps),
5479 DataRate::BitsPerSec(kTargetBitrateBps),
5480 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
mflodmancc3d4422017-08-03 08:27:51 -07005481 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
sprang4847ae62017-06-27 07:06:52 -07005482
5483 // Insert a first video frame, causes another bitrate update.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02005484 int64_t timestamp_ms = CurrentTimeMs();
sprang4847ae62017-06-27 07:06:52 -07005485 video_source_.IncomingCapturedFrame(
5486 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
5487 WaitForEncodedFrame(timestamp_ms);
Per Kjellanderdcef6412020-10-07 15:09:05 +02005488 EXPECT_EQ(sink_.number_of_bitrate_allocations(), 1);
sprang4847ae62017-06-27 07:06:52 -07005489
5490 // Next, simulate video suspension due to pacer queue overrun.
Henrik Boström381d1092020-05-12 18:49:07 +02005491 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
5492 DataRate::BitsPerSec(0), DataRate::BitsPerSec(0), DataRate::BitsPerSec(0),
5493 0, 1, 0);
sprang4847ae62017-06-27 07:06:52 -07005494
5495 // Skip ahead until a new periodic parameter update should have occured.
Niels Möllerfe407b72019-09-10 10:48:48 +02005496 timestamp_ms += kProcessIntervalMs;
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02005497 AdvanceTime(TimeDelta::Millis(kProcessIntervalMs));
sprang4847ae62017-06-27 07:06:52 -07005498
Per Kjellanderdcef6412020-10-07 15:09:05 +02005499 // No more allocations has been made.
sprang4847ae62017-06-27 07:06:52 -07005500 video_source_.IncomingCapturedFrame(
5501 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
5502 ExpectDroppedFrame();
Per Kjellanderdcef6412020-10-07 15:09:05 +02005503 EXPECT_EQ(sink_.number_of_bitrate_allocations(), 1);
sprang4847ae62017-06-27 07:06:52 -07005504
mflodmancc3d4422017-08-03 08:27:51 -07005505 video_stream_encoder_->Stop();
sprang4847ae62017-06-27 07:06:52 -07005506}
ilnik6b826ef2017-06-16 06:53:48 -07005507
Niels Möller4db138e2018-04-19 09:04:13 +02005508TEST_F(VideoStreamEncoderTest,
5509 DefaultCpuAdaptationThresholdsForSoftwareEncoder) {
5510 const int kFrameWidth = 1280;
5511 const int kFrameHeight = 720;
5512 const CpuOveruseOptions default_options;
Henrik Boström381d1092020-05-12 18:49:07 +02005513 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005514 DataRate::BitsPerSec(kTargetBitrateBps),
5515 DataRate::BitsPerSec(kTargetBitrateBps),
5516 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Niels Möller4db138e2018-04-19 09:04:13 +02005517 video_source_.IncomingCapturedFrame(
5518 CreateFrame(1, kFrameWidth, kFrameHeight));
5519 WaitForEncodedFrame(1);
5520 EXPECT_EQ(video_stream_encoder_->overuse_detector_proxy_->GetOptions()
5521 .low_encode_usage_threshold_percent,
5522 default_options.low_encode_usage_threshold_percent);
5523 EXPECT_EQ(video_stream_encoder_->overuse_detector_proxy_->GetOptions()
5524 .high_encode_usage_threshold_percent,
5525 default_options.high_encode_usage_threshold_percent);
5526 video_stream_encoder_->Stop();
5527}
5528
5529TEST_F(VideoStreamEncoderTest,
5530 HigherCpuAdaptationThresholdsForHardwareEncoder) {
5531 const int kFrameWidth = 1280;
5532 const int kFrameHeight = 720;
5533 CpuOveruseOptions hardware_options;
5534 hardware_options.low_encode_usage_threshold_percent = 150;
5535 hardware_options.high_encode_usage_threshold_percent = 200;
Mirta Dvornicicccc1b572019-01-15 12:42:18 +01005536 fake_encoder_.SetIsHardwareAccelerated(true);
Niels Möller4db138e2018-04-19 09:04:13 +02005537
Henrik Boström381d1092020-05-12 18:49:07 +02005538 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005539 DataRate::BitsPerSec(kTargetBitrateBps),
5540 DataRate::BitsPerSec(kTargetBitrateBps),
5541 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Niels Möller4db138e2018-04-19 09:04:13 +02005542 video_source_.IncomingCapturedFrame(
5543 CreateFrame(1, kFrameWidth, kFrameHeight));
5544 WaitForEncodedFrame(1);
5545 EXPECT_EQ(video_stream_encoder_->overuse_detector_proxy_->GetOptions()
5546 .low_encode_usage_threshold_percent,
5547 hardware_options.low_encode_usage_threshold_percent);
5548 EXPECT_EQ(video_stream_encoder_->overuse_detector_proxy_->GetOptions()
5549 .high_encode_usage_threshold_percent,
5550 hardware_options.high_encode_usage_threshold_percent);
5551 video_stream_encoder_->Stop();
5552}
5553
Niels Möller6bb5ab92019-01-11 11:11:10 +01005554TEST_F(VideoStreamEncoderTest, DropsFramesWhenEncoderOvershoots) {
5555 const int kFrameWidth = 320;
5556 const int kFrameHeight = 240;
5557 const int kFps = 30;
5558 const int kTargetBitrateBps = 120000;
5559 const int kNumFramesInRun = kFps * 5; // Runs of five seconds.
5560
Henrik Boström381d1092020-05-12 18:49:07 +02005561 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005562 DataRate::BitsPerSec(kTargetBitrateBps),
5563 DataRate::BitsPerSec(kTargetBitrateBps),
5564 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Niels Möller6bb5ab92019-01-11 11:11:10 +01005565
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02005566 int64_t timestamp_ms = CurrentTimeMs();
Niels Möller6bb5ab92019-01-11 11:11:10 +01005567 max_framerate_ = kFps;
5568
5569 // Insert 3 seconds of video, verify number of drops with normal bitrate.
5570 fake_encoder_.SimulateOvershoot(1.0);
5571 int num_dropped = 0;
5572 for (int i = 0; i < kNumFramesInRun; ++i) {
5573 video_source_.IncomingCapturedFrame(
5574 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
5575 // Wait up to two frame durations for a frame to arrive.
5576 if (!TimedWaitForEncodedFrame(timestamp_ms, 2 * 1000 / kFps)) {
5577 ++num_dropped;
5578 }
5579 timestamp_ms += 1000 / kFps;
5580 }
5581
Erik Språnga8d48ab2019-02-08 14:17:40 +01005582 // Framerate should be measured to be near the expected target rate.
5583 EXPECT_NEAR(fake_encoder_.GetLastFramerate(), kFps, 1);
5584
5585 // Frame drops should be within 5% of expected 0%.
5586 EXPECT_NEAR(num_dropped, 0, 5 * kNumFramesInRun / 100);
Niels Möller6bb5ab92019-01-11 11:11:10 +01005587
5588 // Make encoder produce frames at double the expected bitrate during 3 seconds
5589 // of video, verify number of drops. Rate needs to be slightly changed in
5590 // order to force the rate to be reconfigured.
Erik Språng7ca375c2019-02-06 16:20:17 +01005591 double overshoot_factor = 2.0;
Erik Språng9d69cbe2020-10-22 17:44:42 +02005592 const RateControlSettings trials =
5593 RateControlSettings::ParseFromFieldTrials();
5594 if (trials.UseEncoderBitrateAdjuster()) {
Erik Språng7ca375c2019-02-06 16:20:17 +01005595 // With bitrate adjuster, when need to overshoot even more to trigger
Erik Språng9d69cbe2020-10-22 17:44:42 +02005596 // frame dropping since the adjuter will try to just lower the target
5597 // bitrate rather than drop frames. If network headroom can be used, it
5598 // doesn't push back as hard so we don't need quite as much overshoot.
5599 // These numbers are unfortunately a bit magical but there's not trivial
5600 // way to algebraically infer them.
5601 if (trials.BitrateAdjusterCanUseNetworkHeadroom()) {
5602 overshoot_factor = 2.4;
5603 } else {
5604 overshoot_factor = 4.0;
5605 }
Erik Språng7ca375c2019-02-06 16:20:17 +01005606 }
5607 fake_encoder_.SimulateOvershoot(overshoot_factor);
Henrik Boström381d1092020-05-12 18:49:07 +02005608 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005609 DataRate::BitsPerSec(kTargetBitrateBps + 1000),
5610 DataRate::BitsPerSec(kTargetBitrateBps + 1000),
5611 DataRate::BitsPerSec(kTargetBitrateBps + 1000), 0, 0, 0);
Niels Möller6bb5ab92019-01-11 11:11:10 +01005612 num_dropped = 0;
5613 for (int i = 0; i < kNumFramesInRun; ++i) {
5614 video_source_.IncomingCapturedFrame(
5615 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
5616 // Wait up to two frame durations for a frame to arrive.
5617 if (!TimedWaitForEncodedFrame(timestamp_ms, 2 * 1000 / kFps)) {
5618 ++num_dropped;
5619 }
5620 timestamp_ms += 1000 / kFps;
5621 }
5622
Henrik Boström381d1092020-05-12 18:49:07 +02005623 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005624 DataRate::BitsPerSec(kTargetBitrateBps),
5625 DataRate::BitsPerSec(kTargetBitrateBps),
5626 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Erik Språnga8d48ab2019-02-08 14:17:40 +01005627
5628 // Target framerate should be still be near the expected target, despite
5629 // the frame drops.
5630 EXPECT_NEAR(fake_encoder_.GetLastFramerate(), kFps, 1);
5631
5632 // Frame drops should be within 5% of expected 50%.
5633 EXPECT_NEAR(num_dropped, kNumFramesInRun / 2, 5 * kNumFramesInRun / 100);
Niels Möller6bb5ab92019-01-11 11:11:10 +01005634
5635 video_stream_encoder_->Stop();
5636}
5637
5638TEST_F(VideoStreamEncoderTest, ConfiguresCorrectFrameRate) {
5639 const int kFrameWidth = 320;
5640 const int kFrameHeight = 240;
5641 const int kActualInputFps = 24;
5642 const int kTargetBitrateBps = 120000;
5643
5644 ASSERT_GT(max_framerate_, kActualInputFps);
5645
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02005646 int64_t timestamp_ms = CurrentTimeMs();
Niels Möller6bb5ab92019-01-11 11:11:10 +01005647 max_framerate_ = kActualInputFps;
Henrik Boström381d1092020-05-12 18:49:07 +02005648 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005649 DataRate::BitsPerSec(kTargetBitrateBps),
5650 DataRate::BitsPerSec(kTargetBitrateBps),
5651 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Niels Möller6bb5ab92019-01-11 11:11:10 +01005652
5653 // Insert 3 seconds of video, with an input fps lower than configured max.
5654 for (int i = 0; i < kActualInputFps * 3; ++i) {
5655 video_source_.IncomingCapturedFrame(
5656 CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
5657 // Wait up to two frame durations for a frame to arrive.
5658 WaitForEncodedFrame(timestamp_ms);
5659 timestamp_ms += 1000 / kActualInputFps;
5660 }
5661
5662 EXPECT_NEAR(kActualInputFps, fake_encoder_.GetLastFramerate(), 1);
5663
5664 video_stream_encoder_->Stop();
5665}
5666
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02005667TEST_F(VideoStreamEncoderBlockedTest, AccumulatesUpdateRectOnDroppedFrames) {
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01005668 VideoFrame::UpdateRect rect;
Henrik Boström381d1092020-05-12 18:49:07 +02005669 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005670 DataRate::BitsPerSec(kTargetBitrateBps),
5671 DataRate::BitsPerSec(kTargetBitrateBps),
5672 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Ilya Nikolaevskiy71aee3a2019-02-18 13:01:26 +01005673
5674 fake_encoder_.BlockNextEncode();
5675 video_source_.IncomingCapturedFrame(
5676 CreateFrameWithUpdatedPixel(1, nullptr, 0));
5677 WaitForEncodedFrame(1);
5678 // On the very first frame full update should be forced.
5679 rect = fake_encoder_.GetLastUpdateRect();
5680 EXPECT_EQ(rect.offset_x, 0);
5681 EXPECT_EQ(rect.offset_y, 0);
5682 EXPECT_EQ(rect.height, codec_height_);
5683 EXPECT_EQ(rect.width, codec_width_);
5684 // Here, the encoder thread will be blocked in the TestEncoder waiting for a
5685 // call to ContinueEncode.
5686 video_source_.IncomingCapturedFrame(
5687 CreateFrameWithUpdatedPixel(2, nullptr, 1));
5688 ExpectDroppedFrame();
5689 video_source_.IncomingCapturedFrame(
5690 CreateFrameWithUpdatedPixel(3, nullptr, 10));
5691 ExpectDroppedFrame();
5692 fake_encoder_.ContinueEncode();
5693 WaitForEncodedFrame(3);
5694 // Updates to pixels 1 and 10 should be accumulated to one 10x1 rect.
5695 rect = fake_encoder_.GetLastUpdateRect();
5696 EXPECT_EQ(rect.offset_x, 1);
5697 EXPECT_EQ(rect.offset_y, 0);
5698 EXPECT_EQ(rect.width, 10);
5699 EXPECT_EQ(rect.height, 1);
5700
5701 video_source_.IncomingCapturedFrame(
5702 CreateFrameWithUpdatedPixel(4, nullptr, 0));
5703 WaitForEncodedFrame(4);
5704 // Previous frame was encoded, so no accumulation should happen.
5705 rect = fake_encoder_.GetLastUpdateRect();
5706 EXPECT_EQ(rect.offset_x, 0);
5707 EXPECT_EQ(rect.offset_y, 0);
5708 EXPECT_EQ(rect.width, 1);
5709 EXPECT_EQ(rect.height, 1);
5710
5711 video_stream_encoder_->Stop();
5712}
5713
Erik Språngd7329ca2019-02-21 21:19:53 +01005714TEST_F(VideoStreamEncoderTest, SetsFrameTypes) {
Henrik Boström381d1092020-05-12 18:49:07 +02005715 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005716 DataRate::BitsPerSec(kTargetBitrateBps),
5717 DataRate::BitsPerSec(kTargetBitrateBps),
5718 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Erik Språngd7329ca2019-02-21 21:19:53 +01005719
5720 // First frame is always keyframe.
5721 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
5722 WaitForEncodedFrame(1);
Niels Möller8f7ce222019-03-21 15:43:58 +01005723 EXPECT_THAT(
5724 fake_encoder_.LastFrameTypes(),
Mirko Bonadei6a489f22019-04-09 15:11:12 +02005725 ::testing::ElementsAre(VideoFrameType{VideoFrameType::kVideoFrameKey}));
Erik Språngd7329ca2019-02-21 21:19:53 +01005726
5727 // Insert delta frame.
5728 video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
5729 WaitForEncodedFrame(2);
Niels Möller8f7ce222019-03-21 15:43:58 +01005730 EXPECT_THAT(
5731 fake_encoder_.LastFrameTypes(),
Mirko Bonadei6a489f22019-04-09 15:11:12 +02005732 ::testing::ElementsAre(VideoFrameType{VideoFrameType::kVideoFrameDelta}));
Erik Språngd7329ca2019-02-21 21:19:53 +01005733
5734 // Request next frame be a key-frame.
5735 video_stream_encoder_->SendKeyFrame();
5736 video_source_.IncomingCapturedFrame(CreateFrame(3, nullptr));
5737 WaitForEncodedFrame(3);
Niels Möller8f7ce222019-03-21 15:43:58 +01005738 EXPECT_THAT(
5739 fake_encoder_.LastFrameTypes(),
Mirko Bonadei6a489f22019-04-09 15:11:12 +02005740 ::testing::ElementsAre(VideoFrameType{VideoFrameType::kVideoFrameKey}));
Erik Språngd7329ca2019-02-21 21:19:53 +01005741
5742 video_stream_encoder_->Stop();
5743}
5744
5745TEST_F(VideoStreamEncoderTest, SetsFrameTypesSimulcast) {
5746 // Setup simulcast with three streams.
5747 ResetEncoder("VP8", 3, 1, 1, false);
Henrik Boström381d1092020-05-12 18:49:07 +02005748 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005749 DataRate::BitsPerSec(kSimulcastTargetBitrateBps),
5750 DataRate::BitsPerSec(kSimulcastTargetBitrateBps),
5751 DataRate::BitsPerSec(kSimulcastTargetBitrateBps), 0, 0, 0);
Erik Språngd7329ca2019-02-21 21:19:53 +01005752 // Wait for all three layers before triggering event.
5753 sink_.SetNumExpectedLayers(3);
5754
5755 // First frame is always keyframe.
5756 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
5757 WaitForEncodedFrame(1);
5758 EXPECT_THAT(fake_encoder_.LastFrameTypes(),
Mirko Bonadei6a489f22019-04-09 15:11:12 +02005759 ::testing::ElementsAreArray({VideoFrameType::kVideoFrameKey,
5760 VideoFrameType::kVideoFrameKey,
5761 VideoFrameType::kVideoFrameKey}));
Erik Språngd7329ca2019-02-21 21:19:53 +01005762
5763 // Insert delta frame.
5764 video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
5765 WaitForEncodedFrame(2);
5766 EXPECT_THAT(fake_encoder_.LastFrameTypes(),
Mirko Bonadei6a489f22019-04-09 15:11:12 +02005767 ::testing::ElementsAreArray({VideoFrameType::kVideoFrameDelta,
5768 VideoFrameType::kVideoFrameDelta,
5769 VideoFrameType::kVideoFrameDelta}));
Erik Språngd7329ca2019-02-21 21:19:53 +01005770
5771 // Request next frame be a key-frame.
5772 // Only first stream is configured to produce key-frame.
5773 video_stream_encoder_->SendKeyFrame();
5774 video_source_.IncomingCapturedFrame(CreateFrame(3, nullptr));
5775 WaitForEncodedFrame(3);
Sergey Silkine62a08a2019-05-13 13:45:39 +02005776
5777 // TODO(webrtc:10615): Map keyframe request to spatial layer. Currently
5778 // keyframe request on any layer triggers keyframe on all layers.
Erik Språngd7329ca2019-02-21 21:19:53 +01005779 EXPECT_THAT(fake_encoder_.LastFrameTypes(),
Mirko Bonadei6a489f22019-04-09 15:11:12 +02005780 ::testing::ElementsAreArray({VideoFrameType::kVideoFrameKey,
Sergey Silkine62a08a2019-05-13 13:45:39 +02005781 VideoFrameType::kVideoFrameKey,
5782 VideoFrameType::kVideoFrameKey}));
Erik Språngd7329ca2019-02-21 21:19:53 +01005783
5784 video_stream_encoder_->Stop();
5785}
5786
5787TEST_F(VideoStreamEncoderTest, RequestKeyframeInternalSource) {
5788 // Configure internal source factory and setup test again.
5789 encoder_factory_.SetHasInternalSource(true);
5790 ResetEncoder("VP8", 1, 1, 1, false);
Henrik Boström381d1092020-05-12 18:49:07 +02005791 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005792 DataRate::BitsPerSec(kTargetBitrateBps),
5793 DataRate::BitsPerSec(kTargetBitrateBps),
5794 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Erik Språngd7329ca2019-02-21 21:19:53 +01005795
5796 // Call encoder directly, simulating internal source where encoded frame
5797 // callback in VideoStreamEncoder is called despite no OnFrame().
5798 fake_encoder_.InjectFrame(CreateFrame(1, nullptr), true);
5799 EXPECT_TRUE(WaitForFrame(kDefaultTimeoutMs));
Niels Möller8f7ce222019-03-21 15:43:58 +01005800 EXPECT_THAT(
5801 fake_encoder_.LastFrameTypes(),
Mirko Bonadei6a489f22019-04-09 15:11:12 +02005802 ::testing::ElementsAre(VideoFrameType{VideoFrameType::kVideoFrameKey}));
Erik Språngd7329ca2019-02-21 21:19:53 +01005803
Niels Möller8f7ce222019-03-21 15:43:58 +01005804 const std::vector<VideoFrameType> kDeltaFrame = {
5805 VideoFrameType::kVideoFrameDelta};
Erik Språngd7329ca2019-02-21 21:19:53 +01005806 // Need to set timestamp manually since manually for injected frame.
5807 VideoFrame frame = CreateFrame(101, nullptr);
5808 frame.set_timestamp(101);
5809 fake_encoder_.InjectFrame(frame, false);
5810 EXPECT_TRUE(WaitForFrame(kDefaultTimeoutMs));
Niels Möller8f7ce222019-03-21 15:43:58 +01005811 EXPECT_THAT(
5812 fake_encoder_.LastFrameTypes(),
Mirko Bonadei6a489f22019-04-09 15:11:12 +02005813 ::testing::ElementsAre(VideoFrameType{VideoFrameType::kVideoFrameDelta}));
Erik Språngd7329ca2019-02-21 21:19:53 +01005814
5815 // Request key-frame. The forces a dummy frame down into the encoder.
5816 fake_encoder_.ExpectNullFrame();
5817 video_stream_encoder_->SendKeyFrame();
5818 EXPECT_TRUE(WaitForFrame(kDefaultTimeoutMs));
Niels Möller8f7ce222019-03-21 15:43:58 +01005819 EXPECT_THAT(
5820 fake_encoder_.LastFrameTypes(),
Mirko Bonadei6a489f22019-04-09 15:11:12 +02005821 ::testing::ElementsAre(VideoFrameType{VideoFrameType::kVideoFrameKey}));
Erik Språngd7329ca2019-02-21 21:19:53 +01005822
5823 video_stream_encoder_->Stop();
5824}
Erik Språngb7cb7b52019-02-26 15:52:33 +01005825
5826TEST_F(VideoStreamEncoderTest, AdjustsTimestampInternalSource) {
5827 // Configure internal source factory and setup test again.
5828 encoder_factory_.SetHasInternalSource(true);
5829 ResetEncoder("VP8", 1, 1, 1, false);
Henrik Boström381d1092020-05-12 18:49:07 +02005830 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005831 DataRate::BitsPerSec(kTargetBitrateBps),
5832 DataRate::BitsPerSec(kTargetBitrateBps),
5833 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Erik Språngb7cb7b52019-02-26 15:52:33 +01005834
5835 int64_t timestamp = 1;
5836 EncodedImage image;
Niels Möller4d504c72019-06-18 15:56:56 +02005837 image.SetEncodedData(
5838 EncodedImageBuffer::Create(kTargetBitrateBps / kDefaultFramerate / 8));
Erik Språngb7cb7b52019-02-26 15:52:33 +01005839 image.capture_time_ms_ = ++timestamp;
5840 image.SetTimestamp(static_cast<uint32_t>(timestamp * 90));
5841 const int64_t kEncodeFinishDelayMs = 10;
5842 image.timing_.encode_start_ms = timestamp;
5843 image.timing_.encode_finish_ms = timestamp + kEncodeFinishDelayMs;
5844 fake_encoder_.InjectEncodedImage(image);
5845 // Wait for frame without incrementing clock.
5846 EXPECT_TRUE(sink_.WaitForFrame(kDefaultTimeoutMs));
5847 // Frame is captured kEncodeFinishDelayMs before it's encoded, so restored
5848 // capture timestamp should be kEncodeFinishDelayMs in the past.
5849 EXPECT_EQ(sink_.GetLastCaptureTimeMs(),
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02005850 CurrentTimeMs() - kEncodeFinishDelayMs);
Erik Språngb7cb7b52019-02-26 15:52:33 +01005851
5852 video_stream_encoder_->Stop();
5853}
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +02005854
5855TEST_F(VideoStreamEncoderTest, DoesNotRewriteH264BitstreamWithOptimalSps) {
Mirta Dvornicic97910da2020-07-14 15:29:23 +02005856 // SPS contains VUI with restrictions on the maximum number of reordered
5857 // pictures, there is no need to rewrite the bitstream to enable faster
5858 // decoding.
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +02005859 ResetEncoder("H264", 1, 1, 1, false);
5860
Mirta Dvornicic97910da2020-07-14 15:29:23 +02005861 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
5862 DataRate::BitsPerSec(kTargetBitrateBps),
5863 DataRate::BitsPerSec(kTargetBitrateBps),
5864 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
5865 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +02005866
Mirta Dvornicic97910da2020-07-14 15:29:23 +02005867 fake_encoder_.SetEncodedImageData(
5868 EncodedImageBuffer::Create(optimal_sps, sizeof(optimal_sps)));
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +02005869
Mirta Dvornicic97910da2020-07-14 15:29:23 +02005870 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
5871 WaitForEncodedFrame(1);
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +02005872
5873 EXPECT_THAT(sink_.GetLastEncodedImageData(),
5874 testing::ElementsAreArray(optimal_sps));
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +02005875
5876 video_stream_encoder_->Stop();
5877}
5878
5879TEST_F(VideoStreamEncoderTest, RewritesH264BitstreamWithNonOptimalSps) {
Mirta Dvornicic97910da2020-07-14 15:29:23 +02005880 // SPS does not contain VUI, the bitstream is will be rewritten with added
5881 // VUI with restrictions on the maximum number of reordered pictures to
5882 // enable faster decoding.
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +02005883 uint8_t original_sps[] = {0, 0, 0, 1, H264::NaluType::kSps,
5884 0x00, 0x00, 0x03, 0x03, 0xF4,
5885 0x05, 0x03, 0xC7, 0xC0};
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +02005886 ResetEncoder("H264", 1, 1, 1, false);
5887
Mirta Dvornicic97910da2020-07-14 15:29:23 +02005888 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
5889 DataRate::BitsPerSec(kTargetBitrateBps),
5890 DataRate::BitsPerSec(kTargetBitrateBps),
5891 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
5892 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +02005893
Mirta Dvornicic97910da2020-07-14 15:29:23 +02005894 fake_encoder_.SetEncodedImageData(
5895 EncodedImageBuffer::Create(original_sps, sizeof(original_sps)));
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +02005896
Mirta Dvornicic97910da2020-07-14 15:29:23 +02005897 video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
5898 WaitForEncodedFrame(1);
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +02005899
5900 EXPECT_THAT(sink_.GetLastEncodedImageData(),
5901 testing::ElementsAreArray(optimal_sps));
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +02005902
5903 video_stream_encoder_->Stop();
5904}
5905
Ilya Nikolaevskiyba96e2f2019-06-04 15:15:14 +02005906TEST_F(VideoStreamEncoderTest, CopiesVideoFrameMetadataAfterDownscale) {
5907 const int kFrameWidth = 1280;
5908 const int kFrameHeight = 720;
5909 const int kTargetBitrateBps = 300000; // To low for HD resolution.
5910
Henrik Boström381d1092020-05-12 18:49:07 +02005911 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005912 DataRate::BitsPerSec(kTargetBitrateBps),
5913 DataRate::BitsPerSec(kTargetBitrateBps),
5914 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Ilya Nikolaevskiyba96e2f2019-06-04 15:15:14 +02005915 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
5916
5917 // Insert a first video frame. It should be dropped because of downscale in
5918 // resolution.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02005919 int64_t timestamp_ms = CurrentTimeMs();
Ilya Nikolaevskiyba96e2f2019-06-04 15:15:14 +02005920 VideoFrame frame = CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight);
5921 frame.set_rotation(kVideoRotation_270);
5922 video_source_.IncomingCapturedFrame(frame);
5923
5924 ExpectDroppedFrame();
5925
5926 // Second frame is downscaled.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02005927 timestamp_ms = CurrentTimeMs();
Ilya Nikolaevskiyba96e2f2019-06-04 15:15:14 +02005928 frame = CreateFrame(timestamp_ms, kFrameWidth / 2, kFrameHeight / 2);
5929 frame.set_rotation(kVideoRotation_90);
5930 video_source_.IncomingCapturedFrame(frame);
5931
5932 WaitForEncodedFrame(timestamp_ms);
5933 sink_.CheckLastFrameRotationMatches(kVideoRotation_90);
5934
5935 // Insert another frame, also downscaled.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02005936 timestamp_ms = CurrentTimeMs();
Ilya Nikolaevskiyba96e2f2019-06-04 15:15:14 +02005937 frame = CreateFrame(timestamp_ms, kFrameWidth / 2, kFrameHeight / 2);
5938 frame.set_rotation(kVideoRotation_180);
5939 video_source_.IncomingCapturedFrame(frame);
5940
5941 WaitForEncodedFrame(timestamp_ms);
5942 sink_.CheckLastFrameRotationMatches(kVideoRotation_180);
5943
5944 video_stream_encoder_->Stop();
5945}
5946
Erik Språng5056af02019-09-02 15:53:11 +02005947TEST_F(VideoStreamEncoderTest, BandwidthAllocationLowerBound) {
5948 const int kFrameWidth = 320;
5949 const int kFrameHeight = 180;
5950
5951 // Initial rate.
Henrik Boström381d1092020-05-12 18:49:07 +02005952 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005953 /*target_bitrate=*/DataRate::KilobitsPerSec(300),
5954 /*stable_target_bitrate=*/DataRate::KilobitsPerSec(300),
5955 /*link_allocation=*/DataRate::KilobitsPerSec(300),
Erik Språng5056af02019-09-02 15:53:11 +02005956 /*fraction_lost=*/0,
Ying Wang9b881ab2020-02-07 14:29:32 +01005957 /*rtt_ms=*/0,
5958 /*cwnd_reduce_ratio=*/0);
Erik Språng5056af02019-09-02 15:53:11 +02005959
5960 // Insert a first video frame so that encoder gets configured.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02005961 int64_t timestamp_ms = CurrentTimeMs();
Erik Språng5056af02019-09-02 15:53:11 +02005962 VideoFrame frame = CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight);
5963 frame.set_rotation(kVideoRotation_270);
5964 video_source_.IncomingCapturedFrame(frame);
5965 WaitForEncodedFrame(timestamp_ms);
5966
5967 // Set a target rate below the minimum allowed by the codec settings.
5968 VideoCodec codec_config = fake_encoder_.codec_config();
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005969 DataRate min_rate = DataRate::KilobitsPerSec(codec_config.minBitrate);
5970 DataRate target_rate = min_rate - DataRate::KilobitsPerSec(1);
Henrik Boström381d1092020-05-12 18:49:07 +02005971 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Erik Språng5056af02019-09-02 15:53:11 +02005972 /*target_bitrate=*/target_rate,
Florent Castellia8336d32019-09-09 13:36:55 +02005973 /*stable_target_bitrate=*/target_rate,
Erik Språng5056af02019-09-02 15:53:11 +02005974 /*link_allocation=*/target_rate,
5975 /*fraction_lost=*/0,
Ying Wang9b881ab2020-02-07 14:29:32 +01005976 /*rtt_ms=*/0,
5977 /*cwnd_reduce_ratio=*/0);
Erik Språng5056af02019-09-02 15:53:11 +02005978 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
5979
5980 // Target bitrate and bandwidth allocation should both be capped at min_rate.
5981 auto rate_settings = fake_encoder_.GetAndResetLastRateControlSettings();
5982 ASSERT_TRUE(rate_settings.has_value());
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005983 DataRate allocation_sum =
5984 DataRate::BitsPerSec(rate_settings->bitrate.get_sum_bps());
Erik Språng5056af02019-09-02 15:53:11 +02005985 EXPECT_EQ(min_rate, allocation_sum);
5986 EXPECT_EQ(rate_settings->bandwidth_allocation, min_rate);
5987
5988 video_stream_encoder_->Stop();
5989}
5990
Rasmus Brandt5cad55b2019-12-19 09:47:11 +01005991TEST_F(VideoStreamEncoderTest, EncoderRatesPropagatedOnReconfigure) {
Henrik Boström381d1092020-05-12 18:49:07 +02005992 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01005993 DataRate::BitsPerSec(kTargetBitrateBps),
5994 DataRate::BitsPerSec(kTargetBitrateBps),
5995 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Evan Shrubsolee32ae4f2019-09-25 12:50:23 +02005996 // Capture a frame and wait for it to synchronize with the encoder thread.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02005997 int64_t timestamp_ms = CurrentTimeMs();
Evan Shrubsolee32ae4f2019-09-25 12:50:23 +02005998 video_source_.IncomingCapturedFrame(CreateFrame(timestamp_ms, nullptr));
5999 WaitForEncodedFrame(1);
6000
6001 auto prev_rate_settings = fake_encoder_.GetAndResetLastRateControlSettings();
6002 ASSERT_TRUE(prev_rate_settings.has_value());
6003 EXPECT_EQ(static_cast<int>(prev_rate_settings->framerate_fps),
6004 kDefaultFramerate);
6005
6006 // Send 1s of video to ensure the framerate is stable at kDefaultFramerate.
6007 for (int i = 0; i < 2 * kDefaultFramerate; i++) {
6008 timestamp_ms += 1000 / kDefaultFramerate;
6009 video_source_.IncomingCapturedFrame(CreateFrame(timestamp_ms, nullptr));
6010 WaitForEncodedFrame(timestamp_ms);
6011 }
6012 EXPECT_EQ(static_cast<int>(fake_encoder_.GetLastFramerate()),
6013 kDefaultFramerate);
6014 // Capture larger frame to trigger a reconfigure.
6015 codec_height_ *= 2;
6016 codec_width_ *= 2;
6017 timestamp_ms += 1000 / kDefaultFramerate;
6018 video_source_.IncomingCapturedFrame(CreateFrame(timestamp_ms, nullptr));
6019 WaitForEncodedFrame(timestamp_ms);
6020
6021 EXPECT_EQ(2, sink_.number_of_reconfigurations());
6022 auto current_rate_settings =
6023 fake_encoder_.GetAndResetLastRateControlSettings();
6024 // Ensure we have actually reconfigured twice
6025 // The rate settings should have been set again even though
6026 // they haven't changed.
6027 ASSERT_TRUE(current_rate_settings.has_value());
Evan Shrubsole7c079f62019-09-26 09:55:03 +02006028 EXPECT_EQ(prev_rate_settings, current_rate_settings);
Evan Shrubsolee32ae4f2019-09-25 12:50:23 +02006029
6030 video_stream_encoder_->Stop();
6031}
6032
philipeld9cc8c02019-09-16 14:53:40 +02006033struct MockEncoderSwitchRequestCallback : public EncoderSwitchRequestCallback {
Danil Chapovalov91fdc602020-05-14 19:17:51 +02006034 MOCK_METHOD(void, RequestEncoderFallback, (), (override));
6035 MOCK_METHOD(void, RequestEncoderSwitch, (const Config& conf), (override));
6036 MOCK_METHOD(void,
6037 RequestEncoderSwitch,
6038 (const webrtc::SdpVideoFormat& format),
6039 (override));
philipeld9cc8c02019-09-16 14:53:40 +02006040};
6041
6042TEST_F(VideoStreamEncoderTest, BitrateEncoderSwitch) {
6043 constexpr int kDontCare = 100;
6044
6045 StrictMock<MockEncoderSwitchRequestCallback> switch_callback;
6046 video_send_config_.encoder_settings.encoder_switch_request_callback =
6047 &switch_callback;
6048 VideoEncoderConfig encoder_config = video_encoder_config_.Copy();
6049 encoder_config.codec_type = kVideoCodecVP8;
6050 webrtc::test::ScopedFieldTrials field_trial(
6051 "WebRTC-NetworkCondition-EncoderSwitch/"
6052 "codec_thresholds:VP8;100;-1|H264;-1;30000,"
6053 "to_codec:AV1,to_param:ping,to_value:pong,window:2.0/");
6054
6055 // Reset encoder for new configuration to take effect.
6056 ConfigureEncoder(std::move(encoder_config));
6057
6058 // Send one frame to trigger ReconfigureEncoder.
6059 video_source_.IncomingCapturedFrame(
6060 CreateFrame(kDontCare, kDontCare, kDontCare));
6061
6062 using Config = EncoderSwitchRequestCallback::Config;
philipel9b058032020-02-10 11:30:00 +01006063 EXPECT_CALL(switch_callback, RequestEncoderSwitch(Matcher<const Config&>(
6064 AllOf(Field(&Config::codec_name, "AV1"),
philipeld9cc8c02019-09-16 14:53:40 +02006065 Field(&Config::param, "ping"),
philipel9b058032020-02-10 11:30:00 +01006066 Field(&Config::value, "pong")))));
philipeld9cc8c02019-09-16 14:53:40 +02006067
Henrik Boström381d1092020-05-12 18:49:07 +02006068 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01006069 /*target_bitrate=*/DataRate::KilobitsPerSec(50),
6070 /*stable_target_bitrate=*/DataRate::KilobitsPerSec(kDontCare),
6071 /*link_allocation=*/DataRate::KilobitsPerSec(kDontCare),
philipeld9cc8c02019-09-16 14:53:40 +02006072 /*fraction_lost=*/0,
Ying Wang9b881ab2020-02-07 14:29:32 +01006073 /*rtt_ms=*/0,
6074 /*cwnd_reduce_ratio=*/0);
Tomas Gunnarssond41c2a62020-09-21 15:56:42 +02006075 AdvanceTime(TimeDelta::Millis(0));
philipeld9cc8c02019-09-16 14:53:40 +02006076
6077 video_stream_encoder_->Stop();
6078}
6079
Mirta Dvornicic5ed40cf2020-02-21 16:35:51 +01006080TEST_F(VideoStreamEncoderTest, VideoSuspendedNoEncoderSwitch) {
6081 constexpr int kDontCare = 100;
6082
6083 StrictMock<MockEncoderSwitchRequestCallback> switch_callback;
6084 video_send_config_.encoder_settings.encoder_switch_request_callback =
6085 &switch_callback;
6086 VideoEncoderConfig encoder_config = video_encoder_config_.Copy();
6087 encoder_config.codec_type = kVideoCodecVP8;
6088 webrtc::test::ScopedFieldTrials field_trial(
6089 "WebRTC-NetworkCondition-EncoderSwitch/"
6090 "codec_thresholds:VP8;100;-1|H264;-1;30000,"
6091 "to_codec:AV1,to_param:ping,to_value:pong,window:2.0/");
6092
6093 // Reset encoder for new configuration to take effect.
6094 ConfigureEncoder(std::move(encoder_config));
6095
6096 // Send one frame to trigger ReconfigureEncoder.
6097 video_source_.IncomingCapturedFrame(
6098 CreateFrame(kDontCare, kDontCare, kDontCare));
6099
6100 using Config = EncoderSwitchRequestCallback::Config;
6101 EXPECT_CALL(switch_callback, RequestEncoderSwitch(Matcher<const Config&>(_)))
6102 .Times(0);
6103
Henrik Boström381d1092020-05-12 18:49:07 +02006104 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Mirta Dvornicic5ed40cf2020-02-21 16:35:51 +01006105 /*target_bitrate=*/DataRate::KilobitsPerSec(0),
6106 /*stable_target_bitrate=*/DataRate::KilobitsPerSec(0),
6107 /*link_allocation=*/DataRate::KilobitsPerSec(kDontCare),
6108 /*fraction_lost=*/0,
6109 /*rtt_ms=*/0,
6110 /*cwnd_reduce_ratio=*/0);
6111
6112 video_stream_encoder_->Stop();
6113}
6114
philipeld9cc8c02019-09-16 14:53:40 +02006115TEST_F(VideoStreamEncoderTest, ResolutionEncoderSwitch) {
6116 constexpr int kSufficientBitrateToNotDrop = 1000;
6117 constexpr int kHighRes = 500;
6118 constexpr int kLowRes = 100;
6119
6120 StrictMock<MockEncoderSwitchRequestCallback> switch_callback;
6121 video_send_config_.encoder_settings.encoder_switch_request_callback =
6122 &switch_callback;
6123 webrtc::test::ScopedFieldTrials field_trial(
6124 "WebRTC-NetworkCondition-EncoderSwitch/"
6125 "codec_thresholds:VP8;120;-1|H264;-1;30000,"
6126 "to_codec:AV1,to_param:ping,to_value:pong,window:2.0/");
6127 VideoEncoderConfig encoder_config = video_encoder_config_.Copy();
6128 encoder_config.codec_type = kVideoCodecH264;
6129
6130 // Reset encoder for new configuration to take effect.
6131 ConfigureEncoder(std::move(encoder_config));
6132
6133 // The VideoStreamEncoder needs some bitrate before it can start encoding,
6134 // setting some bitrate so that subsequent calls to WaitForEncodedFrame does
6135 // not fail.
Henrik Boström381d1092020-05-12 18:49:07 +02006136 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01006137 /*target_bitrate=*/DataRate::KilobitsPerSec(kSufficientBitrateToNotDrop),
6138 /*stable_target_bitrate=*/
6139 DataRate::KilobitsPerSec(kSufficientBitrateToNotDrop),
6140 /*link_allocation=*/DataRate::KilobitsPerSec(kSufficientBitrateToNotDrop),
philipeld9cc8c02019-09-16 14:53:40 +02006141 /*fraction_lost=*/0,
Ying Wang9b881ab2020-02-07 14:29:32 +01006142 /*rtt_ms=*/0,
6143 /*cwnd_reduce_ratio=*/0);
philipeld9cc8c02019-09-16 14:53:40 +02006144
6145 // Send one frame to trigger ReconfigureEncoder.
6146 video_source_.IncomingCapturedFrame(CreateFrame(1, kHighRes, kHighRes));
6147 WaitForEncodedFrame(1);
6148
6149 using Config = EncoderSwitchRequestCallback::Config;
philipel9b058032020-02-10 11:30:00 +01006150 EXPECT_CALL(switch_callback, RequestEncoderSwitch(Matcher<const Config&>(
6151 AllOf(Field(&Config::codec_name, "AV1"),
philipeld9cc8c02019-09-16 14:53:40 +02006152 Field(&Config::param, "ping"),
philipel9b058032020-02-10 11:30:00 +01006153 Field(&Config::value, "pong")))));
philipeld9cc8c02019-09-16 14:53:40 +02006154
6155 video_source_.IncomingCapturedFrame(CreateFrame(2, kLowRes, kLowRes));
6156 WaitForEncodedFrame(2);
6157
6158 video_stream_encoder_->Stop();
6159}
6160
philipel9b058032020-02-10 11:30:00 +01006161TEST_F(VideoStreamEncoderTest, EncoderSelectorCurrentEncoderIsSignaled) {
6162 constexpr int kDontCare = 100;
6163 StrictMock<MockEncoderSelector> encoder_selector;
6164 auto encoder_factory = std::make_unique<test::VideoEncoderProxyFactory>(
6165 &fake_encoder_, &encoder_selector);
6166 video_send_config_.encoder_settings.encoder_factory = encoder_factory.get();
6167
6168 // Reset encoder for new configuration to take effect.
6169 ConfigureEncoder(video_encoder_config_.Copy());
6170
6171 EXPECT_CALL(encoder_selector, OnCurrentEncoder(_));
6172
6173 video_source_.IncomingCapturedFrame(
6174 CreateFrame(kDontCare, kDontCare, kDontCare));
6175 video_stream_encoder_->Stop();
6176
6177 // The encoders produces by the VideoEncoderProxyFactory have a pointer back
6178 // to it's factory, so in order for the encoder instance in the
6179 // |video_stream_encoder_| to be destroyed before the |encoder_factory| we
6180 // reset the |video_stream_encoder_| here.
6181 video_stream_encoder_.reset();
6182}
6183
6184TEST_F(VideoStreamEncoderTest, EncoderSelectorBitrateSwitch) {
6185 constexpr int kDontCare = 100;
6186
6187 NiceMock<MockEncoderSelector> encoder_selector;
6188 StrictMock<MockEncoderSwitchRequestCallback> switch_callback;
6189 video_send_config_.encoder_settings.encoder_switch_request_callback =
6190 &switch_callback;
6191 auto encoder_factory = std::make_unique<test::VideoEncoderProxyFactory>(
6192 &fake_encoder_, &encoder_selector);
6193 video_send_config_.encoder_settings.encoder_factory = encoder_factory.get();
6194
6195 // Reset encoder for new configuration to take effect.
6196 ConfigureEncoder(video_encoder_config_.Copy());
6197
Mirta Dvornicic4f34d782020-02-26 13:01:19 +01006198 ON_CALL(encoder_selector, OnAvailableBitrate(_))
philipel9b058032020-02-10 11:30:00 +01006199 .WillByDefault(Return(SdpVideoFormat("AV1")));
6200 EXPECT_CALL(switch_callback,
6201 RequestEncoderSwitch(Matcher<const SdpVideoFormat&>(
6202 Field(&SdpVideoFormat::name, "AV1"))));
6203
Henrik Boström381d1092020-05-12 18:49:07 +02006204 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01006205 /*target_bitrate=*/DataRate::KilobitsPerSec(50),
6206 /*stable_target_bitrate=*/DataRate::KilobitsPerSec(kDontCare),
6207 /*link_allocation=*/DataRate::KilobitsPerSec(kDontCare),
philipel9b058032020-02-10 11:30:00 +01006208 /*fraction_lost=*/0,
6209 /*rtt_ms=*/0,
6210 /*cwnd_reduce_ratio=*/0);
Tomas Gunnarssond41c2a62020-09-21 15:56:42 +02006211 AdvanceTime(TimeDelta::Millis(0));
philipel9b058032020-02-10 11:30:00 +01006212
6213 video_stream_encoder_->Stop();
6214}
6215
6216TEST_F(VideoStreamEncoderTest, EncoderSelectorBrokenEncoderSwitch) {
6217 constexpr int kSufficientBitrateToNotDrop = 1000;
6218 constexpr int kDontCare = 100;
6219
6220 NiceMock<MockVideoEncoder> video_encoder;
6221 NiceMock<MockEncoderSelector> encoder_selector;
6222 StrictMock<MockEncoderSwitchRequestCallback> switch_callback;
6223 video_send_config_.encoder_settings.encoder_switch_request_callback =
6224 &switch_callback;
6225 auto encoder_factory = std::make_unique<test::VideoEncoderProxyFactory>(
6226 &video_encoder, &encoder_selector);
6227 video_send_config_.encoder_settings.encoder_factory = encoder_factory.get();
6228
6229 // Reset encoder for new configuration to take effect.
6230 ConfigureEncoder(video_encoder_config_.Copy());
6231
6232 // The VideoStreamEncoder needs some bitrate before it can start encoding,
6233 // setting some bitrate so that subsequent calls to WaitForEncodedFrame does
6234 // not fail.
Henrik Boström381d1092020-05-12 18:49:07 +02006235 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01006236 /*target_bitrate=*/DataRate::KilobitsPerSec(kSufficientBitrateToNotDrop),
6237 /*stable_target_bitrate=*/
6238 DataRate::KilobitsPerSec(kSufficientBitrateToNotDrop),
6239 /*link_allocation=*/DataRate::KilobitsPerSec(kSufficientBitrateToNotDrop),
philipel9b058032020-02-10 11:30:00 +01006240 /*fraction_lost=*/0,
6241 /*rtt_ms=*/0,
6242 /*cwnd_reduce_ratio=*/0);
6243
6244 ON_CALL(video_encoder, Encode(_, _))
6245 .WillByDefault(Return(WEBRTC_VIDEO_CODEC_ENCODER_FAILURE));
6246 ON_CALL(encoder_selector, OnEncoderBroken())
6247 .WillByDefault(Return(SdpVideoFormat("AV2")));
6248
6249 rtc::Event encode_attempted;
6250 EXPECT_CALL(switch_callback,
6251 RequestEncoderSwitch(Matcher<const SdpVideoFormat&>(_)))
6252 .WillOnce([&encode_attempted](const SdpVideoFormat& format) {
6253 EXPECT_EQ(format.name, "AV2");
6254 encode_attempted.Set();
6255 });
6256
6257 video_source_.IncomingCapturedFrame(CreateFrame(1, kDontCare, kDontCare));
6258 encode_attempted.Wait(3000);
6259
Tomas Gunnarssond41c2a62020-09-21 15:56:42 +02006260 AdvanceTime(TimeDelta::Millis(0));
6261
philipel9b058032020-02-10 11:30:00 +01006262 video_stream_encoder_->Stop();
6263
6264 // The encoders produces by the VideoEncoderProxyFactory have a pointer back
6265 // to it's factory, so in order for the encoder instance in the
6266 // |video_stream_encoder_| to be destroyed before the |encoder_factory| we
6267 // reset the |video_stream_encoder_| here.
6268 video_stream_encoder_.reset();
6269}
6270
Evan Shrubsole7c079f62019-09-26 09:55:03 +02006271TEST_F(VideoStreamEncoderTest,
Rasmus Brandt5cad55b2019-12-19 09:47:11 +01006272 AllocationPropagatedToEncoderWhenTargetRateChanged) {
Evan Shrubsole7c079f62019-09-26 09:55:03 +02006273 const int kFrameWidth = 320;
6274 const int kFrameHeight = 180;
6275
6276 // Set initial rate.
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01006277 auto rate = DataRate::KilobitsPerSec(100);
Henrik Boström381d1092020-05-12 18:49:07 +02006278 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Evan Shrubsole7c079f62019-09-26 09:55:03 +02006279 /*target_bitrate=*/rate,
6280 /*stable_target_bitrate=*/rate,
6281 /*link_allocation=*/rate,
6282 /*fraction_lost=*/0,
Ying Wang9b881ab2020-02-07 14:29:32 +01006283 /*rtt_ms=*/0,
6284 /*cwnd_reduce_ratio=*/0);
Evan Shrubsole7c079f62019-09-26 09:55:03 +02006285
6286 // Insert a first video frame so that encoder gets configured.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02006287 int64_t timestamp_ms = CurrentTimeMs();
Evan Shrubsole7c079f62019-09-26 09:55:03 +02006288 VideoFrame frame = CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight);
6289 frame.set_rotation(kVideoRotation_270);
6290 video_source_.IncomingCapturedFrame(frame);
6291 WaitForEncodedFrame(timestamp_ms);
6292 EXPECT_EQ(1, fake_encoder_.GetNumSetRates());
6293
6294 // Change of target bitrate propagates to the encoder.
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01006295 auto new_stable_rate = rate - DataRate::KilobitsPerSec(5);
Henrik Boström381d1092020-05-12 18:49:07 +02006296 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Evan Shrubsole7c079f62019-09-26 09:55:03 +02006297 /*target_bitrate=*/new_stable_rate,
6298 /*stable_target_bitrate=*/new_stable_rate,
6299 /*link_allocation=*/rate,
6300 /*fraction_lost=*/0,
Ying Wang9b881ab2020-02-07 14:29:32 +01006301 /*rtt_ms=*/0,
6302 /*cwnd_reduce_ratio=*/0);
Evan Shrubsole7c079f62019-09-26 09:55:03 +02006303 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
6304 EXPECT_EQ(2, fake_encoder_.GetNumSetRates());
6305 video_stream_encoder_->Stop();
6306}
6307
6308TEST_F(VideoStreamEncoderTest,
Rasmus Brandt5cad55b2019-12-19 09:47:11 +01006309 AllocationNotPropagatedToEncoderWhenTargetRateUnchanged) {
Evan Shrubsole7c079f62019-09-26 09:55:03 +02006310 const int kFrameWidth = 320;
6311 const int kFrameHeight = 180;
6312
6313 // Set initial rate.
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01006314 auto rate = DataRate::KilobitsPerSec(100);
Henrik Boström381d1092020-05-12 18:49:07 +02006315 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Evan Shrubsole7c079f62019-09-26 09:55:03 +02006316 /*target_bitrate=*/rate,
6317 /*stable_target_bitrate=*/rate,
6318 /*link_allocation=*/rate,
6319 /*fraction_lost=*/0,
Ying Wang9b881ab2020-02-07 14:29:32 +01006320 /*rtt_ms=*/0,
6321 /*cwnd_reduce_ratio=*/0);
Evan Shrubsole7c079f62019-09-26 09:55:03 +02006322
6323 // Insert a first video frame so that encoder gets configured.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02006324 int64_t timestamp_ms = CurrentTimeMs();
Evan Shrubsole7c079f62019-09-26 09:55:03 +02006325 VideoFrame frame = CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight);
6326 frame.set_rotation(kVideoRotation_270);
6327 video_source_.IncomingCapturedFrame(frame);
6328 WaitForEncodedFrame(timestamp_ms);
6329 EXPECT_EQ(1, fake_encoder_.GetNumSetRates());
6330
6331 // Set a higher target rate without changing the link_allocation. Should not
6332 // reset encoder's rate.
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01006333 auto new_stable_rate = rate - DataRate::KilobitsPerSec(5);
Henrik Boström381d1092020-05-12 18:49:07 +02006334 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Evan Shrubsole7c079f62019-09-26 09:55:03 +02006335 /*target_bitrate=*/rate,
6336 /*stable_target_bitrate=*/new_stable_rate,
6337 /*link_allocation=*/rate,
6338 /*fraction_lost=*/0,
Ying Wang9b881ab2020-02-07 14:29:32 +01006339 /*rtt_ms=*/0,
6340 /*cwnd_reduce_ratio=*/0);
Evan Shrubsole7c079f62019-09-26 09:55:03 +02006341 video_stream_encoder_->WaitUntilTaskQueueIsIdle();
6342 EXPECT_EQ(1, fake_encoder_.GetNumSetRates());
6343 video_stream_encoder_->Stop();
6344}
6345
Ilya Nikolaevskiy648b9d72019-12-03 16:54:17 +01006346TEST_F(VideoStreamEncoderTest, AutomaticAnimationDetection) {
6347 test::ScopedFieldTrials field_trials(
6348 "WebRTC-AutomaticAnimationDetectionScreenshare/"
6349 "enabled:true,min_fps:20,min_duration_ms:1000,min_area_ratio:0.8/");
6350 const int kFramerateFps = 30;
6351 const int kWidth = 1920;
6352 const int kHeight = 1080;
6353 const int kNumFrames = 2 * kFramerateFps; // >1 seconds of frames.
6354 // Works on screenshare mode.
6355 ResetEncoder("VP8", 1, 1, 1, /*screenshare*/ true);
6356 // We rely on the automatic resolution adaptation, but we handle framerate
6357 // adaptation manually by mocking the stats proxy.
6358 video_source_.set_adaptation_enabled(true);
6359
6360 // BALANCED degradation preference is required for this feature.
Henrik Boström381d1092020-05-12 18:49:07 +02006361 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
Danil Chapovalovcad3e0e2020-02-17 18:46:07 +01006362 DataRate::BitsPerSec(kTargetBitrateBps),
6363 DataRate::BitsPerSec(kTargetBitrateBps),
6364 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
Ilya Nikolaevskiy648b9d72019-12-03 16:54:17 +01006365 video_stream_encoder_->SetSource(&video_source_,
6366 webrtc::DegradationPreference::BALANCED);
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02006367 EXPECT_THAT(video_source_.sink_wants(), UnlimitedSinkWants());
Ilya Nikolaevskiy648b9d72019-12-03 16:54:17 +01006368
6369 VideoFrame frame = CreateFrame(1, kWidth, kHeight);
6370 frame.set_update_rect(VideoFrame::UpdateRect{0, 0, kWidth, kHeight});
6371
6372 // Pass enough frames with the full update to trigger animation detection.
6373 for (int i = 0; i < kNumFrames; ++i) {
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02006374 int64_t timestamp_ms = CurrentTimeMs();
Ilya Nikolaevskiy648b9d72019-12-03 16:54:17 +01006375 frame.set_ntp_time_ms(timestamp_ms);
6376 frame.set_timestamp_us(timestamp_ms * 1000);
6377 video_source_.IncomingCapturedFrame(frame);
6378 WaitForEncodedFrame(timestamp_ms);
6379 }
6380
6381 // Resolution should be limited.
6382 rtc::VideoSinkWants expected;
6383 expected.max_framerate_fps = kFramerateFps;
6384 expected.max_pixel_count = 1280 * 720 + 1;
Evan Shrubsole5fd40602020-05-25 16:19:54 +02006385 EXPECT_THAT(video_source_.sink_wants(), FpsEqResolutionLt(expected));
Ilya Nikolaevskiy648b9d72019-12-03 16:54:17 +01006386
6387 // Pass one frame with no known update.
6388 // Resolution cap should be removed immediately.
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02006389 int64_t timestamp_ms = CurrentTimeMs();
Ilya Nikolaevskiy648b9d72019-12-03 16:54:17 +01006390 frame.set_ntp_time_ms(timestamp_ms);
6391 frame.set_timestamp_us(timestamp_ms * 1000);
6392 frame.clear_update_rect();
6393
6394 video_source_.IncomingCapturedFrame(frame);
6395 WaitForEncodedFrame(timestamp_ms);
6396
6397 // Resolution should be unlimited now.
Evan Shrubsole5cd7eb82020-05-25 14:08:39 +02006398 EXPECT_THAT(video_source_.sink_wants(),
6399 FpsMatchesResolutionMax(Eq(kFramerateFps)));
Ilya Nikolaevskiy648b9d72019-12-03 16:54:17 +01006400
6401 video_stream_encoder_->Stop();
6402}
6403
Ilya Nikolaevskiy09eb6e22020-06-05 12:36:32 +02006404TEST_F(VideoStreamEncoderTest, ConfiguresVp9SvcAtOddResolutions) {
6405 const int kWidth = 720; // 540p adapted down.
6406 const int kHeight = 405;
6407 const int kNumFrames = 3;
6408 // Works on screenshare mode.
6409 ResetEncoder("VP9", /*num_streams=*/1, /*num_temporal_layers=*/1,
6410 /*num_spatial_layers=*/2, /*screenshare=*/true);
6411
6412 video_source_.set_adaptation_enabled(true);
6413
6414 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
6415 DataRate::BitsPerSec(kTargetBitrateBps),
6416 DataRate::BitsPerSec(kTargetBitrateBps),
6417 DataRate::BitsPerSec(kTargetBitrateBps), 0, 0, 0);
6418
6419 VideoFrame frame = CreateFrame(1, kWidth, kHeight);
6420
6421 // Pass enough frames with the full update to trigger animation detection.
6422 for (int i = 0; i < kNumFrames; ++i) {
Tomas Gunnarsson612445e2020-09-21 14:31:23 +02006423 int64_t timestamp_ms = CurrentTimeMs();
Ilya Nikolaevskiy09eb6e22020-06-05 12:36:32 +02006424 frame.set_ntp_time_ms(timestamp_ms);
6425 frame.set_timestamp_us(timestamp_ms * 1000);
6426 video_source_.IncomingCapturedFrame(frame);
6427 WaitForEncodedFrame(timestamp_ms);
6428 }
6429
6430 video_stream_encoder_->Stop();
6431}
6432
Yun Zhang1e4d4fd2020-09-30 00:22:46 -07006433TEST_F(VideoStreamEncoderTest, EncoderResetAccordingToParameterChange) {
6434 const float downscale_factors[] = {4.0, 2.0, 1.0};
6435 const int number_layers =
6436 sizeof(downscale_factors) / sizeof(downscale_factors[0]);
6437 VideoEncoderConfig config;
6438 test::FillEncoderConfiguration(kVideoCodecVP8, number_layers, &config);
6439 for (int i = 0; i < number_layers; ++i) {
6440 config.simulcast_layers[i].scale_resolution_down_by = downscale_factors[i];
6441 config.simulcast_layers[i].active = true;
6442 }
6443 config.video_stream_factory =
6444 new rtc::RefCountedObject<cricket::EncoderStreamFactory>(
6445 "VP8", /*max qp*/ 56, /*screencast*/ false,
6446 /*screenshare enabled*/ false);
6447 video_stream_encoder_->OnBitrateUpdatedAndWaitForManagedResources(
6448 DataRate::BitsPerSec(kSimulcastTargetBitrateBps),
6449 DataRate::BitsPerSec(kSimulcastTargetBitrateBps),
6450 DataRate::BitsPerSec(kSimulcastTargetBitrateBps), 0, 0, 0);
6451
6452 // First initialization.
6453 // Encoder should be initialized. Next frame should be key frame.
6454 video_stream_encoder_->ConfigureEncoder(config.Copy(), kMaxPayloadLength);
6455 sink_.SetNumExpectedLayers(number_layers);
6456 int64_t timestamp_ms = kFrameIntervalMs;
6457 video_source_.IncomingCapturedFrame(CreateFrame(timestamp_ms, 1280, 720));
6458 WaitForEncodedFrame(timestamp_ms);
6459 EXPECT_EQ(1, fake_encoder_.GetNumEncoderInitializations());
6460 EXPECT_THAT(fake_encoder_.LastFrameTypes(),
6461 ::testing::ElementsAreArray({VideoFrameType::kVideoFrameKey,
6462 VideoFrameType::kVideoFrameKey,
6463 VideoFrameType::kVideoFrameKey}));
6464
6465 // Disable top layer.
6466 // Encoder shouldn't be re-initialized. Next frame should be delta frame.
6467 config.simulcast_layers[number_layers - 1].active = false;
6468 video_stream_encoder_->ConfigureEncoder(config.Copy(), kMaxPayloadLength);
6469 sink_.SetNumExpectedLayers(number_layers - 1);
6470 timestamp_ms += kFrameIntervalMs;
6471 video_source_.IncomingCapturedFrame(CreateFrame(timestamp_ms, 1280, 720));
6472 WaitForEncodedFrame(timestamp_ms);
6473 EXPECT_EQ(1, fake_encoder_.GetNumEncoderInitializations());
6474 EXPECT_THAT(fake_encoder_.LastFrameTypes(),
6475 ::testing::ElementsAreArray({VideoFrameType::kVideoFrameDelta,
6476 VideoFrameType::kVideoFrameDelta,
6477 VideoFrameType::kVideoFrameDelta}));
6478
6479 // Re-enable top layer.
6480 // Encoder should be re-initialized. Next frame should be key frame.
6481 config.simulcast_layers[number_layers - 1].active = true;
6482 video_stream_encoder_->ConfigureEncoder(config.Copy(), kMaxPayloadLength);
6483 sink_.SetNumExpectedLayers(number_layers);
6484 timestamp_ms += kFrameIntervalMs;
6485 video_source_.IncomingCapturedFrame(CreateFrame(timestamp_ms, 1280, 720));
6486 WaitForEncodedFrame(timestamp_ms);
6487 EXPECT_EQ(2, fake_encoder_.GetNumEncoderInitializations());
6488 EXPECT_THAT(fake_encoder_.LastFrameTypes(),
6489 ::testing::ElementsAreArray({VideoFrameType::kVideoFrameKey,
6490 VideoFrameType::kVideoFrameKey,
6491 VideoFrameType::kVideoFrameKey}));
6492
6493 // Top layer max rate change.
6494 // Encoder shouldn't be re-initialized. Next frame should be delta frame.
6495 config.simulcast_layers[number_layers - 1].max_bitrate_bps -= 100;
6496 video_stream_encoder_->ConfigureEncoder(config.Copy(), kMaxPayloadLength);
6497 sink_.SetNumExpectedLayers(number_layers);
6498 timestamp_ms += kFrameIntervalMs;
6499 video_source_.IncomingCapturedFrame(CreateFrame(timestamp_ms, 1280, 720));
6500 WaitForEncodedFrame(timestamp_ms);
6501 EXPECT_EQ(2, fake_encoder_.GetNumEncoderInitializations());
6502 EXPECT_THAT(fake_encoder_.LastFrameTypes(),
6503 ::testing::ElementsAreArray({VideoFrameType::kVideoFrameDelta,
6504 VideoFrameType::kVideoFrameDelta,
6505 VideoFrameType::kVideoFrameDelta}));
6506
6507 // Top layer resolution change.
6508 // Encoder should be re-initialized. Next frame should be key frame.
6509 config.simulcast_layers[number_layers - 1].scale_resolution_down_by += 0.1;
6510 video_stream_encoder_->ConfigureEncoder(config.Copy(), kMaxPayloadLength);
6511 sink_.SetNumExpectedLayers(number_layers);
6512 timestamp_ms += kFrameIntervalMs;
6513 video_source_.IncomingCapturedFrame(CreateFrame(timestamp_ms, 1280, 720));
6514 WaitForEncodedFrame(timestamp_ms);
6515 EXPECT_EQ(3, fake_encoder_.GetNumEncoderInitializations());
6516 EXPECT_THAT(fake_encoder_.LastFrameTypes(),
6517 ::testing::ElementsAreArray({VideoFrameType::kVideoFrameKey,
6518 VideoFrameType::kVideoFrameKey,
6519 VideoFrameType::kVideoFrameKey}));
6520 video_stream_encoder_->Stop();
6521}
6522
perkj26091b12016-09-01 01:17:40 -07006523} // namespace webrtc