blob: 5e3090a0f8c578ef582e8631dfd67d4066cf4539 [file] [log] [blame]
ivica5d6a06c2015-09-17 05:30:24 -07001/*
2 * Copyright (c) 2015 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 */
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020010#include "video/video_quality_test.h"
perkj9fdbda62016-09-15 09:19:20 -070011
perkja49cbd32016-09-16 07:53:41 -070012#include <stdio.h>
ivica5d6a06c2015-09-17 05:30:24 -070013#include <algorithm>
14#include <deque>
15#include <map>
sprangce4aef12015-11-02 07:23:20 -080016#include <sstream>
mflodmand1590b22015-12-09 07:07:59 -080017#include <string>
ivica5d6a06c2015-09-17 05:30:24 -070018#include <vector>
19
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020020#include "api/optional.h"
21#include "call/call.h"
22#include "common_video/libyuv/include/webrtc_libyuv.h"
Elad Alon83ccca12017-10-04 13:18:26 +020023#include "logging/rtc_event_log/output/rtc_event_log_output_file.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020024#include "logging/rtc_event_log/rtc_event_log.h"
Magnus Jedvert46a27652017-11-13 14:10:02 +010025#include "media/engine/internalencoderfactory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020026#include "media/engine/webrtcvideoengine.h"
27#include "modules/audio_mixer/audio_mixer_impl.h"
28#include "modules/rtp_rtcp/include/rtp_header_parser.h"
29#include "modules/rtp_rtcp/source/rtp_format.h"
30#include "modules/rtp_rtcp/source/rtp_utility.h"
31#include "modules/video_coding/codecs/h264/include/h264.h"
32#include "modules/video_coding/codecs/vp8/include/vp8.h"
33#include "modules/video_coding/codecs/vp8/include/vp8_common_types.h"
34#include "modules/video_coding/codecs/vp9/include/vp9.h"
35#include "rtc_base/checks.h"
36#include "rtc_base/cpu_time.h"
37#include "rtc_base/event.h"
38#include "rtc_base/flags.h"
39#include "rtc_base/format_macros.h"
40#include "rtc_base/logging.h"
41#include "rtc_base/memory_usage.h"
42#include "rtc_base/pathutils.h"
43#include "rtc_base/platform_file.h"
44#include "rtc_base/ptr_util.h"
45#include "rtc_base/timeutils.h"
46#include "system_wrappers/include/cpu_info.h"
47#include "system_wrappers/include/field_trial.h"
48#include "test/gtest.h"
49#include "test/layer_filtering_transport.h"
50#include "test/run_loop.h"
51#include "test/statistics.h"
52#include "test/testsupport/fileutils.h"
53#include "test/testsupport/frame_writer.h"
Edward Lemuraf8659a2017-09-27 14:46:24 +020054#include "test/testsupport/test_artifacts.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020055#include "test/vcm_capturer.h"
56#include "test/video_renderer.h"
57#include "voice_engine/include/voe_base.h"
minyue73208662016-08-18 06:28:55 -070058
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020059#include "test/rtp_file_writer.h"
ilnik98436952017-07-13 00:47:03 -070060
ilnikee42d192017-08-22 07:16:20 -070061DEFINE_bool(save_worst_frame,
62 false,
63 "Enable saving a frame with the lowest PSNR to a jpeg file in the "
Edward Lemuraf8659a2017-09-27 14:46:24 +020064 "test_artifacts_dir");
ilnikee42d192017-08-22 07:16:20 -070065
minyue73208662016-08-18 06:28:55 -070066namespace {
67
68constexpr int kSendStatsPollingIntervalMs = 1000;
minyue20c84cc2017-04-10 16:57:57 -070069
minyue73208662016-08-18 06:28:55 -070070constexpr size_t kMaxComparisons = 10;
71constexpr char kSyncGroup[] = "av_sync";
minyue10cbb462016-11-07 09:29:22 -080072constexpr int kOpusMinBitrateBps = 6000;
73constexpr int kOpusBitrateFbBps = 32000;
ilnik9ae0d762017-02-15 00:53:12 -080074constexpr int kFramesSentInQuickTest = 1;
ilnika014cc52017-03-07 04:21:04 -080075constexpr uint32_t kThumbnailSendSsrcStart = 0xE0000;
76constexpr uint32_t kThumbnailRtxSsrcStart = 0xF0000;
minyue73208662016-08-18 06:28:55 -070077
sprang1168fd42017-06-21 09:00:17 -070078constexpr int kDefaultMaxQp = cricket::WebRtcVideoChannel::kDefaultQpMax;
79
minyue73208662016-08-18 06:28:55 -070080struct VoiceEngineState {
81 VoiceEngineState()
82 : voice_engine(nullptr),
83 base(nullptr),
minyue73208662016-08-18 06:28:55 -070084 send_channel_id(-1),
85 receive_channel_id(-1) {}
86
87 webrtc::VoiceEngine* voice_engine;
88 webrtc::VoEBase* base;
minyue73208662016-08-18 06:28:55 -070089 int send_channel_id;
90 int receive_channel_id;
91};
92
peaha9cc40b2017-06-29 08:32:09 -070093void CreateVoiceEngine(
94 VoiceEngineState* voe,
Fredrik Solenbergd3195342017-11-21 20:33:05 +010095 webrtc::AudioDeviceModule* adm,
peaha9cc40b2017-06-29 08:32:09 -070096 webrtc::AudioProcessing* apm,
97 rtc::scoped_refptr<webrtc::AudioDecoderFactory> decoder_factory) {
minyue73208662016-08-18 06:28:55 -070098 voe->voice_engine = webrtc::VoiceEngine::Create();
99 voe->base = webrtc::VoEBase::GetInterface(voe->voice_engine);
Fredrik Solenbergd3195342017-11-21 20:33:05 +0100100 EXPECT_EQ(0, adm->Init());
101 EXPECT_EQ(0, voe->base->Init(adm, apm, decoder_factory));
solenberg88499ec2016-09-07 07:34:41 -0700102 webrtc::VoEBase::ChannelConfig config;
103 config.enable_voice_pacing = true;
104 voe->send_channel_id = voe->base->CreateChannel(config);
minyue73208662016-08-18 06:28:55 -0700105 EXPECT_GE(voe->send_channel_id, 0);
106 voe->receive_channel_id = voe->base->CreateChannel();
107 EXPECT_GE(voe->receive_channel_id, 0);
108}
109
110void DestroyVoiceEngine(VoiceEngineState* voe) {
111 voe->base->DeleteChannel(voe->send_channel_id);
112 voe->send_channel_id = -1;
113 voe->base->DeleteChannel(voe->receive_channel_id);
114 voe->receive_channel_id = -1;
115 voe->base->Release();
116 voe->base = nullptr;
minyue73208662016-08-18 06:28:55 -0700117
118 webrtc::VoiceEngine::Delete(voe->voice_engine);
119 voe->voice_engine = nullptr;
120}
121
perkjfa10b552016-10-02 23:45:26 -0700122class VideoStreamFactory
123 : public webrtc::VideoEncoderConfig::VideoStreamFactoryInterface {
124 public:
125 explicit VideoStreamFactory(const std::vector<webrtc::VideoStream>& streams)
126 : streams_(streams) {}
127
128 private:
129 std::vector<webrtc::VideoStream> CreateEncoderStreams(
130 int width,
131 int height,
132 const webrtc::VideoEncoderConfig& encoder_config) override {
mflodmand79f97b2016-12-15 07:24:33 -0800133 // The highest layer must match the incoming resolution.
134 std::vector<webrtc::VideoStream> streams = streams_;
135 streams[streams_.size() - 1].height = height;
136 streams[streams_.size() - 1].width = width;
137 return streams;
perkjfa10b552016-10-02 23:45:26 -0700138 }
139
140 std::vector<webrtc::VideoStream> streams_;
141};
142
brandtr504b95e2016-12-21 02:54:35 -0800143bool IsFlexfec(int payload_type) {
144 return payload_type == webrtc::VideoQualityTest::kFlexfecPayloadType;
145}
146
minyue73208662016-08-18 06:28:55 -0700147} // namespace
ivica5d6a06c2015-09-17 05:30:24 -0700148
149namespace webrtc {
150
ivica5d6a06c2015-09-17 05:30:24 -0700151class VideoAnalyzer : public PacketReceiver,
pbos2d566682015-09-28 09:59:31 -0700152 public Transport,
ilnik1e7732c2017-02-23 05:07:56 -0800153 public rtc::VideoSinkInterface<VideoFrame> {
ivica5d6a06c2015-09-17 05:30:24 -0700154 public:
sprangce4aef12015-11-02 07:23:20 -0800155 VideoAnalyzer(test::LayerFilteringTransport* transport,
ivica5d6a06c2015-09-17 05:30:24 -0700156 const std::string& test_label,
157 double avg_psnr_threshold,
158 double avg_ssim_threshold,
159 int duration_frames,
sprangce4aef12015-11-02 07:23:20 -0800160 FILE* graph_data_output_file,
161 const std::string& graph_title,
ilnik3dd5ad92017-02-09 04:58:53 -0800162 uint32_t ssrc_to_analyze,
ilnik46a00212017-02-10 09:16:05 -0800163 uint32_t rtx_ssrc_to_analyze,
ilnikcb8c1462017-03-09 09:23:30 -0800164 size_t selected_stream,
ilnik1e7732c2017-02-23 05:07:56 -0800165 int selected_sl,
166 int selected_tl,
ilnik6b826ef2017-06-16 06:53:48 -0700167 bool is_quick_test_enabled,
ilnik98436952017-07-13 00:47:03 -0700168 Clock* clock,
169 std::string rtp_dump_name)
perkja49cbd32016-09-16 07:53:41 -0700170 : transport_(transport),
ivica5d6a06c2015-09-17 05:30:24 -0700171 receiver_(nullptr),
stefan889d9652017-07-05 03:03:02 -0700172 call_(nullptr),
ivica5d6a06c2015-09-17 05:30:24 -0700173 send_stream_(nullptr),
philipelfd870db2017-01-23 03:22:15 -0800174 receive_stream_(nullptr),
ilnik6b826ef2017-06-16 06:53:48 -0700175 captured_frame_forwarder_(this, clock),
ivica5d6a06c2015-09-17 05:30:24 -0700176 test_label_(test_label),
177 graph_data_output_file_(graph_data_output_file),
sprangce4aef12015-11-02 07:23:20 -0800178 graph_title_(graph_title),
179 ssrc_to_analyze_(ssrc_to_analyze),
ilnik46a00212017-02-10 09:16:05 -0800180 rtx_ssrc_to_analyze_(rtx_ssrc_to_analyze),
ilnikcb8c1462017-03-09 09:23:30 -0800181 selected_stream_(selected_stream),
ilnik1e7732c2017-02-23 05:07:56 -0800182 selected_sl_(selected_sl),
183 selected_tl_(selected_tl),
pbos14fe7082016-04-20 06:35:56 -0700184 pre_encode_proxy_(this),
Peter Boströme4499152016-02-05 11:13:28 +0100185 encode_timing_proxy_(this),
stefan889d9652017-07-05 03:03:02 -0700186 last_fec_bytes_(0),
ivica5d6a06c2015-09-17 05:30:24 -0700187 frames_to_process_(duration_frames),
188 frames_recorded_(0),
189 frames_processed_(0),
190 dropped_frames_(0),
pbos14fe7082016-04-20 06:35:56 -0700191 dropped_frames_before_first_encode_(0),
192 dropped_frames_before_rendering_(0),
ivica5d6a06c2015-09-17 05:30:24 -0700193 last_render_time_(0),
194 rtp_timestamp_delta_(0),
ilnik1e7732c2017-02-23 05:07:56 -0800195 total_media_bytes_(0),
196 first_sending_time_(0),
197 last_sending_time_(0),
ilnikdf92c5c2017-02-23 02:08:44 -0800198 cpu_time_(0),
199 wallclock_time_(0),
ivica5d6a06c2015-09-17 05:30:24 -0700200 avg_psnr_threshold_(avg_psnr_threshold),
201 avg_ssim_threshold_(avg_ssim_threshold),
ilnik9ae0d762017-02-15 00:53:12 -0800202 is_quick_test_enabled_(is_quick_test_enabled),
Peter Boström8c38e8b2015-11-26 17:45:47 +0100203 stats_polling_thread_(&PollStatsThread, this, "StatsPoller"),
Peter Boström5811a392015-12-10 13:02:50 +0100204 comparison_available_event_(false, false),
ilnik98436952017-07-13 00:47:03 -0700205 done_(true, false),
206 clock_(clock),
207 start_ms_(clock->TimeInMilliseconds()) {
ivica5d6a06c2015-09-17 05:30:24 -0700208 // Create thread pool for CPU-expensive PSNR/SSIM calculations.
209
210 // Try to use about as many threads as cores, but leave kMinCoresLeft alone,
211 // so that we don't accidentally starve "real" worker threads (codec etc).
212 // Also, don't allocate more than kMaxComparisonThreads, even if there are
213 // spare cores.
214
215 uint32_t num_cores = CpuInfo::DetectNumberOfCores();
kwibergaf476c72016-11-28 15:21:39 -0800216 RTC_DCHECK_GE(num_cores, 1);
ivica5d6a06c2015-09-17 05:30:24 -0700217 static const uint32_t kMinCoresLeft = 4;
218 static const uint32_t kMaxComparisonThreads = 8;
219
220 if (num_cores <= kMinCoresLeft) {
221 num_cores = 1;
222 } else {
223 num_cores -= kMinCoresLeft;
224 num_cores = std::min(num_cores, kMaxComparisonThreads);
225 }
226
227 for (uint32_t i = 0; i < num_cores; ++i) {
Peter Boström8c38e8b2015-11-26 17:45:47 +0100228 rtc::PlatformThread* thread =
229 new rtc::PlatformThread(&FrameComparisonThread, this, "Analyzer");
230 thread->Start();
231 comparison_thread_pool_.push_back(thread);
ivica5d6a06c2015-09-17 05:30:24 -0700232 }
ilnik98436952017-07-13 00:47:03 -0700233
234 if (!rtp_dump_name.empty()) {
235 fprintf(stdout, "Writing rtp dump to %s\n", rtp_dump_name.c_str());
236 rtp_file_writer_.reset(test::RtpFileWriter::Create(
237 test::RtpFileWriter::kRtpDump, rtp_dump_name));
238 }
ivica5d6a06c2015-09-17 05:30:24 -0700239 }
240
241 ~VideoAnalyzer() {
Peter Boström8c38e8b2015-11-26 17:45:47 +0100242 for (rtc::PlatformThread* thread : comparison_thread_pool_) {
243 thread->Stop();
ivica5d6a06c2015-09-17 05:30:24 -0700244 delete thread;
245 }
246 }
247
248 virtual void SetReceiver(PacketReceiver* receiver) { receiver_ = receiver; }
249
ilnik6b826ef2017-06-16 06:53:48 -0700250 void SetSource(test::VideoCapturer* video_capturer, bool respect_sink_wants) {
251 if (respect_sink_wants)
252 captured_frame_forwarder_.SetSource(video_capturer);
253 rtc::VideoSinkWants wants;
254 video_capturer->AddOrUpdateSink(InputInterface(), wants);
255 }
256
stefan889d9652017-07-05 03:03:02 -0700257 void SetCall(Call* call) {
258 rtc::CritScope lock(&crit_);
259 RTC_DCHECK(!call_);
260 call_ = call;
261 }
262
perkja49cbd32016-09-16 07:53:41 -0700263 void SetSendStream(VideoSendStream* stream) {
264 rtc::CritScope lock(&crit_);
265 RTC_DCHECK(!send_stream_);
266 send_stream_ = stream;
267 }
268
philipelfd870db2017-01-23 03:22:15 -0800269 void SetReceiveStream(VideoReceiveStream* stream) {
270 rtc::CritScope lock(&crit_);
271 RTC_DCHECK(!receive_stream_);
272 receive_stream_ = stream;
273 }
274
perkja49cbd32016-09-16 07:53:41 -0700275 rtc::VideoSinkInterface<VideoFrame>* InputInterface() {
276 return &captured_frame_forwarder_;
277 }
278 rtc::VideoSourceInterface<VideoFrame>* OutputInterface() {
279 return &captured_frame_forwarder_;
280 }
281
ivica5d6a06c2015-09-17 05:30:24 -0700282 DeliveryStatus DeliverPacket(MediaType media_type,
Danil Chapovalov292a73e2017-12-07 17:00:40 +0100283 rtc::CopyOnWriteBuffer packet,
ivica5d6a06c2015-09-17 05:30:24 -0700284 const PacketTime& packet_time) override {
Taylor Brandstetter433b95a2016-03-18 11:41:03 -0700285 // Ignore timestamps of RTCP packets. They're not synchronized with
286 // RTP packet timestamps and so they would confuse wrap_handler_.
Danil Chapovalov292a73e2017-12-07 17:00:40 +0100287 if (RtpHeaderParser::IsRtcp(packet.cdata(), packet.size())) {
288 return receiver_->DeliverPacket(media_type, std::move(packet),
289 packet_time);
Taylor Brandstetter433b95a2016-03-18 11:41:03 -0700290 }
ilnik98436952017-07-13 00:47:03 -0700291
292 if (rtp_file_writer_) {
293 test::RtpPacket p;
Danil Chapovalov292a73e2017-12-07 17:00:40 +0100294 memcpy(p.data, packet.cdata(), packet.size());
295 p.length = packet.size();
296 p.original_length = packet.size();
ilnik98436952017-07-13 00:47:03 -0700297 p.time_ms = clock_->TimeInMilliseconds() - start_ms_;
298 rtp_file_writer_->WritePacket(&p);
299 }
300
Danil Chapovalov292a73e2017-12-07 17:00:40 +0100301 RtpUtility::RtpHeaderParser parser(packet.cdata(), packet.size());
ivica5d6a06c2015-09-17 05:30:24 -0700302 RTPHeader header;
danilchapf6975f42015-12-28 10:18:46 -0800303 parser.Parse(&header);
ilnik46a00212017-02-10 09:16:05 -0800304 if (!IsFlexfec(header.payloadType) &&
305 (header.ssrc == ssrc_to_analyze_ ||
306 header.ssrc == rtx_ssrc_to_analyze_)) {
brandtr504b95e2016-12-21 02:54:35 -0800307 // Ignore FlexFEC timestamps, to avoid collisions with media timestamps.
308 // (FlexFEC and media are sent on different SSRCs, which have different
309 // timestamps spaces.)
ilnik46a00212017-02-10 09:16:05 -0800310 // Also ignore packets from wrong SSRC, but include retransmits.
ivica5d6a06c2015-09-17 05:30:24 -0700311 rtc::CritScope lock(&crit_);
sprang16daaa52016-03-09 01:30:24 -0800312 int64_t timestamp =
313 wrap_handler_.Unwrap(header.timestamp - rtp_timestamp_delta_);
314 recv_times_[timestamp] =
ivica5d6a06c2015-09-17 05:30:24 -0700315 Clock::GetRealTimeClock()->CurrentNtpInMilliseconds();
316 }
317
Danil Chapovalov292a73e2017-12-07 17:00:40 +0100318 return receiver_->DeliverPacket(media_type, std::move(packet), packet_time);
ivica5d6a06c2015-09-17 05:30:24 -0700319 }
320
Peter Boströme4499152016-02-05 11:13:28 +0100321 void MeasuredEncodeTiming(int64_t ntp_time_ms, int encode_time_ms) {
ivica8d15bd62015-10-07 02:43:12 -0700322 rtc::CritScope crit(&comparison_lock_);
323 samples_encode_time_ms_[ntp_time_ms] = encode_time_ms;
324 }
325
pbos14fe7082016-04-20 06:35:56 -0700326 void PreEncodeOnFrame(const VideoFrame& video_frame) {
327 rtc::CritScope lock(&crit_);
ilnik3dd5ad92017-02-09 04:58:53 -0800328 if (!first_encoded_timestamp_) {
pbos14fe7082016-04-20 06:35:56 -0700329 while (frames_.front().timestamp() != video_frame.timestamp()) {
330 ++dropped_frames_before_first_encode_;
331 frames_.pop_front();
332 RTC_CHECK(!frames_.empty());
333 }
ilnik3dd5ad92017-02-09 04:58:53 -0800334 first_encoded_timestamp_ =
335 rtc::Optional<uint32_t>(video_frame.timestamp());
336 }
337 }
338
339 void PostEncodeFrameCallback(const EncodedFrame& encoded_frame) {
340 rtc::CritScope lock(&crit_);
341 if (!first_sent_timestamp_ &&
ilnikcb8c1462017-03-09 09:23:30 -0800342 encoded_frame.stream_id_ == selected_stream_) {
ilnik3dd5ad92017-02-09 04:58:53 -0800343 first_sent_timestamp_ = rtc::Optional<uint32_t>(encoded_frame.timestamp_);
pbos14fe7082016-04-20 06:35:56 -0700344 }
345 }
346
stefan1d8a5062015-10-02 03:39:33 -0700347 bool SendRtp(const uint8_t* packet,
348 size_t length,
349 const PacketOptions& options) override {
sprangce4aef12015-11-02 07:23:20 -0800350 RtpUtility::RtpHeaderParser parser(packet, length);
ivica5d6a06c2015-09-17 05:30:24 -0700351 RTPHeader header;
danilchapf6975f42015-12-28 10:18:46 -0800352 parser.Parse(&header);
ivica5d6a06c2015-09-17 05:30:24 -0700353
sprangce4aef12015-11-02 07:23:20 -0800354 int64_t current_time =
355 Clock::GetRealTimeClock()->CurrentNtpInMilliseconds();
ilnik2a8c2f52017-02-15 02:23:28 -0800356
sprangce4aef12015-11-02 07:23:20 -0800357 bool result = transport_->SendRtp(packet, length, options);
ivica5d6a06c2015-09-17 05:30:24 -0700358 {
359 rtc::CritScope lock(&crit_);
ilnik3dd5ad92017-02-09 04:58:53 -0800360 if (rtp_timestamp_delta_ == 0 && header.ssrc == ssrc_to_analyze_) {
ilnik1e1c84d2017-02-09 08:32:53 -0800361 RTC_CHECK(static_cast<bool>(first_sent_timestamp_));
ilnik3dd5ad92017-02-09 04:58:53 -0800362 rtp_timestamp_delta_ = header.timestamp - *first_sent_timestamp_;
ilnike67c59e2017-02-09 04:08:56 -0800363 }
ilnik3dd5ad92017-02-09 04:58:53 -0800364
365 if (!IsFlexfec(header.payloadType) && header.ssrc == ssrc_to_analyze_) {
brandtr504b95e2016-12-21 02:54:35 -0800366 // Ignore FlexFEC timestamps, to avoid collisions with media timestamps.
367 // (FlexFEC and media are sent on different SSRCs, which have different
368 // timestamps spaces.)
ilnik46a00212017-02-10 09:16:05 -0800369 // Also ignore packets from wrong SSRC and retransmits.
brandtr504b95e2016-12-21 02:54:35 -0800370 int64_t timestamp =
371 wrap_handler_.Unwrap(header.timestamp - rtp_timestamp_delta_);
372 send_times_[timestamp] = current_time;
ilnik1e7732c2017-02-23 05:07:56 -0800373
374 if (IsInSelectedSpatialAndTemporalLayer(packet, length, header)) {
brandtr504b95e2016-12-21 02:54:35 -0800375 encoded_frame_sizes_[timestamp] +=
376 length - (header.headerLength + header.paddingLength);
ilnik1e7732c2017-02-23 05:07:56 -0800377 total_media_bytes_ +=
378 length - (header.headerLength + header.paddingLength);
brandtr504b95e2016-12-21 02:54:35 -0800379 }
ilnik1e7732c2017-02-23 05:07:56 -0800380 if (first_sending_time_ == 0)
381 first_sending_time_ = current_time;
382 last_sending_time_ = current_time;
sprangce4aef12015-11-02 07:23:20 -0800383 }
ivica5d6a06c2015-09-17 05:30:24 -0700384 }
sprangce4aef12015-11-02 07:23:20 -0800385 return result;
ivica5d6a06c2015-09-17 05:30:24 -0700386 }
387
388 bool SendRtcp(const uint8_t* packet, size_t length) override {
389 return transport_->SendRtcp(packet, length);
390 }
391
nisseeb83a1a2016-03-21 01:27:56 -0700392 void OnFrame(const VideoFrame& video_frame) override {
ivica5d6a06c2015-09-17 05:30:24 -0700393 int64_t render_time_ms =
394 Clock::GetRealTimeClock()->CurrentNtpInMilliseconds();
ivica5d6a06c2015-09-17 05:30:24 -0700395
396 rtc::CritScope lock(&crit_);
ilnikdf92c5c2017-02-23 02:08:44 -0800397
398 StartExcludingCpuThreadTime();
399
Taylor Brandstetter433b95a2016-03-18 11:41:03 -0700400 int64_t send_timestamp =
sprang16daaa52016-03-09 01:30:24 -0800401 wrap_handler_.Unwrap(video_frame.timestamp() - rtp_timestamp_delta_);
ivica5d6a06c2015-09-17 05:30:24 -0700402
sprang16daaa52016-03-09 01:30:24 -0800403 while (wrap_handler_.Unwrap(frames_.front().timestamp()) < send_timestamp) {
nisse97f0b932016-05-26 09:44:40 -0700404 if (!last_rendered_frame_) {
pbos14fe7082016-04-20 06:35:56 -0700405 // No previous frame rendered, this one was dropped after sending but
406 // before rendering.
407 ++dropped_frames_before_rendering_;
kthelgason2bc68642017-02-07 07:02:22 -0800408 } else {
409 AddFrameComparison(frames_.front(), *last_rendered_frame_, true,
410 render_time_ms);
pbos14fe7082016-04-20 06:35:56 -0700411 }
ivica5d6a06c2015-09-17 05:30:24 -0700412 frames_.pop_front();
pbos14fe7082016-04-20 06:35:56 -0700413 RTC_DCHECK(!frames_.empty());
ivica5d6a06c2015-09-17 05:30:24 -0700414 }
415
416 VideoFrame reference_frame = frames_.front();
417 frames_.pop_front();
sprang16daaa52016-03-09 01:30:24 -0800418 int64_t reference_timestamp =
419 wrap_handler_.Unwrap(reference_frame.timestamp());
420 if (send_timestamp == reference_timestamp - 1) {
sprangce4aef12015-11-02 07:23:20 -0800421 // TODO(ivica): Make this work for > 2 streams.
Peter Boströme4499152016-02-05 11:13:28 +0100422 // Look at RTPSender::BuildRTPHeader.
sprangce4aef12015-11-02 07:23:20 -0800423 ++send_timestamp;
424 }
sprang16daaa52016-03-09 01:30:24 -0800425 ASSERT_EQ(reference_timestamp, send_timestamp);
ivica5d6a06c2015-09-17 05:30:24 -0700426
427 AddFrameComparison(reference_frame, video_frame, false, render_time_ms);
428
nisse97f0b932016-05-26 09:44:40 -0700429 last_rendered_frame_ = rtc::Optional<VideoFrame>(video_frame);
ilnikdf92c5c2017-02-23 02:08:44 -0800430
431 StopExcludingCpuThreadTime();
ivica5d6a06c2015-09-17 05:30:24 -0700432 }
433
ivica5d6a06c2015-09-17 05:30:24 -0700434 void Wait() {
435 // Frame comparisons can be very expensive. Wait for test to be done, but
436 // at time-out check if frames_processed is going up. If so, give it more
437 // time, otherwise fail. Hopefully this will reduce test flakiness.
438
Peter Boström8c38e8b2015-11-26 17:45:47 +0100439 stats_polling_thread_.Start();
sprangce4aef12015-11-02 07:23:20 -0800440
ivica5d6a06c2015-09-17 05:30:24 -0700441 int last_frames_processed = -1;
ivica5d6a06c2015-09-17 05:30:24 -0700442 int iteration = 0;
Peter Boström5811a392015-12-10 13:02:50 +0100443 while (!done_.Wait(VideoQualityTest::kDefaultTimeoutMs)) {
ivica5d6a06c2015-09-17 05:30:24 -0700444 int frames_processed;
445 {
446 rtc::CritScope crit(&comparison_lock_);
447 frames_processed = frames_processed_;
448 }
449
450 // Print some output so test infrastructure won't think we've crashed.
451 const char* kKeepAliveMessages[3] = {
452 "Uh, I'm-I'm not quite dead, sir.",
453 "Uh, I-I think uh, I could pull through, sir.",
454 "Actually, I think I'm all right to come with you--"};
455 printf("- %s\n", kKeepAliveMessages[iteration++ % 3]);
456
457 if (last_frames_processed == -1) {
458 last_frames_processed = frames_processed;
459 continue;
460 }
Peter Boströmdd45eb62016-01-19 15:22:32 +0100461 if (frames_processed == last_frames_processed) {
462 EXPECT_GT(frames_processed, last_frames_processed)
463 << "Analyzer stalled while waiting for test to finish.";
464 done_.Set();
465 break;
466 }
ivica5d6a06c2015-09-17 05:30:24 -0700467 last_frames_processed = frames_processed;
468 }
469
470 if (iteration > 0)
471 printf("- Farewell, sweet Concorde!\n");
472
Peter Boström8c38e8b2015-11-26 17:45:47 +0100473 stats_polling_thread_.Stop();
ivica5d6a06c2015-09-17 05:30:24 -0700474 }
475
pbos14fe7082016-04-20 06:35:56 -0700476 rtc::VideoSinkInterface<VideoFrame>* pre_encode_proxy() {
477 return &pre_encode_proxy_;
478 }
Peter Boströme4499152016-02-05 11:13:28 +0100479 EncodedFrameObserver* encode_timing_proxy() { return &encode_timing_proxy_; }
480
ilnikdf92c5c2017-02-23 02:08:44 -0800481 void StartMeasuringCpuProcessTime() {
482 rtc::CritScope lock(&cpu_measurement_lock_);
483 cpu_time_ -= rtc::GetProcessCpuTimeNanos();
484 wallclock_time_ -= rtc::SystemTimeNanos();
485 }
486
487 void StopMeasuringCpuProcessTime() {
488 rtc::CritScope lock(&cpu_measurement_lock_);
489 cpu_time_ += rtc::GetProcessCpuTimeNanos();
490 wallclock_time_ += rtc::SystemTimeNanos();
491 }
492
493 void StartExcludingCpuThreadTime() {
494 rtc::CritScope lock(&cpu_measurement_lock_);
495 cpu_time_ += rtc::GetThreadCpuTimeNanos();
496 }
497
498 void StopExcludingCpuThreadTime() {
499 rtc::CritScope lock(&cpu_measurement_lock_);
500 cpu_time_ -= rtc::GetThreadCpuTimeNanos();
501 }
502
503 double GetCpuUsagePercent() {
504 rtc::CritScope lock(&cpu_measurement_lock_);
505 return static_cast<double>(cpu_time_) / wallclock_time_ * 100.0;
506 }
507
sprangce4aef12015-11-02 07:23:20 -0800508 test::LayerFilteringTransport* const transport_;
ivica5d6a06c2015-09-17 05:30:24 -0700509 PacketReceiver* receiver_;
ivica5d6a06c2015-09-17 05:30:24 -0700510
511 private:
512 struct FrameComparison {
513 FrameComparison()
514 : dropped(false),
nissedf2ceb82016-12-15 06:29:53 -0800515 input_time_ms(0),
ivica5d6a06c2015-09-17 05:30:24 -0700516 send_time_ms(0),
517 recv_time_ms(0),
518 render_time_ms(0),
519 encoded_frame_size(0) {}
520
521 FrameComparison(const VideoFrame& reference,
522 const VideoFrame& render,
523 bool dropped,
nissedf2ceb82016-12-15 06:29:53 -0800524 int64_t input_time_ms,
ivica5d6a06c2015-09-17 05:30:24 -0700525 int64_t send_time_ms,
526 int64_t recv_time_ms,
527 int64_t render_time_ms,
528 size_t encoded_frame_size)
529 : reference(reference),
530 render(render),
531 dropped(dropped),
nissedf2ceb82016-12-15 06:29:53 -0800532 input_time_ms(input_time_ms),
ivica5d6a06c2015-09-17 05:30:24 -0700533 send_time_ms(send_time_ms),
534 recv_time_ms(recv_time_ms),
535 render_time_ms(render_time_ms),
536 encoded_frame_size(encoded_frame_size) {}
537
nissedf2ceb82016-12-15 06:29:53 -0800538 FrameComparison(bool dropped,
539 int64_t input_time_ms,
540 int64_t send_time_ms,
541 int64_t recv_time_ms,
542 int64_t render_time_ms,
543 size_t encoded_frame_size)
544 : dropped(dropped),
545 input_time_ms(input_time_ms),
546 send_time_ms(send_time_ms),
547 recv_time_ms(recv_time_ms),
548 render_time_ms(render_time_ms),
549 encoded_frame_size(encoded_frame_size) {}
550
551 rtc::Optional<VideoFrame> reference;
552 rtc::Optional<VideoFrame> render;
ivica5d6a06c2015-09-17 05:30:24 -0700553 bool dropped;
nissedf2ceb82016-12-15 06:29:53 -0800554 int64_t input_time_ms;
ivica5d6a06c2015-09-17 05:30:24 -0700555 int64_t send_time_ms;
556 int64_t recv_time_ms;
557 int64_t render_time_ms;
558 size_t encoded_frame_size;
559 };
560
561 struct Sample {
ivica8d15bd62015-10-07 02:43:12 -0700562 Sample(int dropped,
563 int64_t input_time_ms,
564 int64_t send_time_ms,
565 int64_t recv_time_ms,
566 int64_t render_time_ms,
567 size_t encoded_frame_size,
ivica5d6a06c2015-09-17 05:30:24 -0700568 double psnr,
ivica8d15bd62015-10-07 02:43:12 -0700569 double ssim)
ivica5d6a06c2015-09-17 05:30:24 -0700570 : dropped(dropped),
571 input_time_ms(input_time_ms),
572 send_time_ms(send_time_ms),
573 recv_time_ms(recv_time_ms),
ivica8d15bd62015-10-07 02:43:12 -0700574 render_time_ms(render_time_ms),
ivica5d6a06c2015-09-17 05:30:24 -0700575 encoded_frame_size(encoded_frame_size),
576 psnr(psnr),
ivica8d15bd62015-10-07 02:43:12 -0700577 ssim(ssim) {}
ivica5d6a06c2015-09-17 05:30:24 -0700578
ivica8d15bd62015-10-07 02:43:12 -0700579 int dropped;
580 int64_t input_time_ms;
581 int64_t send_time_ms;
582 int64_t recv_time_ms;
583 int64_t render_time_ms;
584 size_t encoded_frame_size;
ivica5d6a06c2015-09-17 05:30:24 -0700585 double psnr;
586 double ssim;
ivica5d6a06c2015-09-17 05:30:24 -0700587 };
588
Peter Boströme4499152016-02-05 11:13:28 +0100589 // This class receives the send-side OnEncodeTiming and is provided to not
590 // conflict with the receiver-side pre_decode_callback.
591 class OnEncodeTimingProxy : public EncodedFrameObserver {
592 public:
593 explicit OnEncodeTimingProxy(VideoAnalyzer* parent) : parent_(parent) {}
594
595 void OnEncodeTiming(int64_t ntp_time_ms, int encode_time_ms) override {
596 parent_->MeasuredEncodeTiming(ntp_time_ms, encode_time_ms);
597 }
ilnik3dd5ad92017-02-09 04:58:53 -0800598 void EncodedFrameCallback(const EncodedFrame& frame) override {
599 parent_->PostEncodeFrameCallback(frame);
600 }
Peter Boströme4499152016-02-05 11:13:28 +0100601
602 private:
603 VideoAnalyzer* const parent_;
604 };
605
pbos14fe7082016-04-20 06:35:56 -0700606 // This class receives the send-side OnFrame callback and is provided to not
607 // conflict with the receiver-side renderer callback.
608 class PreEncodeProxy : public rtc::VideoSinkInterface<VideoFrame> {
609 public:
610 explicit PreEncodeProxy(VideoAnalyzer* parent) : parent_(parent) {}
611
612 void OnFrame(const VideoFrame& video_frame) override {
613 parent_->PreEncodeOnFrame(video_frame);
614 }
615
616 private:
617 VideoAnalyzer* const parent_;
618 };
619
ilnik1e7732c2017-02-23 05:07:56 -0800620 bool IsInSelectedSpatialAndTemporalLayer(const uint8_t* packet,
621 size_t length,
622 const RTPHeader& header) {
ilnik863f03b2017-07-11 02:38:36 -0700623 if (header.payloadType != test::CallTest::kPayloadTypeVP9 &&
624 header.payloadType != test::CallTest::kPayloadTypeVP8) {
ilnik1e7732c2017-02-23 05:07:56 -0800625 return true;
626 } else {
627 // Get VP8 and VP9 specific header to check layers indexes.
628 const uint8_t* payload = packet + header.headerLength;
629 const size_t payload_length = length - header.headerLength;
630 const size_t payload_data_length = payload_length - header.paddingLength;
ilnik863f03b2017-07-11 02:38:36 -0700631 const bool is_vp8 = header.payloadType == test::CallTest::kPayloadTypeVP8;
ilnik1e7732c2017-02-23 05:07:56 -0800632 std::unique_ptr<RtpDepacketizer> depacketizer(
633 RtpDepacketizer::Create(is_vp8 ? kRtpVideoVp8 : kRtpVideoVp9));
634 RtpDepacketizer::ParsedPayload parsed_payload;
635 bool result =
636 depacketizer->Parse(&parsed_payload, payload, payload_data_length);
637 RTC_DCHECK(result);
638 const int temporal_idx = static_cast<int>(
639 is_vp8 ? parsed_payload.type.Video.codecHeader.VP8.temporalIdx
640 : parsed_payload.type.Video.codecHeader.VP9.temporal_idx);
641 const int spatial_idx = static_cast<int>(
642 is_vp8 ? kNoSpatialIdx
643 : parsed_payload.type.Video.codecHeader.VP9.spatial_idx);
644 return (selected_tl_ < 0 || temporal_idx == kNoTemporalIdx ||
645 temporal_idx <= selected_tl_) &&
646 (selected_sl_ < 0 || spatial_idx == kNoSpatialIdx ||
647 spatial_idx <= selected_sl_);
648 }
649 }
650
ivica5d6a06c2015-09-17 05:30:24 -0700651 void AddFrameComparison(const VideoFrame& reference,
652 const VideoFrame& render,
653 bool dropped,
654 int64_t render_time_ms)
danilchapa37de392017-09-09 04:17:22 -0700655 RTC_EXCLUSIVE_LOCKS_REQUIRED(crit_) {
sprange1f2f1f2016-02-01 02:04:52 -0800656 int64_t reference_timestamp = wrap_handler_.Unwrap(reference.timestamp());
657 int64_t send_time_ms = send_times_[reference_timestamp];
658 send_times_.erase(reference_timestamp);
659 int64_t recv_time_ms = recv_times_[reference_timestamp];
660 recv_times_.erase(reference_timestamp);
ivica5d6a06c2015-09-17 05:30:24 -0700661
sprangce4aef12015-11-02 07:23:20 -0800662 // TODO(ivica): Make this work for > 2 streams.
sprange1f2f1f2016-02-01 02:04:52 -0800663 auto it = encoded_frame_sizes_.find(reference_timestamp);
sprangce4aef12015-11-02 07:23:20 -0800664 if (it == encoded_frame_sizes_.end())
sprange1f2f1f2016-02-01 02:04:52 -0800665 it = encoded_frame_sizes_.find(reference_timestamp - 1);
sprangce4aef12015-11-02 07:23:20 -0800666 size_t encoded_size = it == encoded_frame_sizes_.end() ? 0 : it->second;
667 if (it != encoded_frame_sizes_.end())
668 encoded_frame_sizes_.erase(it);
ivica5d6a06c2015-09-17 05:30:24 -0700669
ivica5d6a06c2015-09-17 05:30:24 -0700670 rtc::CritScope crit(&comparison_lock_);
stefanb1797672016-08-11 07:00:57 -0700671 if (comparisons_.size() < kMaxComparisons) {
nissedf2ceb82016-12-15 06:29:53 -0800672 comparisons_.push_back(FrameComparison(reference, render, dropped,
673 reference.ntp_time_ms(),
674 send_time_ms, recv_time_ms,
675 render_time_ms, encoded_size));
stefanb1797672016-08-11 07:00:57 -0700676 } else {
nissedf2ceb82016-12-15 06:29:53 -0800677 comparisons_.push_back(FrameComparison(dropped,
678 reference.ntp_time_ms(),
679 send_time_ms, recv_time_ms,
680 render_time_ms, encoded_size));
stefanb1797672016-08-11 07:00:57 -0700681 }
Peter Boström5811a392015-12-10 13:02:50 +0100682 comparison_available_event_.Set();
ivica5d6a06c2015-09-17 05:30:24 -0700683 }
684
tommi0f8b4032017-02-22 11:22:05 -0800685 static void PollStatsThread(void* obj) {
686 static_cast<VideoAnalyzer*>(obj)->PollStats();
ivica5d6a06c2015-09-17 05:30:24 -0700687 }
688
tommi0f8b4032017-02-22 11:22:05 -0800689 void PollStats() {
690 while (!done_.Wait(kSendStatsPollingIntervalMs)) {
691 rtc::CritScope crit(&comparison_lock_);
ivica5d6a06c2015-09-17 05:30:24 -0700692
stefan889d9652017-07-05 03:03:02 -0700693 Call::Stats call_stats = call_->GetStats();
694 send_bandwidth_bps_.AddSample(call_stats.send_bandwidth_bps);
695
tommi0f8b4032017-02-22 11:22:05 -0800696 VideoSendStream::Stats send_stats = send_stream_->GetStats();
697 // It's not certain that we yet have estimates for any of these stats.
698 // Check that they are positive before mixing them in.
699 if (send_stats.encode_frame_rate > 0)
700 encode_frame_rate_.AddSample(send_stats.encode_frame_rate);
701 if (send_stats.avg_encode_time_ms > 0)
702 encode_time_ms_.AddSample(send_stats.avg_encode_time_ms);
703 if (send_stats.encode_usage_percent > 0)
704 encode_usage_percent_.AddSample(send_stats.encode_usage_percent);
705 if (send_stats.media_bitrate_bps > 0)
706 media_bitrate_bps_.AddSample(send_stats.media_bitrate_bps);
stefan889d9652017-07-05 03:03:02 -0700707 size_t fec_bytes = 0;
708 for (auto kv : send_stats.substreams) {
709 fec_bytes += kv.second.rtp_stats.fec.payload_bytes +
710 kv.second.rtp_stats.fec.padding_bytes;
711 }
712 fec_bitrate_bps_.AddSample((fec_bytes - last_fec_bytes_) * 8);
713 last_fec_bytes_ = fec_bytes;
philipelfd870db2017-01-23 03:22:15 -0800714
tommi0f8b4032017-02-22 11:22:05 -0800715 if (receive_stream_ != nullptr) {
716 VideoReceiveStream::Stats receive_stats = receive_stream_->GetStats();
717 if (receive_stats.decode_ms > 0)
718 decode_time_ms_.AddSample(receive_stats.decode_ms);
719 if (receive_stats.max_decode_ms > 0)
720 decode_time_max_ms_.AddSample(receive_stats.max_decode_ms);
721 }
ilnikdaa574d2017-03-01 06:46:05 -0800722
723 memory_usage_.AddSample(rtc::GetProcessResidentSizeBytes());
philipelfd870db2017-01-23 03:22:15 -0800724 }
ivica5d6a06c2015-09-17 05:30:24 -0700725 }
726
727 static bool FrameComparisonThread(void* obj) {
728 return static_cast<VideoAnalyzer*>(obj)->CompareFrames();
729 }
730
731 bool CompareFrames() {
732 if (AllFramesRecorded())
733 return false;
734
ivica5d6a06c2015-09-17 05:30:24 -0700735 FrameComparison comparison;
736
737 if (!PopComparison(&comparison)) {
738 // Wait until new comparison task is available, or test is done.
739 // If done, wake up remaining threads waiting.
Peter Boström5811a392015-12-10 13:02:50 +0100740 comparison_available_event_.Wait(1000);
ivica5d6a06c2015-09-17 05:30:24 -0700741 if (AllFramesRecorded()) {
Peter Boström5811a392015-12-10 13:02:50 +0100742 comparison_available_event_.Set();
ivica5d6a06c2015-09-17 05:30:24 -0700743 return false;
744 }
745 return true; // Try again.
746 }
747
ilnikdf92c5c2017-02-23 02:08:44 -0800748 StartExcludingCpuThreadTime();
749
ivica5d6a06c2015-09-17 05:30:24 -0700750 PerformFrameComparison(comparison);
751
ilnikdf92c5c2017-02-23 02:08:44 -0800752 StopExcludingCpuThreadTime();
753
ivica5d6a06c2015-09-17 05:30:24 -0700754 if (FrameProcessed()) {
755 PrintResults();
756 if (graph_data_output_file_)
757 PrintSamplesToFile();
Peter Boström5811a392015-12-10 13:02:50 +0100758 done_.Set();
759 comparison_available_event_.Set();
ivica5d6a06c2015-09-17 05:30:24 -0700760 return false;
761 }
762
763 return true;
764 }
765
766 bool PopComparison(FrameComparison* comparison) {
767 rtc::CritScope crit(&comparison_lock_);
768 // If AllFramesRecorded() is true, it means we have already popped
769 // frames_to_process_ frames from comparisons_, so there is no more work
770 // for this thread to be done. frames_processed_ might still be lower if
771 // all comparisons are not done, but those frames are currently being
772 // worked on by other threads.
773 if (comparisons_.empty() || AllFramesRecorded())
774 return false;
775
776 *comparison = comparisons_.front();
777 comparisons_.pop_front();
778
779 FrameRecorded();
780 return true;
781 }
782
783 // Increment counter for number of frames received for comparison.
784 void FrameRecorded() {
785 rtc::CritScope crit(&comparison_lock_);
786 ++frames_recorded_;
787 }
788
789 // Returns true if all frames to be compared have been taken from the queue.
790 bool AllFramesRecorded() {
791 rtc::CritScope crit(&comparison_lock_);
792 assert(frames_recorded_ <= frames_to_process_);
793 return frames_recorded_ == frames_to_process_;
794 }
795
796 // Increase count of number of frames processed. Returns true if this was the
797 // last frame to be processed.
798 bool FrameProcessed() {
799 rtc::CritScope crit(&comparison_lock_);
800 ++frames_processed_;
801 assert(frames_processed_ <= frames_to_process_);
802 return frames_processed_ == frames_to_process_;
803 }
804
805 void PrintResults() {
ilnikdf92c5c2017-02-23 02:08:44 -0800806 StopMeasuringCpuProcessTime();
ivica5d6a06c2015-09-17 05:30:24 -0700807 rtc::CritScope crit(&comparison_lock_);
808 PrintResult("psnr", psnr_, " dB");
tnakamura3123cbc2016-02-10 11:21:51 -0800809 PrintResult("ssim", ssim_, " score");
stefan2da7a242017-03-30 01:02:15 -0700810 PrintResult("sender_time", sender_time_, " ms");
811 PrintResult("receiver_time", receiver_time_, " ms");
ivica5d6a06c2015-09-17 05:30:24 -0700812 PrintResult("total_delay_incl_network", end_to_end_, " ms");
813 PrintResult("time_between_rendered_frames", rendered_delta_, " ms");
ivica5d6a06c2015-09-17 05:30:24 -0700814 PrintResult("encode_frame_rate", encode_frame_rate_, " fps");
philipelfd870db2017-01-23 03:22:15 -0800815 PrintResult("encode_time", encode_time_ms_, " ms");
philipelfd870db2017-01-23 03:22:15 -0800816 PrintResult("media_bitrate", media_bitrate_bps_, " bps");
stefan889d9652017-07-05 03:03:02 -0700817 PrintResult("fec_bitrate", fec_bitrate_bps_, " bps");
818 PrintResult("send_bandwidth", send_bandwidth_bps_, " bps");
philipelfd870db2017-01-23 03:22:15 -0800819
ilnik59cac992017-07-25 05:45:03 -0700820 if (worst_frame_) {
821 printf("RESULT min_psnr: %s = %lf dB\n", test_label_.c_str(),
822 worst_frame_->psnr);
823 }
824
philipelfd870db2017-01-23 03:22:15 -0800825 if (receive_stream_ != nullptr) {
826 PrintResult("decode_time", decode_time_ms_, " ms");
philipelfd870db2017-01-23 03:22:15 -0800827 }
ivica5d6a06c2015-09-17 05:30:24 -0700828
pbos14fe7082016-04-20 06:35:56 -0700829 printf("RESULT dropped_frames: %s = %d frames\n", test_label_.c_str(),
830 dropped_frames_);
ilnikdf92c5c2017-02-23 02:08:44 -0800831 printf("RESULT cpu_usage: %s = %lf %%\n", test_label_.c_str(),
832 GetCpuUsagePercent());
ilnikdaa574d2017-03-01 06:46:05 -0800833
834#if defined(WEBRTC_WIN)
835 // On Linux and Mac in Resident Set some unused pages may be counted.
836 // Therefore this metric will depend on order in which tests are run and
837 // will be flaky.
838 PrintResult("memory_usage", memory_usage_, " bytes");
839#endif
ilnik59cac992017-07-25 05:45:03 -0700840
ilnikee42d192017-08-22 07:16:20 -0700841 // Saving only the worst frame for manual analysis. Intention here is to
842 // only detect video corruptions and not to track picture quality. Thus,
843 // jpeg is used here.
oprypin9b2f20c2017-08-29 05:51:57 -0700844 if (FLAG_save_worst_frame && worst_frame_) {
ilnikee42d192017-08-22 07:16:20 -0700845 std::string output_dir;
Edward Lemuraf8659a2017-09-27 14:46:24 +0200846 test::GetTestArtifactsDir(&output_dir);
ilnikee42d192017-08-22 07:16:20 -0700847 std::string output_path =
848 rtc::Pathname(output_dir, test_label_ + ".jpg").pathname();
Mirko Bonadei675513b2017-11-09 11:09:25 +0100849 RTC_LOG(LS_INFO) << "Saving worst frame to " << output_path;
ilnikee42d192017-08-22 07:16:20 -0700850 test::JpegFrameWriter frame_writer(output_path);
851 RTC_CHECK(frame_writer.WriteFrame(worst_frame_->frame,
852 100 /*best quality*/));
ilnik59cac992017-07-25 05:45:03 -0700853 }
ilnikdaa574d2017-03-01 06:46:05 -0800854
ilnik9ae0d762017-02-15 00:53:12 -0800855 // Disable quality check for quick test, as quality checks may fail
856 // because too few samples were collected.
857 if (!is_quick_test_enabled_) {
858 EXPECT_GT(psnr_.Mean(), avg_psnr_threshold_);
859 EXPECT_GT(ssim_.Mean(), avg_ssim_threshold_);
860 }
ivica5d6a06c2015-09-17 05:30:24 -0700861 }
862
863 void PerformFrameComparison(const FrameComparison& comparison) {
864 // Perform expensive psnr and ssim calculations while not holding lock.
stefanb1797672016-08-11 07:00:57 -0700865 double psnr = -1.0;
866 double ssim = -1.0;
ilnik6b826ef2017-06-16 06:53:48 -0700867 if (comparison.reference && !comparison.dropped) {
nissedf2ceb82016-12-15 06:29:53 -0800868 psnr = I420PSNR(&*comparison.reference, &*comparison.render);
869 ssim = I420SSIM(&*comparison.reference, &*comparison.render);
stefanb1797672016-08-11 07:00:57 -0700870 }
ivica5d6a06c2015-09-17 05:30:24 -0700871
ivica5d6a06c2015-09-17 05:30:24 -0700872 rtc::CritScope crit(&comparison_lock_);
ilnik59cac992017-07-25 05:45:03 -0700873
874 if (psnr >= 0.0 && (!worst_frame_ || worst_frame_->psnr > psnr)) {
875 worst_frame_.emplace(FrameWithPsnr{psnr, *comparison.render});
876 }
877
ivica5d6a06c2015-09-17 05:30:24 -0700878 if (graph_data_output_file_) {
nissedf2ceb82016-12-15 06:29:53 -0800879 samples_.push_back(Sample(
880 comparison.dropped, comparison.input_time_ms, comparison.send_time_ms,
881 comparison.recv_time_ms, comparison.render_time_ms,
882 comparison.encoded_frame_size, psnr, ssim));
ivica5d6a06c2015-09-17 05:30:24 -0700883 }
stefanb1797672016-08-11 07:00:57 -0700884 if (psnr >= 0.0)
885 psnr_.AddSample(psnr);
886 if (ssim >= 0.0)
887 ssim_.AddSample(ssim);
ivica5d6a06c2015-09-17 05:30:24 -0700888
889 if (comparison.dropped) {
890 ++dropped_frames_;
891 return;
892 }
893 if (last_render_time_ != 0)
894 rendered_delta_.AddSample(comparison.render_time_ms - last_render_time_);
895 last_render_time_ = comparison.render_time_ms;
896
nissedf2ceb82016-12-15 06:29:53 -0800897 sender_time_.AddSample(comparison.send_time_ms - comparison.input_time_ms);
brandtr504b95e2016-12-21 02:54:35 -0800898 if (comparison.recv_time_ms > 0) {
899 // If recv_time_ms == 0, this frame consisted of a packets which were all
900 // lost in the transport. Since we were able to render the frame, however,
901 // the dropped packets were recovered by FlexFEC. The FlexFEC recovery
902 // happens internally in Call, and we can therefore here not know which
903 // FEC packets that protected the lost media packets. Consequently, we
904 // were not able to record a meaningful recv_time_ms. We therefore skip
905 // this sample.
906 //
907 // The reasoning above does not hold for ULPFEC and RTX, as for those
908 // strategies the timestamp of the received packets is set to the
909 // timestamp of the protected/retransmitted media packet. I.e., then
910 // recv_time_ms != 0, even though the media packets were lost.
911 receiver_time_.AddSample(comparison.render_time_ms -
912 comparison.recv_time_ms);
913 }
nissedf2ceb82016-12-15 06:29:53 -0800914 end_to_end_.AddSample(comparison.render_time_ms - comparison.input_time_ms);
ivica5d6a06c2015-09-17 05:30:24 -0700915 encoded_frame_size_.AddSample(comparison.encoded_frame_size);
916 }
917
918 void PrintResult(const char* result_type,
919 test::Statistics stats,
920 const char* unit) {
921 printf("RESULT %s: %s = {%f, %f}%s\n",
922 result_type,
923 test_label_.c_str(),
924 stats.Mean(),
925 stats.StandardDeviation(),
926 unit);
927 }
928
929 void PrintSamplesToFile(void) {
930 FILE* out = graph_data_output_file_;
931 rtc::CritScope crit(&comparison_lock_);
932 std::sort(samples_.begin(), samples_.end(),
933 [](const Sample& A, const Sample& B) -> bool {
934 return A.input_time_ms < B.input_time_ms;
935 });
936
sprangce4aef12015-11-02 07:23:20 -0800937 fprintf(out, "%s\n", graph_title_.c_str());
ivica5d6a06c2015-09-17 05:30:24 -0700938 fprintf(out, "%" PRIuS "\n", samples_.size());
939 fprintf(out,
940 "dropped "
941 "input_time_ms "
942 "send_time_ms "
943 "recv_time_ms "
ivica8d15bd62015-10-07 02:43:12 -0700944 "render_time_ms "
ivica5d6a06c2015-09-17 05:30:24 -0700945 "encoded_frame_size "
946 "psnr "
947 "ssim "
ivica8d15bd62015-10-07 02:43:12 -0700948 "encode_time_ms\n");
949 int missing_encode_time_samples = 0;
ivica5d6a06c2015-09-17 05:30:24 -0700950 for (const Sample& sample : samples_) {
ivica8d15bd62015-10-07 02:43:12 -0700951 auto it = samples_encode_time_ms_.find(sample.input_time_ms);
952 int encode_time_ms;
953 if (it != samples_encode_time_ms_.end()) {
954 encode_time_ms = it->second;
955 } else {
956 ++missing_encode_time_samples;
957 encode_time_ms = -1;
958 }
959 fprintf(out, "%d %" PRId64 " %" PRId64 " %" PRId64 " %" PRId64 " %" PRIuS
960 " %lf %lf %d\n",
961 sample.dropped, sample.input_time_ms, sample.send_time_ms,
962 sample.recv_time_ms, sample.render_time_ms,
ivica5d6a06c2015-09-17 05:30:24 -0700963 sample.encoded_frame_size, sample.psnr, sample.ssim,
ivica8d15bd62015-10-07 02:43:12 -0700964 encode_time_ms);
965 }
966 if (missing_encode_time_samples) {
967 fprintf(stderr,
968 "Warning: Missing encode_time_ms samples for %d frame(s).\n",
969 missing_encode_time_samples);
ivica5d6a06c2015-09-17 05:30:24 -0700970 }
971 }
972
ilnik1e7732c2017-02-23 05:07:56 -0800973 double GetAverageMediaBitrateBps() {
974 if (last_sending_time_ == first_sending_time_) {
975 return 0;
976 } else {
977 return static_cast<double>(total_media_bytes_) * 8 /
978 (last_sending_time_ - first_sending_time_) *
979 rtc::kNumMillisecsPerSec;
980 }
981 }
982
perkja49cbd32016-09-16 07:53:41 -0700983 // Implements VideoSinkInterface to receive captured frames from a
984 // FrameGeneratorCapturer. Implements VideoSourceInterface to be able to act
985 // as a source to VideoSendStream.
986 // It forwards all input frames to the VideoAnalyzer for later comparison and
987 // forwards the captured frames to the VideoSendStream.
988 class CapturedFrameForwarder : public rtc::VideoSinkInterface<VideoFrame>,
989 public rtc::VideoSourceInterface<VideoFrame> {
990 public:
ilnik6b826ef2017-06-16 06:53:48 -0700991 explicit CapturedFrameForwarder(VideoAnalyzer* analyzer, Clock* clock)
992 : analyzer_(analyzer),
993 send_stream_input_(nullptr),
994 video_capturer_(nullptr),
995 clock_(clock) {}
996
997 void SetSource(test::VideoCapturer* video_capturer) {
998 video_capturer_ = video_capturer;
999 }
perkja49cbd32016-09-16 07:53:41 -07001000
1001 private:
1002 void OnFrame(const VideoFrame& video_frame) override {
1003 VideoFrame copy = video_frame;
ilnik3dd5ad92017-02-09 04:58:53 -08001004 // Frames from the capturer does not have a rtp timestamp.
1005 // Create one so it can be used for comparison.
1006 RTC_DCHECK_EQ(0, video_frame.timestamp());
ilnik6b826ef2017-06-16 06:53:48 -07001007 if (video_frame.ntp_time_ms() == 0)
1008 copy.set_ntp_time_ms(clock_->CurrentNtpInMilliseconds());
perkja49cbd32016-09-16 07:53:41 -07001009 copy.set_timestamp(copy.ntp_time_ms() * 90);
ilnik3dd5ad92017-02-09 04:58:53 -08001010 analyzer_->AddCapturedFrameForComparison(copy);
perkja49cbd32016-09-16 07:53:41 -07001011 rtc::CritScope lock(&crit_);
1012 if (send_stream_input_)
ilnikb82ac6a2017-05-02 00:48:41 -07001013 send_stream_input_->OnFrame(copy);
perkja49cbd32016-09-16 07:53:41 -07001014 }
1015
1016 // Called when |send_stream_.SetSource()| is called.
1017 void AddOrUpdateSink(rtc::VideoSinkInterface<VideoFrame>* sink,
1018 const rtc::VideoSinkWants& wants) override {
ilnik267041c2017-06-27 07:21:01 -07001019 {
1020 rtc::CritScope lock(&crit_);
1021 RTC_DCHECK(!send_stream_input_ || send_stream_input_ == sink);
1022 send_stream_input_ = sink;
1023 }
ilnik6b826ef2017-06-16 06:53:48 -07001024 if (video_capturer_) {
1025 video_capturer_->AddOrUpdateSink(this, wants);
1026 }
perkja49cbd32016-09-16 07:53:41 -07001027 }
1028
1029 // Called by |send_stream_| when |send_stream_.SetSource()| is called.
1030 void RemoveSink(rtc::VideoSinkInterface<VideoFrame>* sink) override {
1031 rtc::CritScope lock(&crit_);
1032 RTC_DCHECK(sink == send_stream_input_);
1033 send_stream_input_ = nullptr;
1034 }
1035
1036 VideoAnalyzer* const analyzer_;
1037 rtc::CriticalSection crit_;
danilchapa37de392017-09-09 04:17:22 -07001038 rtc::VideoSinkInterface<VideoFrame>* send_stream_input_
1039 RTC_GUARDED_BY(crit_);
ilnik6b826ef2017-06-16 06:53:48 -07001040 test::VideoCapturer* video_capturer_;
1041 Clock* clock_;
perkja49cbd32016-09-16 07:53:41 -07001042 };
1043
1044 void AddCapturedFrameForComparison(const VideoFrame& video_frame) {
1045 rtc::CritScope lock(&crit_);
ilnik3dd5ad92017-02-09 04:58:53 -08001046 frames_.push_back(video_frame);
perkja49cbd32016-09-16 07:53:41 -07001047 }
1048
stefan889d9652017-07-05 03:03:02 -07001049 Call* call_;
perkja49cbd32016-09-16 07:53:41 -07001050 VideoSendStream* send_stream_;
philipelfd870db2017-01-23 03:22:15 -08001051 VideoReceiveStream* receive_stream_;
perkja49cbd32016-09-16 07:53:41 -07001052 CapturedFrameForwarder captured_frame_forwarder_;
ivica5d6a06c2015-09-17 05:30:24 -07001053 const std::string test_label_;
1054 FILE* const graph_data_output_file_;
sprangce4aef12015-11-02 07:23:20 -08001055 const std::string graph_title_;
1056 const uint32_t ssrc_to_analyze_;
ilnik46a00212017-02-10 09:16:05 -08001057 const uint32_t rtx_ssrc_to_analyze_;
ilnikcb8c1462017-03-09 09:23:30 -08001058 const size_t selected_stream_;
ilnik1e7732c2017-02-23 05:07:56 -08001059 const int selected_sl_;
1060 const int selected_tl_;
pbos14fe7082016-04-20 06:35:56 -07001061 PreEncodeProxy pre_encode_proxy_;
Peter Boströme4499152016-02-05 11:13:28 +01001062 OnEncodeTimingProxy encode_timing_proxy_;
danilchapa37de392017-09-09 04:17:22 -07001063 std::vector<Sample> samples_ RTC_GUARDED_BY(comparison_lock_);
1064 std::map<int64_t, int> samples_encode_time_ms_
1065 RTC_GUARDED_BY(comparison_lock_);
1066 test::Statistics sender_time_ RTC_GUARDED_BY(comparison_lock_);
1067 test::Statistics receiver_time_ RTC_GUARDED_BY(comparison_lock_);
1068 test::Statistics psnr_ RTC_GUARDED_BY(comparison_lock_);
1069 test::Statistics ssim_ RTC_GUARDED_BY(comparison_lock_);
1070 test::Statistics end_to_end_ RTC_GUARDED_BY(comparison_lock_);
1071 test::Statistics rendered_delta_ RTC_GUARDED_BY(comparison_lock_);
1072 test::Statistics encoded_frame_size_ RTC_GUARDED_BY(comparison_lock_);
1073 test::Statistics encode_frame_rate_ RTC_GUARDED_BY(comparison_lock_);
1074 test::Statistics encode_time_ms_ RTC_GUARDED_BY(comparison_lock_);
1075 test::Statistics encode_usage_percent_ RTC_GUARDED_BY(comparison_lock_);
1076 test::Statistics decode_time_ms_ RTC_GUARDED_BY(comparison_lock_);
1077 test::Statistics decode_time_max_ms_ RTC_GUARDED_BY(comparison_lock_);
1078 test::Statistics media_bitrate_bps_ RTC_GUARDED_BY(comparison_lock_);
1079 test::Statistics fec_bitrate_bps_ RTC_GUARDED_BY(comparison_lock_);
1080 test::Statistics send_bandwidth_bps_ RTC_GUARDED_BY(comparison_lock_);
1081 test::Statistics memory_usage_ RTC_GUARDED_BY(comparison_lock_);
ilnikdaa574d2017-03-01 06:46:05 -08001082
ilnik59cac992017-07-25 05:45:03 -07001083 struct FrameWithPsnr {
1084 double psnr;
1085 VideoFrame frame;
1086 };
1087
1088 // Rendered frame with worst PSNR is saved for further analysis.
danilchapa37de392017-09-09 04:17:22 -07001089 rtc::Optional<FrameWithPsnr> worst_frame_ RTC_GUARDED_BY(comparison_lock_);
ilnik59cac992017-07-25 05:45:03 -07001090
stefan889d9652017-07-05 03:03:02 -07001091 size_t last_fec_bytes_;
ivica5d6a06c2015-09-17 05:30:24 -07001092
1093 const int frames_to_process_;
1094 int frames_recorded_;
1095 int frames_processed_;
1096 int dropped_frames_;
pbos14fe7082016-04-20 06:35:56 -07001097 int dropped_frames_before_first_encode_;
1098 int dropped_frames_before_rendering_;
ivica5d6a06c2015-09-17 05:30:24 -07001099 int64_t last_render_time_;
1100 uint32_t rtp_timestamp_delta_;
ilnik1e7732c2017-02-23 05:07:56 -08001101 int64_t total_media_bytes_;
1102 int64_t first_sending_time_;
1103 int64_t last_sending_time_;
ivica5d6a06c2015-09-17 05:30:24 -07001104
danilchapa37de392017-09-09 04:17:22 -07001105 int64_t cpu_time_ RTC_GUARDED_BY(cpu_measurement_lock_);
1106 int64_t wallclock_time_ RTC_GUARDED_BY(cpu_measurement_lock_);
ilnikdf92c5c2017-02-23 02:08:44 -08001107 rtc::CriticalSection cpu_measurement_lock_;
1108
ivica5d6a06c2015-09-17 05:30:24 -07001109 rtc::CriticalSection crit_;
danilchapa37de392017-09-09 04:17:22 -07001110 std::deque<VideoFrame> frames_ RTC_GUARDED_BY(crit_);
1111 rtc::Optional<VideoFrame> last_rendered_frame_ RTC_GUARDED_BY(crit_);
1112 rtc::TimestampWrapAroundHandler wrap_handler_ RTC_GUARDED_BY(crit_);
1113 std::map<int64_t, int64_t> send_times_ RTC_GUARDED_BY(crit_);
1114 std::map<int64_t, int64_t> recv_times_ RTC_GUARDED_BY(crit_);
1115 std::map<int64_t, size_t> encoded_frame_sizes_ RTC_GUARDED_BY(crit_);
1116 rtc::Optional<uint32_t> first_encoded_timestamp_ RTC_GUARDED_BY(crit_);
1117 rtc::Optional<uint32_t> first_sent_timestamp_ RTC_GUARDED_BY(crit_);
ivica5d6a06c2015-09-17 05:30:24 -07001118 const double avg_psnr_threshold_;
1119 const double avg_ssim_threshold_;
ilnik9ae0d762017-02-15 00:53:12 -08001120 bool is_quick_test_enabled_;
ivica5d6a06c2015-09-17 05:30:24 -07001121
1122 rtc::CriticalSection comparison_lock_;
Peter Boström8c38e8b2015-11-26 17:45:47 +01001123 std::vector<rtc::PlatformThread*> comparison_thread_pool_;
1124 rtc::PlatformThread stats_polling_thread_;
Peter Boström5811a392015-12-10 13:02:50 +01001125 rtc::Event comparison_available_event_;
danilchapa37de392017-09-09 04:17:22 -07001126 std::deque<FrameComparison> comparisons_ RTC_GUARDED_BY(comparison_lock_);
Peter Boström5811a392015-12-10 13:02:50 +01001127 rtc::Event done_;
ilnik98436952017-07-13 00:47:03 -07001128
1129 std::unique_ptr<test::RtpFileWriter> rtp_file_writer_;
1130 Clock* const clock_;
1131 const int64_t start_ms_;
ivica5d6a06c2015-09-17 05:30:24 -07001132};
1133
palmkviste75f2042016-09-28 06:19:48 -07001134VideoQualityTest::VideoQualityTest()
minyue20c84cc2017-04-10 16:57:57 -07001135 : clock_(Clock::GetRealTimeClock()), receive_logs_(0), send_logs_(0) {
1136 payload_type_map_ = test::CallTest::payload_type_map_;
1137 RTC_DCHECK(payload_type_map_.find(kPayloadTypeH264) ==
1138 payload_type_map_.end());
1139 RTC_DCHECK(payload_type_map_.find(kPayloadTypeVP8) ==
1140 payload_type_map_.end());
1141 RTC_DCHECK(payload_type_map_.find(kPayloadTypeVP9) ==
1142 payload_type_map_.end());
1143 payload_type_map_[kPayloadTypeH264] = webrtc::MediaType::VIDEO;
1144 payload_type_map_[kPayloadTypeVP8] = webrtc::MediaType::VIDEO;
1145 payload_type_map_[kPayloadTypeVP9] = webrtc::MediaType::VIDEO;
1146}
ivica5d6a06c2015-09-17 05:30:24 -07001147
minyue626bc952016-10-31 05:47:02 -07001148VideoQualityTest::Params::Params()
ilnik98436952017-07-13 00:47:03 -07001149 : call({false, Call::Config::BitrateConfig(), 0}),
Rasmus Brandt31027342017-09-29 13:48:12 +00001150 video({false, 640, 480, 30, 50, 800, 800, false, "VP8", 1, -1, 0, false,
1151 false, ""}),
minyue4c8b9422017-03-21 04:11:43 -07001152 audio({false, false, false}),
erikvarga579de6f2017-08-29 09:12:57 -07001153 screenshare({false, false, 10, 0}),
minyue626bc952016-10-31 05:47:02 -07001154 analyzer({"", 0.0, 0.0, 0, "", ""}),
1155 pipe(),
ilnika014cc52017-03-07 04:21:04 -08001156 ss({std::vector<VideoStream>(), 0, 0, -1, std::vector<SpatialLayer>()}),
ilnik98436952017-07-13 00:47:03 -07001157 logging({false, "", "", ""}) {}
minyue626bc952016-10-31 05:47:02 -07001158
1159VideoQualityTest::Params::~Params() = default;
1160
ivica5d6a06c2015-09-17 05:30:24 -07001161void VideoQualityTest::TestBody() {}
1162
sprangce4aef12015-11-02 07:23:20 -08001163std::string VideoQualityTest::GenerateGraphTitle() const {
1164 std::stringstream ss;
minyue626bc952016-10-31 05:47:02 -07001165 ss << params_.video.codec;
1166 ss << " (" << params_.video.target_bitrate_bps / 1000 << "kbps";
1167 ss << ", " << params_.video.fps << " FPS";
sprangce4aef12015-11-02 07:23:20 -08001168 if (params_.screenshare.scroll_duration)
1169 ss << ", " << params_.screenshare.scroll_duration << "s scroll";
1170 if (params_.ss.streams.size() > 1)
1171 ss << ", Stream #" << params_.ss.selected_stream;
1172 if (params_.ss.num_spatial_layers > 1)
1173 ss << ", Layer #" << params_.ss.selected_sl;
1174 ss << ")";
1175 return ss.str();
1176}
1177
1178void VideoQualityTest::CheckParams() {
stefan7de8d642017-02-07 07:14:08 -08001179 if (!params_.video.enabled)
1180 return;
sprangce4aef12015-11-02 07:23:20 -08001181 // Add a default stream in none specified.
1182 if (params_.ss.streams.empty())
1183 params_.ss.streams.push_back(VideoQualityTest::DefaultVideoStream(params_));
1184 if (params_.ss.num_spatial_layers == 0)
1185 params_.ss.num_spatial_layers = 1;
1186
1187 if (params_.pipe.loss_percent != 0 ||
1188 params_.pipe.queue_length_packets != 0) {
1189 // Since LayerFilteringTransport changes the sequence numbers, we can't
1190 // use that feature with pack loss, since the NACK request would end up
1191 // retransmitting the wrong packets.
1192 RTC_CHECK(params_.ss.selected_sl == -1 ||
sprangee37de32015-11-23 06:10:23 -08001193 params_.ss.selected_sl == params_.ss.num_spatial_layers - 1);
minyue626bc952016-10-31 05:47:02 -07001194 RTC_CHECK(params_.video.selected_tl == -1 ||
1195 params_.video.selected_tl ==
1196 params_.video.num_temporal_layers - 1);
sprangce4aef12015-11-02 07:23:20 -08001197 }
1198
1199 // TODO(ivica): Should max_bitrate_bps == -1 represent inf max bitrate, as it
1200 // does in some parts of the code?
minyue626bc952016-10-31 05:47:02 -07001201 RTC_CHECK_GE(params_.video.max_bitrate_bps, params_.video.target_bitrate_bps);
1202 RTC_CHECK_GE(params_.video.target_bitrate_bps, params_.video.min_bitrate_bps);
1203 RTC_CHECK_LT(params_.video.selected_tl, params_.video.num_temporal_layers);
sprang1168fd42017-06-21 09:00:17 -07001204 RTC_CHECK_LE(params_.ss.selected_stream, params_.ss.streams.size());
sprangce4aef12015-11-02 07:23:20 -08001205 for (const VideoStream& stream : params_.ss.streams) {
1206 RTC_CHECK_GE(stream.min_bitrate_bps, 0);
1207 RTC_CHECK_GE(stream.target_bitrate_bps, stream.min_bitrate_bps);
1208 RTC_CHECK_GE(stream.max_bitrate_bps, stream.target_bitrate_bps);
sprangce4aef12015-11-02 07:23:20 -08001209 }
1210 // TODO(ivica): Should we check if the sum of all streams/layers is equal to
1211 // the total bitrate? We anyway have to update them in the case bitrate
1212 // estimator changes the total bitrates.
1213 RTC_CHECK_GE(params_.ss.num_spatial_layers, 1);
1214 RTC_CHECK_LE(params_.ss.selected_sl, params_.ss.num_spatial_layers);
1215 RTC_CHECK(params_.ss.spatial_layers.empty() ||
1216 params_.ss.spatial_layers.size() ==
1217 static_cast<size_t>(params_.ss.num_spatial_layers));
minyue626bc952016-10-31 05:47:02 -07001218 if (params_.video.codec == "VP8") {
sprangce4aef12015-11-02 07:23:20 -08001219 RTC_CHECK_EQ(params_.ss.num_spatial_layers, 1);
minyue626bc952016-10-31 05:47:02 -07001220 } else if (params_.video.codec == "VP9") {
kwibergaf476c72016-11-28 15:21:39 -08001221 RTC_CHECK_EQ(params_.ss.streams.size(), 1);
sprangce4aef12015-11-02 07:23:20 -08001222 }
ilnik98436952017-07-13 00:47:03 -07001223 RTC_CHECK_GE(params_.call.num_thumbnails, 0);
1224 if (params_.call.num_thumbnails > 0) {
ilnika014cc52017-03-07 04:21:04 -08001225 RTC_CHECK_EQ(params_.ss.num_spatial_layers, 1);
1226 RTC_CHECK_EQ(params_.ss.streams.size(), 3);
1227 RTC_CHECK_EQ(params_.video.num_temporal_layers, 3);
1228 RTC_CHECK_EQ(params_.video.codec, "VP8");
1229 }
sprangce4aef12015-11-02 07:23:20 -08001230}
1231
1232// Static.
1233std::vector<int> VideoQualityTest::ParseCSV(const std::string& str) {
1234 // Parse comma separated nonnegative integers, where some elements may be
1235 // empty. The empty values are replaced with -1.
1236 // E.g. "10,-20,,30,40" --> {10, 20, -1, 30,40}
1237 // E.g. ",,10,,20," --> {-1, -1, 10, -1, 20, -1}
1238 std::vector<int> result;
1239 if (str.empty())
1240 return result;
1241
1242 const char* p = str.c_str();
1243 int value = -1;
1244 int pos;
1245 while (*p) {
1246 if (*p == ',') {
1247 result.push_back(value);
1248 value = -1;
1249 ++p;
1250 continue;
1251 }
1252 RTC_CHECK_EQ(sscanf(p, "%d%n", &value, &pos), 1)
1253 << "Unexpected non-number value.";
1254 p += pos;
1255 }
1256 result.push_back(value);
1257 return result;
1258}
1259
1260// Static.
1261VideoStream VideoQualityTest::DefaultVideoStream(const Params& params) {
1262 VideoStream stream;
minyue626bc952016-10-31 05:47:02 -07001263 stream.width = params.video.width;
1264 stream.height = params.video.height;
1265 stream.max_framerate = params.video.fps;
1266 stream.min_bitrate_bps = params.video.min_bitrate_bps;
1267 stream.target_bitrate_bps = params.video.target_bitrate_bps;
1268 stream.max_bitrate_bps = params.video.max_bitrate_bps;
sprang1168fd42017-06-21 09:00:17 -07001269 stream.max_qp = kDefaultMaxQp;
sprang6ef1b342017-03-13 02:01:32 -07001270 // TODO(sprang): Can we make this less of a hack?
1271 if (params.video.num_temporal_layers == 2) {
1272 stream.temporal_layer_thresholds_bps.push_back(stream.target_bitrate_bps);
1273 } else if (params.video.num_temporal_layers == 3) {
1274 stream.temporal_layer_thresholds_bps.push_back(stream.max_bitrate_bps / 4);
1275 stream.temporal_layer_thresholds_bps.push_back(stream.target_bitrate_bps);
sprangff19d352017-09-06 07:14:02 -07001276 } else {
1277 RTC_CHECK_LE(params.video.num_temporal_layers, kMaxTemporalStreams);
1278 for (int i = 0; i < params.video.num_temporal_layers - 1; ++i) {
1279 stream.temporal_layer_thresholds_bps.push_back(static_cast<int>(
1280 stream.max_bitrate_bps * kVp8LayerRateAlloction[0][i] + 0.5));
1281 }
ilnika014cc52017-03-07 04:21:04 -08001282 }
1283 return stream;
1284}
1285
1286// Static.
1287VideoStream VideoQualityTest::DefaultThumbnailStream() {
1288 VideoStream stream;
1289 stream.width = 320;
1290 stream.height = 180;
1291 stream.max_framerate = 7;
1292 stream.min_bitrate_bps = 7500;
1293 stream.target_bitrate_bps = 37500;
1294 stream.max_bitrate_bps = 50000;
sprang1168fd42017-06-21 09:00:17 -07001295 stream.max_qp = kDefaultMaxQp;
sprangce4aef12015-11-02 07:23:20 -08001296 return stream;
1297}
1298
1299// Static.
1300void VideoQualityTest::FillScalabilitySettings(
1301 Params* params,
1302 const std::vector<std::string>& stream_descriptors,
sprang1168fd42017-06-21 09:00:17 -07001303 int num_streams,
sprangce4aef12015-11-02 07:23:20 -08001304 size_t selected_stream,
1305 int num_spatial_layers,
1306 int selected_sl,
1307 const std::vector<std::string>& sl_descriptors) {
sprang1168fd42017-06-21 09:00:17 -07001308 if (params->ss.streams.empty() && params->ss.infer_streams) {
1309 webrtc::VideoEncoderConfig encoder_config;
1310 encoder_config.content_type =
1311 params->screenshare.enabled
1312 ? webrtc::VideoEncoderConfig::ContentType::kScreen
1313 : webrtc::VideoEncoderConfig::ContentType::kRealtimeVideo;
1314 encoder_config.max_bitrate_bps = params->video.max_bitrate_bps;
1315 encoder_config.min_transmit_bitrate_bps = params->video.min_transmit_bps;
1316 encoder_config.number_of_streams = num_streams;
1317 encoder_config.spatial_layers = params->ss.spatial_layers;
1318 encoder_config.video_stream_factory =
1319 new rtc::RefCountedObject<cricket::EncoderStreamFactory>(
1320 params->video.codec, kDefaultMaxQp, params->video.fps,
1321 params->screenshare.enabled, true);
1322 params->ss.streams =
1323 encoder_config.video_stream_factory->CreateEncoderStreams(
1324 static_cast<int>(params->video.width),
1325 static_cast<int>(params->video.height), encoder_config);
1326 } else {
1327 // Read VideoStream and SpatialLayer elements from a list of comma separated
1328 // lists. To use a default value for an element, use -1 or leave empty.
1329 // Validity checks performed in CheckParams.
1330 RTC_CHECK(params->ss.streams.empty());
1331 for (auto descriptor : stream_descriptors) {
1332 if (descriptor.empty())
1333 continue;
1334 VideoStream stream = VideoQualityTest::DefaultVideoStream(*params);
1335 std::vector<int> v = VideoQualityTest::ParseCSV(descriptor);
1336 if (v[0] != -1)
1337 stream.width = static_cast<size_t>(v[0]);
1338 if (v[1] != -1)
1339 stream.height = static_cast<size_t>(v[1]);
1340 if (v[2] != -1)
1341 stream.max_framerate = v[2];
1342 if (v[3] != -1)
1343 stream.min_bitrate_bps = v[3];
1344 if (v[4] != -1)
1345 stream.target_bitrate_bps = v[4];
1346 if (v[5] != -1)
1347 stream.max_bitrate_bps = v[5];
1348 if (v.size() > 6 && v[6] != -1)
1349 stream.max_qp = v[6];
1350 if (v.size() > 7) {
1351 stream.temporal_layer_thresholds_bps.clear();
1352 stream.temporal_layer_thresholds_bps.insert(
1353 stream.temporal_layer_thresholds_bps.end(), v.begin() + 7, v.end());
1354 } else {
1355 // Automatic TL thresholds for more than two layers not supported.
1356 RTC_CHECK_LE(params->video.num_temporal_layers, 2);
1357 }
1358 params->ss.streams.push_back(stream);
sprangce4aef12015-11-02 07:23:20 -08001359 }
sprangce4aef12015-11-02 07:23:20 -08001360 }
sprangce4aef12015-11-02 07:23:20 -08001361
sprang1168fd42017-06-21 09:00:17 -07001362 params->ss.num_spatial_layers = std::max(1, num_spatial_layers);
1363 params->ss.selected_stream = selected_stream;
1364
sprangce4aef12015-11-02 07:23:20 -08001365 params->ss.selected_sl = selected_sl;
1366 RTC_CHECK(params->ss.spatial_layers.empty());
1367 for (auto descriptor : sl_descriptors) {
1368 if (descriptor.empty())
1369 continue;
1370 std::vector<int> v = VideoQualityTest::ParseCSV(descriptor);
1371 RTC_CHECK_GT(v[2], 0);
1372
1373 SpatialLayer layer;
1374 layer.scaling_factor_num = v[0] == -1 ? 1 : v[0];
1375 layer.scaling_factor_den = v[1] == -1 ? 1 : v[1];
1376 layer.target_bitrate_bps = v[2];
1377 params->ss.spatial_layers.push_back(layer);
1378 }
1379}
1380
minyuea27172d2016-11-01 05:59:29 -07001381void VideoQualityTest::SetupVideo(Transport* send_transport,
1382 Transport* recv_transport) {
brandtr8313a6f2017-01-13 07:41:19 -08001383 size_t num_video_streams = params_.ss.streams.size();
1384 size_t num_flexfec_streams = params_.video.flexfec ? 1 : 0;
1385 CreateSendConfig(num_video_streams, 0, num_flexfec_streams, send_transport);
ivica5d6a06c2015-09-17 05:30:24 -07001386
1387 int payload_type;
minyue626bc952016-10-31 05:47:02 -07001388 if (params_.video.codec == "H264") {
Magnus Jedvert46a27652017-11-13 14:10:02 +01001389 video_encoder_ = H264Encoder::Create(cricket::VideoCodec("H264"));
hbosbab934b2016-01-27 01:36:03 -08001390 payload_type = kPayloadTypeH264;
minyue626bc952016-10-31 05:47:02 -07001391 } else if (params_.video.codec == "VP8") {
ilnikcb8c1462017-03-09 09:23:30 -08001392 if (params_.screenshare.enabled && params_.ss.streams.size() > 1) {
Rasmus Brandt31027342017-09-29 13:48:12 +00001393 // Simulcast screenshare needs a simulcast encoder adapter to work, since
1394 // encoders usually can't natively do simulcast with different frame rates
1395 // for the different layers.
ilnikcb8c1462017-03-09 09:23:30 -08001396 video_encoder_.reset(
Magnus Jedvertdf4883d2017-11-17 14:44:55 +01001397 new SimulcastEncoderAdapter(new InternalEncoderFactory()));
ilnikcb8c1462017-03-09 09:23:30 -08001398 } else {
Magnus Jedvert46a27652017-11-13 14:10:02 +01001399 video_encoder_ = VP8Encoder::Create();
ilnikcb8c1462017-03-09 09:23:30 -08001400 }
ivica5d6a06c2015-09-17 05:30:24 -07001401 payload_type = kPayloadTypeVP8;
minyue626bc952016-10-31 05:47:02 -07001402 } else if (params_.video.codec == "VP9") {
Magnus Jedvert46a27652017-11-13 14:10:02 +01001403 video_encoder_ = VP9Encoder::Create();
ivica5d6a06c2015-09-17 05:30:24 -07001404 payload_type = kPayloadTypeVP9;
1405 } else {
1406 RTC_NOTREACHED() << "Codec not supported!";
1407 return;
1408 }
minyuea27172d2016-11-01 05:59:29 -07001409 video_send_config_.encoder_settings.encoder = video_encoder_.get();
minyue626bc952016-10-31 05:47:02 -07001410 video_send_config_.encoder_settings.payload_name = params_.video.codec;
stefanff483612015-12-21 03:14:00 -08001411 video_send_config_.encoder_settings.payload_type = payload_type;
1412 video_send_config_.rtp.nack.rtp_history_ms = kNackRtpHistoryMs;
1413 video_send_config_.rtp.rtx.payload_type = kSendRtxPayloadType;
brandtr8313a6f2017-01-13 07:41:19 -08001414 for (size_t i = 0; i < num_video_streams; ++i)
stefanff483612015-12-21 03:14:00 -08001415 video_send_config_.rtp.rtx.ssrcs.push_back(kSendRtxSsrcs[i]);
ivica5d6a06c2015-09-17 05:30:24 -07001416
stefanff483612015-12-21 03:14:00 -08001417 video_send_config_.rtp.extensions.clear();
minyue626bc952016-10-31 05:47:02 -07001418 if (params_.call.send_side_bwe) {
stefanff483612015-12-21 03:14:00 -08001419 video_send_config_.rtp.extensions.push_back(
isheriff6f8d6862016-05-26 11:24:55 -07001420 RtpExtension(RtpExtension::kTransportSequenceNumberUri,
Stefan Holmer12952972015-10-29 15:13:24 +01001421 test::kTransportSequenceNumberExtensionId));
1422 } else {
stefanff483612015-12-21 03:14:00 -08001423 video_send_config_.rtp.extensions.push_back(RtpExtension(
isheriff6f8d6862016-05-26 11:24:55 -07001424 RtpExtension::kAbsSendTimeUri, test::kAbsSendTimeExtensionId));
Erik Språng6b8d3552015-09-24 15:06:57 +02001425 }
ilnik00d802b2017-04-11 10:34:31 -07001426 video_send_config_.rtp.extensions.push_back(RtpExtension(
1427 RtpExtension::kVideoContentTypeUri, test::kVideoContentTypeExtensionId));
ilnik04f4d122017-06-19 07:18:55 -07001428 video_send_config_.rtp.extensions.push_back(RtpExtension(
1429 RtpExtension::kVideoTimingUri, test::kVideoTimingExtensionId));
Erik Språng6b8d3552015-09-24 15:06:57 +02001430
stefanff483612015-12-21 03:14:00 -08001431 video_encoder_config_.min_transmit_bitrate_bps =
minyue626bc952016-10-31 05:47:02 -07001432 params_.video.min_transmit_bps;
perkjfa10b552016-10-02 23:45:26 -07001433
brandtr1293aca2016-11-16 22:47:29 -08001434 video_send_config_.suspend_below_min_bitrate =
1435 params_.video.suspend_below_min_bitrate;
1436
perkjfa10b552016-10-02 23:45:26 -07001437 video_encoder_config_.number_of_streams = params_.ss.streams.size();
1438 video_encoder_config_.max_bitrate_bps = 0;
1439 for (size_t i = 0; i < params_.ss.streams.size(); ++i) {
1440 video_encoder_config_.max_bitrate_bps +=
1441 params_.ss.streams[i].max_bitrate_bps;
1442 }
ilnik6b826ef2017-06-16 06:53:48 -07001443 if (params_.ss.infer_streams) {
1444 video_encoder_config_.video_stream_factory =
1445 new rtc::RefCountedObject<cricket::EncoderStreamFactory>(
1446 params_.video.codec, params_.ss.streams[0].max_qp,
1447 params_.video.fps, params_.screenshare.enabled, true);
1448 } else {
1449 video_encoder_config_.video_stream_factory =
1450 new rtc::RefCountedObject<VideoStreamFactory>(params_.ss.streams);
1451 }
perkjfa10b552016-10-02 23:45:26 -07001452
stefanff483612015-12-21 03:14:00 -08001453 video_encoder_config_.spatial_layers = params_.ss.spatial_layers;
ivica5d6a06c2015-09-17 05:30:24 -07001454
1455 CreateMatchingReceiveConfigs(recv_transport);
1456
sprang1168fd42017-06-21 09:00:17 -07001457 const bool decode_all_receive_streams =
1458 params_.ss.selected_stream == params_.ss.streams.size();
1459
brandtr8313a6f2017-01-13 07:41:19 -08001460 for (size_t i = 0; i < num_video_streams; ++i) {
stefanff483612015-12-21 03:14:00 -08001461 video_receive_configs_[i].rtp.nack.rtp_history_ms = kNackRtpHistoryMs;
brandtr14742122017-01-27 04:53:07 -08001462 video_receive_configs_[i].rtp.rtx_ssrc = kSendRtxSsrcs[i];
nisse26e3abb2017-08-25 04:44:25 -07001463 video_receive_configs_[i]
1464 .rtp.rtx_associated_payload_types[kSendRtxPayloadType] = payload_type;
minyue626bc952016-10-31 05:47:02 -07001465 video_receive_configs_[i].rtp.transport_cc = params_.call.send_side_bwe;
Stefan Holmer85d5ac72017-02-09 16:25:16 +01001466 video_receive_configs_[i].rtp.remb = !params_.call.send_side_bwe;
ilnik00d802b2017-04-11 10:34:31 -07001467 // Enable RTT calculation so NTP time estimator will work.
1468 video_receive_configs_[i].rtp.rtcp_xr.receiver_reference_time_report = true;
ilnik9fd9f6c2017-03-02 08:10:10 -08001469 // Force fake decoders on non-selected simulcast streams.
sprang1168fd42017-06-21 09:00:17 -07001470 if (!decode_all_receive_streams && i != params_.ss.selected_stream) {
ilnik9fd9f6c2017-03-02 08:10:10 -08001471 VideoReceiveStream::Decoder decoder;
1472 decoder.decoder = new test::FakeDecoder();
1473 decoder.payload_type = video_send_config_.encoder_settings.payload_type;
1474 decoder.payload_name = video_send_config_.encoder_settings.payload_name;
1475 video_receive_configs_[i].decoders.clear();
1476 allocated_decoders_.emplace_back(decoder.decoder);
1477 video_receive_configs_[i].decoders.push_back(decoder);
1478 }
sprangce4aef12015-11-02 07:23:20 -08001479 }
brandtr1293aca2016-11-16 22:47:29 -08001480
1481 if (params_.video.flexfec) {
brandtr8313a6f2017-01-13 07:41:19 -08001482 // Override send config constructed by CreateSendConfig.
sprang1168fd42017-06-21 09:00:17 -07001483 if (decode_all_receive_streams) {
1484 for (uint32_t media_ssrc : video_send_config_.rtp.ssrcs) {
1485 video_send_config_.rtp.flexfec.protected_media_ssrcs.push_back(
1486 media_ssrc);
1487 }
1488 } else {
1489 video_send_config_.rtp.flexfec.protected_media_ssrcs = {
1490 kVideoSendSsrcs[params_.ss.selected_stream]};
1491 }
brandtr1293aca2016-11-16 22:47:29 -08001492
brandtr8313a6f2017-01-13 07:41:19 -08001493 // The matching receive config is _not_ created by
1494 // CreateMatchingReceiveConfigs, since VideoQualityTest is not a BaseTest.
1495 // Set up the receive config manually instead.
1496 FlexfecReceiveStream::Config flexfec_receive_config(recv_transport);
brandtr1cfbd602016-12-08 04:17:53 -08001497 flexfec_receive_config.payload_type =
brandtr3d200bd2017-01-16 06:59:19 -08001498 video_send_config_.rtp.flexfec.payload_type;
1499 flexfec_receive_config.remote_ssrc = video_send_config_.rtp.flexfec.ssrc;
brandtr1293aca2016-11-16 22:47:29 -08001500 flexfec_receive_config.protected_media_ssrcs =
1501 video_send_config_.rtp.flexfec.protected_media_ssrcs;
brandtrfa5a3682017-01-17 01:33:54 -08001502 flexfec_receive_config.local_ssrc = kReceiverLocalVideoSsrc;
brandtrb29e6522016-12-21 06:37:18 -08001503 flexfec_receive_config.transport_cc = params_.call.send_side_bwe;
1504 if (params_.call.send_side_bwe) {
1505 flexfec_receive_config.rtp_header_extensions.push_back(
1506 RtpExtension(RtpExtension::kTransportSequenceNumberUri,
1507 test::kTransportSequenceNumberExtensionId));
1508 } else {
1509 flexfec_receive_config.rtp_header_extensions.push_back(RtpExtension(
1510 RtpExtension::kAbsSendTimeUri, test::kAbsSendTimeExtensionId));
1511 }
brandtr1293aca2016-11-16 22:47:29 -08001512 flexfec_receive_configs_.push_back(flexfec_receive_config);
brandtr7cd28b92017-09-22 00:26:25 -07001513 if (num_video_streams > 0) {
1514 video_receive_configs_[0].rtp.protected_by_flexfec = true;
1515 }
brandtr1293aca2016-11-16 22:47:29 -08001516 }
1517
1518 if (params_.video.ulpfec) {
1519 video_send_config_.rtp.ulpfec.red_payload_type = kRedPayloadType;
1520 video_send_config_.rtp.ulpfec.ulpfec_payload_type = kUlpfecPayloadType;
1521 video_send_config_.rtp.ulpfec.red_rtx_payload_type = kRtxRedPayloadType;
1522
sprang1168fd42017-06-21 09:00:17 -07001523 if (decode_all_receive_streams) {
1524 for (auto it = video_receive_configs_.begin();
1525 it != video_receive_configs_.end(); ++it) {
nisse3b3622f2017-09-26 02:49:21 -07001526 it->rtp.red_payload_type =
sprang1168fd42017-06-21 09:00:17 -07001527 video_send_config_.rtp.ulpfec.red_payload_type;
nisse3b3622f2017-09-26 02:49:21 -07001528 it->rtp.ulpfec_payload_type =
sprang1168fd42017-06-21 09:00:17 -07001529 video_send_config_.rtp.ulpfec.ulpfec_payload_type;
nisseca5706d2017-09-11 02:32:16 -07001530 it->rtp.rtx_associated_payload_types[video_send_config_.rtp.ulpfec
1531 .red_rtx_payload_type] =
1532 video_send_config_.rtp.ulpfec.red_payload_type;
sprang1168fd42017-06-21 09:00:17 -07001533 }
1534 } else {
nisse3b3622f2017-09-26 02:49:21 -07001535 video_receive_configs_[params_.ss.selected_stream].rtp.red_payload_type =
sprang1168fd42017-06-21 09:00:17 -07001536 video_send_config_.rtp.ulpfec.red_payload_type;
1537 video_receive_configs_[params_.ss.selected_stream]
nisse3b3622f2017-09-26 02:49:21 -07001538 .rtp.ulpfec_payload_type =
sprang1168fd42017-06-21 09:00:17 -07001539 video_send_config_.rtp.ulpfec.ulpfec_payload_type;
1540 video_receive_configs_[params_.ss.selected_stream]
nisseca5706d2017-09-11 02:32:16 -07001541 .rtp.rtx_associated_payload_types[video_send_config_.rtp.ulpfec
1542 .red_rtx_payload_type] =
1543 video_send_config_.rtp.ulpfec.red_payload_type;
sprang1168fd42017-06-21 09:00:17 -07001544 }
brandtr1293aca2016-11-16 22:47:29 -08001545 }
ivica5d6a06c2015-09-17 05:30:24 -07001546}
1547
ilnika014cc52017-03-07 04:21:04 -08001548void VideoQualityTest::SetupThumbnails(Transport* send_transport,
1549 Transport* recv_transport) {
ilnik98436952017-07-13 00:47:03 -07001550 for (int i = 0; i < params_.call.num_thumbnails; ++i) {
ilnika014cc52017-03-07 04:21:04 -08001551 thumbnail_encoders_.emplace_back(VP8Encoder::Create());
1552
1553 // Thumbnails will be send in the other way: from receiver_call to
1554 // sender_call.
1555 VideoSendStream::Config thumbnail_send_config(recv_transport);
1556 thumbnail_send_config.rtp.ssrcs.push_back(kThumbnailSendSsrcStart + i);
1557 thumbnail_send_config.encoder_settings.encoder =
1558 thumbnail_encoders_.back().get();
1559 thumbnail_send_config.encoder_settings.payload_name = params_.video.codec;
1560 thumbnail_send_config.encoder_settings.payload_type = kPayloadTypeVP8;
1561 thumbnail_send_config.rtp.nack.rtp_history_ms = kNackRtpHistoryMs;
1562 thumbnail_send_config.rtp.rtx.payload_type = kSendRtxPayloadType;
1563 thumbnail_send_config.rtp.rtx.ssrcs.push_back(kThumbnailRtxSsrcStart + i);
1564 thumbnail_send_config.rtp.extensions.clear();
1565 if (params_.call.send_side_bwe) {
1566 thumbnail_send_config.rtp.extensions.push_back(
1567 RtpExtension(RtpExtension::kTransportSequenceNumberUri,
1568 test::kTransportSequenceNumberExtensionId));
1569 } else {
1570 thumbnail_send_config.rtp.extensions.push_back(RtpExtension(
1571 RtpExtension::kAbsSendTimeUri, test::kAbsSendTimeExtensionId));
1572 }
1573
1574 VideoEncoderConfig thumbnail_encoder_config;
1575 thumbnail_encoder_config.min_transmit_bitrate_bps = 7500;
1576 thumbnail_send_config.suspend_below_min_bitrate =
1577 params_.video.suspend_below_min_bitrate;
1578 thumbnail_encoder_config.number_of_streams = 1;
1579 thumbnail_encoder_config.max_bitrate_bps = 50000;
ilnik6b826ef2017-06-16 06:53:48 -07001580 if (params_.ss.infer_streams) {
1581 thumbnail_encoder_config.video_stream_factory =
1582 new rtc::RefCountedObject<VideoStreamFactory>(params_.ss.streams);
1583 } else {
1584 thumbnail_encoder_config.video_stream_factory =
1585 new rtc::RefCountedObject<cricket::EncoderStreamFactory>(
1586 params_.video.codec, params_.ss.streams[0].max_qp,
1587 params_.video.fps, params_.screenshare.enabled, true);
1588 }
ilnika014cc52017-03-07 04:21:04 -08001589 thumbnail_encoder_config.spatial_layers = params_.ss.spatial_layers;
1590
1591 VideoReceiveStream::Config thumbnail_receive_config(send_transport);
1592 thumbnail_receive_config.rtp.remb = false;
1593 thumbnail_receive_config.rtp.transport_cc = true;
1594 thumbnail_receive_config.rtp.local_ssrc = kReceiverLocalVideoSsrc;
1595 for (const RtpExtension& extension : thumbnail_send_config.rtp.extensions)
1596 thumbnail_receive_config.rtp.extensions.push_back(extension);
1597 thumbnail_receive_config.renderer = &fake_renderer_;
1598
1599 VideoReceiveStream::Decoder decoder =
1600 test::CreateMatchingDecoder(thumbnail_send_config.encoder_settings);
1601 allocated_decoders_.push_back(
1602 std::unique_ptr<VideoDecoder>(decoder.decoder));
1603 thumbnail_receive_config.decoders.clear();
1604 thumbnail_receive_config.decoders.push_back(decoder);
1605 thumbnail_receive_config.rtp.remote_ssrc =
1606 thumbnail_send_config.rtp.ssrcs[0];
1607
1608 thumbnail_receive_config.rtp.nack.rtp_history_ms = kNackRtpHistoryMs;
1609 thumbnail_receive_config.rtp.rtx_ssrc = kThumbnailRtxSsrcStart + i;
nisse26e3abb2017-08-25 04:44:25 -07001610 thumbnail_receive_config.rtp
1611 .rtx_associated_payload_types[kSendRtxPayloadType] = kPayloadTypeVP8;
ilnika014cc52017-03-07 04:21:04 -08001612 thumbnail_receive_config.rtp.transport_cc = params_.call.send_side_bwe;
1613 thumbnail_receive_config.rtp.remb = !params_.call.send_side_bwe;
1614
1615 thumbnail_encoder_configs_.push_back(thumbnail_encoder_config.Copy());
1616 thumbnail_send_configs_.push_back(thumbnail_send_config.Copy());
1617 thumbnail_receive_configs_.push_back(thumbnail_receive_config.Copy());
1618 }
1619
ilnik98436952017-07-13 00:47:03 -07001620 for (int i = 0; i < params_.call.num_thumbnails; ++i) {
ilnika014cc52017-03-07 04:21:04 -08001621 thumbnail_send_streams_.push_back(receiver_call_->CreateVideoSendStream(
1622 thumbnail_send_configs_[i].Copy(),
1623 thumbnail_encoder_configs_[i].Copy()));
1624 thumbnail_receive_streams_.push_back(sender_call_->CreateVideoReceiveStream(
1625 thumbnail_receive_configs_[i].Copy()));
1626 }
1627}
1628
1629void VideoQualityTest::DestroyThumbnailStreams() {
1630 for (VideoSendStream* thumbnail_send_stream : thumbnail_send_streams_)
1631 receiver_call_->DestroyVideoSendStream(thumbnail_send_stream);
1632 thumbnail_send_streams_.clear();
1633 for (VideoReceiveStream* thumbnail_receive_stream :
1634 thumbnail_receive_streams_)
1635 sender_call_->DestroyVideoReceiveStream(thumbnail_receive_stream);
1636 thumbnail_send_streams_.clear();
1637 thumbnail_receive_streams_.clear();
eladalon413ee9a2017-08-22 04:02:52 -07001638 for (std::unique_ptr<test::VideoCapturer>& video_caputurer :
1639 thumbnail_capturers_) {
1640 video_caputurer.reset();
1641 }
ilnika014cc52017-03-07 04:21:04 -08001642}
1643
ilnik2a8c2f52017-02-15 02:23:28 -08001644void VideoQualityTest::SetupScreenshareOrSVC() {
1645 if (params_.screenshare.enabled) {
1646 // Fill out codec settings.
1647 video_encoder_config_.content_type =
1648 VideoEncoderConfig::ContentType::kScreen;
1649 degradation_preference_ =
1650 VideoSendStream::DegradationPreference::kMaintainResolution;
1651 if (params_.video.codec == "VP8") {
1652 VideoCodecVP8 vp8_settings = VideoEncoder::GetDefaultVp8Settings();
1653 vp8_settings.denoisingOn = false;
1654 vp8_settings.frameDroppingOn = false;
1655 vp8_settings.numberOfTemporalLayers =
1656 static_cast<unsigned char>(params_.video.num_temporal_layers);
1657 video_encoder_config_.encoder_specific_settings =
1658 new rtc::RefCountedObject<
1659 VideoEncoderConfig::Vp8EncoderSpecificSettings>(vp8_settings);
1660 } else if (params_.video.codec == "VP9") {
1661 VideoCodecVP9 vp9_settings = VideoEncoder::GetDefaultVp9Settings();
1662 vp9_settings.denoisingOn = false;
1663 vp9_settings.frameDroppingOn = false;
1664 vp9_settings.numberOfTemporalLayers =
1665 static_cast<unsigned char>(params_.video.num_temporal_layers);
1666 vp9_settings.numberOfSpatialLayers =
1667 static_cast<unsigned char>(params_.ss.num_spatial_layers);
1668 video_encoder_config_.encoder_specific_settings =
1669 new rtc::RefCountedObject<
1670 VideoEncoderConfig::Vp9EncoderSpecificSettings>(vp9_settings);
1671 }
1672 // Setup frame generator.
1673 const size_t kWidth = 1850;
1674 const size_t kHeight = 1110;
erikvarga579de6f2017-08-29 09:12:57 -07001675 if (params_.screenshare.generate_slides) {
1676 frame_generator_ = test::FrameGenerator::CreateSlideGenerator(
1677 kWidth, kHeight,
perkja8ba1952017-02-27 06:52:10 -08001678 params_.screenshare.slide_change_interval * params_.video.fps);
ilnik2a8c2f52017-02-15 02:23:28 -08001679 } else {
erikvarga579de6f2017-08-29 09:12:57 -07001680 std::vector<std::string> slides = params_.screenshare.slides;
1681 if (slides.size() == 0) {
1682 slides.push_back(test::ResourcePath("web_screenshot_1850_1110", "yuv"));
1683 slides.push_back(test::ResourcePath("presentation_1850_1110", "yuv"));
1684 slides.push_back(test::ResourcePath("photo_1850_1110", "yuv"));
1685 slides.push_back(
1686 test::ResourcePath("difficult_photo_1850_1110", "yuv"));
1687 }
1688 if (params_.screenshare.scroll_duration == 0) {
1689 // Cycle image every slide_change_interval seconds.
1690 frame_generator_ = test::FrameGenerator::CreateFromYuvFile(
1691 slides, kWidth, kHeight,
1692 params_.screenshare.slide_change_interval * params_.video.fps);
1693 } else {
1694 RTC_CHECK_LE(params_.video.width, kWidth);
1695 RTC_CHECK_LE(params_.video.height, kHeight);
1696 RTC_CHECK_GT(params_.screenshare.slide_change_interval, 0);
1697 const int kPauseDurationMs =
1698 (params_.screenshare.slide_change_interval -
1699 params_.screenshare.scroll_duration) *
1700 1000;
1701 RTC_CHECK_LE(params_.screenshare.scroll_duration,
1702 params_.screenshare.slide_change_interval);
ilnik2a8c2f52017-02-15 02:23:28 -08001703
erikvarga579de6f2017-08-29 09:12:57 -07001704 frame_generator_ =
1705 test::FrameGenerator::CreateScrollingInputFromYuvFiles(
1706 clock_, slides, kWidth, kHeight, params_.video.width,
1707 params_.video.height,
1708 params_.screenshare.scroll_duration * 1000, kPauseDurationMs);
1709 }
ilnik2a8c2f52017-02-15 02:23:28 -08001710 }
1711 } else if (params_.ss.num_spatial_layers > 1) { // For non-screenshare case.
1712 RTC_CHECK(params_.video.codec == "VP9");
kthelgason29a44e32016-09-27 03:52:02 -07001713 VideoCodecVP9 vp9_settings = VideoEncoder::GetDefaultVp9Settings();
kthelgason29a44e32016-09-27 03:52:02 -07001714 vp9_settings.numberOfTemporalLayers =
minyue626bc952016-10-31 05:47:02 -07001715 static_cast<unsigned char>(params_.video.num_temporal_layers);
kthelgason29a44e32016-09-27 03:52:02 -07001716 vp9_settings.numberOfSpatialLayers =
sprangce4aef12015-11-02 07:23:20 -08001717 static_cast<unsigned char>(params_.ss.num_spatial_layers);
kthelgason29a44e32016-09-27 03:52:02 -07001718 video_encoder_config_.encoder_specific_settings = new rtc::RefCountedObject<
1719 VideoEncoderConfig::Vp9EncoderSpecificSettings>(vp9_settings);
ivica5d6a06c2015-09-17 05:30:24 -07001720 }
ivica5d6a06c2015-09-17 05:30:24 -07001721}
1722
ilnika014cc52017-03-07 04:21:04 -08001723void VideoQualityTest::SetupThumbnailCapturers(size_t num_thumbnail_streams) {
1724 VideoStream thumbnail = DefaultThumbnailStream();
1725 for (size_t i = 0; i < num_thumbnail_streams; ++i) {
1726 thumbnail_capturers_.emplace_back(test::FrameGeneratorCapturer::Create(
1727 static_cast<int>(thumbnail.width), static_cast<int>(thumbnail.height),
1728 thumbnail.max_framerate, clock_));
ilnikf89a7382017-03-07 06:15:27 -08001729 RTC_DCHECK(thumbnail_capturers_.back());
ilnika014cc52017-03-07 04:21:04 -08001730 }
1731}
1732
perkja49cbd32016-09-16 07:53:41 -07001733void VideoQualityTest::CreateCapturer() {
sprangce4aef12015-11-02 07:23:20 -08001734 if (params_.screenshare.enabled) {
1735 test::FrameGeneratorCapturer* frame_generator_capturer =
perkja8ba1952017-02-27 06:52:10 -08001736 new test::FrameGeneratorCapturer(clock_, std::move(frame_generator_),
minyue626bc952016-10-31 05:47:02 -07001737 params_.video.fps);
ivica2d4e6c52015-09-23 01:57:06 -07001738 EXPECT_TRUE(frame_generator_capturer->Init());
minyuea27172d2016-11-01 05:59:29 -07001739 video_capturer_.reset(frame_generator_capturer);
ivica5d6a06c2015-09-17 05:30:24 -07001740 } else {
ilnik6b826ef2017-06-16 06:53:48 -07001741 if (params_.video.clip_name == "Generator") {
1742 video_capturer_.reset(test::FrameGeneratorCapturer::Create(
1743 static_cast<int>(params_.video.width),
1744 static_cast<int>(params_.video.height), params_.video.fps, clock_));
1745 } else if (params_.video.clip_name.empty()) {
minyuea27172d2016-11-01 05:59:29 -07001746 video_capturer_.reset(test::VcmCapturer::Create(
Tarun Chawla8e857d12017-05-31 19:20:57 +05301747 params_.video.width, params_.video.height, params_.video.fps,
1748 params_.video.capture_device_index));
sprang1bed2e42017-01-23 08:46:51 -08001749 if (!video_capturer_) {
1750 // Failed to get actual camera, use chroma generator as backup.
1751 video_capturer_.reset(test::FrameGeneratorCapturer::Create(
perkja8ba1952017-02-27 06:52:10 -08001752 static_cast<int>(params_.video.width),
1753 static_cast<int>(params_.video.height), params_.video.fps, clock_));
sprang1bed2e42017-01-23 08:46:51 -08001754 }
ivica5d6a06c2015-09-17 05:30:24 -07001755 } else {
minyuea27172d2016-11-01 05:59:29 -07001756 video_capturer_.reset(test::FrameGeneratorCapturer::CreateFromYuvFile(
perkja49cbd32016-09-16 07:53:41 -07001757 test::ResourcePath(params_.video.clip_name, "yuv"),
minyue626bc952016-10-31 05:47:02 -07001758 params_.video.width, params_.video.height, params_.video.fps,
ivica2d4e6c52015-09-23 01:57:06 -07001759 clock_));
minyuea27172d2016-11-01 05:59:29 -07001760 ASSERT_TRUE(video_capturer_) << "Could not create capturer for "
1761 << params_.video.clip_name
1762 << ".yuv. Is this resource file present?";
ivica5d6a06c2015-09-17 05:30:24 -07001763 }
1764 }
sprang1bed2e42017-01-23 08:46:51 -08001765 RTC_DCHECK(video_capturer_.get());
ivica5d6a06c2015-09-17 05:30:24 -07001766}
1767
Christoffer Rodbrob4bb4eb2017-11-13 13:03:52 +01001768std::unique_ptr<test::LayerFilteringTransport>
1769VideoQualityTest::CreateSendTransport() {
1770 return rtc::MakeUnique<test::LayerFilteringTransport>(
1771 &task_queue_, params_.pipe, sender_call_.get(), kPayloadTypeVP8,
1772 kPayloadTypeVP9, params_.video.selected_tl, params_.ss.selected_sl,
1773 payload_type_map_);
1774}
1775
1776std::unique_ptr<test::DirectTransport>
1777VideoQualityTest::CreateReceiveTransport() {
1778 return rtc::MakeUnique<test::DirectTransport>(
1779 &task_queue_, params_.pipe, receiver_call_.get(), payload_type_map_);
1780}
1781
sprang7a975f72015-10-12 06:33:21 -07001782void VideoQualityTest::RunWithAnalyzer(const Params& params) {
eladalon413ee9a2017-08-22 04:02:52 -07001783 std::unique_ptr<test::LayerFilteringTransport> send_transport;
1784 std::unique_ptr<test::DirectTransport> recv_transport;
1785 FILE* graph_data_output_file = nullptr;
1786 std::unique_ptr<VideoAnalyzer> analyzer;
1787
sprangce4aef12015-11-02 07:23:20 -08001788 params_ = params;
1789
minyue626bc952016-10-31 05:47:02 -07001790 RTC_CHECK(!params_.audio.enabled);
ivica5d6a06c2015-09-17 05:30:24 -07001791 // TODO(ivica): Merge with RunWithRenderer and use a flag / argument to
1792 // differentiate between the analyzer and the renderer case.
sprangce4aef12015-11-02 07:23:20 -08001793 CheckParams();
ivica5d6a06c2015-09-17 05:30:24 -07001794
sprangce4aef12015-11-02 07:23:20 -08001795 if (!params_.analyzer.graph_data_output_filename.empty()) {
ivica5d6a06c2015-09-17 05:30:24 -07001796 graph_data_output_file =
sprangce4aef12015-11-02 07:23:20 -08001797 fopen(params_.analyzer.graph_data_output_filename.c_str(), "w");
Peter Boström74f6e9e2016-04-04 17:56:10 +02001798 RTC_CHECK(graph_data_output_file)
sprangce4aef12015-11-02 07:23:20 -08001799 << "Can't open the file " << params_.analyzer.graph_data_output_filename
1800 << "!";
ivica87f83a92015-10-08 05:13:32 -07001801 }
sprang7a975f72015-10-12 06:33:21 -07001802
ilnik98436952017-07-13 00:47:03 -07001803 if (!params.logging.rtc_event_log_name.empty()) {
Ilya Nikolaevskiya4259f62017-12-05 13:19:45 +01001804 send_event_log_ =
1805 RtcEventLog::Create(clock_, RtcEventLog::EncodingType::Legacy);
1806 recv_event_log_ =
1807 RtcEventLog::Create(clock_, RtcEventLog::EncodingType::Legacy);
1808 std::unique_ptr<RtcEventLogOutputFile> send_output(
Bjorn Tereliusde939432017-11-20 17:38:14 +01001809 rtc::MakeUnique<RtcEventLogOutputFile>(
Ilya Nikolaevskiya4259f62017-12-05 13:19:45 +01001810 params.logging.rtc_event_log_name + "_send",
1811 RtcEventLog::kUnlimitedOutput));
1812 std::unique_ptr<RtcEventLogOutputFile> recv_output(
1813 rtc::MakeUnique<RtcEventLogOutputFile>(
1814 params.logging.rtc_event_log_name + "_recv",
1815 RtcEventLog::kUnlimitedOutput));
1816 bool event_log_started =
1817 send_event_log_->StartLogging(std::move(send_output),
1818 RtcEventLog::kImmediateOutput) &&
1819 recv_event_log_->StartLogging(std::move(recv_output),
1820 RtcEventLog::kImmediateOutput);
ilnik98436952017-07-13 00:47:03 -07001821 RTC_DCHECK(event_log_started);
Ilya Nikolaevskiya4259f62017-12-05 13:19:45 +01001822 } else {
1823 send_event_log_ = RtcEventLog::CreateNull();
1824 recv_event_log_ = RtcEventLog::CreateNull();
ilnik98436952017-07-13 00:47:03 -07001825 }
1826
Ilya Nikolaevskiya4259f62017-12-05 13:19:45 +01001827 Call::Config send_call_config(send_event_log_.get());
1828 Call::Config recv_call_config(recv_event_log_.get());
1829 send_call_config.bitrate_config = params.call.call_bitrate_config;
1830 recv_call_config.bitrate_config = params.call.call_bitrate_config;
stefanf116bd02015-10-27 08:29:42 -07001831
Ilya Nikolaevskiya4259f62017-12-05 13:19:45 +01001832 task_queue_.SendTask([this, &send_call_config, &recv_call_config,
1833 &send_transport, &recv_transport]() {
1834 CreateCalls(send_call_config, recv_call_config);
1835 send_transport = CreateSendTransport();
1836 recv_transport = CreateReceiveTransport();
1837 });
stefanf116bd02015-10-27 08:29:42 -07001838
sprangce4aef12015-11-02 07:23:20 -08001839 std::string graph_title = params_.analyzer.graph_title;
1840 if (graph_title.empty())
1841 graph_title = VideoQualityTest::GenerateGraphTitle();
sprangc1b57a12017-02-28 08:50:47 -08001842 bool is_quick_test_enabled = field_trial::IsEnabled("WebRTC-QuickPerfTest");
eladalon413ee9a2017-08-22 04:02:52 -07001843 analyzer = rtc::MakeUnique<VideoAnalyzer>(
1844 send_transport.get(), params_.analyzer.test_label,
ilnik2a8c2f52017-02-15 02:23:28 -08001845 params_.analyzer.avg_psnr_threshold, params_.analyzer.avg_ssim_threshold,
ilnik9ae0d762017-02-15 00:53:12 -08001846 is_quick_test_enabled
1847 ? kFramesSentInQuickTest
1848 : params_.analyzer.test_durations_secs * params_.video.fps,
sprangce4aef12015-11-02 07:23:20 -08001849 graph_data_output_file, graph_title,
ilnik3dd5ad92017-02-09 04:58:53 -08001850 kVideoSendSsrcs[params_.ss.selected_stream],
ilnik46a00212017-02-10 09:16:05 -08001851 kSendRtxSsrcs[params_.ss.selected_stream],
ilnikcb8c1462017-03-09 09:23:30 -08001852 static_cast<size_t>(params_.ss.selected_stream), params.ss.selected_sl,
ilnik98436952017-07-13 00:47:03 -07001853 params_.video.selected_tl, is_quick_test_enabled, clock_,
1854 params_.logging.rtp_dump_name);
ivica5d6a06c2015-09-17 05:30:24 -07001855
eladalon413ee9a2017-08-22 04:02:52 -07001856 task_queue_.SendTask([&]() {
1857 analyzer->SetCall(sender_call_.get());
1858 analyzer->SetReceiver(receiver_call_->Receiver());
1859 send_transport->SetReceiver(analyzer.get());
1860 recv_transport->SetReceiver(sender_call_->Receiver());
ivica5d6a06c2015-09-17 05:30:24 -07001861
eladalon413ee9a2017-08-22 04:02:52 -07001862 SetupVideo(analyzer.get(), recv_transport.get());
1863 SetupThumbnails(analyzer.get(), recv_transport.get());
1864 video_receive_configs_[params_.ss.selected_stream].renderer =
1865 analyzer.get();
1866 video_send_config_.pre_encode_callback = analyzer->pre_encode_proxy();
1867 RTC_DCHECK(!video_send_config_.post_encode_callback);
1868 video_send_config_.post_encode_callback = analyzer->encode_timing_proxy();
ivica5d6a06c2015-09-17 05:30:24 -07001869
eladalon413ee9a2017-08-22 04:02:52 -07001870 SetupScreenshareOrSVC();
kthelgason2bc68642017-02-07 07:02:22 -08001871
eladalon413ee9a2017-08-22 04:02:52 -07001872 CreateFlexfecStreams();
1873 CreateVideoStreams();
1874 analyzer->SetSendStream(video_send_stream_);
1875 if (video_receive_streams_.size() == 1)
1876 analyzer->SetReceiveStream(video_receive_streams_[0]);
ivica5d6a06c2015-09-17 05:30:24 -07001877
eladalon413ee9a2017-08-22 04:02:52 -07001878 video_send_stream_->SetSource(analyzer->OutputInterface(),
1879 degradation_preference_);
ilnika014cc52017-03-07 04:21:04 -08001880
eladalon413ee9a2017-08-22 04:02:52 -07001881 SetupThumbnailCapturers(params_.call.num_thumbnails);
1882 for (size_t i = 0; i < thumbnail_send_streams_.size(); ++i) {
1883 thumbnail_send_streams_[i]->SetSource(thumbnail_capturers_[i].get(),
1884 degradation_preference_);
1885 }
ilnika014cc52017-03-07 04:21:04 -08001886
eladalon413ee9a2017-08-22 04:02:52 -07001887 CreateCapturer();
ivicac1cc8542015-10-08 03:44:06 -07001888
eladalon413ee9a2017-08-22 04:02:52 -07001889 analyzer->SetSource(video_capturer_.get(), params_.ss.infer_streams);
ilnika014cc52017-03-07 04:21:04 -08001890
eladalon413ee9a2017-08-22 04:02:52 -07001891 StartEncodedFrameLogs(video_send_stream_);
1892 StartEncodedFrameLogs(video_receive_streams_[params_.ss.selected_stream]);
1893 video_send_stream_->Start();
1894 for (VideoSendStream* thumbnail_send_stream : thumbnail_send_streams_)
1895 thumbnail_send_stream->Start();
1896 for (VideoReceiveStream* receive_stream : video_receive_streams_)
1897 receive_stream->Start();
1898 for (VideoReceiveStream* thumbnail_receive_stream :
1899 thumbnail_receive_streams_)
1900 thumbnail_receive_stream->Start();
ilnika014cc52017-03-07 04:21:04 -08001901
eladalon413ee9a2017-08-22 04:02:52 -07001902 analyzer->StartMeasuringCpuProcessTime();
ivica5d6a06c2015-09-17 05:30:24 -07001903
eladalon413ee9a2017-08-22 04:02:52 -07001904 video_capturer_->Start();
1905 for (std::unique_ptr<test::VideoCapturer>& video_caputurer :
1906 thumbnail_capturers_) {
1907 video_caputurer->Start();
1908 }
1909 });
ivica5d6a06c2015-09-17 05:30:24 -07001910
eladalon413ee9a2017-08-22 04:02:52 -07001911 analyzer->Wait();
ivica5d6a06c2015-09-17 05:30:24 -07001912
Ilya Nikolaevskiy2c72fe82017-10-02 13:01:04 +02001913 event_log_->StopLogging();
1914
eladalon413ee9a2017-08-22 04:02:52 -07001915 task_queue_.SendTask([&]() {
1916 for (std::unique_ptr<test::VideoCapturer>& video_caputurer :
1917 thumbnail_capturers_)
1918 video_caputurer->Stop();
1919 video_capturer_->Stop();
1920 for (VideoReceiveStream* thumbnail_receive_stream :
1921 thumbnail_receive_streams_)
1922 thumbnail_receive_stream->Stop();
1923 for (VideoReceiveStream* receive_stream : video_receive_streams_)
1924 receive_stream->Stop();
1925 for (VideoSendStream* thumbnail_send_stream : thumbnail_send_streams_)
1926 thumbnail_send_stream->Stop();
1927 video_send_stream_->Stop();
ivica5d6a06c2015-09-17 05:30:24 -07001928
eladalon413ee9a2017-08-22 04:02:52 -07001929 DestroyStreams();
1930 DestroyThumbnailStreams();
ivica5d6a06c2015-09-17 05:30:24 -07001931
eladalon413ee9a2017-08-22 04:02:52 -07001932 if (graph_data_output_file)
1933 fclose(graph_data_output_file);
1934
1935 video_capturer_.reset();
1936 send_transport.reset();
1937 recv_transport.reset();
1938
1939 DestroyCalls();
1940 });
ivica5d6a06c2015-09-17 05:30:24 -07001941}
1942
minyuea27172d2016-11-01 05:59:29 -07001943void VideoQualityTest::SetupAudio(int send_channel_id,
1944 int receive_channel_id,
minyuea27172d2016-11-01 05:59:29 -07001945 Transport* transport,
1946 AudioReceiveStream** audio_receive_stream) {
1947 audio_send_config_ = AudioSendStream::Config(transport);
1948 audio_send_config_.voe_channel_id = send_channel_id;
1949 audio_send_config_.rtp.ssrc = kAudioSendSsrc;
1950
1951 // Add extension to enable audio send side BWE, and allow audio bit rate
1952 // adaptation.
1953 audio_send_config_.rtp.extensions.clear();
1954 if (params_.call.send_side_bwe) {
1955 audio_send_config_.rtp.extensions.push_back(
1956 webrtc::RtpExtension(webrtc::RtpExtension::kTransportSequenceNumberUri,
1957 test::kTransportSequenceNumberExtensionId));
minyue10cbb462016-11-07 09:29:22 -08001958 audio_send_config_.min_bitrate_bps = kOpusMinBitrateBps;
1959 audio_send_config_.max_bitrate_bps = kOpusBitrateFbBps;
minyuea27172d2016-11-01 05:59:29 -07001960 }
ossu20a4b3f2017-04-27 02:08:52 -07001961 audio_send_config_.send_codec_spec =
1962 rtc::Optional<AudioSendStream::Config::SendCodecSpec>(
1963 {kAudioSendPayloadType,
1964 {"OPUS", 48000, 2,
1965 {{"usedtx", (params_.audio.dtx ? "1" : "0")},
1966 {"stereo", "1"}}}});
Rasmus Brandt31027342017-09-29 13:48:12 +00001967 audio_send_config_.encoder_factory = encoder_factory_;
sprang1168fd42017-06-21 09:00:17 -07001968 audio_send_stream_ = sender_call_->CreateAudioSendStream(audio_send_config_);
minyuea27172d2016-11-01 05:59:29 -07001969
1970 AudioReceiveStream::Config audio_config;
1971 audio_config.rtp.local_ssrc = kReceiverLocalAudioSsrc;
1972 audio_config.rtcp_send_transport = transport;
1973 audio_config.voe_channel_id = receive_channel_id;
1974 audio_config.rtp.remote_ssrc = audio_send_config_.rtp.ssrc;
1975 audio_config.rtp.transport_cc = params_.call.send_side_bwe;
1976 audio_config.rtp.extensions = audio_send_config_.rtp.extensions;
Rasmus Brandt31027342017-09-29 13:48:12 +00001977 audio_config.decoder_factory = decoder_factory_;
minyue20c84cc2017-04-10 16:57:57 -07001978 audio_config.decoder_map = {{kAudioSendPayloadType, {"OPUS", 48000, 2}}};
minyuea27172d2016-11-01 05:59:29 -07001979 if (params_.video.enabled && params_.audio.sync_video)
1980 audio_config.sync_group = kSyncGroup;
1981
sprang1168fd42017-06-21 09:00:17 -07001982 *audio_receive_stream =
1983 receiver_call_->CreateAudioReceiveStream(audio_config);
minyuea27172d2016-11-01 05:59:29 -07001984}
1985
minyue73208662016-08-18 06:28:55 -07001986void VideoQualityTest::RunWithRenderers(const Params& params) {
eladalon413ee9a2017-08-22 04:02:52 -07001987 std::unique_ptr<test::LayerFilteringTransport> send_transport;
1988 std::unique_ptr<test::DirectTransport> recv_transport;
Fredrik Solenbergd3195342017-11-21 20:33:05 +01001989 std::unique_ptr<test::FakeAudioDevice> fake_audio_device;
minyue73208662016-08-18 06:28:55 -07001990 ::VoiceEngineState voe;
minyuea27172d2016-11-01 05:59:29 -07001991 std::unique_ptr<test::VideoRenderer> local_preview;
eladalon413ee9a2017-08-22 04:02:52 -07001992 std::vector<std::unique_ptr<test::VideoRenderer>> loopback_renderers;
minyue73208662016-08-18 06:28:55 -07001993 AudioReceiveStream* audio_receive_stream = nullptr;
minyue73208662016-08-18 06:28:55 -07001994
eladalon413ee9a2017-08-22 04:02:52 -07001995 task_queue_.SendTask([&]() {
1996 params_ = params;
1997 CheckParams();
palmkviste75f2042016-09-28 06:19:48 -07001998
eladalon413ee9a2017-08-22 04:02:52 -07001999 // TODO(ivica): Remove bitrate_config and use the default Call::Config(), to
2000 // match the full stack tests.
2001 Call::Config call_config(event_log_.get());
2002 call_config.bitrate_config = params_.call.call_bitrate_config;
Niels Möller2bf9e732017-08-14 11:26:16 +02002003
Fredrik Solenbergd3195342017-11-21 20:33:05 +01002004 fake_audio_device.reset(new test::FakeAudioDevice(
2005 test::FakeAudioDevice::CreatePulsedNoiseCapturer(32000, 48000),
2006 test::FakeAudioDevice::CreateDiscardRenderer(48000),
2007 1.f));
2008
eladalon413ee9a2017-08-22 04:02:52 -07002009 rtc::scoped_refptr<webrtc::AudioProcessing> audio_processing(
2010 webrtc::AudioProcessing::Create());
ivica5d6a06c2015-09-17 05:30:24 -07002011
eladalon413ee9a2017-08-22 04:02:52 -07002012 if (params_.audio.enabled) {
Fredrik Solenbergd3195342017-11-21 20:33:05 +01002013 CreateVoiceEngine(&voe, fake_audio_device.get(), audio_processing.get(),
2014 decoder_factory_);
eladalon413ee9a2017-08-22 04:02:52 -07002015 AudioState::Config audio_state_config;
2016 audio_state_config.voice_engine = voe.voice_engine;
2017 audio_state_config.audio_mixer = AudioMixerImpl::Create();
2018 audio_state_config.audio_processing = audio_processing;
2019 call_config.audio_state = AudioState::Create(audio_state_config);
Fredrik Solenbergd3195342017-11-21 20:33:05 +01002020 fake_audio_device->RegisterAudioCallback(
2021 call_config.audio_state->audio_transport());
eladalon413ee9a2017-08-22 04:02:52 -07002022 }
minyue73208662016-08-18 06:28:55 -07002023
eladalon413ee9a2017-08-22 04:02:52 -07002024 CreateCalls(call_config, call_config);
2025
2026 // TODO(minyue): consider if this is a good transport even for audio only
2027 // calls.
2028 send_transport = rtc::MakeUnique<test::LayerFilteringTransport>(
2029 &task_queue_, params.pipe, sender_call_.get(), kPayloadTypeVP8,
2030 kPayloadTypeVP9, params.video.selected_tl, params_.ss.selected_sl,
2031 payload_type_map_);
2032
2033 recv_transport = rtc::MakeUnique<test::DirectTransport>(
2034 &task_queue_, params_.pipe, receiver_call_.get(), payload_type_map_);
2035
2036 // TODO(ivica): Use two calls to be able to merge with RunWithAnalyzer or at
2037 // least share as much code as possible. That way this test would also match
2038 // the full stack tests better.
2039 send_transport->SetReceiver(receiver_call_->Receiver());
2040 recv_transport->SetReceiver(sender_call_->Receiver());
2041
2042 if (params_.video.enabled) {
2043 // Create video renderers.
2044 local_preview.reset(test::VideoRenderer::Create(
2045 "Local Preview", params_.video.width, params_.video.height));
2046
2047 const size_t selected_stream_id = params_.ss.selected_stream;
2048 const size_t num_streams = params_.ss.streams.size();
2049
2050 if (selected_stream_id == num_streams) {
2051 for (size_t stream_id = 0; stream_id < num_streams; ++stream_id) {
2052 std::ostringstream oss;
2053 oss << "Loopback Video - Stream #" << static_cast<int>(stream_id);
2054 loopback_renderers.emplace_back(test::VideoRenderer::Create(
2055 oss.str().c_str(), params_.ss.streams[stream_id].width,
2056 params_.ss.streams[stream_id].height));
2057 }
2058 } else {
2059 loopback_renderers.emplace_back(test::VideoRenderer::Create(
2060 "Loopback Video", params_.ss.streams[selected_stream_id].width,
2061 params_.ss.streams[selected_stream_id].height));
2062 }
2063
2064 SetupVideo(send_transport.get(), recv_transport.get());
2065
2066 video_send_config_.pre_encode_callback = local_preview.get();
2067 if (selected_stream_id == num_streams) {
2068 for (size_t stream_id = 0; stream_id < num_streams; ++stream_id) {
2069 video_receive_configs_[stream_id].renderer =
2070 loopback_renderers[stream_id].get();
2071 if (params_.audio.enabled && params_.audio.sync_video)
2072 video_receive_configs_[stream_id].sync_group = kSyncGroup;
2073 }
2074 } else {
2075 video_receive_configs_[selected_stream_id].renderer =
2076 loopback_renderers.back().get();
2077 if (params_.audio.enabled && params_.audio.sync_video)
2078 video_receive_configs_[selected_stream_id].sync_group = kSyncGroup;
2079 }
2080
Sergey Silkin2248ab62017-11-09 18:01:13 +01002081 SetupScreenshareOrSVC();
eladalon413ee9a2017-08-22 04:02:52 -07002082
2083 CreateFlexfecStreams();
2084 CreateVideoStreams();
2085
2086 CreateCapturer();
2087 video_send_stream_->SetSource(video_capturer_.get(),
2088 degradation_preference_);
2089 }
2090
2091 if (params_.audio.enabled) {
2092 SetupAudio(voe.send_channel_id, voe.receive_channel_id,
2093 send_transport.get(), &audio_receive_stream);
2094 }
2095
2096 for (VideoReceiveStream* receive_stream : video_receive_streams_)
2097 StartEncodedFrameLogs(receive_stream);
2098 StartEncodedFrameLogs(video_send_stream_);
2099
2100 // Start sending and receiving video.
2101 if (params_.video.enabled) {
2102 for (VideoReceiveStream* video_receive_stream : video_receive_streams_)
2103 video_receive_stream->Start();
2104
2105 video_send_stream_->Start();
2106 video_capturer_->Start();
2107 }
2108
2109 if (params_.audio.enabled) {
2110 // Start receiving audio.
2111 audio_receive_stream->Start();
2112 EXPECT_EQ(0, voe.base->StartPlayout(voe.receive_channel_id));
2113
2114 // Start sending audio.
2115 audio_send_stream_->Start();
2116 EXPECT_EQ(0, voe.base->StartSend(voe.send_channel_id));
2117 }
2118 });
minyue73208662016-08-18 06:28:55 -07002119
ivica5d6a06c2015-09-17 05:30:24 -07002120 test::PressEnterToContinue();
2121
eladalon413ee9a2017-08-22 04:02:52 -07002122 task_queue_.SendTask([&]() {
2123 if (params_.audio.enabled) {
2124 // Stop sending audio.
2125 EXPECT_EQ(0, voe.base->StopSend(voe.send_channel_id));
2126 audio_send_stream_->Stop();
minyue73208662016-08-18 06:28:55 -07002127
eladalon413ee9a2017-08-22 04:02:52 -07002128 // Stop receiving audio.
2129 EXPECT_EQ(0, voe.base->StopPlayout(voe.receive_channel_id));
2130 audio_receive_stream->Stop();
2131 sender_call_->DestroyAudioSendStream(audio_send_stream_);
2132 receiver_call_->DestroyAudioReceiveStream(audio_receive_stream);
2133 }
minyue73208662016-08-18 06:28:55 -07002134
eladalon413ee9a2017-08-22 04:02:52 -07002135 // Stop receiving and sending video.
2136 if (params_.video.enabled) {
2137 video_capturer_->Stop();
2138 video_send_stream_->Stop();
2139 for (FlexfecReceiveStream* flexfec_receive_stream :
2140 flexfec_receive_streams_) {
2141 for (VideoReceiveStream* video_receive_stream :
2142 video_receive_streams_) {
2143 video_receive_stream->RemoveSecondarySink(flexfec_receive_stream);
2144 }
2145 receiver_call_->DestroyFlexfecReceiveStream(flexfec_receive_stream);
eladalonc0d481a2017-08-02 07:39:07 -07002146 }
eladalon413ee9a2017-08-22 04:02:52 -07002147 for (VideoReceiveStream* receive_stream : video_receive_streams_) {
2148 receive_stream->Stop();
2149 receiver_call_->DestroyVideoReceiveStream(receive_stream);
2150 }
2151 sender_call_->DestroyVideoSendStream(video_send_stream_);
brandtr1293aca2016-11-16 22:47:29 -08002152 }
minyue73208662016-08-18 06:28:55 -07002153
eladalon413ee9a2017-08-22 04:02:52 -07002154 video_capturer_.reset();
2155 send_transport.reset();
2156 recv_transport.reset();
sprang1168fd42017-06-21 09:00:17 -07002157
eladalon413ee9a2017-08-22 04:02:52 -07002158 if (params_.audio.enabled)
2159 DestroyVoiceEngine(&voe);
2160
2161 local_preview.reset();
2162 loopback_renderers.clear();
2163
2164 DestroyCalls();
2165 });
ivica5d6a06c2015-09-17 05:30:24 -07002166}
2167
palmkviste75f2042016-09-28 06:19:48 -07002168void VideoQualityTest::StartEncodedFrameLogs(VideoSendStream* stream) {
ilnik98436952017-07-13 00:47:03 -07002169 if (!params_.logging.encoded_frame_base_path.empty()) {
palmkviste75f2042016-09-28 06:19:48 -07002170 std::ostringstream str;
2171 str << send_logs_++;
2172 std::string prefix =
ilnik98436952017-07-13 00:47:03 -07002173 params_.logging.encoded_frame_base_path + "." + str.str() + ".send.";
palmkviste75f2042016-09-28 06:19:48 -07002174 stream->EnableEncodedFrameRecording(
2175 std::vector<rtc::PlatformFile>(
2176 {rtc::CreatePlatformFile(prefix + "1.ivf"),
2177 rtc::CreatePlatformFile(prefix + "2.ivf"),
2178 rtc::CreatePlatformFile(prefix + "3.ivf")}),
ilnik98436952017-07-13 00:47:03 -07002179 100000000);
palmkviste75f2042016-09-28 06:19:48 -07002180 }
2181}
ilnikcb8c1462017-03-09 09:23:30 -08002182
palmkviste75f2042016-09-28 06:19:48 -07002183void VideoQualityTest::StartEncodedFrameLogs(VideoReceiveStream* stream) {
ilnik98436952017-07-13 00:47:03 -07002184 if (!params_.logging.encoded_frame_base_path.empty()) {
palmkviste75f2042016-09-28 06:19:48 -07002185 std::ostringstream str;
2186 str << receive_logs_++;
2187 std::string path =
ilnik98436952017-07-13 00:47:03 -07002188 params_.logging.encoded_frame_base_path + "." + str.str() + ".recv.ivf";
palmkviste75f2042016-09-28 06:19:48 -07002189 stream->EnableEncodedFrameRecording(rtc::CreatePlatformFile(path),
ilnik98436952017-07-13 00:47:03 -07002190 100000000);
palmkviste75f2042016-09-28 06:19:48 -07002191 }
2192}
ivica5d6a06c2015-09-17 05:30:24 -07002193} // namespace webrtc