blob: 07781b19d5c2b45ab58b3651afb4f6dbfaee626e [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 */
perkja49cbd32016-09-16 07:53:41 -070010#include "webrtc/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
ivica5d6a06c2015-09-17 05:30:24 -070020#include "webrtc/base/checks.h"
Peter Boström5811a392015-12-10 13:02:50 +010021#include "webrtc/base/event.h"
ivica5d6a06c2015-09-17 05:30:24 -070022#include "webrtc/base/format_macros.h"
nissec7fe3c22016-04-20 03:25:36 -070023#include "webrtc/base/optional.h"
palmkviste75f2042016-09-28 06:19:48 -070024#include "webrtc/base/platform_file.h"
sprange1f2f1f2016-02-01 02:04:52 -080025#include "webrtc/base/timeutils.h"
ossuf515ab82016-12-07 04:52:58 -080026#include "webrtc/call/call.h"
ivica5d6a06c2015-09-17 05:30:24 -070027#include "webrtc/common_video/libyuv/include/webrtc_libyuv.h"
skvlad11a9cbf2016-10-07 11:53:05 -070028#include "webrtc/logging/rtc_event_log/rtc_event_log.h"
aleloi10111bc2016-11-17 06:48:48 -080029#include "webrtc/modules/audio_mixer/audio_mixer_impl.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010030#include "webrtc/modules/rtp_rtcp/include/rtp_header_parser.h"
sprangce4aef12015-11-02 07:23:20 -080031#include "webrtc/modules/rtp_rtcp/source/rtp_utility.h"
magjed509e4fe2016-11-18 01:34:11 -080032#include "webrtc/modules/video_coding/codecs/h264/include/h264.h"
33#include "webrtc/modules/video_coding/codecs/vp8/include/vp8.h"
34#include "webrtc/modules/video_coding/codecs/vp9/include/vp9.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010035#include "webrtc/system_wrappers/include/cpu_info.h"
kwibergac9f8762016-09-30 22:29:43 -070036#include "webrtc/test/gtest.h"
ivica5d6a06c2015-09-17 05:30:24 -070037#include "webrtc/test/layer_filtering_transport.h"
38#include "webrtc/test/run_loop.h"
39#include "webrtc/test/statistics.h"
40#include "webrtc/test/testsupport/fileutils.h"
perkja49cbd32016-09-16 07:53:41 -070041#include "webrtc/test/vcm_capturer.h"
ivica5d6a06c2015-09-17 05:30:24 -070042#include "webrtc/test/video_renderer.h"
minyue73208662016-08-18 06:28:55 -070043#include "webrtc/voice_engine/include/voe_base.h"
minyue73208662016-08-18 06:28:55 -070044
45namespace {
46
47constexpr int kSendStatsPollingIntervalMs = 1000;
48constexpr int kPayloadTypeH264 = 122;
49constexpr int kPayloadTypeVP8 = 123;
50constexpr int kPayloadTypeVP9 = 124;
51constexpr size_t kMaxComparisons = 10;
52constexpr char kSyncGroup[] = "av_sync";
minyue10cbb462016-11-07 09:29:22 -080053constexpr int kOpusMinBitrateBps = 6000;
54constexpr int kOpusBitrateFbBps = 32000;
minyue73208662016-08-18 06:28:55 -070055
56struct VoiceEngineState {
57 VoiceEngineState()
58 : voice_engine(nullptr),
59 base(nullptr),
minyue73208662016-08-18 06:28:55 -070060 send_channel_id(-1),
61 receive_channel_id(-1) {}
62
63 webrtc::VoiceEngine* voice_engine;
64 webrtc::VoEBase* base;
minyue73208662016-08-18 06:28:55 -070065 int send_channel_id;
66 int receive_channel_id;
67};
68
69void CreateVoiceEngine(VoiceEngineState* voe,
70 rtc::scoped_refptr<webrtc::AudioDecoderFactory>
71 decoder_factory) {
72 voe->voice_engine = webrtc::VoiceEngine::Create();
73 voe->base = webrtc::VoEBase::GetInterface(voe->voice_engine);
minyue73208662016-08-18 06:28:55 -070074 EXPECT_EQ(0, voe->base->Init(nullptr, nullptr, decoder_factory));
solenberg88499ec2016-09-07 07:34:41 -070075 webrtc::VoEBase::ChannelConfig config;
76 config.enable_voice_pacing = true;
77 voe->send_channel_id = voe->base->CreateChannel(config);
minyue73208662016-08-18 06:28:55 -070078 EXPECT_GE(voe->send_channel_id, 0);
79 voe->receive_channel_id = voe->base->CreateChannel();
80 EXPECT_GE(voe->receive_channel_id, 0);
81}
82
83void DestroyVoiceEngine(VoiceEngineState* voe) {
84 voe->base->DeleteChannel(voe->send_channel_id);
85 voe->send_channel_id = -1;
86 voe->base->DeleteChannel(voe->receive_channel_id);
87 voe->receive_channel_id = -1;
88 voe->base->Release();
89 voe->base = nullptr;
minyue73208662016-08-18 06:28:55 -070090
91 webrtc::VoiceEngine::Delete(voe->voice_engine);
92 voe->voice_engine = nullptr;
93}
94
perkjfa10b552016-10-02 23:45:26 -070095class VideoStreamFactory
96 : public webrtc::VideoEncoderConfig::VideoStreamFactoryInterface {
97 public:
98 explicit VideoStreamFactory(const std::vector<webrtc::VideoStream>& streams)
99 : streams_(streams) {}
100
101 private:
102 std::vector<webrtc::VideoStream> CreateEncoderStreams(
103 int width,
104 int height,
105 const webrtc::VideoEncoderConfig& encoder_config) override {
mflodmand79f97b2016-12-15 07:24:33 -0800106 // The highest layer must match the incoming resolution.
107 std::vector<webrtc::VideoStream> streams = streams_;
108 streams[streams_.size() - 1].height = height;
109 streams[streams_.size() - 1].width = width;
110 return streams;
perkjfa10b552016-10-02 23:45:26 -0700111 }
112
113 std::vector<webrtc::VideoStream> streams_;
114};
115
brandtr504b95e2016-12-21 02:54:35 -0800116bool IsFlexfec(int payload_type) {
117 return payload_type == webrtc::VideoQualityTest::kFlexfecPayloadType;
118}
119
minyue73208662016-08-18 06:28:55 -0700120} // namespace
ivica5d6a06c2015-09-17 05:30:24 -0700121
122namespace webrtc {
123
ivica5d6a06c2015-09-17 05:30:24 -0700124class VideoAnalyzer : public PacketReceiver,
pbos2d566682015-09-28 09:59:31 -0700125 public Transport,
nisse7ade7b32016-03-23 04:48:10 -0700126 public rtc::VideoSinkInterface<VideoFrame>,
Peter Boströme4499152016-02-05 11:13:28 +0100127 public EncodedFrameObserver {
ivica5d6a06c2015-09-17 05:30:24 -0700128 public:
sprangce4aef12015-11-02 07:23:20 -0800129 VideoAnalyzer(test::LayerFilteringTransport* transport,
ivica5d6a06c2015-09-17 05:30:24 -0700130 const std::string& test_label,
131 double avg_psnr_threshold,
132 double avg_ssim_threshold,
133 int duration_frames,
sprangce4aef12015-11-02 07:23:20 -0800134 FILE* graph_data_output_file,
135 const std::string& graph_title,
136 uint32_t ssrc_to_analyze)
perkja49cbd32016-09-16 07:53:41 -0700137 : transport_(transport),
ivica5d6a06c2015-09-17 05:30:24 -0700138 receiver_(nullptr),
139 send_stream_(nullptr),
philipelfd870db2017-01-23 03:22:15 -0800140 receive_stream_(nullptr),
perkja49cbd32016-09-16 07:53:41 -0700141 captured_frame_forwarder_(this),
ivica5d6a06c2015-09-17 05:30:24 -0700142 test_label_(test_label),
143 graph_data_output_file_(graph_data_output_file),
sprangce4aef12015-11-02 07:23:20 -0800144 graph_title_(graph_title),
145 ssrc_to_analyze_(ssrc_to_analyze),
pbos14fe7082016-04-20 06:35:56 -0700146 pre_encode_proxy_(this),
Peter Boströme4499152016-02-05 11:13:28 +0100147 encode_timing_proxy_(this),
ivica5d6a06c2015-09-17 05:30:24 -0700148 frames_to_process_(duration_frames),
149 frames_recorded_(0),
150 frames_processed_(0),
151 dropped_frames_(0),
pbos14fe7082016-04-20 06:35:56 -0700152 dropped_frames_before_first_encode_(0),
153 dropped_frames_before_rendering_(0),
ivica5d6a06c2015-09-17 05:30:24 -0700154 last_render_time_(0),
155 rtp_timestamp_delta_(0),
156 avg_psnr_threshold_(avg_psnr_threshold),
157 avg_ssim_threshold_(avg_ssim_threshold),
Peter Boström8c38e8b2015-11-26 17:45:47 +0100158 stats_polling_thread_(&PollStatsThread, this, "StatsPoller"),
Peter Boström5811a392015-12-10 13:02:50 +0100159 comparison_available_event_(false, false),
Peter Boströmdd45eb62016-01-19 15:22:32 +0100160 done_(true, false) {
ivica5d6a06c2015-09-17 05:30:24 -0700161 // Create thread pool for CPU-expensive PSNR/SSIM calculations.
162
163 // Try to use about as many threads as cores, but leave kMinCoresLeft alone,
164 // so that we don't accidentally starve "real" worker threads (codec etc).
165 // Also, don't allocate more than kMaxComparisonThreads, even if there are
166 // spare cores.
167
168 uint32_t num_cores = CpuInfo::DetectNumberOfCores();
kwibergaf476c72016-11-28 15:21:39 -0800169 RTC_DCHECK_GE(num_cores, 1);
ivica5d6a06c2015-09-17 05:30:24 -0700170 static const uint32_t kMinCoresLeft = 4;
171 static const uint32_t kMaxComparisonThreads = 8;
172
173 if (num_cores <= kMinCoresLeft) {
174 num_cores = 1;
175 } else {
176 num_cores -= kMinCoresLeft;
177 num_cores = std::min(num_cores, kMaxComparisonThreads);
178 }
179
180 for (uint32_t i = 0; i < num_cores; ++i) {
Peter Boström8c38e8b2015-11-26 17:45:47 +0100181 rtc::PlatformThread* thread =
182 new rtc::PlatformThread(&FrameComparisonThread, this, "Analyzer");
183 thread->Start();
184 comparison_thread_pool_.push_back(thread);
ivica5d6a06c2015-09-17 05:30:24 -0700185 }
ivica5d6a06c2015-09-17 05:30:24 -0700186 }
187
188 ~VideoAnalyzer() {
Peter Boström8c38e8b2015-11-26 17:45:47 +0100189 for (rtc::PlatformThread* thread : comparison_thread_pool_) {
190 thread->Stop();
ivica5d6a06c2015-09-17 05:30:24 -0700191 delete thread;
192 }
193 }
194
195 virtual void SetReceiver(PacketReceiver* receiver) { receiver_ = receiver; }
196
perkja49cbd32016-09-16 07:53:41 -0700197 void SetSendStream(VideoSendStream* stream) {
198 rtc::CritScope lock(&crit_);
199 RTC_DCHECK(!send_stream_);
200 send_stream_ = stream;
201 }
202
philipelfd870db2017-01-23 03:22:15 -0800203 void SetReceiveStream(VideoReceiveStream* stream) {
204 rtc::CritScope lock(&crit_);
205 RTC_DCHECK(!receive_stream_);
206 receive_stream_ = stream;
207 }
208
perkja49cbd32016-09-16 07:53:41 -0700209 rtc::VideoSinkInterface<VideoFrame>* InputInterface() {
210 return &captured_frame_forwarder_;
211 }
212 rtc::VideoSourceInterface<VideoFrame>* OutputInterface() {
213 return &captured_frame_forwarder_;
214 }
215
ivica5d6a06c2015-09-17 05:30:24 -0700216 DeliveryStatus DeliverPacket(MediaType media_type,
217 const uint8_t* packet,
218 size_t length,
219 const PacketTime& packet_time) override {
Taylor Brandstetter433b95a2016-03-18 11:41:03 -0700220 // Ignore timestamps of RTCP packets. They're not synchronized with
221 // RTP packet timestamps and so they would confuse wrap_handler_.
222 if (RtpHeaderParser::IsRtcp(packet, length)) {
223 return receiver_->DeliverPacket(media_type, packet, length, packet_time);
224 }
225
sprangce4aef12015-11-02 07:23:20 -0800226 RtpUtility::RtpHeaderParser parser(packet, length);
ivica5d6a06c2015-09-17 05:30:24 -0700227 RTPHeader header;
danilchapf6975f42015-12-28 10:18:46 -0800228 parser.Parse(&header);
brandtr504b95e2016-12-21 02:54:35 -0800229 if (!IsFlexfec(header.payloadType)) {
230 // Ignore FlexFEC timestamps, to avoid collisions with media timestamps.
231 // (FlexFEC and media are sent on different SSRCs, which have different
232 // timestamps spaces.)
ivica5d6a06c2015-09-17 05:30:24 -0700233 rtc::CritScope lock(&crit_);
sprang16daaa52016-03-09 01:30:24 -0800234 int64_t timestamp =
235 wrap_handler_.Unwrap(header.timestamp - rtp_timestamp_delta_);
236 recv_times_[timestamp] =
ivica5d6a06c2015-09-17 05:30:24 -0700237 Clock::GetRealTimeClock()->CurrentNtpInMilliseconds();
238 }
239
240 return receiver_->DeliverPacket(media_type, packet, length, packet_time);
241 }
242
Peter Boströme4499152016-02-05 11:13:28 +0100243 void MeasuredEncodeTiming(int64_t ntp_time_ms, int encode_time_ms) {
ivica8d15bd62015-10-07 02:43:12 -0700244 rtc::CritScope crit(&comparison_lock_);
245 samples_encode_time_ms_[ntp_time_ms] = encode_time_ms;
246 }
247
pbos14fe7082016-04-20 06:35:56 -0700248 void PreEncodeOnFrame(const VideoFrame& video_frame) {
249 rtc::CritScope lock(&crit_);
250 if (!first_send_timestamp_ && rtp_timestamp_delta_ == 0) {
251 while (frames_.front().timestamp() != video_frame.timestamp()) {
252 ++dropped_frames_before_first_encode_;
253 frames_.pop_front();
254 RTC_CHECK(!frames_.empty());
255 }
256 first_send_timestamp_ = rtc::Optional<uint32_t>(video_frame.timestamp());
257 }
258 }
259
stefan1d8a5062015-10-02 03:39:33 -0700260 bool SendRtp(const uint8_t* packet,
261 size_t length,
262 const PacketOptions& options) override {
sprangce4aef12015-11-02 07:23:20 -0800263 RtpUtility::RtpHeaderParser parser(packet, length);
ivica5d6a06c2015-09-17 05:30:24 -0700264 RTPHeader header;
danilchapf6975f42015-12-28 10:18:46 -0800265 parser.Parse(&header);
ivica5d6a06c2015-09-17 05:30:24 -0700266
sprangce4aef12015-11-02 07:23:20 -0800267 int64_t current_time =
268 Clock::GetRealTimeClock()->CurrentNtpInMilliseconds();
269 bool result = transport_->SendRtp(packet, length, options);
ivica5d6a06c2015-09-17 05:30:24 -0700270 {
271 rtc::CritScope lock(&crit_);
sprange1f2f1f2016-02-01 02:04:52 -0800272
Peter Boström81cbd922016-03-22 12:19:07 +0100273 if (rtp_timestamp_delta_ == 0) {
nissec7fe3c22016-04-20 03:25:36 -0700274 rtp_timestamp_delta_ = header.timestamp - *first_send_timestamp_;
275 first_send_timestamp_ = rtc::Optional<uint32_t>();
ivica5d6a06c2015-09-17 05:30:24 -0700276 }
brandtr504b95e2016-12-21 02:54:35 -0800277 if (!IsFlexfec(header.payloadType)) {
278 // Ignore FlexFEC timestamps, to avoid collisions with media timestamps.
279 // (FlexFEC and media are sent on different SSRCs, which have different
280 // timestamps spaces.)
281 int64_t timestamp =
282 wrap_handler_.Unwrap(header.timestamp - rtp_timestamp_delta_);
283 send_times_[timestamp] = current_time;
284 if (!transport_->DiscardedLastPacket() &&
285 header.ssrc == ssrc_to_analyze_) {
286 encoded_frame_sizes_[timestamp] +=
287 length - (header.headerLength + header.paddingLength);
288 }
sprangce4aef12015-11-02 07:23:20 -0800289 }
ivica5d6a06c2015-09-17 05:30:24 -0700290 }
sprangce4aef12015-11-02 07:23:20 -0800291 return result;
ivica5d6a06c2015-09-17 05:30:24 -0700292 }
293
294 bool SendRtcp(const uint8_t* packet, size_t length) override {
295 return transport_->SendRtcp(packet, length);
296 }
297
298 void EncodedFrameCallback(const EncodedFrame& frame) override {
299 rtc::CritScope lock(&comparison_lock_);
300 if (frames_recorded_ < frames_to_process_)
301 encoded_frame_size_.AddSample(frame.length_);
302 }
303
nisseeb83a1a2016-03-21 01:27:56 -0700304 void OnFrame(const VideoFrame& video_frame) override {
ivica5d6a06c2015-09-17 05:30:24 -0700305 int64_t render_time_ms =
306 Clock::GetRealTimeClock()->CurrentNtpInMilliseconds();
ivica5d6a06c2015-09-17 05:30:24 -0700307
308 rtc::CritScope lock(&crit_);
Taylor Brandstetter433b95a2016-03-18 11:41:03 -0700309 int64_t send_timestamp =
sprang16daaa52016-03-09 01:30:24 -0800310 wrap_handler_.Unwrap(video_frame.timestamp() - rtp_timestamp_delta_);
ivica5d6a06c2015-09-17 05:30:24 -0700311
sprang16daaa52016-03-09 01:30:24 -0800312 while (wrap_handler_.Unwrap(frames_.front().timestamp()) < send_timestamp) {
nisse97f0b932016-05-26 09:44:40 -0700313 if (!last_rendered_frame_) {
pbos14fe7082016-04-20 06:35:56 -0700314 // No previous frame rendered, this one was dropped after sending but
315 // before rendering.
316 ++dropped_frames_before_rendering_;
317 frames_.pop_front();
318 RTC_CHECK(!frames_.empty());
319 continue;
320 }
nisse97f0b932016-05-26 09:44:40 -0700321 AddFrameComparison(frames_.front(), *last_rendered_frame_, true,
ivica5d6a06c2015-09-17 05:30:24 -0700322 render_time_ms);
323 frames_.pop_front();
pbos14fe7082016-04-20 06:35:56 -0700324 RTC_DCHECK(!frames_.empty());
ivica5d6a06c2015-09-17 05:30:24 -0700325 }
326
327 VideoFrame reference_frame = frames_.front();
328 frames_.pop_front();
sprang16daaa52016-03-09 01:30:24 -0800329 int64_t reference_timestamp =
330 wrap_handler_.Unwrap(reference_frame.timestamp());
331 if (send_timestamp == reference_timestamp - 1) {
sprangce4aef12015-11-02 07:23:20 -0800332 // TODO(ivica): Make this work for > 2 streams.
Peter Boströme4499152016-02-05 11:13:28 +0100333 // Look at RTPSender::BuildRTPHeader.
sprangce4aef12015-11-02 07:23:20 -0800334 ++send_timestamp;
335 }
sprang16daaa52016-03-09 01:30:24 -0800336 ASSERT_EQ(reference_timestamp, send_timestamp);
ivica5d6a06c2015-09-17 05:30:24 -0700337
338 AddFrameComparison(reference_frame, video_frame, false, render_time_ms);
339
nisse97f0b932016-05-26 09:44:40 -0700340 last_rendered_frame_ = rtc::Optional<VideoFrame>(video_frame);
ivica5d6a06c2015-09-17 05:30:24 -0700341 }
342
ivica5d6a06c2015-09-17 05:30:24 -0700343 void Wait() {
344 // Frame comparisons can be very expensive. Wait for test to be done, but
345 // at time-out check if frames_processed is going up. If so, give it more
346 // time, otherwise fail. Hopefully this will reduce test flakiness.
347
Peter Boström8c38e8b2015-11-26 17:45:47 +0100348 stats_polling_thread_.Start();
sprangce4aef12015-11-02 07:23:20 -0800349
ivica5d6a06c2015-09-17 05:30:24 -0700350 int last_frames_processed = -1;
ivica5d6a06c2015-09-17 05:30:24 -0700351 int iteration = 0;
Peter Boström5811a392015-12-10 13:02:50 +0100352 while (!done_.Wait(VideoQualityTest::kDefaultTimeoutMs)) {
ivica5d6a06c2015-09-17 05:30:24 -0700353 int frames_processed;
354 {
355 rtc::CritScope crit(&comparison_lock_);
356 frames_processed = frames_processed_;
357 }
358
359 // Print some output so test infrastructure won't think we've crashed.
360 const char* kKeepAliveMessages[3] = {
361 "Uh, I'm-I'm not quite dead, sir.",
362 "Uh, I-I think uh, I could pull through, sir.",
363 "Actually, I think I'm all right to come with you--"};
364 printf("- %s\n", kKeepAliveMessages[iteration++ % 3]);
365
366 if (last_frames_processed == -1) {
367 last_frames_processed = frames_processed;
368 continue;
369 }
Peter Boströmdd45eb62016-01-19 15:22:32 +0100370 if (frames_processed == last_frames_processed) {
371 EXPECT_GT(frames_processed, last_frames_processed)
372 << "Analyzer stalled while waiting for test to finish.";
373 done_.Set();
374 break;
375 }
ivica5d6a06c2015-09-17 05:30:24 -0700376 last_frames_processed = frames_processed;
377 }
378
379 if (iteration > 0)
380 printf("- Farewell, sweet Concorde!\n");
381
Peter Boström8c38e8b2015-11-26 17:45:47 +0100382 stats_polling_thread_.Stop();
ivica5d6a06c2015-09-17 05:30:24 -0700383 }
384
pbos14fe7082016-04-20 06:35:56 -0700385 rtc::VideoSinkInterface<VideoFrame>* pre_encode_proxy() {
386 return &pre_encode_proxy_;
387 }
Peter Boströme4499152016-02-05 11:13:28 +0100388 EncodedFrameObserver* encode_timing_proxy() { return &encode_timing_proxy_; }
389
sprangce4aef12015-11-02 07:23:20 -0800390 test::LayerFilteringTransport* const transport_;
ivica5d6a06c2015-09-17 05:30:24 -0700391 PacketReceiver* receiver_;
ivica5d6a06c2015-09-17 05:30:24 -0700392
393 private:
394 struct FrameComparison {
395 FrameComparison()
396 : dropped(false),
nissedf2ceb82016-12-15 06:29:53 -0800397 input_time_ms(0),
ivica5d6a06c2015-09-17 05:30:24 -0700398 send_time_ms(0),
399 recv_time_ms(0),
400 render_time_ms(0),
401 encoded_frame_size(0) {}
402
403 FrameComparison(const VideoFrame& reference,
404 const VideoFrame& render,
405 bool dropped,
nissedf2ceb82016-12-15 06:29:53 -0800406 int64_t input_time_ms,
ivica5d6a06c2015-09-17 05:30:24 -0700407 int64_t send_time_ms,
408 int64_t recv_time_ms,
409 int64_t render_time_ms,
410 size_t encoded_frame_size)
411 : reference(reference),
412 render(render),
413 dropped(dropped),
nissedf2ceb82016-12-15 06:29:53 -0800414 input_time_ms(input_time_ms),
ivica5d6a06c2015-09-17 05:30:24 -0700415 send_time_ms(send_time_ms),
416 recv_time_ms(recv_time_ms),
417 render_time_ms(render_time_ms),
418 encoded_frame_size(encoded_frame_size) {}
419
nissedf2ceb82016-12-15 06:29:53 -0800420 FrameComparison(bool dropped,
421 int64_t input_time_ms,
422 int64_t send_time_ms,
423 int64_t recv_time_ms,
424 int64_t render_time_ms,
425 size_t encoded_frame_size)
426 : dropped(dropped),
427 input_time_ms(input_time_ms),
428 send_time_ms(send_time_ms),
429 recv_time_ms(recv_time_ms),
430 render_time_ms(render_time_ms),
431 encoded_frame_size(encoded_frame_size) {}
432
433 rtc::Optional<VideoFrame> reference;
434 rtc::Optional<VideoFrame> render;
ivica5d6a06c2015-09-17 05:30:24 -0700435 bool dropped;
nissedf2ceb82016-12-15 06:29:53 -0800436 int64_t input_time_ms;
ivica5d6a06c2015-09-17 05:30:24 -0700437 int64_t send_time_ms;
438 int64_t recv_time_ms;
439 int64_t render_time_ms;
440 size_t encoded_frame_size;
441 };
442
443 struct Sample {
ivica8d15bd62015-10-07 02:43:12 -0700444 Sample(int dropped,
445 int64_t input_time_ms,
446 int64_t send_time_ms,
447 int64_t recv_time_ms,
448 int64_t render_time_ms,
449 size_t encoded_frame_size,
ivica5d6a06c2015-09-17 05:30:24 -0700450 double psnr,
ivica8d15bd62015-10-07 02:43:12 -0700451 double ssim)
ivica5d6a06c2015-09-17 05:30:24 -0700452 : dropped(dropped),
453 input_time_ms(input_time_ms),
454 send_time_ms(send_time_ms),
455 recv_time_ms(recv_time_ms),
ivica8d15bd62015-10-07 02:43:12 -0700456 render_time_ms(render_time_ms),
ivica5d6a06c2015-09-17 05:30:24 -0700457 encoded_frame_size(encoded_frame_size),
458 psnr(psnr),
ivica8d15bd62015-10-07 02:43:12 -0700459 ssim(ssim) {}
ivica5d6a06c2015-09-17 05:30:24 -0700460
ivica8d15bd62015-10-07 02:43:12 -0700461 int dropped;
462 int64_t input_time_ms;
463 int64_t send_time_ms;
464 int64_t recv_time_ms;
465 int64_t render_time_ms;
466 size_t encoded_frame_size;
ivica5d6a06c2015-09-17 05:30:24 -0700467 double psnr;
468 double ssim;
ivica5d6a06c2015-09-17 05:30:24 -0700469 };
470
Peter Boströme4499152016-02-05 11:13:28 +0100471 // This class receives the send-side OnEncodeTiming and is provided to not
472 // conflict with the receiver-side pre_decode_callback.
473 class OnEncodeTimingProxy : public EncodedFrameObserver {
474 public:
475 explicit OnEncodeTimingProxy(VideoAnalyzer* parent) : parent_(parent) {}
476
477 void OnEncodeTiming(int64_t ntp_time_ms, int encode_time_ms) override {
478 parent_->MeasuredEncodeTiming(ntp_time_ms, encode_time_ms);
479 }
480 void EncodedFrameCallback(const EncodedFrame& frame) override {}
481
482 private:
483 VideoAnalyzer* const parent_;
484 };
485
pbos14fe7082016-04-20 06:35:56 -0700486 // This class receives the send-side OnFrame callback and is provided to not
487 // conflict with the receiver-side renderer callback.
488 class PreEncodeProxy : public rtc::VideoSinkInterface<VideoFrame> {
489 public:
490 explicit PreEncodeProxy(VideoAnalyzer* parent) : parent_(parent) {}
491
492 void OnFrame(const VideoFrame& video_frame) override {
493 parent_->PreEncodeOnFrame(video_frame);
494 }
495
496 private:
497 VideoAnalyzer* const parent_;
498 };
499
ivica5d6a06c2015-09-17 05:30:24 -0700500 void AddFrameComparison(const VideoFrame& reference,
501 const VideoFrame& render,
502 bool dropped,
503 int64_t render_time_ms)
504 EXCLUSIVE_LOCKS_REQUIRED(crit_) {
sprange1f2f1f2016-02-01 02:04:52 -0800505 int64_t reference_timestamp = wrap_handler_.Unwrap(reference.timestamp());
506 int64_t send_time_ms = send_times_[reference_timestamp];
507 send_times_.erase(reference_timestamp);
508 int64_t recv_time_ms = recv_times_[reference_timestamp];
509 recv_times_.erase(reference_timestamp);
ivica5d6a06c2015-09-17 05:30:24 -0700510
sprangce4aef12015-11-02 07:23:20 -0800511 // TODO(ivica): Make this work for > 2 streams.
sprange1f2f1f2016-02-01 02:04:52 -0800512 auto it = encoded_frame_sizes_.find(reference_timestamp);
sprangce4aef12015-11-02 07:23:20 -0800513 if (it == encoded_frame_sizes_.end())
sprange1f2f1f2016-02-01 02:04:52 -0800514 it = encoded_frame_sizes_.find(reference_timestamp - 1);
sprangce4aef12015-11-02 07:23:20 -0800515 size_t encoded_size = it == encoded_frame_sizes_.end() ? 0 : it->second;
516 if (it != encoded_frame_sizes_.end())
517 encoded_frame_sizes_.erase(it);
ivica5d6a06c2015-09-17 05:30:24 -0700518
ivica5d6a06c2015-09-17 05:30:24 -0700519 rtc::CritScope crit(&comparison_lock_);
stefanb1797672016-08-11 07:00:57 -0700520 if (comparisons_.size() < kMaxComparisons) {
nissedf2ceb82016-12-15 06:29:53 -0800521 comparisons_.push_back(FrameComparison(reference, render, dropped,
522 reference.ntp_time_ms(),
523 send_time_ms, recv_time_ms,
524 render_time_ms, encoded_size));
stefanb1797672016-08-11 07:00:57 -0700525 } else {
nissedf2ceb82016-12-15 06:29:53 -0800526 comparisons_.push_back(FrameComparison(dropped,
527 reference.ntp_time_ms(),
528 send_time_ms, recv_time_ms,
529 render_time_ms, encoded_size));
stefanb1797672016-08-11 07:00:57 -0700530 }
Peter Boström5811a392015-12-10 13:02:50 +0100531 comparison_available_event_.Set();
ivica5d6a06c2015-09-17 05:30:24 -0700532 }
533
534 static bool PollStatsThread(void* obj) {
535 return static_cast<VideoAnalyzer*>(obj)->PollStats();
536 }
537
538 bool PollStats() {
Peter Boströmdd45eb62016-01-19 15:22:32 +0100539 if (done_.Wait(kSendStatsPollingIntervalMs))
Peter Boström5811a392015-12-10 13:02:50 +0100540 return false;
ivica5d6a06c2015-09-17 05:30:24 -0700541
ivica5d6a06c2015-09-17 05:30:24 -0700542 rtc::CritScope crit(&comparison_lock_);
philipelfd870db2017-01-23 03:22:15 -0800543
544 VideoSendStream::Stats send_stats = send_stream_->GetStats();
Peter Boströmb1eaa8d2016-02-23 17:30:49 +0100545 // It's not certain that we yet have estimates for any of these stats. Check
546 // that they are positive before mixing them in.
philipelfd870db2017-01-23 03:22:15 -0800547 if (send_stats.encode_frame_rate > 0)
548 encode_frame_rate_.AddSample(send_stats.encode_frame_rate);
549 if (send_stats.avg_encode_time_ms > 0)
550 encode_time_ms_.AddSample(send_stats.avg_encode_time_ms);
551 if (send_stats.encode_usage_percent > 0)
552 encode_usage_percent_.AddSample(send_stats.encode_usage_percent);
553 if (send_stats.media_bitrate_bps > 0)
554 media_bitrate_bps_.AddSample(send_stats.media_bitrate_bps);
555
556 if (receive_stream_ != nullptr) {
557 VideoReceiveStream::Stats receive_stats = receive_stream_->GetStats();
558 if (receive_stats.decode_ms > 0)
559 decode_time_ms_.AddSample(receive_stats.decode_ms);
560 if (receive_stats.max_decode_ms > 0)
561 decode_time_max_ms_.AddSample(receive_stats.max_decode_ms);
562 }
ivica5d6a06c2015-09-17 05:30:24 -0700563
564 return true;
565 }
566
567 static bool FrameComparisonThread(void* obj) {
568 return static_cast<VideoAnalyzer*>(obj)->CompareFrames();
569 }
570
571 bool CompareFrames() {
572 if (AllFramesRecorded())
573 return false;
574
ivica5d6a06c2015-09-17 05:30:24 -0700575 FrameComparison comparison;
576
577 if (!PopComparison(&comparison)) {
578 // Wait until new comparison task is available, or test is done.
579 // If done, wake up remaining threads waiting.
Peter Boström5811a392015-12-10 13:02:50 +0100580 comparison_available_event_.Wait(1000);
ivica5d6a06c2015-09-17 05:30:24 -0700581 if (AllFramesRecorded()) {
Peter Boström5811a392015-12-10 13:02:50 +0100582 comparison_available_event_.Set();
ivica5d6a06c2015-09-17 05:30:24 -0700583 return false;
584 }
585 return true; // Try again.
586 }
587
588 PerformFrameComparison(comparison);
589
590 if (FrameProcessed()) {
591 PrintResults();
592 if (graph_data_output_file_)
593 PrintSamplesToFile();
Peter Boström5811a392015-12-10 13:02:50 +0100594 done_.Set();
595 comparison_available_event_.Set();
ivica5d6a06c2015-09-17 05:30:24 -0700596 return false;
597 }
598
599 return true;
600 }
601
602 bool PopComparison(FrameComparison* comparison) {
603 rtc::CritScope crit(&comparison_lock_);
604 // If AllFramesRecorded() is true, it means we have already popped
605 // frames_to_process_ frames from comparisons_, so there is no more work
606 // for this thread to be done. frames_processed_ might still be lower if
607 // all comparisons are not done, but those frames are currently being
608 // worked on by other threads.
609 if (comparisons_.empty() || AllFramesRecorded())
610 return false;
611
612 *comparison = comparisons_.front();
613 comparisons_.pop_front();
614
615 FrameRecorded();
616 return true;
617 }
618
619 // Increment counter for number of frames received for comparison.
620 void FrameRecorded() {
621 rtc::CritScope crit(&comparison_lock_);
622 ++frames_recorded_;
623 }
624
625 // Returns true if all frames to be compared have been taken from the queue.
626 bool AllFramesRecorded() {
627 rtc::CritScope crit(&comparison_lock_);
628 assert(frames_recorded_ <= frames_to_process_);
629 return frames_recorded_ == frames_to_process_;
630 }
631
632 // Increase count of number of frames processed. Returns true if this was the
633 // last frame to be processed.
634 bool FrameProcessed() {
635 rtc::CritScope crit(&comparison_lock_);
636 ++frames_processed_;
637 assert(frames_processed_ <= frames_to_process_);
638 return frames_processed_ == frames_to_process_;
639 }
640
641 void PrintResults() {
642 rtc::CritScope crit(&comparison_lock_);
643 PrintResult("psnr", psnr_, " dB");
tnakamura3123cbc2016-02-10 11:21:51 -0800644 PrintResult("ssim", ssim_, " score");
ivica5d6a06c2015-09-17 05:30:24 -0700645 PrintResult("sender_time", sender_time_, " ms");
ivica5d6a06c2015-09-17 05:30:24 -0700646 PrintResult("receiver_time", receiver_time_, " ms");
647 PrintResult("total_delay_incl_network", end_to_end_, " ms");
648 PrintResult("time_between_rendered_frames", rendered_delta_, " ms");
649 PrintResult("encoded_frame_size", encoded_frame_size_, " bytes");
650 PrintResult("encode_frame_rate", encode_frame_rate_, " fps");
philipelfd870db2017-01-23 03:22:15 -0800651 PrintResult("encode_time", encode_time_ms_, " ms");
652 PrintResult("encode_usage_percent", encode_usage_percent_, " percent");
653 PrintResult("media_bitrate", media_bitrate_bps_, " bps");
654
655 if (receive_stream_ != nullptr) {
656 PrintResult("decode_time", decode_time_ms_, " ms");
657 PrintResult("decode_time_max", decode_time_max_ms_, " ms");
658 }
ivica5d6a06c2015-09-17 05:30:24 -0700659
pbos14fe7082016-04-20 06:35:56 -0700660 printf("RESULT dropped_frames: %s = %d frames\n", test_label_.c_str(),
661 dropped_frames_);
662 printf("RESULT dropped_frames_before_first_encode: %s = %d frames\n",
663 test_label_.c_str(), dropped_frames_before_first_encode_);
664 printf("RESULT dropped_frames_before_rendering: %s = %d frames\n",
665 test_label_.c_str(), dropped_frames_before_rendering_);
666
ivica5d6a06c2015-09-17 05:30:24 -0700667 EXPECT_GT(psnr_.Mean(), avg_psnr_threshold_);
668 EXPECT_GT(ssim_.Mean(), avg_ssim_threshold_);
669 }
670
671 void PerformFrameComparison(const FrameComparison& comparison) {
672 // Perform expensive psnr and ssim calculations while not holding lock.
stefanb1797672016-08-11 07:00:57 -0700673 double psnr = -1.0;
674 double ssim = -1.0;
nissedf2ceb82016-12-15 06:29:53 -0800675 if (comparison.reference) {
676 psnr = I420PSNR(&*comparison.reference, &*comparison.render);
677 ssim = I420SSIM(&*comparison.reference, &*comparison.render);
stefanb1797672016-08-11 07:00:57 -0700678 }
ivica5d6a06c2015-09-17 05:30:24 -0700679
ivica5d6a06c2015-09-17 05:30:24 -0700680 rtc::CritScope crit(&comparison_lock_);
681 if (graph_data_output_file_) {
nissedf2ceb82016-12-15 06:29:53 -0800682 samples_.push_back(Sample(
683 comparison.dropped, comparison.input_time_ms, comparison.send_time_ms,
684 comparison.recv_time_ms, comparison.render_time_ms,
685 comparison.encoded_frame_size, psnr, ssim));
ivica5d6a06c2015-09-17 05:30:24 -0700686 }
stefanb1797672016-08-11 07:00:57 -0700687 if (psnr >= 0.0)
688 psnr_.AddSample(psnr);
689 if (ssim >= 0.0)
690 ssim_.AddSample(ssim);
ivica5d6a06c2015-09-17 05:30:24 -0700691
692 if (comparison.dropped) {
693 ++dropped_frames_;
694 return;
695 }
696 if (last_render_time_ != 0)
697 rendered_delta_.AddSample(comparison.render_time_ms - last_render_time_);
698 last_render_time_ = comparison.render_time_ms;
699
nissedf2ceb82016-12-15 06:29:53 -0800700 sender_time_.AddSample(comparison.send_time_ms - comparison.input_time_ms);
brandtr504b95e2016-12-21 02:54:35 -0800701 if (comparison.recv_time_ms > 0) {
702 // If recv_time_ms == 0, this frame consisted of a packets which were all
703 // lost in the transport. Since we were able to render the frame, however,
704 // the dropped packets were recovered by FlexFEC. The FlexFEC recovery
705 // happens internally in Call, and we can therefore here not know which
706 // FEC packets that protected the lost media packets. Consequently, we
707 // were not able to record a meaningful recv_time_ms. We therefore skip
708 // this sample.
709 //
710 // The reasoning above does not hold for ULPFEC and RTX, as for those
711 // strategies the timestamp of the received packets is set to the
712 // timestamp of the protected/retransmitted media packet. I.e., then
713 // recv_time_ms != 0, even though the media packets were lost.
714 receiver_time_.AddSample(comparison.render_time_ms -
715 comparison.recv_time_ms);
716 }
nissedf2ceb82016-12-15 06:29:53 -0800717 end_to_end_.AddSample(comparison.render_time_ms - comparison.input_time_ms);
ivica5d6a06c2015-09-17 05:30:24 -0700718 encoded_frame_size_.AddSample(comparison.encoded_frame_size);
719 }
720
721 void PrintResult(const char* result_type,
722 test::Statistics stats,
723 const char* unit) {
724 printf("RESULT %s: %s = {%f, %f}%s\n",
725 result_type,
726 test_label_.c_str(),
727 stats.Mean(),
728 stats.StandardDeviation(),
729 unit);
730 }
731
732 void PrintSamplesToFile(void) {
733 FILE* out = graph_data_output_file_;
734 rtc::CritScope crit(&comparison_lock_);
735 std::sort(samples_.begin(), samples_.end(),
736 [](const Sample& A, const Sample& B) -> bool {
737 return A.input_time_ms < B.input_time_ms;
738 });
739
sprangce4aef12015-11-02 07:23:20 -0800740 fprintf(out, "%s\n", graph_title_.c_str());
ivica5d6a06c2015-09-17 05:30:24 -0700741 fprintf(out, "%" PRIuS "\n", samples_.size());
742 fprintf(out,
743 "dropped "
744 "input_time_ms "
745 "send_time_ms "
746 "recv_time_ms "
ivica8d15bd62015-10-07 02:43:12 -0700747 "render_time_ms "
ivica5d6a06c2015-09-17 05:30:24 -0700748 "encoded_frame_size "
749 "psnr "
750 "ssim "
ivica8d15bd62015-10-07 02:43:12 -0700751 "encode_time_ms\n");
752 int missing_encode_time_samples = 0;
ivica5d6a06c2015-09-17 05:30:24 -0700753 for (const Sample& sample : samples_) {
ivica8d15bd62015-10-07 02:43:12 -0700754 auto it = samples_encode_time_ms_.find(sample.input_time_ms);
755 int encode_time_ms;
756 if (it != samples_encode_time_ms_.end()) {
757 encode_time_ms = it->second;
758 } else {
759 ++missing_encode_time_samples;
760 encode_time_ms = -1;
761 }
762 fprintf(out, "%d %" PRId64 " %" PRId64 " %" PRId64 " %" PRId64 " %" PRIuS
763 " %lf %lf %d\n",
764 sample.dropped, sample.input_time_ms, sample.send_time_ms,
765 sample.recv_time_ms, sample.render_time_ms,
ivica5d6a06c2015-09-17 05:30:24 -0700766 sample.encoded_frame_size, sample.psnr, sample.ssim,
ivica8d15bd62015-10-07 02:43:12 -0700767 encode_time_ms);
768 }
769 if (missing_encode_time_samples) {
770 fprintf(stderr,
771 "Warning: Missing encode_time_ms samples for %d frame(s).\n",
772 missing_encode_time_samples);
ivica5d6a06c2015-09-17 05:30:24 -0700773 }
774 }
775
perkja49cbd32016-09-16 07:53:41 -0700776 // Implements VideoSinkInterface to receive captured frames from a
777 // FrameGeneratorCapturer. Implements VideoSourceInterface to be able to act
778 // as a source to VideoSendStream.
779 // It forwards all input frames to the VideoAnalyzer for later comparison and
780 // forwards the captured frames to the VideoSendStream.
781 class CapturedFrameForwarder : public rtc::VideoSinkInterface<VideoFrame>,
782 public rtc::VideoSourceInterface<VideoFrame> {
783 public:
784 explicit CapturedFrameForwarder(VideoAnalyzer* analyzer)
785 : analyzer_(analyzer), send_stream_input_(nullptr) {}
786
787 private:
788 void OnFrame(const VideoFrame& video_frame) override {
789 VideoFrame copy = video_frame;
790 copy.set_timestamp(copy.ntp_time_ms() * 90);
791
792 analyzer_->AddCapturedFrameForComparison(video_frame);
793 rtc::CritScope lock(&crit_);
794 if (send_stream_input_)
795 send_stream_input_->OnFrame(video_frame);
796 }
797
798 // Called when |send_stream_.SetSource()| is called.
799 void AddOrUpdateSink(rtc::VideoSinkInterface<VideoFrame>* sink,
800 const rtc::VideoSinkWants& wants) override {
801 rtc::CritScope lock(&crit_);
802 RTC_DCHECK(!send_stream_input_ || send_stream_input_ == sink);
803 send_stream_input_ = sink;
804 }
805
806 // Called by |send_stream_| when |send_stream_.SetSource()| is called.
807 void RemoveSink(rtc::VideoSinkInterface<VideoFrame>* sink) override {
808 rtc::CritScope lock(&crit_);
809 RTC_DCHECK(sink == send_stream_input_);
810 send_stream_input_ = nullptr;
811 }
812
813 VideoAnalyzer* const analyzer_;
814 rtc::CriticalSection crit_;
815 rtc::VideoSinkInterface<VideoFrame>* send_stream_input_ GUARDED_BY(crit_);
816 };
817
818 void AddCapturedFrameForComparison(const VideoFrame& video_frame) {
819 rtc::CritScope lock(&crit_);
kwibergaf476c72016-11-28 15:21:39 -0800820 RTC_DCHECK_EQ(0, video_frame.timestamp());
perkja49cbd32016-09-16 07:53:41 -0700821 // Frames from the capturer does not have a rtp timestamp. Create one so it
822 // can be used for comparison.
823 VideoFrame copy = video_frame;
824 copy.set_timestamp(copy.ntp_time_ms() * 90);
825 frames_.push_back(copy);
826 }
827
828 VideoSendStream* send_stream_;
philipelfd870db2017-01-23 03:22:15 -0800829 VideoReceiveStream* receive_stream_;
perkja49cbd32016-09-16 07:53:41 -0700830 CapturedFrameForwarder captured_frame_forwarder_;
ivica5d6a06c2015-09-17 05:30:24 -0700831 const std::string test_label_;
832 FILE* const graph_data_output_file_;
sprangce4aef12015-11-02 07:23:20 -0800833 const std::string graph_title_;
834 const uint32_t ssrc_to_analyze_;
pbos14fe7082016-04-20 06:35:56 -0700835 PreEncodeProxy pre_encode_proxy_;
Peter Boströme4499152016-02-05 11:13:28 +0100836 OnEncodeTimingProxy encode_timing_proxy_;
ivica5d6a06c2015-09-17 05:30:24 -0700837 std::vector<Sample> samples_ GUARDED_BY(comparison_lock_);
ivica8d15bd62015-10-07 02:43:12 -0700838 std::map<int64_t, int> samples_encode_time_ms_ GUARDED_BY(comparison_lock_);
ivica5d6a06c2015-09-17 05:30:24 -0700839 test::Statistics sender_time_ GUARDED_BY(comparison_lock_);
840 test::Statistics receiver_time_ GUARDED_BY(comparison_lock_);
841 test::Statistics psnr_ GUARDED_BY(comparison_lock_);
842 test::Statistics ssim_ GUARDED_BY(comparison_lock_);
843 test::Statistics end_to_end_ GUARDED_BY(comparison_lock_);
844 test::Statistics rendered_delta_ GUARDED_BY(comparison_lock_);
845 test::Statistics encoded_frame_size_ GUARDED_BY(comparison_lock_);
846 test::Statistics encode_frame_rate_ GUARDED_BY(comparison_lock_);
philipelfd870db2017-01-23 03:22:15 -0800847 test::Statistics encode_time_ms_ GUARDED_BY(comparison_lock_);
848 test::Statistics encode_usage_percent_ GUARDED_BY(comparison_lock_);
849 test::Statistics decode_time_ms_ GUARDED_BY(comparison_lock_);
850 test::Statistics decode_time_max_ms_ GUARDED_BY(comparison_lock_);
851 test::Statistics media_bitrate_bps_ GUARDED_BY(comparison_lock_);
ivica5d6a06c2015-09-17 05:30:24 -0700852
853 const int frames_to_process_;
854 int frames_recorded_;
855 int frames_processed_;
856 int dropped_frames_;
pbos14fe7082016-04-20 06:35:56 -0700857 int dropped_frames_before_first_encode_;
858 int dropped_frames_before_rendering_;
ivica5d6a06c2015-09-17 05:30:24 -0700859 int64_t last_render_time_;
860 uint32_t rtp_timestamp_delta_;
861
862 rtc::CriticalSection crit_;
863 std::deque<VideoFrame> frames_ GUARDED_BY(crit_);
nisse97f0b932016-05-26 09:44:40 -0700864 rtc::Optional<VideoFrame> last_rendered_frame_ GUARDED_BY(crit_);
sprange1f2f1f2016-02-01 02:04:52 -0800865 rtc::TimestampWrapAroundHandler wrap_handler_ GUARDED_BY(crit_);
866 std::map<int64_t, int64_t> send_times_ GUARDED_BY(crit_);
867 std::map<int64_t, int64_t> recv_times_ GUARDED_BY(crit_);
868 std::map<int64_t, size_t> encoded_frame_sizes_ GUARDED_BY(crit_);
nissec7fe3c22016-04-20 03:25:36 -0700869 rtc::Optional<uint32_t> first_send_timestamp_ GUARDED_BY(crit_);
ivica5d6a06c2015-09-17 05:30:24 -0700870 const double avg_psnr_threshold_;
871 const double avg_ssim_threshold_;
872
873 rtc::CriticalSection comparison_lock_;
Peter Boström8c38e8b2015-11-26 17:45:47 +0100874 std::vector<rtc::PlatformThread*> comparison_thread_pool_;
875 rtc::PlatformThread stats_polling_thread_;
Peter Boström5811a392015-12-10 13:02:50 +0100876 rtc::Event comparison_available_event_;
ivica5d6a06c2015-09-17 05:30:24 -0700877 std::deque<FrameComparison> comparisons_ GUARDED_BY(comparison_lock_);
Peter Boström5811a392015-12-10 13:02:50 +0100878 rtc::Event done_;
ivica5d6a06c2015-09-17 05:30:24 -0700879};
880
palmkviste75f2042016-09-28 06:19:48 -0700881VideoQualityTest::VideoQualityTest()
882 : clock_(Clock::GetRealTimeClock()), receive_logs_(0), send_logs_(0) {}
ivica5d6a06c2015-09-17 05:30:24 -0700883
minyue626bc952016-10-31 05:47:02 -0700884VideoQualityTest::Params::Params()
885 : call({false, Call::Config::BitrateConfig()}),
886 video({false, 640, 480, 30, 50, 800, 800, false, "VP8", 1, -1, 0, false,
brandtr1293aca2016-11-16 22:47:29 -0800887 false, "", ""}),
minyue626bc952016-10-31 05:47:02 -0700888 audio({false, false}),
889 screenshare({false, 10, 0}),
890 analyzer({"", 0.0, 0.0, 0, "", ""}),
891 pipe(),
892 logs(false),
893 ss({std::vector<VideoStream>(), 0, 0, -1, std::vector<SpatialLayer>()}) {}
894
895VideoQualityTest::Params::~Params() = default;
896
ivica5d6a06c2015-09-17 05:30:24 -0700897void VideoQualityTest::TestBody() {}
898
sprangce4aef12015-11-02 07:23:20 -0800899std::string VideoQualityTest::GenerateGraphTitle() const {
900 std::stringstream ss;
minyue626bc952016-10-31 05:47:02 -0700901 ss << params_.video.codec;
902 ss << " (" << params_.video.target_bitrate_bps / 1000 << "kbps";
903 ss << ", " << params_.video.fps << " FPS";
sprangce4aef12015-11-02 07:23:20 -0800904 if (params_.screenshare.scroll_duration)
905 ss << ", " << params_.screenshare.scroll_duration << "s scroll";
906 if (params_.ss.streams.size() > 1)
907 ss << ", Stream #" << params_.ss.selected_stream;
908 if (params_.ss.num_spatial_layers > 1)
909 ss << ", Layer #" << params_.ss.selected_sl;
910 ss << ")";
911 return ss.str();
912}
913
914void VideoQualityTest::CheckParams() {
915 // Add a default stream in none specified.
916 if (params_.ss.streams.empty())
917 params_.ss.streams.push_back(VideoQualityTest::DefaultVideoStream(params_));
918 if (params_.ss.num_spatial_layers == 0)
919 params_.ss.num_spatial_layers = 1;
920
921 if (params_.pipe.loss_percent != 0 ||
922 params_.pipe.queue_length_packets != 0) {
923 // Since LayerFilteringTransport changes the sequence numbers, we can't
924 // use that feature with pack loss, since the NACK request would end up
925 // retransmitting the wrong packets.
926 RTC_CHECK(params_.ss.selected_sl == -1 ||
sprangee37de32015-11-23 06:10:23 -0800927 params_.ss.selected_sl == params_.ss.num_spatial_layers - 1);
minyue626bc952016-10-31 05:47:02 -0700928 RTC_CHECK(params_.video.selected_tl == -1 ||
929 params_.video.selected_tl ==
930 params_.video.num_temporal_layers - 1);
sprangce4aef12015-11-02 07:23:20 -0800931 }
932
933 // TODO(ivica): Should max_bitrate_bps == -1 represent inf max bitrate, as it
934 // does in some parts of the code?
minyue626bc952016-10-31 05:47:02 -0700935 RTC_CHECK_GE(params_.video.max_bitrate_bps, params_.video.target_bitrate_bps);
936 RTC_CHECK_GE(params_.video.target_bitrate_bps, params_.video.min_bitrate_bps);
937 RTC_CHECK_LT(params_.video.selected_tl, params_.video.num_temporal_layers);
sprangce4aef12015-11-02 07:23:20 -0800938 RTC_CHECK_LT(params_.ss.selected_stream, params_.ss.streams.size());
939 for (const VideoStream& stream : params_.ss.streams) {
940 RTC_CHECK_GE(stream.min_bitrate_bps, 0);
941 RTC_CHECK_GE(stream.target_bitrate_bps, stream.min_bitrate_bps);
942 RTC_CHECK_GE(stream.max_bitrate_bps, stream.target_bitrate_bps);
kwiberg352444f2016-11-28 15:58:53 -0800943 RTC_CHECK_EQ(stream.temporal_layer_thresholds_bps.size(),
minyue626bc952016-10-31 05:47:02 -0700944 params_.video.num_temporal_layers - 1);
sprangce4aef12015-11-02 07:23:20 -0800945 }
946 // TODO(ivica): Should we check if the sum of all streams/layers is equal to
947 // the total bitrate? We anyway have to update them in the case bitrate
948 // estimator changes the total bitrates.
949 RTC_CHECK_GE(params_.ss.num_spatial_layers, 1);
950 RTC_CHECK_LE(params_.ss.selected_sl, params_.ss.num_spatial_layers);
951 RTC_CHECK(params_.ss.spatial_layers.empty() ||
952 params_.ss.spatial_layers.size() ==
953 static_cast<size_t>(params_.ss.num_spatial_layers));
minyue626bc952016-10-31 05:47:02 -0700954 if (params_.video.codec == "VP8") {
sprangce4aef12015-11-02 07:23:20 -0800955 RTC_CHECK_EQ(params_.ss.num_spatial_layers, 1);
minyue626bc952016-10-31 05:47:02 -0700956 } else if (params_.video.codec == "VP9") {
kwibergaf476c72016-11-28 15:21:39 -0800957 RTC_CHECK_EQ(params_.ss.streams.size(), 1);
sprangce4aef12015-11-02 07:23:20 -0800958 }
959}
960
961// Static.
962std::vector<int> VideoQualityTest::ParseCSV(const std::string& str) {
963 // Parse comma separated nonnegative integers, where some elements may be
964 // empty. The empty values are replaced with -1.
965 // E.g. "10,-20,,30,40" --> {10, 20, -1, 30,40}
966 // E.g. ",,10,,20," --> {-1, -1, 10, -1, 20, -1}
967 std::vector<int> result;
968 if (str.empty())
969 return result;
970
971 const char* p = str.c_str();
972 int value = -1;
973 int pos;
974 while (*p) {
975 if (*p == ',') {
976 result.push_back(value);
977 value = -1;
978 ++p;
979 continue;
980 }
981 RTC_CHECK_EQ(sscanf(p, "%d%n", &value, &pos), 1)
982 << "Unexpected non-number value.";
983 p += pos;
984 }
985 result.push_back(value);
986 return result;
987}
988
989// Static.
990VideoStream VideoQualityTest::DefaultVideoStream(const Params& params) {
991 VideoStream stream;
minyue626bc952016-10-31 05:47:02 -0700992 stream.width = params.video.width;
993 stream.height = params.video.height;
994 stream.max_framerate = params.video.fps;
995 stream.min_bitrate_bps = params.video.min_bitrate_bps;
996 stream.target_bitrate_bps = params.video.target_bitrate_bps;
997 stream.max_bitrate_bps = params.video.max_bitrate_bps;
sprangce4aef12015-11-02 07:23:20 -0800998 stream.max_qp = 52;
minyue626bc952016-10-31 05:47:02 -0700999 if (params.video.num_temporal_layers == 2)
sprangce4aef12015-11-02 07:23:20 -08001000 stream.temporal_layer_thresholds_bps.push_back(stream.target_bitrate_bps);
1001 return stream;
1002}
1003
1004// Static.
1005void VideoQualityTest::FillScalabilitySettings(
1006 Params* params,
1007 const std::vector<std::string>& stream_descriptors,
1008 size_t selected_stream,
1009 int num_spatial_layers,
1010 int selected_sl,
1011 const std::vector<std::string>& sl_descriptors) {
1012 // Read VideoStream and SpatialLayer elements from a list of comma separated
1013 // lists. To use a default value for an element, use -1 or leave empty.
1014 // Validity checks performed in CheckParams.
1015
1016 RTC_CHECK(params->ss.streams.empty());
1017 for (auto descriptor : stream_descriptors) {
1018 if (descriptor.empty())
1019 continue;
1020 VideoStream stream = VideoQualityTest::DefaultVideoStream(*params);
1021 std::vector<int> v = VideoQualityTest::ParseCSV(descriptor);
1022 if (v[0] != -1)
1023 stream.width = static_cast<size_t>(v[0]);
1024 if (v[1] != -1)
1025 stream.height = static_cast<size_t>(v[1]);
1026 if (v[2] != -1)
1027 stream.max_framerate = v[2];
1028 if (v[3] != -1)
1029 stream.min_bitrate_bps = v[3];
1030 if (v[4] != -1)
1031 stream.target_bitrate_bps = v[4];
1032 if (v[5] != -1)
1033 stream.max_bitrate_bps = v[5];
1034 if (v.size() > 6 && v[6] != -1)
1035 stream.max_qp = v[6];
1036 if (v.size() > 7) {
1037 stream.temporal_layer_thresholds_bps.clear();
1038 stream.temporal_layer_thresholds_bps.insert(
1039 stream.temporal_layer_thresholds_bps.end(), v.begin() + 7, v.end());
1040 } else {
1041 // Automatic TL thresholds for more than two layers not supported.
minyue626bc952016-10-31 05:47:02 -07001042 RTC_CHECK_LE(params->video.num_temporal_layers, 2);
sprangce4aef12015-11-02 07:23:20 -08001043 }
1044 params->ss.streams.push_back(stream);
1045 }
1046 params->ss.selected_stream = selected_stream;
1047
1048 params->ss.num_spatial_layers = num_spatial_layers ? num_spatial_layers : 1;
1049 params->ss.selected_sl = selected_sl;
1050 RTC_CHECK(params->ss.spatial_layers.empty());
1051 for (auto descriptor : sl_descriptors) {
1052 if (descriptor.empty())
1053 continue;
1054 std::vector<int> v = VideoQualityTest::ParseCSV(descriptor);
1055 RTC_CHECK_GT(v[2], 0);
1056
1057 SpatialLayer layer;
1058 layer.scaling_factor_num = v[0] == -1 ? 1 : v[0];
1059 layer.scaling_factor_den = v[1] == -1 ? 1 : v[1];
1060 layer.target_bitrate_bps = v[2];
1061 params->ss.spatial_layers.push_back(layer);
1062 }
1063}
1064
minyuea27172d2016-11-01 05:59:29 -07001065void VideoQualityTest::SetupVideo(Transport* send_transport,
1066 Transport* recv_transport) {
sprangce4aef12015-11-02 07:23:20 -08001067 if (params_.logs)
ivica5d6a06c2015-09-17 05:30:24 -07001068 trace_to_stderr_.reset(new test::TraceToStderr);
1069
brandtr8313a6f2017-01-13 07:41:19 -08001070 size_t num_video_streams = params_.ss.streams.size();
1071 size_t num_flexfec_streams = params_.video.flexfec ? 1 : 0;
1072 CreateSendConfig(num_video_streams, 0, num_flexfec_streams, send_transport);
ivica5d6a06c2015-09-17 05:30:24 -07001073
1074 int payload_type;
minyue626bc952016-10-31 05:47:02 -07001075 if (params_.video.codec == "H264") {
magjedceecea42016-11-28 07:20:21 -08001076 video_encoder_.reset(H264Encoder::Create(cricket::VideoCodec("H264")));
hbosbab934b2016-01-27 01:36:03 -08001077 payload_type = kPayloadTypeH264;
minyue626bc952016-10-31 05:47:02 -07001078 } else if (params_.video.codec == "VP8") {
magjed509e4fe2016-11-18 01:34:11 -08001079 video_encoder_.reset(VP8Encoder::Create());
ivica5d6a06c2015-09-17 05:30:24 -07001080 payload_type = kPayloadTypeVP8;
minyue626bc952016-10-31 05:47:02 -07001081 } else if (params_.video.codec == "VP9") {
magjed509e4fe2016-11-18 01:34:11 -08001082 video_encoder_.reset(VP9Encoder::Create());
ivica5d6a06c2015-09-17 05:30:24 -07001083 payload_type = kPayloadTypeVP9;
1084 } else {
1085 RTC_NOTREACHED() << "Codec not supported!";
1086 return;
1087 }
minyuea27172d2016-11-01 05:59:29 -07001088 video_send_config_.encoder_settings.encoder = video_encoder_.get();
minyue626bc952016-10-31 05:47:02 -07001089 video_send_config_.encoder_settings.payload_name = params_.video.codec;
stefanff483612015-12-21 03:14:00 -08001090 video_send_config_.encoder_settings.payload_type = payload_type;
1091 video_send_config_.rtp.nack.rtp_history_ms = kNackRtpHistoryMs;
1092 video_send_config_.rtp.rtx.payload_type = kSendRtxPayloadType;
brandtr8313a6f2017-01-13 07:41:19 -08001093 for (size_t i = 0; i < num_video_streams; ++i)
stefanff483612015-12-21 03:14:00 -08001094 video_send_config_.rtp.rtx.ssrcs.push_back(kSendRtxSsrcs[i]);
ivica5d6a06c2015-09-17 05:30:24 -07001095
stefanff483612015-12-21 03:14:00 -08001096 video_send_config_.rtp.extensions.clear();
minyue626bc952016-10-31 05:47:02 -07001097 if (params_.call.send_side_bwe) {
stefanff483612015-12-21 03:14:00 -08001098 video_send_config_.rtp.extensions.push_back(
isheriff6f8d6862016-05-26 11:24:55 -07001099 RtpExtension(RtpExtension::kTransportSequenceNumberUri,
Stefan Holmer12952972015-10-29 15:13:24 +01001100 test::kTransportSequenceNumberExtensionId));
1101 } else {
stefanff483612015-12-21 03:14:00 -08001102 video_send_config_.rtp.extensions.push_back(RtpExtension(
isheriff6f8d6862016-05-26 11:24:55 -07001103 RtpExtension::kAbsSendTimeUri, test::kAbsSendTimeExtensionId));
Erik SprĂ¥ng6b8d3552015-09-24 15:06:57 +02001104 }
1105
stefanff483612015-12-21 03:14:00 -08001106 video_encoder_config_.min_transmit_bitrate_bps =
minyue626bc952016-10-31 05:47:02 -07001107 params_.video.min_transmit_bps;
perkjfa10b552016-10-02 23:45:26 -07001108
brandtr1293aca2016-11-16 22:47:29 -08001109 video_send_config_.suspend_below_min_bitrate =
1110 params_.video.suspend_below_min_bitrate;
1111
perkjfa10b552016-10-02 23:45:26 -07001112 video_encoder_config_.number_of_streams = params_.ss.streams.size();
1113 video_encoder_config_.max_bitrate_bps = 0;
1114 for (size_t i = 0; i < params_.ss.streams.size(); ++i) {
1115 video_encoder_config_.max_bitrate_bps +=
1116 params_.ss.streams[i].max_bitrate_bps;
1117 }
1118 video_encoder_config_.video_stream_factory =
1119 new rtc::RefCountedObject<VideoStreamFactory>(params_.ss.streams);
1120
stefanff483612015-12-21 03:14:00 -08001121 video_encoder_config_.spatial_layers = params_.ss.spatial_layers;
ivica5d6a06c2015-09-17 05:30:24 -07001122
1123 CreateMatchingReceiveConfigs(recv_transport);
1124
brandtr8313a6f2017-01-13 07:41:19 -08001125 for (size_t i = 0; i < num_video_streams; ++i) {
stefanff483612015-12-21 03:14:00 -08001126 video_receive_configs_[i].rtp.nack.rtp_history_ms = kNackRtpHistoryMs;
Stefan Holmer10880012016-02-03 13:29:59 +01001127 video_receive_configs_[i].rtp.rtx[payload_type].ssrc = kSendRtxSsrcs[i];
1128 video_receive_configs_[i].rtp.rtx[payload_type].payload_type =
sprangce4aef12015-11-02 07:23:20 -08001129 kSendRtxPayloadType;
minyue626bc952016-10-31 05:47:02 -07001130 video_receive_configs_[i].rtp.transport_cc = params_.call.send_side_bwe;
sprangce4aef12015-11-02 07:23:20 -08001131 }
brandtr1293aca2016-11-16 22:47:29 -08001132
1133 if (params_.video.flexfec) {
brandtr8313a6f2017-01-13 07:41:19 -08001134 // Override send config constructed by CreateSendConfig.
brandtr1293aca2016-11-16 22:47:29 -08001135 video_send_config_.rtp.flexfec.protected_media_ssrcs = {
1136 kVideoSendSsrcs[params_.ss.selected_stream]};
1137
brandtr8313a6f2017-01-13 07:41:19 -08001138 // The matching receive config is _not_ created by
1139 // CreateMatchingReceiveConfigs, since VideoQualityTest is not a BaseTest.
1140 // Set up the receive config manually instead.
1141 FlexfecReceiveStream::Config flexfec_receive_config(recv_transport);
brandtr1cfbd602016-12-08 04:17:53 -08001142 flexfec_receive_config.payload_type =
brandtr3d200bd2017-01-16 06:59:19 -08001143 video_send_config_.rtp.flexfec.payload_type;
1144 flexfec_receive_config.remote_ssrc = video_send_config_.rtp.flexfec.ssrc;
brandtr1293aca2016-11-16 22:47:29 -08001145 flexfec_receive_config.protected_media_ssrcs =
1146 video_send_config_.rtp.flexfec.protected_media_ssrcs;
brandtrfa5a3682017-01-17 01:33:54 -08001147 flexfec_receive_config.local_ssrc = kReceiverLocalVideoSsrc;
brandtrb29e6522016-12-21 06:37:18 -08001148 flexfec_receive_config.transport_cc = params_.call.send_side_bwe;
1149 if (params_.call.send_side_bwe) {
1150 flexfec_receive_config.rtp_header_extensions.push_back(
1151 RtpExtension(RtpExtension::kTransportSequenceNumberUri,
1152 test::kTransportSequenceNumberExtensionId));
1153 } else {
1154 flexfec_receive_config.rtp_header_extensions.push_back(RtpExtension(
1155 RtpExtension::kAbsSendTimeUri, test::kAbsSendTimeExtensionId));
1156 }
brandtr1293aca2016-11-16 22:47:29 -08001157 flexfec_receive_configs_.push_back(flexfec_receive_config);
1158 }
1159
1160 if (params_.video.ulpfec) {
1161 video_send_config_.rtp.ulpfec.red_payload_type = kRedPayloadType;
1162 video_send_config_.rtp.ulpfec.ulpfec_payload_type = kUlpfecPayloadType;
1163 video_send_config_.rtp.ulpfec.red_rtx_payload_type = kRtxRedPayloadType;
1164
1165 video_receive_configs_[params_.ss.selected_stream]
1166 .rtp.ulpfec.red_payload_type =
1167 video_send_config_.rtp.ulpfec.red_payload_type;
1168 video_receive_configs_[params_.ss.selected_stream]
1169 .rtp.ulpfec.ulpfec_payload_type =
1170 video_send_config_.rtp.ulpfec.ulpfec_payload_type;
1171 video_receive_configs_[params_.ss.selected_stream]
1172 .rtp.ulpfec.red_rtx_payload_type =
1173 video_send_config_.rtp.ulpfec.red_rtx_payload_type;
1174 }
ivica5d6a06c2015-09-17 05:30:24 -07001175}
1176
sprangce4aef12015-11-02 07:23:20 -08001177void VideoQualityTest::SetupScreenshare() {
1178 RTC_CHECK(params_.screenshare.enabled);
ivica5d6a06c2015-09-17 05:30:24 -07001179
1180 // Fill out codec settings.
stefanff483612015-12-21 03:14:00 -08001181 video_encoder_config_.content_type = VideoEncoderConfig::ContentType::kScreen;
minyue626bc952016-10-31 05:47:02 -07001182 if (params_.video.codec == "VP8") {
kthelgason29a44e32016-09-27 03:52:02 -07001183 VideoCodecVP8 vp8_settings = VideoEncoder::GetDefaultVp8Settings();
1184 vp8_settings.denoisingOn = false;
1185 vp8_settings.frameDroppingOn = false;
1186 vp8_settings.numberOfTemporalLayers =
minyue626bc952016-10-31 05:47:02 -07001187 static_cast<unsigned char>(params_.video.num_temporal_layers);
kthelgason29a44e32016-09-27 03:52:02 -07001188 video_encoder_config_.encoder_specific_settings = new rtc::RefCountedObject<
1189 VideoEncoderConfig::Vp8EncoderSpecificSettings>(vp8_settings);
minyue626bc952016-10-31 05:47:02 -07001190 } else if (params_.video.codec == "VP9") {
kthelgason29a44e32016-09-27 03:52:02 -07001191 VideoCodecVP9 vp9_settings = VideoEncoder::GetDefaultVp9Settings();
1192 vp9_settings.denoisingOn = false;
1193 vp9_settings.frameDroppingOn = false;
1194 vp9_settings.numberOfTemporalLayers =
minyue626bc952016-10-31 05:47:02 -07001195 static_cast<unsigned char>(params_.video.num_temporal_layers);
kthelgason29a44e32016-09-27 03:52:02 -07001196 vp9_settings.numberOfSpatialLayers =
sprangce4aef12015-11-02 07:23:20 -08001197 static_cast<unsigned char>(params_.ss.num_spatial_layers);
kthelgason29a44e32016-09-27 03:52:02 -07001198 video_encoder_config_.encoder_specific_settings = new rtc::RefCountedObject<
1199 VideoEncoderConfig::Vp9EncoderSpecificSettings>(vp9_settings);
ivica5d6a06c2015-09-17 05:30:24 -07001200 }
1201
1202 // Setup frame generator.
1203 const size_t kWidth = 1850;
1204 const size_t kHeight = 1110;
1205 std::vector<std::string> slides;
1206 slides.push_back(test::ResourcePath("web_screenshot_1850_1110", "yuv"));
1207 slides.push_back(test::ResourcePath("presentation_1850_1110", "yuv"));
1208 slides.push_back(test::ResourcePath("photo_1850_1110", "yuv"));
1209 slides.push_back(test::ResourcePath("difficult_photo_1850_1110", "yuv"));
1210
sprangce4aef12015-11-02 07:23:20 -08001211 if (params_.screenshare.scroll_duration == 0) {
ivica5d6a06c2015-09-17 05:30:24 -07001212 // Cycle image every slide_change_interval seconds.
1213 frame_generator_.reset(test::FrameGenerator::CreateFromYuvFile(
1214 slides, kWidth, kHeight,
minyue626bc952016-10-31 05:47:02 -07001215 params_.screenshare.slide_change_interval * params_.video.fps));
ivica5d6a06c2015-09-17 05:30:24 -07001216 } else {
minyue626bc952016-10-31 05:47:02 -07001217 RTC_CHECK_LE(params_.video.width, kWidth);
1218 RTC_CHECK_LE(params_.video.height, kHeight);
sprangce4aef12015-11-02 07:23:20 -08001219 RTC_CHECK_GT(params_.screenshare.slide_change_interval, 0);
1220 const int kPauseDurationMs = (params_.screenshare.slide_change_interval -
1221 params_.screenshare.scroll_duration) *
1222 1000;
1223 RTC_CHECK_LE(params_.screenshare.scroll_duration,
1224 params_.screenshare.slide_change_interval);
ivica5d6a06c2015-09-17 05:30:24 -07001225
sprangce4aef12015-11-02 07:23:20 -08001226 frame_generator_.reset(
1227 test::FrameGenerator::CreateScrollingInputFromYuvFiles(
minyue626bc952016-10-31 05:47:02 -07001228 clock_, slides, kWidth, kHeight, params_.video.width,
1229 params_.video.height, params_.screenshare.scroll_duration * 1000,
sprangce4aef12015-11-02 07:23:20 -08001230 kPauseDurationMs));
ivica5d6a06c2015-09-17 05:30:24 -07001231 }
1232}
1233
perkja49cbd32016-09-16 07:53:41 -07001234void VideoQualityTest::CreateCapturer() {
sprangce4aef12015-11-02 07:23:20 -08001235 if (params_.screenshare.enabled) {
1236 test::FrameGeneratorCapturer* frame_generator_capturer =
perkja49cbd32016-09-16 07:53:41 -07001237 new test::FrameGeneratorCapturer(clock_, frame_generator_.release(),
minyue626bc952016-10-31 05:47:02 -07001238 params_.video.fps);
ivica2d4e6c52015-09-23 01:57:06 -07001239 EXPECT_TRUE(frame_generator_capturer->Init());
minyuea27172d2016-11-01 05:59:29 -07001240 video_capturer_.reset(frame_generator_capturer);
ivica5d6a06c2015-09-17 05:30:24 -07001241 } else {
sprangce4aef12015-11-02 07:23:20 -08001242 if (params_.video.clip_name.empty()) {
minyuea27172d2016-11-01 05:59:29 -07001243 video_capturer_.reset(test::VcmCapturer::Create(
minyue626bc952016-10-31 05:47:02 -07001244 params_.video.width, params_.video.height, params_.video.fps));
ivica5d6a06c2015-09-17 05:30:24 -07001245 } else {
minyuea27172d2016-11-01 05:59:29 -07001246 video_capturer_.reset(test::FrameGeneratorCapturer::CreateFromYuvFile(
perkja49cbd32016-09-16 07:53:41 -07001247 test::ResourcePath(params_.video.clip_name, "yuv"),
minyue626bc952016-10-31 05:47:02 -07001248 params_.video.width, params_.video.height, params_.video.fps,
ivica2d4e6c52015-09-23 01:57:06 -07001249 clock_));
minyuea27172d2016-11-01 05:59:29 -07001250 ASSERT_TRUE(video_capturer_) << "Could not create capturer for "
1251 << params_.video.clip_name
1252 << ".yuv. Is this resource file present?";
ivica5d6a06c2015-09-17 05:30:24 -07001253 }
1254 }
1255}
1256
sprang7a975f72015-10-12 06:33:21 -07001257void VideoQualityTest::RunWithAnalyzer(const Params& params) {
sprangce4aef12015-11-02 07:23:20 -08001258 params_ = params;
1259
minyue626bc952016-10-31 05:47:02 -07001260 RTC_CHECK(!params_.audio.enabled);
ivica5d6a06c2015-09-17 05:30:24 -07001261 // TODO(ivica): Merge with RunWithRenderer and use a flag / argument to
1262 // differentiate between the analyzer and the renderer case.
sprangce4aef12015-11-02 07:23:20 -08001263 CheckParams();
ivica5d6a06c2015-09-17 05:30:24 -07001264
1265 FILE* graph_data_output_file = nullptr;
sprangce4aef12015-11-02 07:23:20 -08001266 if (!params_.analyzer.graph_data_output_filename.empty()) {
ivica5d6a06c2015-09-17 05:30:24 -07001267 graph_data_output_file =
sprangce4aef12015-11-02 07:23:20 -08001268 fopen(params_.analyzer.graph_data_output_filename.c_str(), "w");
Peter Boström74f6e9e2016-04-04 17:56:10 +02001269 RTC_CHECK(graph_data_output_file)
sprangce4aef12015-11-02 07:23:20 -08001270 << "Can't open the file " << params_.analyzer.graph_data_output_filename
1271 << "!";
ivica87f83a92015-10-08 05:13:32 -07001272 }
sprang7a975f72015-10-12 06:33:21 -07001273
skvlad11a9cbf2016-10-07 11:53:05 -07001274 webrtc::RtcEventLogNullImpl event_log;
1275 Call::Config call_config(&event_log_);
minyue626bc952016-10-31 05:47:02 -07001276 call_config.bitrate_config = params.call.call_bitrate_config;
stefanf116bd02015-10-27 08:29:42 -07001277 CreateCalls(call_config, call_config);
1278
ivica87f83a92015-10-08 05:13:32 -07001279 test::LayerFilteringTransport send_transport(
minyue626bc952016-10-31 05:47:02 -07001280 params_.pipe, sender_call_.get(), kPayloadTypeVP8, kPayloadTypeVP9,
1281 params_.video.selected_tl, params_.ss.selected_sl);
1282 test::DirectTransport recv_transport(params_.pipe, receiver_call_.get());
stefanf116bd02015-10-27 08:29:42 -07001283
sprangce4aef12015-11-02 07:23:20 -08001284 std::string graph_title = params_.analyzer.graph_title;
1285 if (graph_title.empty())
1286 graph_title = VideoQualityTest::GenerateGraphTitle();
1287
1288 // In the case of different resolutions, the functions calculating PSNR and
1289 // SSIM return -1.0, instead of a positive value as usual. VideoAnalyzer
1290 // aborts if the average psnr/ssim are below the given threshold, which is
1291 // 0.0 by default. Setting the thresholds to -1.1 prevents the unnecessary
1292 // abort.
1293 VideoStream& selected_stream = params_.ss.streams[params_.ss.selected_stream];
1294 int selected_sl = params_.ss.selected_sl != -1
1295 ? params_.ss.selected_sl
1296 : params_.ss.num_spatial_layers - 1;
1297 bool disable_quality_check =
minyue626bc952016-10-31 05:47:02 -07001298 selected_stream.width != params_.video.width ||
1299 selected_stream.height != params_.video.height ||
sprangce4aef12015-11-02 07:23:20 -08001300 (!params_.ss.spatial_layers.empty() &&
1301 params_.ss.spatial_layers[selected_sl].scaling_factor_num !=
1302 params_.ss.spatial_layers[selected_sl].scaling_factor_den);
1303 if (disable_quality_check) {
1304 fprintf(stderr,
1305 "Warning: Calculating PSNR and SSIM for downsized resolution "
1306 "not implemented yet! Skipping PSNR and SSIM calculations!");
1307 }
1308
ivica5d6a06c2015-09-17 05:30:24 -07001309 VideoAnalyzer analyzer(
sprangce4aef12015-11-02 07:23:20 -08001310 &send_transport, params_.analyzer.test_label,
1311 disable_quality_check ? -1.1 : params_.analyzer.avg_psnr_threshold,
1312 disable_quality_check ? -1.1 : params_.analyzer.avg_ssim_threshold,
minyue626bc952016-10-31 05:47:02 -07001313 params_.analyzer.test_durations_secs * params_.video.fps,
sprangce4aef12015-11-02 07:23:20 -08001314 graph_data_output_file, graph_title,
Stefan Holmer9fea80f2016-01-07 17:43:18 +01001315 kVideoSendSsrcs[params_.ss.selected_stream]);
ivica5d6a06c2015-09-17 05:30:24 -07001316
ivica5d6a06c2015-09-17 05:30:24 -07001317 analyzer.SetReceiver(receiver_call_->Receiver());
1318 send_transport.SetReceiver(&analyzer);
1319 recv_transport.SetReceiver(sender_call_->Receiver());
1320
minyuea27172d2016-11-01 05:59:29 -07001321 SetupVideo(&analyzer, &recv_transport);
stefanff483612015-12-21 03:14:00 -08001322 video_receive_configs_[params_.ss.selected_stream].renderer = &analyzer;
pbos14fe7082016-04-20 06:35:56 -07001323 video_send_config_.pre_encode_callback = analyzer.pre_encode_proxy();
stefanff483612015-12-21 03:14:00 -08001324 for (auto& config : video_receive_configs_)
ivica5d6a06c2015-09-17 05:30:24 -07001325 config.pre_decode_callback = &analyzer;
Peter Boströme4499152016-02-05 11:13:28 +01001326 RTC_DCHECK(!video_send_config_.post_encode_callback);
1327 video_send_config_.post_encode_callback = analyzer.encode_timing_proxy();
ivica5d6a06c2015-09-17 05:30:24 -07001328
sprangce4aef12015-11-02 07:23:20 -08001329 if (params_.screenshare.enabled)
1330 SetupScreenshare();
ivica5d6a06c2015-09-17 05:30:24 -07001331
brandtr1293aca2016-11-16 22:47:29 -08001332 CreateFlexfecStreams();
Stefan Holmer9fea80f2016-01-07 17:43:18 +01001333 CreateVideoStreams();
perkja49cbd32016-09-16 07:53:41 -07001334 analyzer.SetSendStream(video_send_stream_);
philipelfd870db2017-01-23 03:22:15 -08001335 if (video_receive_streams_.size() == 1)
1336 analyzer.SetReceiveStream(video_receive_streams_[0]);
perkj803d97f2016-11-01 11:45:46 -07001337 video_send_stream_->SetSource(
1338 analyzer.OutputInterface(),
1339 VideoSendStream::DegradationPreference::kBalanced);
ivica5d6a06c2015-09-17 05:30:24 -07001340
perkja49cbd32016-09-16 07:53:41 -07001341 CreateCapturer();
1342 rtc::VideoSinkWants wants;
minyuea27172d2016-11-01 05:59:29 -07001343 video_capturer_->AddOrUpdateSink(analyzer.InputInterface(), wants);
ivicac1cc8542015-10-08 03:44:06 -07001344
palmkviste75f2042016-09-28 06:19:48 -07001345 StartEncodedFrameLogs(video_send_stream_);
1346 StartEncodedFrameLogs(video_receive_streams_[0]);
stefanff483612015-12-21 03:14:00 -08001347 video_send_stream_->Start();
1348 for (VideoReceiveStream* receive_stream : video_receive_streams_)
1349 receive_stream->Start();
brandtr1293aca2016-11-16 22:47:29 -08001350 for (FlexfecReceiveStream* receive_stream : flexfec_receive_streams_)
1351 receive_stream->Start();
minyuea27172d2016-11-01 05:59:29 -07001352 video_capturer_->Start();
ivica5d6a06c2015-09-17 05:30:24 -07001353
1354 analyzer.Wait();
1355
1356 send_transport.StopSending();
1357 recv_transport.StopSending();
1358
minyuea27172d2016-11-01 05:59:29 -07001359 video_capturer_->Stop();
brandtr1293aca2016-11-16 22:47:29 -08001360 for (FlexfecReceiveStream* receive_stream : flexfec_receive_streams_)
1361 receive_stream->Stop();
stefanff483612015-12-21 03:14:00 -08001362 for (VideoReceiveStream* receive_stream : video_receive_streams_)
1363 receive_stream->Stop();
1364 video_send_stream_->Stop();
ivica5d6a06c2015-09-17 05:30:24 -07001365
1366 DestroyStreams();
1367
1368 if (graph_data_output_file)
1369 fclose(graph_data_output_file);
1370}
1371
minyuea27172d2016-11-01 05:59:29 -07001372void VideoQualityTest::SetupAudio(int send_channel_id,
1373 int receive_channel_id,
1374 Call* call,
1375 Transport* transport,
1376 AudioReceiveStream** audio_receive_stream) {
1377 audio_send_config_ = AudioSendStream::Config(transport);
1378 audio_send_config_.voe_channel_id = send_channel_id;
1379 audio_send_config_.rtp.ssrc = kAudioSendSsrc;
1380
1381 // Add extension to enable audio send side BWE, and allow audio bit rate
1382 // adaptation.
1383 audio_send_config_.rtp.extensions.clear();
1384 if (params_.call.send_side_bwe) {
1385 audio_send_config_.rtp.extensions.push_back(
1386 webrtc::RtpExtension(webrtc::RtpExtension::kTransportSequenceNumberUri,
1387 test::kTransportSequenceNumberExtensionId));
minyue10cbb462016-11-07 09:29:22 -08001388 audio_send_config_.min_bitrate_bps = kOpusMinBitrateBps;
1389 audio_send_config_.max_bitrate_bps = kOpusBitrateFbBps;
minyuea27172d2016-11-01 05:59:29 -07001390 }
1391 audio_send_config_.send_codec_spec.codec_inst =
1392 CodecInst{120, "OPUS", 48000, 960, 2, 64000};
1393
1394 audio_send_stream_ = call->CreateAudioSendStream(audio_send_config_);
1395
1396 AudioReceiveStream::Config audio_config;
1397 audio_config.rtp.local_ssrc = kReceiverLocalAudioSsrc;
1398 audio_config.rtcp_send_transport = transport;
1399 audio_config.voe_channel_id = receive_channel_id;
1400 audio_config.rtp.remote_ssrc = audio_send_config_.rtp.ssrc;
1401 audio_config.rtp.transport_cc = params_.call.send_side_bwe;
1402 audio_config.rtp.extensions = audio_send_config_.rtp.extensions;
1403 audio_config.decoder_factory = decoder_factory_;
1404 if (params_.video.enabled && params_.audio.sync_video)
1405 audio_config.sync_group = kSyncGroup;
1406
1407 *audio_receive_stream = call->CreateAudioReceiveStream(audio_config);
1408}
1409
minyue73208662016-08-18 06:28:55 -07001410void VideoQualityTest::RunWithRenderers(const Params& params) {
sprangce4aef12015-11-02 07:23:20 -08001411 params_ = params;
1412 CheckParams();
ivica5d6a06c2015-09-17 05:30:24 -07001413
ivica5d6a06c2015-09-17 05:30:24 -07001414 // TODO(ivica): Remove bitrate_config and use the default Call::Config(), to
1415 // match the full stack tests.
skvlad11a9cbf2016-10-07 11:53:05 -07001416 webrtc::RtcEventLogNullImpl event_log;
1417 Call::Config call_config(&event_log_);
minyue626bc952016-10-31 05:47:02 -07001418 call_config.bitrate_config = params_.call.call_bitrate_config;
minyue73208662016-08-18 06:28:55 -07001419
1420 ::VoiceEngineState voe;
minyue626bc952016-10-31 05:47:02 -07001421 if (params_.audio.enabled) {
minyue73208662016-08-18 06:28:55 -07001422 CreateVoiceEngine(&voe, decoder_factory_);
1423 AudioState::Config audio_state_config;
1424 audio_state_config.voice_engine = voe.voice_engine;
aleloi10111bc2016-11-17 06:48:48 -08001425 audio_state_config.audio_mixer = AudioMixerImpl::Create();
minyue73208662016-08-18 06:28:55 -07001426 call_config.audio_state = AudioState::Create(audio_state_config);
1427 }
1428
kwiberg27f982b2016-03-01 11:52:33 -08001429 std::unique_ptr<Call> call(Call::Create(call_config));
ivica5d6a06c2015-09-17 05:30:24 -07001430
minyuea27172d2016-11-01 05:59:29 -07001431 // TODO(minyue): consider if this is a good transport even for audio only
1432 // calls.
ivica5d6a06c2015-09-17 05:30:24 -07001433 test::LayerFilteringTransport transport(
stefanf116bd02015-10-27 08:29:42 -07001434 params.pipe, call.get(), kPayloadTypeVP8, kPayloadTypeVP9,
minyue626bc952016-10-31 05:47:02 -07001435 params.video.selected_tl, params_.ss.selected_sl);
ivica5d6a06c2015-09-17 05:30:24 -07001436 // TODO(ivica): Use two calls to be able to merge with RunWithAnalyzer or at
1437 // least share as much code as possible. That way this test would also match
1438 // the full stack tests better.
1439 transport.SetReceiver(call->Receiver());
1440
minyuea27172d2016-11-01 05:59:29 -07001441 VideoReceiveStream* video_receive_stream = nullptr;
brandtr1293aca2016-11-16 22:47:29 -08001442 FlexfecReceiveStream* flexfec_receive_stream = nullptr;
minyuea27172d2016-11-01 05:59:29 -07001443 std::unique_ptr<test::VideoRenderer> local_preview;
1444 std::unique_ptr<test::VideoRenderer> loopback_video;
1445 if (params_.video.enabled) {
1446 // Create video renderers.
1447 local_preview.reset(test::VideoRenderer::Create(
1448 "Local Preview", params_.video.width, params_.video.height));
ivica87f83a92015-10-08 05:13:32 -07001449
minyuea27172d2016-11-01 05:59:29 -07001450 size_t stream_id = params_.ss.selected_stream;
1451 std::string title = "Loopback Video";
1452 if (params_.ss.streams.size() > 1) {
1453 std::ostringstream s;
1454 s << stream_id;
1455 title += " - Stream #" + s.str();
1456 }
sprangce4aef12015-11-02 07:23:20 -08001457
minyuea27172d2016-11-01 05:59:29 -07001458 loopback_video.reset(test::VideoRenderer::Create(
1459 title.c_str(), params_.ss.streams[stream_id].width,
1460 params_.ss.streams[stream_id].height));
mflodman48a4beb2016-07-01 13:03:59 +02001461
minyuea27172d2016-11-01 05:59:29 -07001462 SetupVideo(&transport, &transport);
minyuea27172d2016-11-01 05:59:29 -07001463 video_send_config_.pre_encode_callback = local_preview.get();
1464 video_receive_configs_[stream_id].renderer = loopback_video.get();
1465 if (params_.audio.enabled && params_.audio.sync_video)
1466 video_receive_configs_[stream_id].sync_group = kSyncGroup;
1467
minyuea27172d2016-11-01 05:59:29 -07001468 if (params_.screenshare.enabled)
1469 SetupScreenshare();
1470
1471 video_send_stream_ = call->CreateVideoSendStream(
1472 video_send_config_.Copy(), video_encoder_config_.Copy());
brandtr1293aca2016-11-16 22:47:29 -08001473 if (params_.video.flexfec) {
1474 RTC_DCHECK(!flexfec_receive_configs_.empty());
1475 flexfec_receive_stream =
1476 call->CreateFlexfecReceiveStream(flexfec_receive_configs_[0]);
1477 }
minyuea27172d2016-11-01 05:59:29 -07001478 video_receive_stream = call->CreateVideoReceiveStream(
1479 video_receive_configs_[stream_id].Copy());
1480 CreateCapturer();
perkj803d97f2016-11-01 11:45:46 -07001481 video_send_stream_->SetSource(
1482 video_capturer_.get(),
1483 VideoSendStream::DegradationPreference::kBalanced);
philipel274c1dc2016-05-04 06:21:01 -07001484 }
1485
minyue73208662016-08-18 06:28:55 -07001486 AudioReceiveStream* audio_receive_stream = nullptr;
minyue626bc952016-10-31 05:47:02 -07001487 if (params_.audio.enabled) {
minyuea27172d2016-11-01 05:59:29 -07001488 SetupAudio(voe.send_channel_id, voe.receive_channel_id, call.get(),
1489 &transport, &audio_receive_stream);
minyue73208662016-08-18 06:28:55 -07001490 }
1491
palmkviste75f2042016-09-28 06:19:48 -07001492 StartEncodedFrameLogs(video_receive_stream);
1493 StartEncodedFrameLogs(video_send_stream_);
1494
minyue73208662016-08-18 06:28:55 -07001495 // Start sending and receiving video.
minyuea27172d2016-11-01 05:59:29 -07001496 if (params_.video.enabled) {
brandtr1293aca2016-11-16 22:47:29 -08001497 if (flexfec_receive_stream)
1498 flexfec_receive_stream->Start();
minyuea27172d2016-11-01 05:59:29 -07001499 video_receive_stream->Start();
1500 video_send_stream_->Start();
1501 video_capturer_->Start();
1502 }
ivica5d6a06c2015-09-17 05:30:24 -07001503
minyue626bc952016-10-31 05:47:02 -07001504 if (params_.audio.enabled) {
minyue73208662016-08-18 06:28:55 -07001505 // Start receiving audio.
1506 audio_receive_stream->Start();
1507 EXPECT_EQ(0, voe.base->StartPlayout(voe.receive_channel_id));
minyue73208662016-08-18 06:28:55 -07001508
1509 // Start sending audio.
1510 audio_send_stream_->Start();
1511 EXPECT_EQ(0, voe.base->StartSend(voe.send_channel_id));
1512 }
1513
ivica5d6a06c2015-09-17 05:30:24 -07001514 test::PressEnterToContinue();
1515
minyue626bc952016-10-31 05:47:02 -07001516 if (params_.audio.enabled) {
minyue73208662016-08-18 06:28:55 -07001517 // Stop sending audio.
1518 EXPECT_EQ(0, voe.base->StopSend(voe.send_channel_id));
1519 audio_send_stream_->Stop();
1520
1521 // Stop receiving audio.
minyue73208662016-08-18 06:28:55 -07001522 EXPECT_EQ(0, voe.base->StopPlayout(voe.receive_channel_id));
1523 audio_receive_stream->Stop();
minyuea27172d2016-11-01 05:59:29 -07001524 call->DestroyAudioSendStream(audio_send_stream_);
1525 call->DestroyAudioReceiveStream(audio_receive_stream);
minyue73208662016-08-18 06:28:55 -07001526 }
1527
1528 // Stop receiving and sending video.
minyuea27172d2016-11-01 05:59:29 -07001529 if (params_.video.enabled) {
1530 video_capturer_->Stop();
1531 video_send_stream_->Stop();
1532 video_receive_stream->Stop();
brandtr1293aca2016-11-16 22:47:29 -08001533 if (flexfec_receive_stream) {
1534 flexfec_receive_stream->Stop();
1535 call->DestroyFlexfecReceiveStream(flexfec_receive_stream);
1536 }
minyuea27172d2016-11-01 05:59:29 -07001537 call->DestroyVideoReceiveStream(video_receive_stream);
1538 call->DestroyVideoSendStream(video_send_stream_);
minyue73208662016-08-18 06:28:55 -07001539 }
1540
ivica5d6a06c2015-09-17 05:30:24 -07001541 transport.StopSending();
minyue626bc952016-10-31 05:47:02 -07001542 if (params_.audio.enabled)
minyue73208662016-08-18 06:28:55 -07001543 DestroyVoiceEngine(&voe);
ivica5d6a06c2015-09-17 05:30:24 -07001544}
1545
palmkviste75f2042016-09-28 06:19:48 -07001546void VideoQualityTest::StartEncodedFrameLogs(VideoSendStream* stream) {
minyue626bc952016-10-31 05:47:02 -07001547 if (!params_.video.encoded_frame_base_path.empty()) {
palmkviste75f2042016-09-28 06:19:48 -07001548 std::ostringstream str;
1549 str << send_logs_++;
1550 std::string prefix =
minyue626bc952016-10-31 05:47:02 -07001551 params_.video.encoded_frame_base_path + "." + str.str() + ".send.";
palmkviste75f2042016-09-28 06:19:48 -07001552 stream->EnableEncodedFrameRecording(
1553 std::vector<rtc::PlatformFile>(
1554 {rtc::CreatePlatformFile(prefix + "1.ivf"),
1555 rtc::CreatePlatformFile(prefix + "2.ivf"),
1556 rtc::CreatePlatformFile(prefix + "3.ivf")}),
1557 10000000);
1558 }
1559}
1560void VideoQualityTest::StartEncodedFrameLogs(VideoReceiveStream* stream) {
minyue626bc952016-10-31 05:47:02 -07001561 if (!params_.video.encoded_frame_base_path.empty()) {
palmkviste75f2042016-09-28 06:19:48 -07001562 std::ostringstream str;
1563 str << receive_logs_++;
1564 std::string path =
minyue626bc952016-10-31 05:47:02 -07001565 params_.video.encoded_frame_base_path + "." + str.str() + ".recv.ivf";
palmkviste75f2042016-09-28 06:19:48 -07001566 stream->EnableEncodedFrameRecording(rtc::CreatePlatformFile(path),
1567 10000000);
1568 }
1569}
1570
ivica5d6a06c2015-09-17 05:30:24 -07001571} // namespace webrtc