forked from JumpingYang001/webrtc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvideo_stream_encoder_unittest.cc
3153 lines (2675 loc) · 126 KB
/
video_stream_encoder_unittest.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <algorithm>
#include <limits>
#include <utility>
#include "api/video/i420_buffer.h"
#include "media/base/videoadapter.h"
#include "modules/video_coding/codecs/vp8/temporal_layers.h"
#include "modules/video_coding/codecs/vp9/include/vp9_globals.h"
#include "modules/video_coding/utility/default_video_bitrate_allocator.h"
#include "rtc_base/fakeclock.h"
#include "rtc_base/logging.h"
#include "rtc_base/refcountedobject.h"
#include "system_wrappers/include/metrics_default.h"
#include "system_wrappers/include/sleep.h"
#include "test/encoder_proxy_factory.h"
#include "test/encoder_settings.h"
#include "test/fake_encoder.h"
#include "test/frame_generator.h"
#include "test/gmock.h"
#include "test/gtest.h"
#include "video/send_statistics_proxy.h"
#include "video/video_stream_encoder.h"
namespace {
const int kMinPixelsPerFrame = 320 * 180;
const int kMinFramerateFps = 2;
const int kMinBalancedFramerateFps = 7;
const int64_t kFrameTimeoutMs = 100;
} // namespace
namespace webrtc {
using ScaleReason = AdaptationObserverInterface::AdaptReason;
using ::testing::_;
using ::testing::Return;
namespace {
const size_t kMaxPayloadLength = 1440;
const int kTargetBitrateBps = 1000000;
const int kLowTargetBitrateBps = kTargetBitrateBps / 10;
const int kMaxInitialFramedrop = 4;
const int kDefaultFramerate = 30;
class TestBuffer : public webrtc::I420Buffer {
public:
TestBuffer(rtc::Event* event, int width, int height)
: I420Buffer(width, height), event_(event) {}
private:
friend class rtc::RefCountedObject<TestBuffer>;
~TestBuffer() override {
if (event_)
event_->Set();
}
rtc::Event* const event_;
};
class CpuOveruseDetectorProxy : public OveruseFrameDetector {
public:
explicit CpuOveruseDetectorProxy(CpuOveruseMetricsObserver* metrics_observer)
: OveruseFrameDetector(metrics_observer),
last_target_framerate_fps_(-1) {}
virtual ~CpuOveruseDetectorProxy() {}
void OnTargetFramerateUpdated(int framerate_fps) override {
rtc::CritScope cs(&lock_);
last_target_framerate_fps_ = framerate_fps;
OveruseFrameDetector::OnTargetFramerateUpdated(framerate_fps);
}
int GetLastTargetFramerate() {
rtc::CritScope cs(&lock_);
return last_target_framerate_fps_;
}
CpuOveruseOptions GetOptions() { return options_; }
private:
rtc::CriticalSection lock_;
int last_target_framerate_fps_ RTC_GUARDED_BY(lock_);
};
class VideoStreamEncoderUnderTest : public VideoStreamEncoder {
public:
VideoStreamEncoderUnderTest(SendStatisticsProxy* stats_proxy,
const VideoStreamEncoderSettings& settings)
: VideoStreamEncoder(1 /* number_of_cores */,
stats_proxy,
settings,
nullptr /* pre_encode_callback */,
std::unique_ptr<OveruseFrameDetector>(
overuse_detector_proxy_ =
new CpuOveruseDetectorProxy(stats_proxy))) {}
void PostTaskAndWait(bool down, AdaptReason reason) {
rtc::Event event(false, false);
encoder_queue()->PostTask([this, &event, reason, down] {
down ? AdaptDown(reason) : AdaptUp(reason);
event.Set();
});
ASSERT_TRUE(event.Wait(5000));
}
// This is used as a synchronisation mechanism, to make sure that the
// encoder queue is not blocked before we start sending it frames.
void WaitUntilTaskQueueIsIdle() {
rtc::Event event(false, false);
encoder_queue()->PostTask([&event] { event.Set(); });
ASSERT_TRUE(event.Wait(5000));
}
void TriggerCpuOveruse() { PostTaskAndWait(true, AdaptReason::kCpu); }
void TriggerCpuNormalUsage() { PostTaskAndWait(false, AdaptReason::kCpu); }
void TriggerQualityLow() { PostTaskAndWait(true, AdaptReason::kQuality); }
void TriggerQualityHigh() { PostTaskAndWait(false, AdaptReason::kQuality); }
CpuOveruseDetectorProxy* overuse_detector_proxy_;
};
class VideoStreamFactory
: public VideoEncoderConfig::VideoStreamFactoryInterface {
public:
explicit VideoStreamFactory(size_t num_temporal_layers, int framerate)
: num_temporal_layers_(num_temporal_layers), framerate_(framerate) {
EXPECT_GT(num_temporal_layers, 0u);
EXPECT_GT(framerate, 0);
}
private:
std::vector<VideoStream> CreateEncoderStreams(
int width,
int height,
const VideoEncoderConfig& encoder_config) override {
std::vector<VideoStream> streams =
test::CreateVideoStreams(width, height, encoder_config);
for (VideoStream& stream : streams) {
stream.num_temporal_layers = num_temporal_layers_;
stream.max_framerate = framerate_;
}
return streams;
}
const size_t num_temporal_layers_;
const int framerate_;
};
class AdaptingFrameForwarder : public test::FrameForwarder {
public:
AdaptingFrameForwarder() : adaptation_enabled_(false) {}
~AdaptingFrameForwarder() override {}
void set_adaptation_enabled(bool enabled) {
rtc::CritScope cs(&crit_);
adaptation_enabled_ = enabled;
}
bool adaption_enabled() const {
rtc::CritScope cs(&crit_);
return adaptation_enabled_;
}
rtc::VideoSinkWants last_wants() const {
rtc::CritScope cs(&crit_);
return last_wants_;
}
absl::optional<int> last_sent_width() const { return last_width_; }
absl::optional<int> last_sent_height() const { return last_height_; }
void IncomingCapturedFrame(const VideoFrame& video_frame) override {
int cropped_width = 0;
int cropped_height = 0;
int out_width = 0;
int out_height = 0;
if (adaption_enabled()) {
if (adapter_.AdaptFrameResolution(
video_frame.width(), video_frame.height(),
video_frame.timestamp_us() * 1000, &cropped_width,
&cropped_height, &out_width, &out_height)) {
VideoFrame adapted_frame(new rtc::RefCountedObject<TestBuffer>(
nullptr, out_width, out_height),
99, 99, kVideoRotation_0);
adapted_frame.set_ntp_time_ms(video_frame.ntp_time_ms());
test::FrameForwarder::IncomingCapturedFrame(adapted_frame);
last_width_.emplace(adapted_frame.width());
last_height_.emplace(adapted_frame.height());
} else {
last_width_ = absl::nullopt;
last_height_ = absl::nullopt;
}
} else {
test::FrameForwarder::IncomingCapturedFrame(video_frame);
last_width_.emplace(video_frame.width());
last_height_.emplace(video_frame.height());
}
}
void AddOrUpdateSink(rtc::VideoSinkInterface<VideoFrame>* sink,
const rtc::VideoSinkWants& wants) override {
rtc::CritScope cs(&crit_);
last_wants_ = sink_wants();
adapter_.OnResolutionFramerateRequest(wants.target_pixel_count,
wants.max_pixel_count,
wants.max_framerate_fps);
test::FrameForwarder::AddOrUpdateSink(sink, wants);
}
cricket::VideoAdapter adapter_;
bool adaptation_enabled_ RTC_GUARDED_BY(crit_);
rtc::VideoSinkWants last_wants_ RTC_GUARDED_BY(crit_);
absl::optional<int> last_width_;
absl::optional<int> last_height_;
};
// TODO(nisse): Mock only VideoStreamEncoderObserver.
class MockableSendStatisticsProxy : public SendStatisticsProxy {
public:
MockableSendStatisticsProxy(Clock* clock,
const VideoSendStream::Config& config,
VideoEncoderConfig::ContentType content_type)
: SendStatisticsProxy(clock, config, content_type) {}
VideoSendStream::Stats GetStats() override {
rtc::CritScope cs(&lock_);
if (mock_stats_)
return *mock_stats_;
return SendStatisticsProxy::GetStats();
}
int GetInputFrameRate() const override {
rtc::CritScope cs(&lock_);
if (mock_stats_)
return mock_stats_->input_frame_rate;
return SendStatisticsProxy::GetInputFrameRate();
}
void SetMockStats(const VideoSendStream::Stats& stats) {
rtc::CritScope cs(&lock_);
mock_stats_.emplace(stats);
}
void ResetMockStats() {
rtc::CritScope cs(&lock_);
mock_stats_.reset();
}
private:
rtc::CriticalSection lock_;
absl::optional<VideoSendStream::Stats> mock_stats_ RTC_GUARDED_BY(lock_);
};
class MockBitrateObserver : public VideoBitrateAllocationObserver {
public:
MOCK_METHOD1(OnBitrateAllocationUpdated, void(const VideoBitrateAllocation&));
};
} // namespace
class VideoStreamEncoderTest : public ::testing::Test {
public:
static const int kDefaultTimeoutMs = 30 * 1000;
VideoStreamEncoderTest()
: video_send_config_(VideoSendStream::Config(nullptr)),
codec_width_(320),
codec_height_(240),
max_framerate_(30),
fake_encoder_(),
encoder_factory_(&fake_encoder_),
stats_proxy_(new MockableSendStatisticsProxy(
Clock::GetRealTimeClock(),
video_send_config_,
webrtc::VideoEncoderConfig::ContentType::kRealtimeVideo)),
sink_(&fake_encoder_) {}
void SetUp() override {
metrics::Reset();
video_send_config_ = VideoSendStream::Config(nullptr);
video_send_config_.encoder_settings.encoder_factory = &encoder_factory_;
video_send_config_.rtp.payload_name = "FAKE";
video_send_config_.rtp.payload_type = 125;
VideoEncoderConfig video_encoder_config;
test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
video_encoder_config.video_stream_factory =
new rtc::RefCountedObject<VideoStreamFactory>(1, max_framerate_);
video_encoder_config_ = video_encoder_config.Copy();
// Framerate limit is specified by the VideoStreamFactory.
std::vector<VideoStream> streams =
video_encoder_config.video_stream_factory->CreateEncoderStreams(
codec_width_, codec_height_, video_encoder_config);
max_framerate_ = streams[0].max_framerate;
fake_clock_.SetTimeMicros(1234);
ConfigureEncoder(std::move(video_encoder_config));
}
void ConfigureEncoder(VideoEncoderConfig video_encoder_config) {
if (video_stream_encoder_)
video_stream_encoder_->Stop();
video_stream_encoder_.reset(new VideoStreamEncoderUnderTest(
stats_proxy_.get(), video_send_config_.encoder_settings));
video_stream_encoder_->SetSink(&sink_, false /* rotation_applied */);
video_stream_encoder_->SetSource(
&video_source_, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
video_stream_encoder_->SetStartBitrate(kTargetBitrateBps);
video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config),
kMaxPayloadLength);
video_stream_encoder_->WaitUntilTaskQueueIsIdle();
}
void ResetEncoder(const std::string& payload_name,
size_t num_streams,
size_t num_temporal_layers,
unsigned char num_spatial_layers,
bool screenshare) {
video_send_config_.rtp.payload_name = payload_name;
VideoEncoderConfig video_encoder_config;
video_encoder_config.codec_type = PayloadStringToCodecType(payload_name);
video_encoder_config.number_of_streams = num_streams;
video_encoder_config.max_bitrate_bps = kTargetBitrateBps;
video_encoder_config.video_stream_factory =
new rtc::RefCountedObject<VideoStreamFactory>(num_temporal_layers,
kDefaultFramerate);
video_encoder_config.content_type =
screenshare ? VideoEncoderConfig::ContentType::kScreen
: VideoEncoderConfig::ContentType::kRealtimeVideo;
if (payload_name == "VP9") {
VideoCodecVP9 vp9_settings = VideoEncoder::GetDefaultVp9Settings();
vp9_settings.numberOfSpatialLayers = num_spatial_layers;
video_encoder_config.encoder_specific_settings =
new rtc::RefCountedObject<
VideoEncoderConfig::Vp9EncoderSpecificSettings>(vp9_settings);
}
ConfigureEncoder(std::move(video_encoder_config));
}
VideoFrame CreateFrame(int64_t ntp_time_ms,
rtc::Event* destruction_event) const {
VideoFrame frame(new rtc::RefCountedObject<TestBuffer>(
destruction_event, codec_width_, codec_height_),
99, 99, kVideoRotation_0);
frame.set_ntp_time_ms(ntp_time_ms);
return frame;
}
VideoFrame CreateFrame(int64_t ntp_time_ms, int width, int height) const {
VideoFrame frame(
new rtc::RefCountedObject<TestBuffer>(nullptr, width, height), 99, 99,
kVideoRotation_0);
frame.set_ntp_time_ms(ntp_time_ms);
frame.set_timestamp_us(ntp_time_ms * 1000);
return frame;
}
void VerifyNoLimitation(const rtc::VideoSinkWants& wants) {
EXPECT_EQ(std::numeric_limits<int>::max(), wants.max_framerate_fps);
EXPECT_EQ(std::numeric_limits<int>::max(), wants.max_pixel_count);
EXPECT_FALSE(wants.target_pixel_count);
}
void VerifyFpsEqResolutionEq(const rtc::VideoSinkWants& wants1,
const rtc::VideoSinkWants& wants2) {
EXPECT_EQ(wants1.max_framerate_fps, wants2.max_framerate_fps);
EXPECT_EQ(wants1.max_pixel_count, wants2.max_pixel_count);
}
void VerifyFpsMaxResolutionLt(const rtc::VideoSinkWants& wants1,
const rtc::VideoSinkWants& wants2) {
EXPECT_EQ(std::numeric_limits<int>::max(), wants1.max_framerate_fps);
EXPECT_LT(wants1.max_pixel_count, wants2.max_pixel_count);
EXPECT_GT(wants1.max_pixel_count, 0);
}
void VerifyFpsMaxResolutionGt(const rtc::VideoSinkWants& wants1,
const rtc::VideoSinkWants& wants2) {
EXPECT_EQ(std::numeric_limits<int>::max(), wants1.max_framerate_fps);
EXPECT_GT(wants1.max_pixel_count, wants2.max_pixel_count);
}
void VerifyFpsMaxResolutionEq(const rtc::VideoSinkWants& wants1,
const rtc::VideoSinkWants& wants2) {
EXPECT_EQ(std::numeric_limits<int>::max(), wants1.max_framerate_fps);
EXPECT_EQ(wants1.max_pixel_count, wants2.max_pixel_count);
}
void VerifyFpsLtResolutionEq(const rtc::VideoSinkWants& wants1,
const rtc::VideoSinkWants& wants2) {
EXPECT_LT(wants1.max_framerate_fps, wants2.max_framerate_fps);
EXPECT_EQ(wants1.max_pixel_count, wants2.max_pixel_count);
}
void VerifyFpsGtResolutionEq(const rtc::VideoSinkWants& wants1,
const rtc::VideoSinkWants& wants2) {
EXPECT_GT(wants1.max_framerate_fps, wants2.max_framerate_fps);
EXPECT_EQ(wants1.max_pixel_count, wants2.max_pixel_count);
}
void VerifyFpsEqResolutionLt(const rtc::VideoSinkWants& wants1,
const rtc::VideoSinkWants& wants2) {
EXPECT_EQ(wants1.max_framerate_fps, wants2.max_framerate_fps);
EXPECT_LT(wants1.max_pixel_count, wants2.max_pixel_count);
EXPECT_GT(wants1.max_pixel_count, 0);
}
void VerifyFpsEqResolutionGt(const rtc::VideoSinkWants& wants1,
const rtc::VideoSinkWants& wants2) {
EXPECT_EQ(wants1.max_framerate_fps, wants2.max_framerate_fps);
EXPECT_GT(wants1.max_pixel_count, wants2.max_pixel_count);
}
void VerifyFpsMaxResolutionLt(const rtc::VideoSinkWants& wants,
int pixel_count) {
EXPECT_EQ(std::numeric_limits<int>::max(), wants.max_framerate_fps);
EXPECT_LT(wants.max_pixel_count, pixel_count);
EXPECT_GT(wants.max_pixel_count, 0);
}
void VerifyFpsLtResolutionMax(const rtc::VideoSinkWants& wants, int fps) {
EXPECT_LT(wants.max_framerate_fps, fps);
EXPECT_EQ(std::numeric_limits<int>::max(), wants.max_pixel_count);
EXPECT_FALSE(wants.target_pixel_count);
}
void VerifyFpsEqResolutionMax(const rtc::VideoSinkWants& wants,
int expected_fps) {
EXPECT_EQ(expected_fps, wants.max_framerate_fps);
EXPECT_EQ(std::numeric_limits<int>::max(), wants.max_pixel_count);
EXPECT_FALSE(wants.target_pixel_count);
}
void VerifyBalancedModeFpsRange(const rtc::VideoSinkWants& wants,
int last_frame_pixels) {
// Balanced mode should always scale FPS to the desired range before
// attempting to scale resolution.
int fps_limit = wants.max_framerate_fps;
if (last_frame_pixels <= 320 * 240) {
EXPECT_TRUE(7 <= fps_limit && fps_limit <= 10);
} else if (last_frame_pixels <= 480 * 270) {
EXPECT_TRUE(10 <= fps_limit && fps_limit <= 15);
} else if (last_frame_pixels <= 640 * 480) {
EXPECT_LE(15, fps_limit);
} else {
EXPECT_EQ(std::numeric_limits<int>::max(), fps_limit);
}
}
void WaitForEncodedFrame(int64_t expected_ntp_time) {
sink_.WaitForEncodedFrame(expected_ntp_time);
fake_clock_.AdvanceTimeMicros(rtc::kNumMicrosecsPerSec / max_framerate_);
}
bool TimedWaitForEncodedFrame(int64_t expected_ntp_time, int64_t timeout_ms) {
bool ok = sink_.TimedWaitForEncodedFrame(expected_ntp_time, timeout_ms);
fake_clock_.AdvanceTimeMicros(rtc::kNumMicrosecsPerSec / max_framerate_);
return ok;
}
void WaitForEncodedFrame(uint32_t expected_width, uint32_t expected_height) {
sink_.WaitForEncodedFrame(expected_width, expected_height);
fake_clock_.AdvanceTimeMicros(rtc::kNumMicrosecsPerSec / max_framerate_);
}
void ExpectDroppedFrame() {
sink_.ExpectDroppedFrame();
fake_clock_.AdvanceTimeMicros(rtc::kNumMicrosecsPerSec / max_framerate_);
}
bool WaitForFrame(int64_t timeout_ms) {
bool ok = sink_.WaitForFrame(timeout_ms);
fake_clock_.AdvanceTimeMicros(rtc::kNumMicrosecsPerSec / max_framerate_);
return ok;
}
class TestEncoder : public test::FakeEncoder {
public:
TestEncoder()
: FakeEncoder(Clock::GetRealTimeClock()),
continue_encode_event_(false, false) {}
VideoCodec codec_config() const {
rtc::CritScope lock(&crit_sect_);
return config_;
}
void BlockNextEncode() {
rtc::CritScope lock(&local_crit_sect_);
block_next_encode_ = true;
}
VideoEncoder::ScalingSettings GetScalingSettings() const override {
rtc::CritScope lock(&local_crit_sect_);
if (quality_scaling_)
return VideoEncoder::ScalingSettings(1, 2, kMinPixelsPerFrame);
return VideoEncoder::ScalingSettings::kOff;
}
void ContinueEncode() { continue_encode_event_.Set(); }
void CheckLastTimeStampsMatch(int64_t ntp_time_ms,
uint32_t timestamp) const {
rtc::CritScope lock(&local_crit_sect_);
EXPECT_EQ(timestamp_, timestamp);
EXPECT_EQ(ntp_time_ms_, ntp_time_ms);
}
void SetQualityScaling(bool b) {
rtc::CritScope lock(&local_crit_sect_);
quality_scaling_ = b;
}
void ForceInitEncodeFailure(bool force_failure) {
rtc::CritScope lock(&local_crit_sect_);
force_init_encode_failed_ = force_failure;
}
private:
int32_t Encode(const VideoFrame& input_image,
const CodecSpecificInfo* codec_specific_info,
const std::vector<FrameType>* frame_types) override {
bool block_encode;
{
rtc::CritScope lock(&local_crit_sect_);
EXPECT_GT(input_image.timestamp(), timestamp_);
EXPECT_GT(input_image.ntp_time_ms(), ntp_time_ms_);
EXPECT_EQ(input_image.timestamp(), input_image.ntp_time_ms() * 90);
timestamp_ = input_image.timestamp();
ntp_time_ms_ = input_image.ntp_time_ms();
last_input_width_ = input_image.width();
last_input_height_ = input_image.height();
block_encode = block_next_encode_;
block_next_encode_ = false;
}
int32_t result =
FakeEncoder::Encode(input_image, codec_specific_info, frame_types);
if (block_encode)
EXPECT_TRUE(continue_encode_event_.Wait(kDefaultTimeoutMs));
return result;
}
int32_t InitEncode(const VideoCodec* config,
int32_t number_of_cores,
size_t max_payload_size) override {
int res =
FakeEncoder::InitEncode(config, number_of_cores, max_payload_size);
rtc::CritScope lock(&local_crit_sect_);
if (config->codecType == kVideoCodecVP8) {
// Simulate setting up temporal layers, in order to validate the life
// cycle of these objects.
int num_streams = std::max<int>(1, config->numberOfSimulcastStreams);
for (int i = 0; i < num_streams; ++i) {
allocated_temporal_layers_.emplace_back(
TemporalLayers::CreateTemporalLayers(*config, i));
}
}
if (force_init_encode_failed_)
return -1;
return res;
}
rtc::CriticalSection local_crit_sect_;
bool block_next_encode_ RTC_GUARDED_BY(local_crit_sect_) = false;
rtc::Event continue_encode_event_;
uint32_t timestamp_ RTC_GUARDED_BY(local_crit_sect_) = 0;
int64_t ntp_time_ms_ RTC_GUARDED_BY(local_crit_sect_) = 0;
int last_input_width_ RTC_GUARDED_BY(local_crit_sect_) = 0;
int last_input_height_ RTC_GUARDED_BY(local_crit_sect_) = 0;
bool quality_scaling_ RTC_GUARDED_BY(local_crit_sect_) = true;
std::vector<std::unique_ptr<TemporalLayers>> allocated_temporal_layers_
RTC_GUARDED_BY(local_crit_sect_);
bool force_init_encode_failed_ RTC_GUARDED_BY(local_crit_sect_) = false;
};
class TestSink : public VideoStreamEncoder::EncoderSink {
public:
explicit TestSink(TestEncoder* test_encoder)
: test_encoder_(test_encoder), encoded_frame_event_(false, false) {}
void WaitForEncodedFrame(int64_t expected_ntp_time) {
EXPECT_TRUE(
TimedWaitForEncodedFrame(expected_ntp_time, kDefaultTimeoutMs));
}
bool TimedWaitForEncodedFrame(int64_t expected_ntp_time,
int64_t timeout_ms) {
uint32_t timestamp = 0;
if (!encoded_frame_event_.Wait(timeout_ms))
return false;
{
rtc::CritScope lock(&crit_);
timestamp = last_timestamp_;
}
test_encoder_->CheckLastTimeStampsMatch(expected_ntp_time, timestamp);
return true;
}
void WaitForEncodedFrame(uint32_t expected_width,
uint32_t expected_height) {
EXPECT_TRUE(encoded_frame_event_.Wait(kDefaultTimeoutMs));
CheckLastFrameSizeMatches(expected_width, expected_height);
}
void CheckLastFrameSizeMatches(uint32_t expected_width,
uint32_t expected_height) {
uint32_t width = 0;
uint32_t height = 0;
{
rtc::CritScope lock(&crit_);
width = last_width_;
height = last_height_;
}
EXPECT_EQ(expected_height, height);
EXPECT_EQ(expected_width, width);
}
void ExpectDroppedFrame() { EXPECT_FALSE(encoded_frame_event_.Wait(100)); }
bool WaitForFrame(int64_t timeout_ms) {
return encoded_frame_event_.Wait(timeout_ms);
}
void SetExpectNoFrames() {
rtc::CritScope lock(&crit_);
expect_frames_ = false;
}
int number_of_reconfigurations() const {
rtc::CritScope lock(&crit_);
return number_of_reconfigurations_;
}
int last_min_transmit_bitrate() const {
rtc::CritScope lock(&crit_);
return min_transmit_bitrate_bps_;
}
private:
Result OnEncodedImage(
const EncodedImage& encoded_image,
const CodecSpecificInfo* codec_specific_info,
const RTPFragmentationHeader* fragmentation) override {
rtc::CritScope lock(&crit_);
EXPECT_TRUE(expect_frames_);
last_timestamp_ = encoded_image._timeStamp;
last_width_ = encoded_image._encodedWidth;
last_height_ = encoded_image._encodedHeight;
encoded_frame_event_.Set();
return Result(Result::OK, last_timestamp_);
}
void OnEncoderConfigurationChanged(std::vector<VideoStream> streams,
int min_transmit_bitrate_bps) override {
rtc::CriticalSection crit_;
++number_of_reconfigurations_;
min_transmit_bitrate_bps_ = min_transmit_bitrate_bps;
}
rtc::CriticalSection crit_;
TestEncoder* test_encoder_;
rtc::Event encoded_frame_event_;
uint32_t last_timestamp_ = 0;
uint32_t last_height_ = 0;
uint32_t last_width_ = 0;
bool expect_frames_ = true;
int number_of_reconfigurations_ = 0;
int min_transmit_bitrate_bps_ = 0;
};
VideoSendStream::Config video_send_config_;
VideoEncoderConfig video_encoder_config_;
int codec_width_;
int codec_height_;
int max_framerate_;
TestEncoder fake_encoder_;
test::EncoderProxyFactory encoder_factory_;
std::unique_ptr<MockableSendStatisticsProxy> stats_proxy_;
TestSink sink_;
AdaptingFrameForwarder video_source_;
std::unique_ptr<VideoStreamEncoderUnderTest> video_stream_encoder_;
rtc::ScopedFakeClock fake_clock_;
};
TEST_F(VideoStreamEncoderTest, EncodeOneFrame) {
video_stream_encoder_->OnBitrateUpdated(kTargetBitrateBps, 0, 0);
rtc::Event frame_destroyed_event(false, false);
video_source_.IncomingCapturedFrame(CreateFrame(1, &frame_destroyed_event));
WaitForEncodedFrame(1);
EXPECT_TRUE(frame_destroyed_event.Wait(kDefaultTimeoutMs));
video_stream_encoder_->Stop();
}
TEST_F(VideoStreamEncoderTest, DropsFramesBeforeFirstOnBitrateUpdated) {
// Dropped since no target bitrate has been set.
rtc::Event frame_destroyed_event(false, false);
// The encoder will cache up to one frame for a short duration. Adding two
// frames means that the first frame will be dropped and the second frame will
// be sent when the encoder is enabled.
video_source_.IncomingCapturedFrame(CreateFrame(1, &frame_destroyed_event));
video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
EXPECT_TRUE(frame_destroyed_event.Wait(kDefaultTimeoutMs));
video_stream_encoder_->OnBitrateUpdated(kTargetBitrateBps, 0, 0);
// The pending frame should be received.
WaitForEncodedFrame(2);
video_source_.IncomingCapturedFrame(CreateFrame(3, nullptr));
WaitForEncodedFrame(3);
video_stream_encoder_->Stop();
}
TEST_F(VideoStreamEncoderTest, DropsFramesWhenRateSetToZero) {
video_stream_encoder_->OnBitrateUpdated(kTargetBitrateBps, 0, 0);
video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
WaitForEncodedFrame(1);
video_stream_encoder_->OnBitrateUpdated(0, 0, 0);
// The encoder will cache up to one frame for a short duration. Adding two
// frames means that the first frame will be dropped and the second frame will
// be sent when the encoder is resumed.
video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
video_source_.IncomingCapturedFrame(CreateFrame(3, nullptr));
video_stream_encoder_->OnBitrateUpdated(kTargetBitrateBps, 0, 0);
WaitForEncodedFrame(3);
video_source_.IncomingCapturedFrame(CreateFrame(4, nullptr));
WaitForEncodedFrame(4);
video_stream_encoder_->Stop();
}
TEST_F(VideoStreamEncoderTest, DropsFramesWithSameOrOldNtpTimestamp) {
video_stream_encoder_->OnBitrateUpdated(kTargetBitrateBps, 0, 0);
video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
WaitForEncodedFrame(1);
// This frame will be dropped since it has the same ntp timestamp.
video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
WaitForEncodedFrame(2);
video_stream_encoder_->Stop();
}
TEST_F(VideoStreamEncoderTest, DropsFrameAfterStop) {
video_stream_encoder_->OnBitrateUpdated(kTargetBitrateBps, 0, 0);
video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
WaitForEncodedFrame(1);
video_stream_encoder_->Stop();
sink_.SetExpectNoFrames();
rtc::Event frame_destroyed_event(false, false);
video_source_.IncomingCapturedFrame(CreateFrame(2, &frame_destroyed_event));
EXPECT_TRUE(frame_destroyed_event.Wait(kDefaultTimeoutMs));
}
TEST_F(VideoStreamEncoderTest, DropsPendingFramesOnSlowEncode) {
video_stream_encoder_->OnBitrateUpdated(kTargetBitrateBps, 0, 0);
fake_encoder_.BlockNextEncode();
video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
WaitForEncodedFrame(1);
// Here, the encoder thread will be blocked in the TestEncoder waiting for a
// call to ContinueEncode.
video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
video_source_.IncomingCapturedFrame(CreateFrame(3, nullptr));
fake_encoder_.ContinueEncode();
WaitForEncodedFrame(3);
video_stream_encoder_->Stop();
}
TEST_F(VideoStreamEncoderTest,
ConfigureEncoderTriggersOnEncoderConfigurationChanged) {
video_stream_encoder_->OnBitrateUpdated(kTargetBitrateBps, 0, 0);
EXPECT_EQ(0, sink_.number_of_reconfigurations());
// Capture a frame and wait for it to synchronize with the encoder thread.
video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
WaitForEncodedFrame(1);
// The encoder will have been configured once when the first frame is
// received.
EXPECT_EQ(1, sink_.number_of_reconfigurations());
VideoEncoderConfig video_encoder_config;
test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
video_encoder_config.min_transmit_bitrate_bps = 9999;
video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config),
kMaxPayloadLength);
// Capture a frame and wait for it to synchronize with the encoder thread.
video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
WaitForEncodedFrame(2);
EXPECT_EQ(2, sink_.number_of_reconfigurations());
EXPECT_EQ(9999, sink_.last_min_transmit_bitrate());
video_stream_encoder_->Stop();
}
TEST_F(VideoStreamEncoderTest, FrameResolutionChangeReconfigureEncoder) {
video_stream_encoder_->OnBitrateUpdated(kTargetBitrateBps, 0, 0);
// Capture a frame and wait for it to synchronize with the encoder thread.
video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
WaitForEncodedFrame(1);
// The encoder will have been configured once.
EXPECT_EQ(1, sink_.number_of_reconfigurations());
EXPECT_EQ(codec_width_, fake_encoder_.codec_config().width);
EXPECT_EQ(codec_height_, fake_encoder_.codec_config().height);
codec_width_ *= 2;
codec_height_ *= 2;
// Capture a frame with a higher resolution and wait for it to synchronize
// with the encoder thread.
video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
WaitForEncodedFrame(2);
EXPECT_EQ(codec_width_, fake_encoder_.codec_config().width);
EXPECT_EQ(codec_height_, fake_encoder_.codec_config().height);
EXPECT_EQ(2, sink_.number_of_reconfigurations());
video_stream_encoder_->Stop();
}
TEST_F(VideoStreamEncoderTest, SwitchSourceDeregisterEncoderAsSink) {
EXPECT_TRUE(video_source_.has_sinks());
test::FrameForwarder new_video_source;
video_stream_encoder_->SetSource(
&new_video_source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
EXPECT_FALSE(video_source_.has_sinks());
EXPECT_TRUE(new_video_source.has_sinks());
video_stream_encoder_->Stop();
}
TEST_F(VideoStreamEncoderTest, SinkWantsRotationApplied) {
EXPECT_FALSE(video_source_.sink_wants().rotation_applied);
video_stream_encoder_->SetSink(&sink_, true /*rotation_applied*/);
EXPECT_TRUE(video_source_.sink_wants().rotation_applied);
video_stream_encoder_->Stop();
}
TEST_F(VideoStreamEncoderTest, TestCpuDowngrades_BalancedMode) {
const int kFramerateFps = 30;
const int kWidth = 1280;
const int kHeight = 720;
// We rely on the automatic resolution adaptation, but we handle framerate
// adaptation manually by mocking the stats proxy.
video_source_.set_adaptation_enabled(true);
// Enable BALANCED preference, no initial limitation.
video_stream_encoder_->OnBitrateUpdated(kTargetBitrateBps, 0, 0);
video_stream_encoder_->SetSource(&video_source_,
webrtc::DegradationPreference::BALANCED);
VerifyNoLimitation(video_source_.sink_wants());
EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
// Adapt down as far as possible.
rtc::VideoSinkWants last_wants;
int64_t t = 1;
int loop_count = 0;
do {
++loop_count;
last_wants = video_source_.sink_wants();
// Simulate the framerate we've been asked to adapt to.
const int fps = std::min(kFramerateFps, last_wants.max_framerate_fps);
const int frame_interval_ms = rtc::kNumMillisecsPerSec / fps;
VideoSendStream::Stats mock_stats = stats_proxy_->GetStats();
mock_stats.input_frame_rate = fps;
stats_proxy_->SetMockStats(mock_stats);
video_source_.IncomingCapturedFrame(CreateFrame(t, kWidth, kHeight));
sink_.WaitForEncodedFrame(t);
t += frame_interval_ms;
video_stream_encoder_->TriggerCpuOveruse();
VerifyBalancedModeFpsRange(
video_source_.sink_wants(),
*video_source_.last_sent_width() * *video_source_.last_sent_height());
} while (video_source_.sink_wants().max_pixel_count <
last_wants.max_pixel_count ||
video_source_.sink_wants().max_framerate_fps <
last_wants.max_framerate_fps);
// Verify that we've adapted all the way down.
stats_proxy_->ResetMockStats();
EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_framerate);
EXPECT_EQ(loop_count - 1,
stats_proxy_->GetStats().number_of_cpu_adapt_changes);
EXPECT_EQ(kMinPixelsPerFrame, *video_source_.last_sent_width() *
*video_source_.last_sent_height());
EXPECT_EQ(kMinBalancedFramerateFps,
video_source_.sink_wants().max_framerate_fps);
// Adapt back up the same number of times we adapted down.
for (int i = 0; i < loop_count - 1; ++i) {
last_wants = video_source_.sink_wants();
// Simulate the framerate we've been asked to adapt to.
const int fps = std::min(kFramerateFps, last_wants.max_framerate_fps);
const int frame_interval_ms = rtc::kNumMillisecsPerSec / fps;
VideoSendStream::Stats mock_stats = stats_proxy_->GetStats();
mock_stats.input_frame_rate = fps;
stats_proxy_->SetMockStats(mock_stats);
video_source_.IncomingCapturedFrame(CreateFrame(t, kWidth, kHeight));
sink_.WaitForEncodedFrame(t);
t += frame_interval_ms;
video_stream_encoder_->TriggerCpuNormalUsage();
VerifyBalancedModeFpsRange(
video_source_.sink_wants(),
*video_source_.last_sent_width() * *video_source_.last_sent_height());
EXPECT_TRUE(video_source_.sink_wants().max_pixel_count >
last_wants.max_pixel_count ||
video_source_.sink_wants().max_framerate_fps >
last_wants.max_framerate_fps);
}
VerifyNoLimitation(video_source_.sink_wants());
stats_proxy_->ResetMockStats();
EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
EXPECT_EQ((loop_count - 1) * 2,
stats_proxy_->GetStats().number_of_cpu_adapt_changes);
video_stream_encoder_->Stop();
}
TEST_F(VideoStreamEncoderTest, SinkWantsStoredByDegradationPreference) {
video_stream_encoder_->OnBitrateUpdated(kTargetBitrateBps, 0, 0);
VerifyNoLimitation(video_source_.sink_wants());
const int kFrameWidth = 1280;
const int kFrameHeight = 720;
const int kFrameIntervalMs = 1000 / 30;
int frame_timestamp = 1;
video_source_.IncomingCapturedFrame(
CreateFrame(frame_timestamp, kFrameWidth, kFrameHeight));
WaitForEncodedFrame(frame_timestamp);
frame_timestamp += kFrameIntervalMs;
// Trigger CPU overuse.
video_stream_encoder_->TriggerCpuOveruse();
video_source_.IncomingCapturedFrame(
CreateFrame(frame_timestamp, kFrameWidth, kFrameHeight));
WaitForEncodedFrame(frame_timestamp);
frame_timestamp += kFrameIntervalMs;
// Default degradation preference is maintain-framerate, so will lower max
// wanted resolution.
EXPECT_FALSE(video_source_.sink_wants().target_pixel_count);
EXPECT_LT(video_source_.sink_wants().max_pixel_count,
kFrameWidth * kFrameHeight);
EXPECT_EQ(std::numeric_limits<int>::max(),
video_source_.sink_wants().max_framerate_fps);
// Set new source, switch to maintain-resolution.
test::FrameForwarder new_video_source;
video_stream_encoder_->SetSource(
&new_video_source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
// Initially no degradation registered.
VerifyNoLimitation(new_video_source.sink_wants());
// Force an input frame rate to be available, or the adaptation call won't
// know what framerate to adapt form.
const int kInputFps = 30;
VideoSendStream::Stats stats = stats_proxy_->GetStats();
stats.input_frame_rate = kInputFps;
stats_proxy_->SetMockStats(stats);
video_stream_encoder_->TriggerCpuOveruse();
new_video_source.IncomingCapturedFrame(
CreateFrame(frame_timestamp, kFrameWidth, kFrameHeight));
WaitForEncodedFrame(frame_timestamp);
frame_timestamp += kFrameIntervalMs;
// Some framerate constraint should be set.
EXPECT_FALSE(new_video_source.sink_wants().target_pixel_count);
EXPECT_EQ(std::numeric_limits<int>::max(),